text
stringlengths
15
59.8k
meta
dict
Q: How to assign a tf.keras.layers.layer to a class without initializing it? I work on a class to create all sorts of symmetric AE's. I now port this class to TF 2.0 and it is more complicated than I thought. However, I use subclassing of layers and models to achieve this. Therefore I want to group several keras layers to one keras layer. But if I want to write something like this: def __init__(self, name, keras_layer, **kwargs): self.keras_layer = tf.keras.layer.Conv2D super(CoderLayer, self).__init__(name=name, **kwargs) I get the following error, because tf wants to use this uninitialized layer: TypeError: _method_wrapper() missing 1 required positional argument: 'self' I also tried to wrap this in a list, but it did not work either. EDIT Here is a working minimal example and the full traceback: import tensorflow as tf print(tf.__version__) # 2.0.0-alpha0 class CoderLayer(tf.keras.layers.Layer): def __init__(self, name, keras_layer): self.keras_layer = keras_layer self.out = keras_layer(12, [3, 3]) super(CoderLayer, self).__init__(name=name) def call(self, inputs): return self.out(inputs) inputs = tf.keras.Input(shape=(200, 200, 3), batch_size=12) layer = CoderLayer("minimal_example", tf.keras.layers.Conv2D) layer(inputs) Traceback: Traceback (most recent call last): File "..\baseline_cae.py", line 24, in <module> layer(inputs) File "..\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\engine\base_layer.py", line 581, in __call__ self._clear_losses() File "..\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\training\tracking\base.py", line 456, in _method_wrapper result = method(self, *args, **kwargs) File "..\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\engine\base_layer.py", line 818, in _clear_losses layer._clear_losses() TypeError: _method_wrapper() missing 1 required positional argument: 'self' A: The problem is with setting not instantiated class as an attribute in a subclass of tf.keras.layers.Layer. If you remove following line self.keras_layer = keras_layer the code would work: import tensorflow as tf class CoderLayer(tf.keras.layers.Layer): def __init__(self, name, keras_layer): super(CoderLayer, self).__init__(name=name) self.out = keras_layer(12, [3, 3]) def call(self, inputs): return self.out(inputs) inputs = tf.keras.Input(shape=(200, 200, 3), batch_size=12) layer = CoderLayer("minimal_example", tf.keras.layers.Conv2D) print(layer(inputs)) # Tensor("minimal_example_3/conv2d_12/BiasAdd:0", shape=(12, 198, 198, 12), dtype=float32) It is probably a bug. This is a similar issue that had been raised (if you put your not instantiated class into list and try to __setattr__() you will get the same exception). This could be possible workaround if you want to use multiple layers: class CoderLayer(tf.keras.layers.Layer): def __init__(self, name, layername): super(CoderLayer, self).__init__(name=name) self.layer = layername self.out = tf.keras.layers.__dict__[layername](1, 2) def call(self, inputs): return self.out(inputs) inputs = tf.random.normal([1, 3, 3, 1]) layer = CoderLayer("mylayer", 'Conv2D') layer(inputs).numpy()
{ "language": "en", "url": "https://stackoverflow.com/questions/55965135", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Extract user input to python from a table created in browser? I want to create a table in a browser that's been created with python. That part can be done by using DataTable of the bokeh library. The problem is that I want to extract data from the table when a user gives his/her input in the table itself. Any library of python I could use to do this? It would better if I could do this with bokeh though. A: You can use BeautifulSoup it's great for parse HTML content, see this example A: If your requirement is to create an application using Python and users will access via browser and update some data into a table? Use Django or any web framework, basically, you are trying to build a web app!! or if you are looking for something else do mention your requirement thoroughly. A: The slick grid datatable used in bokeh can be edited directly by users: http://docs.bokeh.org/en/latest/docs/reference/models/widgets.tables.html. Since the data for each column of a datatable can correspond to a field of a ColumnDataSource, one could create python or javascript callbacks, to detect any changes to the datavalues in the table. You can then access the updated data for your desired use case. Here is an example using javascript callback when the data is edited. When the data is edited the updated column is printed to the browser console. Note it only detects the data as changed after you edit the value then click out of the cell. You can do exactly the same with a python callback if you want to run outside python functions based off user input. That does require running a bokeh server to work though. from datetime import date from bokeh.io import output_file, show from bokeh.layouts import widgetbox from bokeh.models import ColumnDataSource, CustomJS from bokeh.models.widgets import DataTable, DateFormatter, TableColumn, StringEditor output_file("data_table.html") data = dict( dates=[date(2014, 3, i+1) for i in range(10)], strings=['edit_this' for i in range(10)], ) source = ColumnDataSource(data) columns = [ TableColumn(field="dates", title="Date", formatter=DateFormatter()), TableColumn(field="strings", title="Downloads", editor=StringEditor()), ] data_table = DataTable(source=source, columns=columns, width=400, height=280, editable=True) # callback code to detect user edit of table code = """ data = source.data console.log('data has been updated!') console.log(data['strings']) """ callback = CustomJS(code=code,args={'source':source}) source.js_on_change('data', callback) show(widgetbox(data_table)) edit: Here is a similar example using a python callback. When you edit the cell all of the cells are replaced in this example. Obviously you could do what ever you wanted this is just an illustration. You need to set a callback on source that responds to a change in the data. Hence source.on_change('data', update). Read more https://docs.bokeh.org/en/latest/docs/user_guide/interaction/widgets.html from datetime import date from bokeh.io import curdoc from bokeh.layouts import widgetbox from bokeh.models import ColumnDataSource from bokeh.models.widgets import DataTable, DateFormatter, TableColumn, StringEditor data = dict( dates=[date(2014, 3, i+1) for i in range(10)], strings=['edit_this' for i in range(10)], ) source = ColumnDataSource(data) columns = [ TableColumn(field="dates", title="Date", formatter=DateFormatter()), TableColumn(field="strings", title="Downloads", editor=StringEditor()), ] data_table = DataTable(source=source, columns=columns, width=400, height=280, editable=True) # callback code to detect user edit of table def update(attrname, old, new): data = source.data data['strings'] = ['you just edited the table.']*10 source.data = data source.on_change('data', update) curdoc().add_root(widgetbox(data_table))
{ "language": "en", "url": "https://stackoverflow.com/questions/45540638", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: (python) how can i split tuple variables? from text file, i could import the result with this code: with open('filename.txt') as file: information = [tuple(line) for line in csv.reader(file)] print(information) result: (' 1.1 4.4 7.5 8.9 11.7 15.0 15.3 15.6 13.3 11.1 7.5 5.8 ',) I want to split this tuple and the result has to be: ('1.1', '4.4', '7.5', '8.9', '11.7', '15.0', '15.3', '15.6', '13.3', '11.1', '7.5', '5.8') when i use this code, splitting = information[1].split(' ') print(splitting) Error happens with AttributeError: 'tuple' object has no attribute 'split' Are there any other methods? A: it seems that you converted the csv into list of tuples in this line: information = [tuple(line) for line in csv.reader(file)] which result in: [(//...tuple 1...//) , (//...tuple 1...//) , ...etc] you better just concat them if you dont want nested lists: data_list= [] for line in csv.reader(file): data_list += line.split() information = tuple(data_list)
{ "language": "en", "url": "https://stackoverflow.com/questions/64844522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Click facebook like button and be taken to another url Is something like this possible? I have a client launching an online magazine for his business. He wants to add a facebook like button (for the magazine fanpage) on his current corporate site and ask users to 'like it' in order to be taken to the magazine website. Can it be done? Are there drawbacks to this approach? For example, the same user will have to 'like it' every time they want to access the magazine site? Thank you for any suggestion, I'm pretty new to facebook. A: You can redirect a user on clicking a like button using the Javascript SDK and FB.Event.Subscribe FB.Event.subscribe('edge.create', function(response) { window.parent.location = 'http://www.google.com'; }); edge.create is called when ever a user likes something on the page response is the url that has just been liked. If there are multiple like buttons on the page you could use an if statement with the response to make sure the page only redirects for a particular like button Here's the full javascript code and a like button <div id="fb-root"></div> <script> window.fbAsyncInit = function() { FB.init({ appId : 'YOUR_APP_ID', // App ID status : true, // check login status cookie : true, // enable cookies to allow the server to access the session oauth : true, // enable OAuth 2.0 xfbml : true // parse XFBML }); FB.Event.subscribe('edge.create', function(response) { window.parent.location = 'http://www.google.com'; }); }; // Load the SDK Asynchronously (function(d){ var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.async = true; js.src = "//connect.facebook.net/<?php if(isset($fb_user['locale'])){echo $fb_user['locale'];}else{echo'en_US';}?>/all.js"; d.getElementsByTagName('head')[0].appendChild(js); }(document)); </script> <fb:like href="http://www.google.com" send="false" width="450" show_faces="true"></fb:like>
{ "language": "en", "url": "https://stackoverflow.com/questions/7919403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Instantiating objects This may be a dumb question although due to my poor wording i'm having a hard time getting a good understanding from searching up on it. When instantiating an object why is the declared like so. Object @object = new Object(); // rather than just Object @object; Is this simply just to call the objects constructor or is there something i'm missing? A: Because thats the syntax to make it a new instance.
{ "language": "en", "url": "https://stackoverflow.com/questions/50810977", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Google Assistant test app unavailable in my country I've been following this tutorial on using Dialogflow and Firebase so I can control a simple website, but when trying to Talk to <app name> I receive the response <app name> isn't available on devices set up for your language or country. Sorry about that. I am located in New Zealand, but I did go into the settings for my google assistant and change the search language to English (US) and my search region to United States, although I get the same results, is there any way I can fix this or is there any way around it? Thanks A: Following Nick Felker's comment, changing my phone's locale to English (US) enabled me to test the app. Thanks Nick!
{ "language": "en", "url": "https://stackoverflow.com/questions/53189325", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use the Raycaster with a CombinedCamera? I try to use a Raycaster (for selection) that works fine with a PerspectiveCamera but doesn't work with a CombinedCamera. First it seems that CombinedCamera is not supported by the Raycaster, so among those line of three.js I add this : if ( camera instanceof THREE.CombinedCamera ) { if( camera.inPerspectiveMode ) { camera = camera.cameraP; } else if ( camera.inOrthographicMode ) { camera = camera.cameraO; } } if ( camera instanceof THREE.PerspectiveCamera ) { ... So as it refers to the nested camera, however that doesn't do the trick because, I believe, the nested cameras position-quaternion-rotation are not updated ?? How can I achieve this and make Raycaster work with both Ortho and Perspective modes of a CombinedCamera ? A: The renderer needs world matrix data for the raycasting to work. Make the following modification to the CombinedCamera code: // Add to the .toPerspective() method: this.matrixWorldInverse = this.cameraP.matrixWorldInverse; // this.matrixWorld = this.cameraP.matrixWorld; // // and to the .toOrthographic() method add: this.matrixWorldInverse = this.cameraO.matrixWorldInverse; // this.matrixWorld = this.cameraO.matrixWorld; // r73.
{ "language": "en", "url": "https://stackoverflow.com/questions/34244134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MongoDB hidden node still receiving connections I'm not sure if this question been asked before or if the following behavior of MongoDB is normal. Searching online output no results to this scenario. Initially, we had a 3 node deployment, 1 Primary, 1 Secondary, and 1 Arbiter. We wanted to add a ReadOnly replica to the cluster and remove the Arbiter node as well in the process. We added the following to the new node: * *priority: 0 *hidden: true *votes: 1 And removed the Arbiter in the same reconfiguration process so we always have 3 voting members and it leaves us with 1 Primary and 1 Secondary and 1 ReadOnly Node. The complete process went through smoothly, however, we still end up seeing connections to the ReadOnly replica. But when checking via db.currentOp(), no queries show up. Based on the documentation on MongoDB website, Hidden members are part of a replica set but cannot become primary and are invisible to client applications. Is there a way to investigate why there are connections coming in? And if this is normal behavior? EDIT: (for further clarification) Assuming the following: MongoDB A (Primary): 192.168.1.50 MongoDB B (Secondary): 192.168.1.51 MongoDB C (Hidden): 192.168.1.52 Client A: 192.168.1.60 Client B: 192.168.1.61 In the logs, we see the following: 2018-03-12T07:19:11.607+0000 I ACCESS [conn119719] Successfully authenticated as principal SOMEUSER on SOMEDB 2018-03-12T07:19:11.607+0000 I NETWORK [conn119719] end connection 192.168.1.60 (2 connections now open) 2018-03-12T07:19:17.087+0000 I NETWORK [listener] connection accepted from 192.168.1.60:47806 #119720 (3 connections now open) 2018-03-12T07:19:17.371+0000 I ACCESS [conn119720] Successfully authenticated as principal SOMEUSER on SOMEDB So if the other MongoDB instances were connecting, that would be fine, but my question is regarding why the clients are able to connect even when the hidden option is true and if that behavior is normal. Thank You
{ "language": "en", "url": "https://stackoverflow.com/questions/49186717", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Custom cordova plugin - Get path to file I've created a Cordova plugin for Android, and I've put a file in the src folder: Plugin.xml <source-file src="myfile.ext" target-dir="src/com/example"/> I also can see (in Android Studio) that the file was succesfully added in the src folder: android |-- /src |-- com |-- example |-- myfile.ext |-- MyPlugin.java Now I need to be able to get the path to this file in MyPlugin.java, but I've no clue how to do this. Can anybody help me with this? Thanks! A: Before you updated your question, it was correct - you should copy the asset file to "assets" not "src": <source-file src="myfile.ext" target-dir="assets"/> Then you can reference it via the AssetManager: AssetManager assetManager = this.cordova.getActivity().getAssets(); InputStream inputStream = assetManager.open("myfile.ext"); In terms of "path" to the file, assets are stored in the APK differently from how your Android project is constructed, so the "path" to your file would be file:///android_asset/myfile.ext, but you most likely wouldn't actually be referencing it like this from MyPlugin.java.
{ "language": "en", "url": "https://stackoverflow.com/questions/44044714", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Detect tap touches on CALayer My setup is as follows - UIView - CALayer (container) -CAShapeLayer -CAShapeLayer -.. And i want to detect tap touches on every shapelayer to change its color I have put a UITapGestureRecognizer on my UIView and have the following code CGPoint point = [self tapWithPoint:[recognizer locationInView:pieView]]; PieSliceLayer* layerThatWasTapped = (PieSliceLayer *)[_containerLayer hitTest:point]; [(PieSliceLayer *)[layerThatWasTapped modelLayer] setFillColor:UIColor.redColor]; But it seems that it only changes 1 CAShapeLayer always the first that was added.
{ "language": "en", "url": "https://stackoverflow.com/questions/15024177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Do you need License for OS (Windows) inside Docker I am looking at creating a Docker (set) for applications that run on Windows. So, I need the Docker to have Windows OS. What license do I need for it? Or if I run the Docker on a Windows VM, does it make use of the same license from the Host? A: The container images will use the underlying OS license. Microsoft calls it supplmental license. You are licensed to use this Supplement in conjunction with the underlying host operating system software (“Host Software”) solely to assist running the containers feature in the Host Software. The Host Software license terms apply to your use of the Supplement. You may not use it if you do not have a license for the Host Software. You may use this Supplement with each validly licensed copy of the Host Software.
{ "language": "en", "url": "https://stackoverflow.com/questions/42574038", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "30" }
Q: Using stream_with_context as async I want to stream a file in telegram using pyrogram, but I can't do it because stream_with_context is not working asynchronously, what can I do? How can I send a file (bytes) to the user asynchronously via flask? No matter how hard I searched, I could not find the answer to this question, there are always answers for synchronous flasks on the internet. If I try to use flask synchronously, this time the pyrogram with telegram api starts to cause problems because this api is mainly made for async from flask import Response from flask import Flask, send_file from flask import stream_with_context app = Flask(__name__) import asyncio from pyrogram import Client api_id = 000 api_hash = "" tg = Client("aaa", api_id, api_hash) @app.route('/bigfile') async def bigfile(): msg = await tg.get_messages(0674564523, 4564535254) async def gnn(): async for chunk in tg.stream_media(msg): chnk = io.BytesIO(chunk) yield chnk return Response( stream_with_context(await gnn()), headers={ 'Content-Disposition': f'attachment; filename=asdfasdf.pdf' } ) import threading if __name__ == '__main__': threading.Thread(target=app.run, daemon=True).start() tg.run()
{ "language": "en", "url": "https://stackoverflow.com/questions/73949570", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to update a View without Postback in MVC3 How can I update a dropdownlist in MVC3. I want to refill it with latest data filled by some other view, but I do not want to postback the view and want to achieve it with jquery. I have a dropdownlist like: @Html.DropDownListFor(m => m.Department, Model.Departments) @Html.ValidationMessageFor(m => m.Departments) <input type="button" value="Refresh" id="btnrefresh" /> I have written jquery code to call controller's method: $("#btnrefresh").click(function () { var ref = '@Url.Action("RefreshDepartments")'; var model = '@Model.ToJson()'; var data = { empModel: model }; $.getJSON(ref, data, function (result) { alert(result.message); }); return false; }); And Here is the controller method: public ActionResult RefreshDepartments(EmployeeModel empModel) { empModel.Departments = GetDepartments(); empModel.Roles = GetRoles(); return Json(new { message = "Updated successfully"}, JsonRequestBehavior.AllowGet); } How can I update the dropdownlist with latest values on clicking "Refresh" button without any postback? Is it a good idea to pass the model to the controller and update the model properties? What other ways are possible ? A: It doesn't look to me like you need the model to be posted to your controller for what you're doing. In addition, yes, you absolutely can do this with jquery! On a side note, you could also do it with an Ajax.BeginForm() helper method, but lets deal with your jquery example. Rather than complexify your jquery with your @Url.Action, you can simply call the path itself. $("#btnrefresh").click(function () { var ref = 'ControllerName/RefreshDepartments'; $.each(result, function (index, val) { $('#whateverYourRenderedDropdownListHtmlObjectis') .append($("<option></option>") .attr("value", val.Text) .text(val.Text)); }); }); Now, for your controller... public JsonResult RefreshDepartments() { return Json(GetDepartments, JsonRequestBehavior.AllowGet); } private SelectList GetDepartments { var deparments = GetDepartments; SelectList list = new SelectList(departments); return list; } This is an alternative to returning the model. It allows you to manipulate the raw JSON instead. Hope it helps! A: You almost did it all! Why don't you send the data, I mean list, by RefreshDepartments action? You sent a message to view, so you can send the list similarly and instead of alerting the result you can fill the dropdownlist. something like this: public ActionResult RefreshDepartments(EmployeeModel empModel) { return Json(new { departments = GetDepartments()}, JsonRequestBehavior.AllowGet); } $.getJSON(ref, data, function (result) { $("#Department").html(""); for (var i = 0; i < result.departments.length; i++) { var item = result.departments[i]; $("#Department").append( $("<option></option>").val(item.Id).html(item.Name); ); }); });
{ "language": "en", "url": "https://stackoverflow.com/questions/14515703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Messed up username and permission on raspberry pi, but still logged in as root through ssh I've gotten myself into a pickle, but perhaps there is still hope. I've commented out the user "pi" while acting as root after typing the following: nano etc/passwd Saved and exited. Next I literally exit terminal. Now upon opening a new terminal window I get the following message: I have no name!@raspberrypi ~ $ Any sudo command I type is returned with the following message: sudo: unknown uid #### who are you? Thing is I still have ssh up on my macbook pro where I'm still logged in as root. Since I'm fairly new to the whole command line bit I figured I'd reach out for a bit a help. Any ideas how to fix the pi without reinstalling?? A: This is not a huge problem, since the file can be edited like any text document. If you are at ssh and have root privileges, just nano /etc/passwd (i feel evil typing that haha), otherwise if there is another user with root privileges (other than pi) login in as them and edit the passwd file. If there are no other users, put your SD card in your mac and edit the file in any text editor. A: I solved it by uncommenting the line that begins with #pi 1000 1000 (something like that) in the file passwd (access it by typing nano/etc/paswwd) by erasing the #, when I did that, everything returns to normality and I was enable to use sudo commands again.
{ "language": "en", "url": "https://stackoverflow.com/questions/20963992", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Radian Console adds random Characters as executed I am facing a problem on a Windows PC using a Radian console for R. When I execute a line, random characters are added to the end of the line in the console. As you can see in the image attached, there is a ") added at the end of the line when I try to execute it. Random Characters added Image Can somebody help? Thanks in advance!
{ "language": "en", "url": "https://stackoverflow.com/questions/73517367", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to sort structure C# I've got this structure: struct kluczyk { int id; char litera; } Making a list: List<kluczyk> posortuj = new List<kluczyk>(); for (int i = 0; i < 10; i++) { kluczyk temp = new kluczyk(some char here, i); posortuj.Add(temp); } How to sort this list by litera? A: There are very simple LINQ methods to accomplish sorting by the property of an object. One is OrderBy: var sortedEnumerable = unsortedEnumerable.OrderBy(a => a.property); Likewise, you can use OrderByDescending to ascertain the reverse order of the above: var sortedEnumerable = unsortedEnumerable.OrderByDescending(a => a.property); Note that these return a new enumerable and do not sort in place. If you needed more complex sorting logic, or if you wanted to sort the kluczyk object itself and not any given property, you'd want to create your own object that implements IComparer and establishes less-than/equal/greater relationships between your objects. Brad Christie included a link to List(T).Sort (IComparer<T>), which I've reproduced here unless he wants to make his own answer.
{ "language": "en", "url": "https://stackoverflow.com/questions/26682080", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: How to get local language in IE-11 I am trying to get the local language in Angular in IE-11. I set the local language in the IE-11 browser as french and then trying to get the local language from IE-11 as follows. this.lang = window.navigator.languages ? window.navigator.languages[0] : null; this.lang = this.lang || window.navigator.language || window.navigator['browserLanguage'] || window.navigator['userLanguage']; it is working fine for all browser but for IE-11 I am not getting the correct local language. it is returning me en-US every time. can anyone help me with this how to get the correct local for IE-11 in Angular8? A: Do you set your browser local language in Control Panel like below in win 7? In this situation, we can get local language in IE 11 using window.navigator.browserLanguage which is "fr-FR". In other modern browsers, we can only use window.navigator.language: In your app, you could use the code below: var sAgent = window.navigator.userAgent; var Idx = sAgent.indexOf("Trident"); //check if IE 11 if (Idx > 0) { this.lang = window.navigator.browserLanguage; } else { this.lang = window.navigator.language; }
{ "language": "en", "url": "https://stackoverflow.com/questions/62173691", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unable to make Google Analytics filter work I wish to create a custom filter on Google Analytics (GA), that would allow me to block all views except the genuine ones onto my webpage. I want to do this because the google-analytics ID associated with my property (UA-XXXXXXXX-X) is public. Hence in theory, my analytics data is open to attack. I was trying to follow the instructions here. As suggested I created a custom filter to exclude any hits from Hostnames other than my webpage (or any sub-webpages) - https://ishank-juneja.github.io/. In particular the steps I followed were - New filter --> custom --> include --> Choose filter field as Hostname Then I entered the filter pattern as https://ishank-juneja\.github\.io/. Which I believe is the correct regex corresponding to my site URL/Hostname. I thought this would be enough to make the filter work, however to be sure, I changed the filter type to exclude instead of include, expecting that if the configuration is correct this filter would start rejecting hits from the url https://ishank-juneja.github.io/ and any of its sub-pages. However when I clicked the filter verification button available at the bottom of the create-filter page, I received the message- "This filter would not have changed your data. Either the filter configuration is incorrect, or the set of sampled data is too small." Since I am certain that all my earlier hits were from the mentioned url, it seems that the filter is not configured correctly even in the include mode. Any help in correcting the working of the filter, so that only hits from the desired Hostname are recorded, would be appreciated. A: Try to use this regex for hostname (without protocol and trailing slash): ishank-juneja\.github\.io
{ "language": "en", "url": "https://stackoverflow.com/questions/62128540", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Doubts with Python I have a question. Here you have part of my code for a better understanding: def client (): A=[] B = open("clientes.txt", "r") user = input("To begin, enter your ID number: ") for line in B: C = line.split("$") A.append(C) for i in range (len(A)): if A[i][0]==user: and then I have another function, here is it: def clientpersonalinfo (): A=[] B=[] C = open("accounts.txt", "r") D = open("clients.txt", "r") for line in C: E=line.split("$") A.append(E) for line in D: F=line.split("$") B.append(F) for i in range (len(A)): ***if user==A[i][1]:*** The question is if there is any method in which i can re-use the first input. As you see if I run this, there will be an error saying that the name "user" is not defined. So I want to know if I can recall the user input that I first used in clients () and re-use it in my clientpersonalinfo () function. Thanks for your help!! Thanks to all those who helped me! Thanks a lot! :) A: Please review the python docs on how to write functions with arguments: http://docs.python.org/tutorial/controlflow.html#defining-functions def myFunction1(): user = "foo" return user def myFunction2(user): print user user = myFunction1() myFunction2(user) Ideally you would organize a nice class structure, instead of using globals everywhere which I think is messy. Its a good sign that you should indeed be using a class when all of your functions end up needing to share some kind of state and you think you might need to start defining a ton of globals: class Client(object): def __init__(self): self.userId = None def getClient(self): self.userId = raw_input("To begin, enter your ID number: ") def parseClientInfo(self): # do something with self.userId print self.userId def clientPersonalInfo(self): # do something with self.userId print self.userId Please note that this class is a really simple example. A: You can reuse whatever you want, you just have to store it somewhere that is visible to both funcitons. You could make a class and put the information in a field or you could return it from the function and pass it on when you call the other function. Global variables are bad style, but that's doable too. A: To preserve the content of "user" (which would be better named "user_input" or some such), one way is to return the content of "user" along with whatever else you are returning in client(), perhaps in a tuple, and then passing it to clientpersonalinfo() as an argument, i.e. clientpersonalinfo(user). Another way is to put the code for getting "user" higher up in the hierarchy so that user exists in the function that calls both client() and clientpersonalinfo(), and then passing it as an argument to both functions. A: If I understand your question correctly, then I think that the best thing for you to do is to take the input call out of the first function and change the function definitions of both functions to take the user as an argument. The code would look something like: def client(user): clients = [] with open("clientes.txt",'r') as f: for client in f: clients.append(client.split('$')) for client in clients: if client[0] == user: ... user = raw_input("To begin, enter your ID number: ") client(user) and the other would be similar. There are a couple of changes from how you handle things. It is recommended that use use the "with open" form since it handles problems better than just opening the file, for instance. Also, naming variables so that the name is relevant to what you are doing makes your code easier to read, so avoid using names like A. Finally, you should use raw_input rather than input in general. The input function evaluates what is input by the user, which means that a user could call some code which is generally not what you want. The raw_input function returns a string which contains what the user put in.
{ "language": "en", "url": "https://stackoverflow.com/questions/9958087", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Why is full-laziness a default optimization? Full laziness has been repeatedly demonstrated to cause space leaks. Why is full laziness on from -O onwards? I find myself unconvinced by the reasoning in SPJ's The Implementation of Functional Programming Languages. The claim is that in f = \y -> y + sqrt 4 sqrt 4 is unnecessarily repeated each time f is entered so we should float it outside the lambda. I agree in the small, but since we've seen what problems this transformation causes in the large I don't believe it is worth it. It seems to me that the benefits of this transformation are obtainable unilaterally** with only local code changes and programmers who want it should implement it by hand. Can you convince me otherwise? Is full-laziness actually really useful? I will be especially convinced if you can provide examples which to implement by hand require multilateral cooperation or non-local transformations. ** unlike optimizations like inlining and stream fusion which to implement by hand would require multilateral cooperation between modules and non-local code changes A: There's at least one common case where full laziness is "safe" and an optimization. g :: Int -> Int g z = f (z+1) where f 0 = 0 f y = 1 + f (y-1) This really means g = \z -> let {f = ...} in f (z+1) and, compiled that way, will allocate a closure for f before calling it. Obviously that's silly, and the compiler should transform the program into g_f 0 = 0 g_f y = 1 + g_f (y-1) g z = g_f (z+1) where no allocation is needed to call g_f. Happily the full laziness transformation does exactly that. Obviously programmers could refrain from making these local definitions that do not depend on the arguments of the top-level function, but such definitions are generally considered good style... Another example: h :: [Int] -> [Int] h xs = map (+1) xs In this case you can just eta reduce, but normally you can't eta reduce. And naming the function (+1) is quite ugly.
{ "language": "en", "url": "https://stackoverflow.com/questions/35115172", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: pip install pods command failed in jupyter with FileNotFoundError: [Errno 2] No such file or directory: 'C:\\tmp\\sods.log' I tried installing the pods package in jupyter notebook using the below commands: pip install pods import pods Installation failed with the following error --------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) <ipython-input-3-c6cba4dfa9c3> in <module> 1 get_ipython().run_line_magic('matplotlib', 'inline') ----> 2 import pods 3 import matplotlib.pyplot as plt ~\anaconda3\lib\site-packages\pods\__init__.py in <module> ----> 1 from . import datasets 2 from . import mocap ~\anaconda3\lib\site-packages\pods\datasets.py in <module> 17 import logging 18 ---> 19 logging.basicConfig( 20 level=logging.DEBUG, 21 format="%(asctime)s %(levelname)s %(message)s", ~\anaconda3\lib\logging\__init__.py in basicConfig(**kwargs) 1974 mode = kwargs.pop("filemode", 'a') 1975 if filename: -> 1976 h = FileHandler(filename, mode) 1977 else: 1978 stream = kwargs.pop("stream", None) ~\anaconda3\lib\logging\__init__.py in __init__(self, filename, mode, encoding, delay) 1141 self.stream = None 1142 else: -> 1143 StreamHandler.__init__(self, self._open()) 1144 1145 def close(self): ~\anaconda3\lib\logging\__init__.py in _open(self) 1170 Return the resulting stream. 1171 """ -> 1172 return open(self.baseFilename, self.mode, encoding=self.encoding) 1173 1174 def emit(self, record): FileNotFoundError: [Errno 2] No such file or directory: 'C:\\tmp\\sods.log' I tried to install the pods package with ! pip install pods --user command but still, the issue is the same. Could anyone give your insights for solving the issue? A: The issue is that the path for the log file is hard coded in the source code, as can be seen on github. The path C:\\tmp does however not exist per default in windows. Simplest solution is just to create a tmp folder on your C drive
{ "language": "en", "url": "https://stackoverflow.com/questions/67963850", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android/XML: RelativeLayout design basically, I don't understand how to use RelativeLayout. I don't know how to design it. I always use LinearLayout with Table inside of it. Now I use RelativeLayout for my design. I want to know, how to add text "Sorry, no list available" Below is my current code of XML <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/haha" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MyHistoryList"> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:clickable="false" android:focusable="false" android:gravity="center" android:longClickable="false" android:maxLines="1" android:textColor="#FFFFFF" android:textSize="18sp" android:textStyle="bold" /> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TableRow android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:layout_marginRight="15dp"> <TextView android:id="@+id/tvSuggestion" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight=".80" android:gravity="start" android:text="Suggestion" android:textAllCaps="true" android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" android:textColor="@color/colorAccent" android:textStyle="bold" app:fontFamily="@font/anaheim" /> <TextView android:id="@+id/tvStatus" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight=".20" android:gravity="start" android:text="Status" android:textAllCaps="true" android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium" android:textColor="@color/colorAccent" android:textStyle="bold" app:fontFamily="@font/anaheim" /> </TableRow> </LinearLayout> <RelativeLayout android:id="@+id/huhu" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.RecyclerView android:id="@+id/recylcerView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:layout_marginBottom="10dp" android:visibility="gone" /> <ImageView android:id="@+id/imgEmpty" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:src="@drawable/empty"/> </RelativeLayout> </LinearLayout> This is how it looks like (source: fbcdn.net) But, I want to add text "Sorry, no list available" below of the image (marginTop = 20dp). Can anyone help? A: <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:layout_below="@id/imgEmpty" android:text="Sorry, no list available"/> Insert it below your ImageView of RelativeLayout! A: Replace your Relative layout with this. <RelativeLayout android:id="@+id/huhu" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.RecyclerView android:id="@+id/recylcerView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginLeft="10dp" android:layout_marginTop="10dp" android:layout_marginRight="10dp" android:layout_marginBottom="10dp" android:visibility="gone" /> <ImageView android:id="@+id/imgEmpty" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:src="@drawable/empty"/> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:layout_below="@id/imgEmpty" android:text="Sorry, no list available"/> A: Add this below imgEmpty. Use android:layout_below to place the text below image,android:layout_centerInParent="true" to move text to center. <TextView android:layout_marginTop="20dp" android:layout_centerInParent="true" android:text = "Sorry, no list available" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/imgEmpty"/> Here the output A: in relative layout you can use below/above to put view below/above its sibling <TextView android:id="@+id/textView" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/imgEmpty" android:layout_marginTop="20dp" android:gravity="center_horizontal" android:text="TextView"/>
{ "language": "en", "url": "https://stackoverflow.com/questions/56229996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Use of function inside a for loop I am trying to call functions inside a for loop, but I am not successful. Is it possible to call functions in Python 3.x like you call subroutines in Excel? Here is the code I tried but I do not get any output. def my_fun1(i): x=+i return x def my_func2(x1) print(x1) test_rng=range(124,124+100) for i in test_rng: my_fun1(i) print(x) my_fun2(x) A: Yes, it is possible but your code would not work because x inside the loop will be unknown: for i in test_rng: my_fun1(i) print(x) my_fun2(x) Possibly, you want to do something like: for i in test_rng: x = my_fun1(i) print(x) my_fun2(x) You may also want to double-check the code in my_fun1(): def my_fun1(i): x=+i return x as the use of x=+i may suggest you are trying to do something different from x = i, which is essentially what your code is doing: x=+i -> x = (+i) -> x = i A: Your code contains a wrong logic and I am also assuming that the variable x is globally defined. See below. def my_fun1(i): x=+i#I am assuming you want this x+=i return x def my_func2(x1) print(x1) test_rng=range(124,124+100) for i in test_rng: my_fun1(i) print(x) my_fun2(x)
{ "language": "en", "url": "https://stackoverflow.com/questions/60302452", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to find columns of the partition of a master table in postgresql 9.4? In postgresql I have created a master table CREATE TABLE IF NOT EXISTS table_master( column_1 text NOT NULL, column_2 text NOT NULL, column_3 text NOT NULL ); and a partition table based on columns: column_1, column_2 CREATE TABLE table_col1_col2 ( CONSTRAINT table_col1_col2_pk PRIMARY KEY (column_1, column_2), CHECK ( column_1 = 'value_1' AND column_2 = 'value_2') ) INHERITS (table_master); Is there any select query in order to get the columns of the partition (column_1, column_2)? UPDATE In case I know a child table, I may use the below query: WITH table_id AS ( SELECT oid FROM pg_class WHERE relname = 'child_table_name' ), con AS ( SELECT c.conname, c.contype, c.conkey, c.consrc FROM pg_constraint c INNER JOIN table_id ON c.conrelid = table_id.oid WHERE c.contype = 'c' ) SELECT a.attnum, a.attname FROM pg_attribute a INNER JOIN table_id ON a.attrelid = table_id.oid INNER JOIN con s ON a.attnum = ANY(conkey) FINAL QUERY WITH table_id AS ( SELECT pg_class.oid FROM pg_class INNER JOIN pg_inherits ON pg_class.relname::text = pg_inherits.inhrelid::regclass::text WHERE pg_inherits.inhparent = 'master_table'::regclass ), con AS ( SELECT c.conname, c.contype, c.conkey, c.consrc FROM pg_constraint c INNER JOIN table_id ON c.conrelid = table_id.oid WHERE c.contype = 'c' ) SELECT a.attnum, a.attname FROM pg_attribute a INNER JOIN table_id ON a.attrelid = table_id.oid INNER JOIN con s ON a.attnum = ANY(conkey) A: You can get columns of primary key. This returns the names and data types of all columns of the primary key for the tablename table: SELECT a.attname, format_type(a.atttypid, a.atttypmod) AS data_type FROM pg_index i JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey) WHERE i.indrelid = 'tablename'::regclass AND i.indisprimary; (source) Here used the fact that primary key's uniqueness is handled by Postgres via index, so you can use pg_index table.
{ "language": "en", "url": "https://stackoverflow.com/questions/51965487", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Replacing the value of XML attribute I'm trying to replace the "Visible" attribute value of a Field ID=29 that is duplicated across the xml document. An example of the xml is found below: <Types> <Type ID="4"> <Fields> <Field ID="29" Visible="false"/> </Fields> </Type> <Type ID="5"> <Fields> <Field ID="29" Visible="true"/> </Fields> </Type> <Type ID="6"> <Fields> <Field ID="29" Visible="false"/> </Fields> </Type> </Types> I have tried the following but with no success: update SF set [Static_Form_Properties].modify('replace value of (/Field[@ID=29]/@Visible)[1] with ("true")') from wf_workflow_step_form SF Any help would be greately appreciated. thanks A: It seems you cannot do an update of multiple XML node values in a single UPDATE statement, as mentioned here: How to modify multiple nodes using SQL XQuery in MS SQL 2005 In your query above I think only the first instance found will be updated.
{ "language": "en", "url": "https://stackoverflow.com/questions/21402458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to Filter array of objects based on a field inside one object? I have an array of this form: [ { username: '', id: '', moreInfo: { infoDate: '' } } ] And I need to filter based on the infoDate, whether it's in between two specific dates. I have a function that accepts the object, and the field to search range by and returns : return resultDate >= fromDate && resultDate <= thruDate; But how do I filter such array . I tried userData.filter(userData => functionthatFiltersDate(userData.moreInfo, {from,thru}, 'infoDate') The functionthatFiltersDate is a function that accepts an object as input and dates to check range : functionthatFiltersDate = ( result, { fromDate, thruDate }, fieldName ) => { let resultDate = result[fieldName]; if (!isDate(resultDate)) { resultDate = moment(result[fieldName]).toDate(); } if (!isDate(fromDate)) { fromDate = moment(fromDate).toDate(); } if (!isDate(thruDate)) { thruDate = moment(thruDate).toDate(); } return resultDate >= fromDate && resultDate <= thruDate; }; How do I filter though for an array of objects, based on another object property that's inside? Any help is appreciated! A: call your function this way: function fooBar(item ){ // .... // return truthy condition }; var result = arr.filter(fooBar); - Passing argument to the filter function: const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange']; /** * Array filters items based on search criteria (query) */ const filterItems = (query) => { return fruits.filter((el) => el.toLowerCase().indexOf(query.toLowerCase()) > -1 ); } console.log(filterItems('ap')); // ['apple', 'grapes'] console.log(filterItems('an')); // ['banana', 'mango', 'orange'] Source: Mozilla Docs - Filtering array based on nested values: var arr = [ {foo: 'item1', nested: {nestedFoo: 'returnThis'} }, {foo: 'item2', nested: {nestedFoo: 'notThis'} }, ]; var result = arr.filter(item => item.nested.nestedFoo == 'returnThis'); // result variable now contains an array with one object console.log(result) // array console.log(result[0]) // object console.log(result[0].foo) // 'item1' Refer to this question for explanation on how to access nested values - Making it more clear: var arr = [ { username: '', id: '', moreInfo: { infoDate: '' } }, { username: '', id: '', moreInfo: { infoDate: '' } }, ... ]; const filterItems = (fromDate, thruDate, fieldName) => { return arr.filter((item) => item.moreInfo.infoDate >= fromDate && item.moreInfo.infoDate < thruDate ); }
{ "language": "en", "url": "https://stackoverflow.com/questions/51430982", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I start and stop quartz schedular from my class method? Scheduling in spring I am new to spring. I implemented schedular which invokes a method after every 10 sec. which looks like, <bean id="bidApprovalJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <property name="targetObject" ref="bidApprovalOperations" /> <property name="targetMethod" value="checkExpiredAuctions" /> </bean> <!-- Simple Trigger --> <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"> <property name="jobDetail" ref="bidApprovalJob" /> <property name="repeatInterval" value="10000" /> <!-- 5second delay mentioned in milliseconds --> <property name="startDelay" value="5000" /> </bean> <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="jobDetails"> <list> <ref bean="bidApprovalJob" /> </list> </property> <property name="triggers"> <list> <ref bean="simpleTrigger" /> </list> </property> </bean> But, this schedular runs all the time. I want to start the schedular at run time when user click the button and stop it after certain time. Can I start the schedular from my class method? Can I create instance of schedular in a class and then start and stop that? Thank you in advance. A: Scheduler, created by SchedulerFactoryBean, has standby() and start() methods, which you can use to control firing of trigger.
{ "language": "en", "url": "https://stackoverflow.com/questions/4592029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to select element with single class name in Jquery? I have below html and want to get the element based on 'natural' class. The reason is I get t dynamic classes after 'natural' <coral-checkbox class="natural coral-Form-field coral3-Checkbox" ></coral-checkbox> I am trying below code to get hide the element but it is not working. $("coral-checkbox[class='.natural']").hide(); But it is working when I select entire class like below but I need to do with only 'natural'. Is this possible ? $("coral-checkbox[class='.natural coral-Form-field coral3-Checkbox']").hide(); A: Use .classname to select based on any of the element's classed. When you use an attribute selector, it matches the entire attribute (unless you use modifiers like *=, but they're not appropriate here, either). $("coral-checkbox.natural").hide(); A: Use the class the selector instead of the attribute selector: $("coral-checkbox.natural").hide();
{ "language": "en", "url": "https://stackoverflow.com/questions/68415233", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: error in the following code near throw IOException import java.io.*; import java.lang.*; public class Propogate1 { String reverse(String name) { if(name.length()==0) throw IOException("name"); String reverseStr=""; for(int i=name.length()-1;i>0;--i) { reverseStr+=name.charAt(i); } return reverseStr; } public static void main(String[] args)throws IOException { String name; try { Propogate1 p=new Propogate1(); p.reverse("java"); } finally { System.out.println("done"); } } } I have to create a class propogate and main method which will call reverse(). In that if the name.length is null, it will throw an exception. If it is not null it will reverse the string. Pls help me A: You need to declare which exceptions are thrown in a method: the method declaration should be: String reverse(String name) throws IOException A: You have to create the exception before throwing it: if(name.length()==0) throw new IOException("name"); Also main must not throw an IOException. Catch it and print the message to System.err. A: May be this is what you need. package reversestring; // import java.io.* is not needed here. // And if you want to import anything, // prefer specific imports instead and not entire package. // java.lang.* is auto-imported. You needn't import it explicitly. public class Propogate { // There's no reason this method should be an object method. Make it static. public static String reverse(String name) { if (name == null || name.length() == 0) { // RuntimeExceptions are preferred for this kind of situations. // Checked exception would be inappropriate here. // Also, the error message should describe the kind of exception // occured. throw new RuntimeException("Empty name!"); } // Idiomatic method of string reversal: return new StringBuilder(name).reverse().toString(); } public static void main(String[] args) { String name; try { name = Propogate.reverse("java"); System.out.println("Reversed string: " + name); } catch (RuntimeException rx) { System.err.println(rx.getMessage()); } finally { // I don't get the point of `finally` here. Control will reach this // point irrespective of whether string reversal succeeded or failed. // Can you explain what do you mean by "done" below? System.out.println("done"); } } } /* Output:- Reversed string: avaj done */
{ "language": "en", "url": "https://stackoverflow.com/questions/3956828", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Chrome message extension : From injected script to background /* My Background */ console.log("Init BackGround ! "); chrome.runtime.onMessageExternal.addListener( (request, sender, sendResponse) => { console.log("J'ai bien reçu un truc"); console.log(request); console.log(sender); } ); // Inject script chrome.webNavigation.onCompleted.addListener((details) => { chrome.tabs.executeScript(details.tabId, { file: "include/ts/injectScript.js", runAt: "document_end" }); }, {url: [{urlPrefix: "https://website.com"}]}); console.log("End Background init"); /* My injected script */ var extensionID = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; chrome.runtime.sendMessage(extensionID, {test : 123},(response) => { console.log(response); }); /* One part of my manifest.json (with good url) */ "externally_connectable": { "matches": [ "*://*.exemple.com/tests/*" ] }, "permissions": [..., "*://*.exemple.com/tests/*",...] The background automatically injects JS script at page load. All tests performed in the console (on the current page) work, and the background is receiving messages. Unfortunately, although the background well injects the script loading the page, it does not receive any messages. Sorry for my english, Thank you in advance for your answers Jérémy-F A: You have to use chrome.runtime.onMessage.addListener instead of chrome.runtime.onMessageExternal.addListener to receive messages from your own content scripts. chrome.runtime.onMessageExternal is for messages from other extensions/apps.
{ "language": "en", "url": "https://stackoverflow.com/questions/38273428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: casting elements of uint8 vector to stringstream I'm havig some trouble figuring out how to conver my uint8 vector to stringstream. On input im getting vector of uint8, first 9 bytes are flags which i dont need in my string stream, next 2 bytes are some data i need as string, let's call them "name1", next 2 bytes are another name, lest call it "name2", then comes 4 bytes which are some uint32 number(but writen as 4 uint8 bytes), lets call it just "number". Now i need to pass these data to stringstream but: * *name1 and number2 need to be written as bytes (byte 0x52 -> char[2]={"5","2"}) *number needs to be casted to uint32 *all variables need to be seperated by semicolons in final stringstream so if im getting a vector like this one: ---some 9 bytes---, 0x05, 0x00, 0x01,0x00,0x00,0x00,0x08,0x0E, ---some other data--- i need stringstream to be like this: "0500;0100;2062;" i have managed to figure out how to cast number to uint32: uint8_t tab[4]; for(int i=4; i!=0; --i) { tab[4-i]=data[i+14]; } uint32_t* var = (uint32_t*)tab; is there some better way to do this? EDIT: How can i pass uint8 values to string as characters? example: byte ouput: 0x05 string output: 05 can i put string to stringstream using "<<" operator or is it not recommended? A: if you have a string, just loop on the string and output the characters to your stringstream std::string name = "name1"; std::stringstream ss; for(auto c : name) ss << std::static_cast<int>(c); ss << ";"; As a side note: uint32_t* var = (uint32_t*)tab; is totally useless, you don't need a pointer. A: i'm not sure this will solve your problem, but i would take a different approach. i would use a struct to describe the underlying protocol and then continue with that. example: struct dx{ uint8 _junk0[9]; char name1[2]; char name2[2]; uint32 num; } __attribute__((packed)); uint8 *input; dx* struct=(dx*)input; printf("%d",dx->num);
{ "language": "en", "url": "https://stackoverflow.com/questions/32266003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Httpclient throws Timeout waiting for connection from pool exception Now am working on an exception for our uploading image service, the scenario below: We have a web page, user from all over the world can upload their images to our server, the image normally keep about 3MB. Now we held a promotion, so the images number uploading to our server is extremely huge, which, however caused the server throws the exception as "org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection from pool". We use apache httpclient as the core uploading middleware, its version is 4.5.*, we correctly handled the response by using the method mentioned in this article. The code like below: if (returnType != StorageHttpResponse.class && response != null) { EntityUtils.consumeQuietly(response.getEntity()); httpRequest.abort(); } Also, the max connection pool for the service is 128 and the max connection time out is 50000 ms. We upload the images by using stream mode, not directly upload the image file. So here, I correctly handled the response entity by consuming it in finally code block, but I still can't stop the service throw connection pool timeout exception. Any other stuffs that I need to add to my service? Do I really using redis to make a queue to user's uploading requests and post handling? Whole code here: public <T> T excute(Request request, Class<T> returnType) { Preconditions.checkState(!isShutDown, "JSSHttpClient is destory!"); HttpRequestBase httpRequest = new HttpRequestBuild(this.credential).build(request); HttpResponse response = null; try { response = this.client.execute(httpRequest); if (errorHandler.hasError(request, response)) { int statusCode = response.getStatusLine().getStatusCode(); log.warn("Unexpected response," + request + " http code [" + statusCode + "]"); errorHandler.handleError(response); } if (returnType != null && returnType != StorageHttpResponse.class) { return JsonMessageConverter.read(returnType, response); } if (returnType == StorageHttpResponse.class) { return (T) new StorageHttpResponse(response); } } catch (IOException e) { Throwables.propagate(e); } finally { if (returnType != StorageHttpResponse.class && response != null) { EntityUtils.consumeQuietly(response.getEntity()); httpRequest.abort(); } } return null; } A: Finally, we solved this not by using code. Because we all know if the response not consumed directly, the connection of a request will not released. So in our code, we offen consume the response first. We solved this problem not by using better code but slightly modify some parameters like maxconnectionpoolsize, maxconnectionperroute and maxconnectiontimeout based on our business scenario. Then running it and all seems ok now. Hope this helps you. A: you can set the parameters in either properties or yml file like below. http: pool: size: 100 sockettimeout: 20000 defaultMaxPerRoute: 200 maxPerRoutes: - scheme: http host: localhost port: 8080 maxPerRoute: 100 - scheme: https host: {{URL}} port: -1 maxPerRoute: 200
{ "language": "en", "url": "https://stackoverflow.com/questions/47130057", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TableView sort by distance from current location (parsing locations from JSON) Within xCode, I am trying to sort objects within a TableView so that they appear in order of how close they are to the user. I have seen this question asked, but I can't seem to figure out how to implement it into my project as I am parsing the locations through a JSON file. What do I need to do to calculate the distance between the user's location and the location of each location object? And how can I then sort the objects within the TableView in ascending order? Here is the Location.swift model: import Foundation import MapKit import CoreLocation var currentLocation:CLLocation? class Location: NSObject { var id: String = "" var name: String = "" var type: String = "" var location: String = "" var image: String = "" var activity: String = "" var rating: String = "" var latitude: Double = 0.0 var longitude: Double = 0.0 var distance: Double { get { return CLLocation(latitude: latitude, longitude: longitude).distance(from: currentLocation!) } } init(locationInfo:[String:Any]) { self.id = locationInfo["id"] as! String self.name = locationInfo["name"] as! String self.type = locationInfo["type"] as! String self.location = locationInfo["location"] as! String self.image = locationInfo["image"] as! String self.activity = locationInfo["activity"] as! String self.latitude = locationInfo["latitude"] as! Double self.longitude = locationInfo["longitude"] as! Double } public var coordinate: CLLocationCoordinate2D { get { let coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude) return coordinate } } } Here are the relevant parts from LocationTableViewController.swift: class LocationTableViewController: UITableViewController { var locations = [Location]() override func viewDidLoad() { super.viewDidLoad() let locationService: LocationService = LocationService() locations = locationService.readLocation() locations.sort { $0.distance < $1.distance } self.tableView.reloadData() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) tableView.reloadData() } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "cell" let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! LocationTableViewCell // Configure the cell cell.nameLabel.text = locations[indexPath.row].name cell.thumbnailImageView.image = UIImage(named: locations[indexPath.row].image) cell.locationLabel.text = locations[indexPath.row].location cell.typeLabel.text = locations[indexPath.row].type return cell } } This is what I have implemented in AppDelegate to capture the user's location: import UIKit import CoreLocation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate { var window: UIWindow? var locationManager:CLLocationManager! private var currentCoordinate:CLLocationCoordinate2D? var currentLocation:CLLocation? static var locations: Array<Location> = Array() func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. // Location Manager func setupLocationManager() { locationManager = CLLocationManager() locationManager?.delegate = self self.locationManager?.requestAlwaysAuthorization() locationManager?.desiredAccuracy = kCLLocationAccuracyBest locationManager?.startUpdatingLocation() } } return true } // Location Manager func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if currentLocation == nil { currentLocation = locations.last locationManager?.stopMonitoringSignificantLocationChanges() let locationValue:CLLocationCoordinate2D = manager.location!.coordinate print("locations = \(locationValue)") locationManager?.stopUpdatingLocation() } } A: Defined one more property in your Location model called distance. which is distance from user's current location. var distance: Double { get { return CLLocation(latitude: latitude , longitude: longitude).distance(from: userLocation) } } This returns distance in CLLocationDistance, but you can use it as Double, because it makes easy while sort. Now you can sort locations in ascending array like this and Reload data var locations = [Location]() locations.sort { $0.distance < $1.distance } self.tableView.reloadData()
{ "language": "en", "url": "https://stackoverflow.com/questions/45627533", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Accessing a variable list through a class instance object I currently develop an SDK and I want to know how to access a list of variables through a class instance object as follow: MyClass * myObject = [[MyClass alloc] init]; [myObject changeShape : myObject.FORM_SQUARE]; [myObject changeShape : myObject.FORM_CIRCLE]; [myObject changeShape : myObject.FORM_RECTANGLE]; ... These variables ( three dozen ) are static and return just an integer to identify the form. Do I have to set a @property for each variable or may be there are a more optimized way? A: If they are not properties then you will have to implement a getter method to access them. -(String*)getiVar{ return iVar; } A: Finally, the solution is to use NS_ENUM. Like that: typedef NS_ENUM(NSUInteger, shape) { rectangle = 0, triangle = 1, square = 1, ... }; -(void)changeShape:(shape)newShape;
{ "language": "en", "url": "https://stackoverflow.com/questions/36462634", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: error after importing progect from eclipse to android studio I'm getting this error in Android Studio after i've imported a project from eclipse C:\Users\admn.gradle\caches\transforms-1\files-1.1\actionbarsherlock-4.4.0.aar\9642e2c79c11b0f8f68064f6cbc64e8e\res\values\values.xml Error:(5, 5) error: resource previously defined here. C:\Users\admn.gradle\caches\transforms-1\files-1.1\appcompat-v7-25.2.0.aar\65648038dd839bb6dcf32985b0a61b7d\res\values\values.xml Error:(203, 5) error: duplicate value for resource 'attr/background' with config ''. Error:(203, 5) error: duplicate value for resource 'attr/windowMinWidthMajor' with config ''. Error:(203, 5) error: duplicate value for resource 'attr/windowMinWidthMinor' with config ''. Error:(203, 5) error: resource previously defined here. Error:(203, 5) error: resource previously defined here. D:\pc\andoid-app\apps\infoapps\coloring by number\Coloring Book\studiocoloring\app\build\intermediates\incremental\mergeDebugResources\merged.dir\values\values.xml Error:(165) duplicate value for resource 'attr/background' with config ''. Error:(12) resource previously defined here. Error:(190) resource previously defined here. Error:(357) duplicate value for resource 'attr/windowMinWidthMajor' with config ''. Error:(357) duplicate value for resource 'attr/windowMinWidthMinor' with config ''. Error:(190) resource previously defined here. Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details Error:Execution failed for task ':app:mergeDebugResources'. Error: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details build.geadl module:app apply plugin: 'com.android.application' android { compileSdkVersion 26 buildToolsVersion "27.0.3" defaultConfig { applicationId "com.package.name" minSdkVersion 8 targetSdkVersion 17 } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } } dependencies { compile 'com.android.support:support-v4:26.0.0-alpha1' compile 'com.google.android.gms:play-services:+' compile 'com.actionbarsherlock:actionbarsherlock:4.4.0@aar' compile 'com.android.support:support-v4:20.0.0' compile files('libs/picasso-2.4.0.jar') } build.gradl project // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.0.1' } } allprojects { repositories { jcenter() } } manifest <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.package.namer" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="17" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@drawable/app_icon" android:label="@string/app_name" android:theme="@style/Theme.Sherlock.Light" > <activity android:name="com.package.name.SplashActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.package.name.PicSelect" android:configChanges="orientation|keyboardHidden|screenSize" > </activity> <activity android:name="com.package.name.PicItem" android:configChanges="orientation|keyboardHidden|screenSize" > </activity> <activity android:name="com.package.name.FloodFillActivity" android:configChanges="orientation|keyboardHidden|screenSize" > </activity> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <!-- Activity required to show ad overlays. --> <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" /> </application> </manifest> Does anyone know how to fix it?
{ "language": "en", "url": "https://stackoverflow.com/questions/48895261", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do I recover files using git? I committed 2 days ago. Then, I made changes to some of the files. However, inside one specific directory, I didn't make any changes to it recently. Today, I deleted those files using rm * inside that directory. How can I restore files to that directory using git? A: Simply use this: cd <specific_dir> git checkout . It will restore all files and directories in current directory which were tracked by git. Be aware that this will overwrite uncommitted changes to other files in current directory.
{ "language": "en", "url": "https://stackoverflow.com/questions/18556996", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can not play recorded audio file from android in iOS 5+ I am working on android app which also supports iOS. I want to record the audio & play it in Android as well as in iOS devices. I am recording audio in android using following settings MediaRecorder audioRecorder = new MediaRecorder(); audioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC); audioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); audioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC); audioRecorder.setAudioSamplingRate(44100); audioRecorder.setAudioChannels(1); audioRecorder.setAudioEncodingBitRate(12800); audioRecorder.setOutputFile(<recordedSoundFilePath>); audioRecorder.prepare(); audioRecorder.start(); On iOS side , settings are as follows //audioRecorder is object of AVAudioRecorder NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] initWithCapacity:10]; NSNumber *formatObject; formatObject = [NSNumber numberWithInt: kAudioFormatMPEG4AAC ]; [recordSettings setObject:formatObject forKey: AVFormatIDKey]; [recordSettings setObject:[NSNumber numberWithFloat:44100.0] forKey: AVSampleRateKey]; [recordSettings setObject:[NSNumber numberWithInt:1] forKey:AVNumberOfChannelsKey]; [recordSettings setObject:[NSNumber numberWithInt:12800] forKey:AVEncoderBitRateKey]; [recordSettings setObject:[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey]; [recordSettings setObject:[NSNumber numberWithInt: AVAudioQualityHigh] forKey: AVEncoderAudioQualityKey]; NSURL *soundFileURL = [NSURL fileURLWithPath:[self soundFilePath]]; NSError *error = nil; audioRecorder = [[ AVAudioRecorder alloc] initWithURL:soundFileURL settings:recordSettings error:&error]; if ([audioRecorder prepareToRecord] == YES){ [audioRecorder record]; }else { int errorCode = CFSwapInt32HostToBig ([error code]); NSLog(@"Error: %@ [%4.4s])" , [error localizedDescription], (char*)&errorCode); } I can record the audio & it is playing correctly in android devices. Now the problem is I can play the recorded audio from iOS in Android device , but iOS device can't play the audio recorded on Android device. It returns OSStatus error 1937337955. I searched about this error , but I can't find anything. Can anybody tell me what's going wrong in my code ? Any kind of help is highly appreciated. Thanks in advance. A: try this one: audioRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT); audioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); audioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); A: I faced the same issue in which audio that recorded from Samsung's device is not working on all IOS devices and not even on safari browser. But they working fine in all android devices. I have fixed this issue by adding below lines in AudioRecordingUtil class: recorder?.let{ it.setAudioSource(MediaRecorder.AudioSource.MIC) it.setOutputFormat(MediaRecorder.OutputFormat.AAC_ADTS) it.setAudioEncoder(MediaRecorder.AudioEncoder.AAC) } Hope this can help! A: It is codec issue , the format recorded by iOS is not able decode by android media player , in order to make it work just decode the audio file on IOS side in to android supported format like mp3 or mp4 or 3Gp etc. A: I also suffered issues with MediaRecorder. At the time of Audio Record, Mime Types are different like Mac chrome - Mime Type:audio/webm;codecs=opus Mac Safari - Mime Type:audio/mp4 Windows/Android - Mime Type:audio/webm;codecs=opus Iphone Chrome - Mime Type:audio/mp4 I was saving the file as M4a but Audio was not running in IOS. After some analysis and Testing. I decided to convert the file after Upload in Server and used ffmpeg and It worked like a charm. <!-- https://mvnrepository.com/artifact/org.bytedeco/ffmpeg-platform --> <dependency> <groupId>org.bytedeco</groupId> <artifactId>ffmpeg-platform</artifactId> <version>4.3.2-1.5.5</version> </dependency> /** * Convert the file into MP4 using H264 Codac in order to make it work in IOS Mobile Device * @param file * @param outputFile */ private void convertToM4A(File file, File outputFile) { try { String ffmpeg = Loader.load(org.bytedeco.ffmpeg.ffmpeg.class); ProcessBuilder pb = new ProcessBuilder(ffmpeg, "-i", file.getPath(), "-vcodec", "h264", outputFile.getPath()); pb.inheritIO().start().waitFor(); }catch (Exception e ){ e.printStackTrace(); } }
{ "language": "en", "url": "https://stackoverflow.com/questions/14645735", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "10" }
Q: undefined method `belongs_to' for ActiveRecord:Module I am getting the following error "undefined method `belongs_to' for ActiveRecord:Module" it is showing the following code for my error in line 1. class Posting < ActiveRecord:: belongs_to :user validates :content, length: { maximum: 1000 } end Also showing an error in this code on line 10 class ProfilesController < ApplicationController def show if params[:id].nil? # if there is no user id in params, show current one @user = current_user else @user = User.find(params[:id]) end @alias = @user.alias @posting = Posting.new end end The postings controller if it is needed is... class PostingsController < ApplicationController before_action :set_posting, only: [:show, :edit, :update, :destroy] # GET /postings # GET /postings.json def index @postings = Posting.all end # GET /postings/1 # GET /postings/1.json def show end # GET /postings/new def new @posting = Posting.new end # GET /postings/1/edit def edit end # POST /postings # POST /postings.json def create @posting = Posting.new(posting_params) respond_to do |format| if @posting.save format.html { redirect_to @posting, notice: 'Posting was successfully created.' } format.json { render action: 'show', status: :created, location: @posting } else format.html { render action: 'new' } format.json { render json: @posting.errors, status: :unprocessable_entity } end end end # PATCH/PUT /postings/1 # PATCH/PUT /postings/1.json def update respond_to do |format| if @posting.update(posting_params) format.html { redirect_to @posting, notice: 'Posting was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @posting.errors, status: :unprocessable_entity } end end end # DELETE /postings/1 # DELETE /postings/1.json def destroy @posting.destroy respond_to do |format| format.html { redirect_to postings_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_posting @posting = Posting.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def posting_params params.require(:posting).permit(:content, :user_id) end end A: You need the Posting class to inherit from ActiveRecord::Base and not just ActiveRecord::
{ "language": "en", "url": "https://stackoverflow.com/questions/22118493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: jQuery Autocomplete: Uncaught TypeError: Cannot read property 'length' of null My first time using JQuery. Trying to use Autocomplete, and keep getting the error above. I've tested the MySQL queries and they all work. If I use the same code below but called from a webpage without the Autocomplete code, the JSON looks well-formed. Thanks for any guidance you can provide. <?php $docname=$_POST['docselect']; $surname=$_POST['lastname1']; if (isset($_POST['lastname1'])){ $return_arr = array(); try { $dbc=mysqli_connect('localhost','gotlibc_testuser','**passwordgoeshere**','gotlibc_robo2') or die("Error connecting to MySQL server."); $query="SELECT PT_ID, surname, firstname, jnum FROM patients WHERE surname LIKE '$surname%' ORDER BY surname"; $result=mysqli_query($dbc,$query) or die('Error querying database.'); $row=array(); while($Xrow = mysqli_fetch_array($result)) { $row['label']="{$Xrow['surname']},{$Xrow['firstname']},{$Xrow['jnum']}"; $row['value']=$Xrow['PT_ID']; $return_arr[]=$row; } } // end try catch(Exception $e ) { echo "<script type='text/javascript'> alert('Hi'); </script>"; printf("catch activated"); echo $e->errorMessage(); } echo json_encode($return_arr); mysqli_close($dbc); } ?> Here's the relevant snippets of the calling web page <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script> $(document).ready(function(){ $( "#lastname1" ).autocomplete({ source: "pt_autoshow1.php", minLength: 1 }); }); </script> <h2>Patient Information:</h2> <br> <form id="surnamepicker" action="#" method="post"> or Last name: <input name="lastname1" id="lastname1" type="text"> <div class="rage_button_781076"> <a href="">New Patient</a> </div> with Dr. <select name="docname"> <option value="2">Doctor A</option> <option value="1">Doctor B</option> <option value="3">Doctor C</option> </select></form> A: its working fine for me php function will return the rows/No Results as response public function shamsearchJSON () { $search = $this->input->post('search'); $query = $this->user_model->getmessages($search); if(!empty($query)){ echo json_encode(array('responses'=> $query)); } else{ echo json_encode(array('responses'=> 'No Results')); } } javascript code $( "#search-inbox" ).autocomplete({ minLength: 2, source: function( request, response ) { // $.getJSON( "<?php echo base_url(); ?>index.php/user/shamsearchJSON?search="+request.term,response ); $.ajax({ url: "<?php echo base_url(); ?>index.php/user/shamsearchJSON", data: {"search": request.term}, type:"POST", success: function( data ) { var parsed = JSON.parse(data); if(parsed.responses == "No Results") { alert("no results::"); var newArray = new Array(1); var newObject = { sub: "No Results", id: 0 }; } else{ var newArray = new Array(parsed.length); var i = 0; parsed.responses.forEach(function (entry) { var newObject = { sub: entry.subject, id: entry.mID }; newArray[i] = newObject; i++; }); } response(newArray); }, error:function(){ alert("Please try again later"); } }); }, focus: function( event, ui ) { //$( "#search-inbox" ).val( ui.item.sub ); return false; }, select: function( event, ui ) { if(ui.item.id != 0){ $( "#search-inbox" ).val( ui.item.sub ); openInboxMessage(ui.item.id); } else { } return false; } }).data( "ui-autocomplete" )._renderItem = function( ul, item ){ return $( "<li>" ).append("<a>" + item.sub +"</a>" ).appendTo(ul); };
{ "language": "en", "url": "https://stackoverflow.com/questions/17176939", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Core data issue I am starting with iphone development and am facing an issue with core data. I have a model gathering several entities such as employee, project, project type, etc. On startup, I create several entities that I persist through the core data framework. No problem. The issue raises when I want to display a list of projects basing on a tab the user selects inside the UIToolbar. I've set the argument to show every sql request launched (-com.apple.CoreData.SQLDebug 1) and what is really awkward is that the query shown in the console give me results when I access the db on my side through sqlite but from core data, nope, 0 rows returned... Anyone faced similar issue? Here is the code used to retrieve the list of projects: NSArray* retVal = nil; NSError *error = nil; NSManagedObjectContext *moc = "context retrieved"; NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Project" inManagedObjectContext:moc]; NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease]; [request setEntity:entityDescription]; retVal = [moc executeFetchRequest:request error:&error]; NSLog(@"Project type: %@", [theProjType valueForKey:@"projectTypeName"]); NSLog(@"Employee number: %@", [theEmployee valueForKey:@"employeeNumber"]); NSPredicate *predicate = [NSPredicate predicateWithFormat: @"ANY myEmployees.employeeNumber = %d AND myProjectType.projectTypeName = %d", [theEmployee valueForKey:@"employeeNumber"], [theProjType valueForKey:@"projectTypeName"]]; [request setPredicate:predicate]; retVal = [moc executeFetchRequest:request error:&error]; This code generates this sql request (which returns results when launched on the sqlite db): SELECT DISTINCT 0, t0.Z_PK, t0.Z_OPT, t0.ZPROJECTNUMBER, t0.ZISEDITABLE, t0.ZPROJECTNAME, t0.ZISDELETABLE, t0.ZPROJECTEND, t0.ZPROJECTID, t0.ZPROJECTSTART, t0.ZCUSTOMERORDERNR, t0.ZMYCUSTOMER, t0.ZMYCOSTCENTRE, t0.ZMYPROJECTTYPE, t0.ZMYTRAVELTIMES FROM ZPROJECT t0 JOIN Z_4MYPROJECTS t1 ON t0.Z_PK = t1.Z_10MYPROJECTS1 JOIN ZEMPLOYEE t2 ON t1.Z_4MYEMPLOYEES = t2.Z_PK JOIN ZPROJECTTYPE t3 ON t0.ZMYPROJECTTYPE = t3.Z_PK WHERE ( t2.ZEMPLOYEENUMBER = ? AND t3.ZPROJECTTYPENAME = ?) A: NSPredicate *predicate = [NSPredicate predicateWithFormat: @"ANY myEmployees.employeeNumber = %d AND myProjectType.projectTypeName = %d", [theEmployee valueForKey:@"employeeNumber"], [theProjType valueForKey:@"projectTypeName"]]; Are you sure this is correct? valueForKey: always returns a NSObject but your placeholder is %d. This should create strange behaviour. Try %@ instead
{ "language": "en", "url": "https://stackoverflow.com/questions/3954701", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: YouTube channelid, channel title and googlePlusUserId relatedness In v3 API each logged user may have a number of channels each one with a specific channelId. Moreover, I know that the channel title is not unique. My goal is the group the channels that belong to specific YouTube users if that possible. So: * *Is googlePlusUserId identify the person that has a sequence of channels? In other words can we use googlePlusUserId to group channels that belong to a YouTube user? *If yes, is googlePlusUserId available to all YouTube channels? Thank you. A: * *Is googlePlusUserId identify the person that has a sequence of channels? In other words can we use googlePlusUserId to group channels that belong to a YouTube user? Nop, the googlePlusId identify the GG+ of the channel. It can be a Google+ page or Google+ identity. Each channel have a differents Google+ id. You can read more about YouTube and Google+ id
{ "language": "en", "url": "https://stackoverflow.com/questions/25816840", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to check the username exist in database or not This is my code I don't know what's my fault but it is not checking whether the username exist in database or not. String connectionString = @"Data Source=localhost; Database=pramod; User ID=itesuser; password=ites; Port=3309;"; MySqlConnection con = new MySqlConnection(connectionString); con.Open(); String query = "select * from logins where USERNAME=@username and PASSWORD=@password"; MySqlCommand cmd = new MySqlCommand(query, con); cmd.Parameters.AddWithValue("@username", TextBox1.Text.Trim()); cmd.Parameters.AddWithValue("@password", TextBox2.Text.Trim()); MySqlDataAdapter sda = new MySqlDataAdapter(cmd); DataTable dt = new DataTable(); sda.Fill(dt); int i = (int)cmd.ExecuteScalar(); if (i == 0) { Response.Write("username wrong"); } if (dt.Rows.Count > 0) { Session["username"] = TextBox1.Text.Trim(); Response.Redirect("Dashboard.aspx"); } else { Label1.Visible = true; Label1.Text = "Your password is incorrect"; Label1.ForeColor = System.Drawing.Color.Red; } con.Close(); it is checking whether the password is correct or wrong but not the username, now i need to check username and the the password A: I think your clue is here: String query = "select * from logins where USERNAME=@username and PASSWORD=@password"; By doing this, you check the username and password at the same time. So if the username OR the password is incorrect, you get 0 rows in your result. To get what your want, only mention the username in the SQL query, and if you get a record, you compare the password in .Net code. So: String query = "select * from logins where USERNAME=@username"; MySqlCommand cmd = new MySqlCommand(query, con); cmd.Parameters.AddWithValue("@username", TextBox1.Text.Trim()); MySqlDataAdapter sda = new MySqlDataAdapter(cmd); DataTable dt = new DataTable(); sda.Fill(dt); And then check the password if you get 1 row back. This looks like an insecure way of handling logins, so I hope you at least will hash and salt the passwords. Now you are one database leak away from a very embarasing situation. https://duckduckgo.com/?q=password+hashing+and+salting
{ "language": "en", "url": "https://stackoverflow.com/questions/70002885", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: Why do we have a Main() method (entry method) in the ASP.NET Core Web Application ? What's the reason behind this approach? Program class contains a public static void Main() method. As we already know, when we create a console application in .net then by default the .NET Framework creates a class (i.e. Program class) with the Main Method. We also know that the Main() method is the entry point for that console application execution. Now the question is, here we are not creating a console application, here we create an ASP.NET Core Web Application but application create like console app with Main method as entry point. It's does make sense now ,we can configure the application pipeline and http request pipeline. It's nice idea. But Is there any other specific reason behind this architectural approach? A: Because it is platform-independent that way. Let's put it this way: They could create a DLL with some specific entry-point, and assume it's always consumed by IIS via ISAPI. But what about the cases where you don't run it on IIS, not via ISAPI, and not on Windows ? That's right, you'd have to program some modules for each and every webserver out there, in order for it to be able to interact with your DLL. Plus you'd need a web-server. You might also need to update all of those modules whenever something changes. And then you need to package it for a boatload of different Linux distros, plus Mac and Windows, and Android and iPhone, etc. And why would you do that ? For that it only runs on IIS and only on Windows ? Bad idea. Nowadays, most servers run Linux, so do most routers and printers, while most mobiles run Android (aka Linux) or iOS, and most TV OSes are Linux-based. If you have a main method, you can create a simple console program, with which can start a web-server on a certain port, which you can then use to forward traffic to (from NGINX/Apache via remote-proxy). Or you can forward SSL traffic directely to that web-server via HAproxy. No IIS or ISAPI required. If you use HAproxy, no NGINX or Apache required, too - because you can forward directely to kestrel. And if it must, it can run inside IIS as well. Maybe that makes IIS integration a little bit more complicated, but it also makes integrating into a Linux/Unix/Mac-environment (or any other, such as mobile phones) so much easier. And as said, most servers use Linux nowadays. Especially if run in containers like Docker/LXC. It would be absolutely breathtakingly monumentally stupid to do anything else but that. Also, it's a silent admission that they (MS) lost in the server space, and are now salvaging what there is to salvage (however, that last sentence is just my opinon, not necessarely a fact). A: Why is it required. * *Point 1: We don't have Global.asax that derives from HttpApplication, the entry point, and the main component that configures everything require to set up the ASP.NET pipeline, even if you have no Global.asax, as soon as a request comes to IIS HttpApplication object is created by the framework that holds HttpRequest, HttpResponse object, in .NET Framework. Similarly in .NET Core, to configure the Request Processing pipeline, anyhow you need to call Startup and provide him all the necessary configurations, which is done by the Main() while creating the Host. *Point 2: ASP.NET Core is cross-platform, and Kestrel is the built-in server that is going to host the app on all platforms except on windows where you can host in-process, so you need to configure Kestrel and tell him to host the App, this is done by the UseKestrel() extension method, at the same time IIS, can also be used as a reverse proxy, obviously, on windows, you will never use reverse proxy as you have the option to host in-process, but if you wish then you can configure using UseIISIntegration() extension method, now you might be thinking, where all these methods are, these are defaults and host.CreateDeafultBuilder() does all these for you. Configuring Logging, DI, Services, reading Configuration from sources like appsettings.json or appsettings.{environment}.json etc are all done while creating the host. Now I think, you got the Idea behind Main().
{ "language": "en", "url": "https://stackoverflow.com/questions/63181465", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Implementing logout function I am working on my final year project which is an web based application. I want to implement logout function in that project. But don't know how to do that. Also I want to implement auto logout functionality i.e. after a particular time period say after 20 minutes a user will be automatically logged out if he/she does not perform any action during this period. A message should be displayed to the user "Sorry, Your session has expired Please login again". How to do that? A: You can logout using session.invalidate() (or response.getSession().invalidate() in a servlet) If using cookies, you will have to to call response.addCookie(..) with your cookie with a negative lifetime. The auto-logout can be achieved with setting the session timeout. In web.xml <session-config> <session-timeout>20</session-timeout> </session-config> A: How are you dealing with logins and sessions? If its as simple as a session cookie you'd just expire/delete the cookie to logout A: The way I do this on our CMS is to have a setTimeout started upon page load. This - after 20 minutes redirects the user to a page that clears the session, and hence logs the user out. Unfortunately this has one side effect of when a user has more than one window open, sometimes one window can reach the timeout period before the one the user is active in. This causes a session to timeout prematurely, and breaks flow. One way around this caveat could be to keep an activity ID for each action the user performs (i.e. creating a content item, uploading an image). This activity ID is kept in the user table, and the timeout timer (in Javascript) can check against this ID to see if the window that has timed out is the most recently active window or not. If the ID in that window (passed from say a PHP variable into the HTML output) does not match, then it does not force a session timeout. This is quite a tricky one to approach without introducing breaking changes to an interface.
{ "language": "en", "url": "https://stackoverflow.com/questions/2553378", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: managing data access / user permissions I am building a data structure designed for users to share information with friends based on permissions lists (friends or friend-list). What is most best/efficient method for keeping access permissions for user data up-to-date for access by friends (or friend-list)? A: You'll want to read-up about the offline_access permission. https://developers.facebook.com/docs/reference/api/permissions/ With this permission, you'll be able to query facebook for information about one of your users even when that user is offline. It gives you a "long living" access token. This token does expire after a while or if the user changes his/her facebook password. A: I would suggest looking into the Facbook Realtime API https://developers.facebook.com/docs/reference/api/realtime/ You can subscribe to different user fields (e.g. user.friends), and whenever these fields update, FB hit your server. It doesn't say whether you can subscribe to user.friendlists or not, but it would be worth a try. With regards to the answer from Lix; the offline_access permission is being deprecated. See here: https://developers.facebook.com/docs/offline-access-deprecation/
{ "language": "en", "url": "https://stackoverflow.com/questions/8979947", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Extract lined table from scanned document opencv python I want to extract the information from a scanned table and store it a csv. Right now my table extraction algorithm does the following steps. * *Apply skew correction *Apply a gaussian filter for denoising. *Do a binarization using Otsu thresholding *Do a morphological opening. *Canny egde detection *Do a hough transform to obtain lines of table. *Remove duplicate lines( same lines in the range of 10 pixels) *filter the horizontal and vertical lines using slope of line(slope should be less than +/-5 degree for horizontal and normal of verticals). This algorithm is working fine for digital born pdfs and most of the scanned documents. But, Some of the documents have a noisy table and thus its not identifying the lines correctly. Here is a sample image in which my algorithm fails. These are the operations I am doing on this table. 1.Gaussian blur 2.Otsu thresholding 3.Morphological opening 4.Canny edge detection 5.filtered lines,as you can see the lines are clearly not identified correctly. Can anyone please suggest better method for extracting horizontal and vertical lines from this kind of less quality scans. Thanks in advance!! A: I found a perfect solution in this blog. https://medium.com/coinmonks/a-box-detection-algorithm-for-any-image-containing-boxes-756c15d7ed26 Here,We are doing morphological transformations using a vertical kernel to detect vetical lines and horizontal kernel to detect horizontal lines and then combining them to get all the required lines. Vertical lines Horizontal lines required output A: The problem is and always will be is that you don't have perfect lines. One solution for this approach can be: * *Threshold image to grayscale as you have done. *Now find the largest contour in the image, which will be your table. *Now use Floodfill to separate table from the image, by choosing any point on contour to create a flooded mask, A: The problem might be in HoughLinesTransform() You can try using: HoughLinesTransformP() For HoughLinesTranform() to work perfectly, the lines need to be perfect. From the image you have provided, you can see the distortion clearly which is clearly causing the method to fail. Try dilating your image first. Image Dilation in Python.
{ "language": "en", "url": "https://stackoverflow.com/questions/55276042", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: XQuery : OBJECT_VALUE invalid identifier I've created a table Movie ( title varchar2(40), review XMLTYPE) And review has: ` <review> <reviewer>...</reviewer> <title> ....</title> <rating>.....</rating> </Review> </reviewer> When I try to access : SELECT X.reviewername FROM movie m, XMLTABLE ('for $d in /reviews/review return $d' PASSING OBJECT_VALUE columns reviewername VARCHAR2(50) PATH 'reviewer') AS X I get an error at OBJECT_VALUE. Where am I going wrong? EDIT: I changed the Query to SELECT m.title, warehouse2.* FROM movie M, XMLTABLE('/REVIEW' PASSING m.reviews COLUMNS "Rail" varchar2(60) PATH '//RATING') warehouse2; But no rows are getting selected. Any suggestions? A: Well for one thing, don't you have a typo: '/reviews/review ' ? there is no element called anywhere in your example. Your XML isn't well formed, you have overlapping tags, you have mismatched reviews/Reviews (XML is case sensitive) and in your query you have reviews/review but your xml has /review (no s on the end). –
{ "language": "en", "url": "https://stackoverflow.com/questions/16150791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Git Inconsistent behavior of "checkout"? Consider these commands: # create file myfile.txt git add myfile.txt git commit myfile.txt # sha = SHA1 # modify myfile.txt git status # shows myfile.txt modified git branch branch2 git checkout branch2 # myfile is not replaced git status # shows myfile.txt modified git add myfile.txt git commit myfile.txt git checkout master # myfile is replaced git status # nothing to commit, working directory clean # myfile.txt is back to original state SHA1 When branch2 is checked out, the working directory copy of myfile.txt is not modified. However when master is checked out, the working directory copy of myfile.txt is modified, it is replaced with that from the repo. Is this inconsistent behavior? If not, what is the "mental model" to use that explains it? A: The general mental model is that unstaged changes are left alone, and everything else in the working copy is updated when checking out a different commit. Or as the docs put it: git checkout <branch> To prepare for working on <branch>, switch to it by updating the index and the files in the working tree, and by pointing HEAD at the branch. Local modifications to the files in the working tree are kept, so that they can be committed to the <branch>. This is consistent with both cases that you've observed.
{ "language": "en", "url": "https://stackoverflow.com/questions/47499339", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Calculator not functioning properly Hey I'm trying to make a small calculator for a project, however I'm struggling to get the code to work. import time a = 100 b = 1 while a > b: print("Please select an operation. ") print("1. Multiply") print("2. Divide") print("3. Subtract") print("4. Add") b = 200 x = int(input("Please enter your operation number. ")) if x == 4: y = int(input("Please enter your first number. ")) z = int(input("Please enter your second number. ")) finaladd = (y+z) print(finaladd) c = input("Would you like to do another calculation? ") if c == 'yes' or c == 'Yes': a = 500 if c == 'no' or 'No': b = 1000 if x == 2: y2 = int(input("Please enter your first number. ")) z2 = int(input("Please enter your second number. ")) finaladd2 = (y2/z2) print(finaladd2) if x == 3: y3 = int(input("Please enter your first number. ")) z3 = int(input("Please enter your second number. ")) finaladd3 = (y3-z3) print(finaladd3) if x == 1: y4 = int(input("Please enter your first number. ")) z4 = int(input("Please enter your second number. ")) finaladd4 = (y4*z4) print(finaladd4) When I try to run operation 4, I want the code to ask if you would like to run another calculation, if you answer with 'yes' it will repeat the statement again. However all it does is stop the code. Sorry if it's obvious I'm quite new to coding. A: Try this... import time a = 100 b = 1 while a > b: print("Please select an operation. ") print("1. Multiply") print("2. Divide") print("3. Subtract") print("4. Add") b = 200 x = int(input("Please enter your operation number. ")) if x == 4: y = int(input("Please enter your first number. ")) z = int(input("Please enter your second number. ")) finaladd = (y+z) print(finaladd) c = input("Would you like to do another calculation? ") if c == 'yes' or c == 'Yes': a = 500 elif c == 'no' or c == 'No': b = 1000 elif x == 2: y2 = int(input("Please enter your first number. ")) z2 = int(input("Please enter your second number. ")) finaladd2 = (y2/z2) print(finaladd2) elif x == 3: y3 = int(input("Please enter your first number. ")) z3 = int(input("Please enter your second number. ")) finaladd3 = (y3-z3) print(finaladd3) elif x == 1: y4 = int(input("Please enter your first number. ")) z4 = int(input("Please enter your second number. ")) finaladd4 = (y4*z4) print(finaladd4)
{ "language": "en", "url": "https://stackoverflow.com/questions/73835516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Retrieve latest row for each distinct url_id I have this structure for tables Reviews table: id - grade - url_id 1 2 1 2 4 2 3 5 3 4 3 4 5 4 1 6 5 2 7 2 3 Urls table id - url 1 www.google.com 2 www.apple.com 3 www.bing.com I want to retrieve latest grade inserted for each url_id and join it with urls table, like this: id - grade - url_id - url 5 4 1 www.google.com 6 5 2 www.apple.com 7 2 3 www.bing.com This was my attempt SELECT a.id, a.reviews, a.url_id, b.url FROM ( SELECT id, grade, url_id FROM reviews ORDER BY id DESC ) AS a INNER JOIN urls ON a.url_id = urls.id GROUP BY a.url_id I get this error "Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'a.id' which is not functionally dependent on columns in GROUP BY clause" How can I edit the code so that it is valid? I can't say I understood by searching the net what is the problem, other than disabling only_full_group_by A: If you want the most recent version, then you can filter using a where clause: select r.* from reviews r where r.id = (select max(r2.id) from reviews r2 where r2.url_id = r.url_id); You can join in the url itself, if that is necessary. A: SELECT r.* FROM reviews r WHERE r.grade = ( SELECT Max(r2.grade) FROM reviews r2 WHERE r2.url_id = r.url_id ) ORDER BY r.url_id
{ "language": "en", "url": "https://stackoverflow.com/questions/41003856", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Query BigQuery table partitioned by Day on a timestamp field I have a BigQuery table partitioned by Day on a timestamp field as below: Data Sample: Row _time dummy_column 1 2020-06-15 23:57:00 UTC a 2 2020-06-15 23:58:00 UTC b 3 2020-06-15 23:59:00 UTC c 4 2020-06-16 00:00:00 UTC d 5 2020-06-16 00:00:01 UTC e 6 2020-06-16 00:00:02 UTC f Due to the fact that the table is partitioned on _time but it is partition by Day, so in order to query in a specific day partition 2020-06-15, I run: select * from {DATASET}.{TABLE} where _time >= TIMESTAMP("2020-06-15") and _time < TIMESTAMP("2020-06-16"); Result: Row _time dummy_column 1 2020-06-15 23:57:00 UTC a 2 2020-06-15 23:58:00 UTC b 3 2020-06-15 23:59:00 UTC c My question is: Is there a way to query a Day partition directly by mentioning the it explicitly instead of querying using a timestamp range? A: When you have a table partitioned by Day, you can directly reference the partition day you want to query. In order to demonstrate your case, I have used the following table schema: Field name Type Mode Policy tags Description date_formatted DATE NULLABLE fullvisitorId STRING NULLABLE Other table's details, Table type Partitioned Partitioned by Day Partitioned on field date_formatted Partition filter Not required And some sample data, Row date_formatted fullvisitorId 1 2016-12-30 6449885916997461186 2 2016-12-30 3401232735815769402 3 2016-12-30 2100622457042859506 4 2016-12-30 4434434796889840043 5 2016-12-31 9382207991125014696 6 2017-12-30 4226029488400478200 7 2017-12-31 4304624161918005939 8 2017-12-31 4239590118714521081 9 2018-12-30 0030006068136142781 10 2018-12-30 7849866399135936504 You can use the syntax below to query the above sample data, DECLARE dt DATE DEFAULT Date(2016,12,30); SELECT * FROM `project.dataset.table_name` WHERE date_formatted = dt The output, Row date_formatted fullvisitorId 1 2016-12-30 6449885916997461186 2 2016-12-30 3401232735815769402 3 2016-12-30 2100622457042859506 4 2016-12-30 4434434796889840043 As you can see it only retrieved the data for the specific date I declared. Notice that I have used the DECLARE clause because it facilitates modifying the date filter. Also, if your field is formatted as a TIMESTAMP, you can replace DATE() to TIMESTAMP() to define your filter within your variable. As an additional information, if you want to use a range, consider using the BETWEEN clause such as WHERE partition_field BETWEEN date_1 and date_2. UPDATE: I have used your sample data this time, I have used the below syntax to create a table exactly like you described. Below is the code: create table dataset.table_name(_time timestamp, dummy_column string) partition by date(_time) as select timestamp '2020-06-15 23:57:00 UTC' as _time, "a" as dummy_column union all select timestamp '2020-06-15 23:58:00 UTC' as _time, "b" as dummy_column union all select timestamp '2020-06-15 23:59:00 UTC' as _time, "c" as dummy_column union all select timestamp '2020-06-16 00:00:00 UTC' as _time, "d" as dummy_column union all select timestamp '2020-06-16 00:00:01 UTC' as _time, "e" as dummy_column union all select timestamp '2020-06-16 00:00:02 UTC' as _time, "f" as dummy_column The table: The schema: The details: In order to select only one date from your timestamp field (_time), you can do as follows: SELECT * FROM `project.dataset.table` WHERE DATE(_time) = "2020-06-15" And the output, As it is shown above the output is as you desired. Moreover, as an extra information I would like to encourage you to have a look at this documentation about partition by.
{ "language": "en", "url": "https://stackoverflow.com/questions/62388473", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Opening a modal using a partial view I'm trying to open a modal whenever a button is pressed. The button and modal are in an cshtml file that is ran as a partial view. LoginModal.cshtml: <head> <link rel="stylesheet" href="~/Content/loginmodal.css"> <script src="~/Scripts/loginmodal.js"></script> </head> <div class="wrapper"> <!-- Modal button --> <button id="modBtn" class="modal-btn">Open Modal</button> </div> <!-- Modal --> <div id="modal" class="modal"> <!-- Modal Content --> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h3 class="header-title">Modal Header</h3> <div class="close fa fa-close"></div> </div> <!-- Modal Body --> <div class="modal-body"> <h3>Hello</h3> </div> <div class="modal-footer"> <h3>Modal Footer</h3> </div> </div> </div> loginmodal.js: $(function () { // Vars var modBtn = $('#modBtn'), modal = $('#modal'), close = modal.find('.close'), modContent = modal.find('.modal-content'); // open modal when click on open modal button modBtn.on('click', function () { modal.css('display', 'block'); modContent.removeClass('modal-animated-out').addClass('modal-animated-in'); }); // close modal when click on close button or somewhere out the modal content $(document).on('click', function (e) { var target = $(e.target); if (target.is(modal) || target.is(close)) { modContent.removeClass('modal-animated-in').addClass('modal-animated-out').delay(300).queue(function (next) { modal.css('display', 'none'); next(); }); } }); }); Somewhere in index.cshtml: ... @Html.Partial("LoginModal") ... The button is there but doesn't do anything, what am I doing wrong? A: According to https://www.w3schools.com/bootstrap/bootstrap_modal.asp, you can use the following to open and close the modal. <div class="wrapper"> <!-- Modal button --> <button id="modBtn" class="modal-btn" data-toggle="modal" data-target="#modal">Open Modal</button> </div> <!-- Modal --> <div id="modal" class="modal"> <!-- Modal Content --> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h3 class="header-title">Modal Header</h3> <div class="close fa fa-close"></div> </div> <!-- Modal Body --> <div class="modal-body"> <h3>Hello</h3> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> A: Your css and js references which are: <link rel="stylesheet" href="~/Content/loginmodal.css"> <script src="~/Scripts/loginmodal.js"></script> And the button to open it: <div class="wrapper"> <!-- Modal button --> <button id="modBtn" class="modal-btn">Open Modal</button> </div> should be placed inside Index.cshtml instead of the login partial view.
{ "language": "en", "url": "https://stackoverflow.com/questions/49932362", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: APN authentication detection method I am working on a project involving GPRS. In particular I use u-blox Lisa-U200 GPRS/GSM chip. Ran into a problem with the PDP contexts when I started testing it out with different carriers. And after spending days on Google I don't seem to find the answer anywhere. Why do some phones/devices require APN Authentication (PAP/CHAP/None) and some don't? Or as I have titled the question - how do mobile devices (smartphones) detect APN Authentication method automatically? Or do they at all? The way I test it is this - Linux box, running pppd with a chat script. The chat script defines the context (AT+CGDCONT=1,"IP", and so on) and starts the connection. The symptoms - if I don't specify the authentication method in the PDP context explicitly it does not even activate (or LCP negotiation fails in the ppp). From the little I understand about GPRS networks this makes sense - I suppose because the gateway node refuses the context if it does not indicate there will be authentication to follow. Tested with few operators and here comes the most weird part - some of the operators I tested work ONLY if I set it to either PAP or CHAP (and provide correct username and password). And some work whatever I specify (NOAUTH, wrong user/password, etc). The ideas I have come up with so far are: 1) Provide option to the user to select authentication type. (Not the approach I am fond of because I prefer the user to enter as little as possible.) 2) If the user has set a username/password for the APN - set the auth method to CHAP (I have noticed most operators support both CHAP and PAP). If not - use None as method. (Sounds reasonable?) 3) Brute force - set to CHAP, activate - watch for error; if failed - set to PAP and activate, etc... (Can't say I am too happy about it) Please excuse me if I answer a very dumb and common question with a well known answer in the mobile industry or if I am completely off track in my logic here, but I am a software developer and that just doesn't make any sense to me :) Thanks to anyone who shares some experience and knowledge on the topic!
{ "language": "en", "url": "https://stackoverflow.com/questions/24068719", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to capture key events All of the examples for key listeners I have been able to find deal with components other than the main panel such as a text box or Menu. I know how to use setMnemonic to program Menu hotkeys but this method does not seem to be available and the link to the oracle keylistener tutorial is broken. When I do a Right Click > Events > Key > KeyPressed on the main form I get the following but none of keys cause mainPanelKeyPressed. What is the correct way to use the key events to trigger an action independent of the focus? mainPanel.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { mainPanelKeyPressed(evt); } }); private void mainPanelKeyPressed(java.awt.event.KeyEvent evt) { // Added to help find the ID of each 'arrow' key JOptionPane.showMessageDialog(null, "mainPanelKeyPressed"); } A: What is the correct way to use the key events to trigger an action independent of the focus? See: How to Use Key Bindings Or use a JMenuBar with menus and menu items. A: the focus is important. you may need to click around and experiment, and use component.requestFocusInWindow() to help.
{ "language": "en", "url": "https://stackoverflow.com/questions/8944466", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using save() in Django model produces TypeError *****Working with Django 1.11.x and Python 3.6***** I'm trying to learn how to use the save() method in a Django model (models.py). There are two fields here that I want to become custom, 'calculated' fields (unique_id and age). First I initiate the field variables, then define methods/properties based on existing fields, then I try to save the method results into the fields that I created. from django.db import models from dateutil.relativedelta import relativedelta from datetime import datetime class Person(models.Model): unique_id = models.CharField(max_length=6, primary_key=True) age = models.IntegerField() last_name = models.CharField(max_length=25) birth_date = models.DateField() city_of_birth = models.CharField(max_length=25) @property def get_unique_id(self): a = self.last_name[:2].upper() #First 2 letters of last name b = self.birth_date.strftime('%d') #Day of the month as string c = self.city_of_birth[:2].upper() #First 2 letters of city return a + b + c @property def get_age(self): return relativedelta(self.birth_date.days, datetime.date.now()).years def save(self, *args, **kwarg): self.unique_id = self.get_unique_id() self.age = self.get_age() super(Person, self).save(*args, **kwarg) def __str__(self): return self.unique_id First, I create 5 fields. 2 of them are placeholders: unique_id and age. Then I define two @property methods and each return a different type of result. The "get_unique_id" function works, but I can't get the result stored in the database. The "get_age" function may or may not be working. I haven't been able to produce it yet. My primary question is how to correctly use the save() function to override the initial field values (unique_id and age) with my 'calculated field' methods (get_unique_id and get_age). My primary problem is that when I add a Person (using the Person ModelForm in /Admin), it produces a TypeError: 'str' object is not callable at the line "self.unique_id = self.get_unique_id()". I am currently using the Admin interface to test. Eventually, I need to learn how to NOT display these 2 fields in the forms, since they will be calculated based on the other fields. I think I may have found documentation on Meta that might help. Also, I want the unique_id field to be the primary key, so I added this option to the initial field. I have a secondary question (my apologies for being new to Django) about the *args, and **kwargs. Is it okay to leave them there? I'm really unsure about which arguments I need to use, if any, and whether or not it's necessary to include *args and **kwargs in the code. NOTE: To anyone who helped me yesterday with this app, I really appreciate your help. I consider this to be different than my previous question, although I'm using much of the same code. A: Properties are not callable. When you access self.get_unique_id, Python makes the call to the underlying method decorated by @property behind the scenes, which in this case returns a string. You don't need to call it again, drop the parens: def save(self, *args, **kwarg): self.unique_id = self.get_unique_id self.age = self.get_age super(Person, self).save(*args, **kwarg) OTOH, going by @DanielRoseman's comment, you don't need store the age in the database. Just calculate it when its needed. You could rename get_age as age and drop the age field, so age becomes a property.
{ "language": "en", "url": "https://stackoverflow.com/questions/44831911", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Django Send emails to all users in the database table I have started django building my first app tutorials, i have to send email to all my users store in the database table on some special Ocations. i have searched on google and found many apis but found it very hard to configure with my app. here is my model.py class Users(models.Model): UserID = models.IntegerField(verbose_name='User ID',max_length=255,primary_key=True) UserName = models.CharField(verbose_name='User Name',max_length=254,null=True,blank=True) Email = models.EmailField(verbose_name='Email',max_length=254,null=True,blank=True) Phone = models.CharField(verbose_name='Phone Number',max_length=254,null=True,blank=True) i want to have a function here which should get all users one-by-one and send email also tells the status weather the email has been sent or not. A: battery's answer is ok, but i would do this way: recievers = [] for user in Users.objects.all(): recievers.append(user.email) send_mail(subject, message, from_email, recievers) this way, you will open only once connection to mail server rather than opening for each email. A: Sending email is very simple. For your Users model this would be: for user in Users.objects.all(): send_mail(subject, message, from_email, user.Email) Checkout Django's Documentation on send emails for more details. Would be useful if you mention what problem you are facing if you've tried this. Also note, IntegerField does not have a max_length argument. A: for user in Users.objects.all(): send_mail(subject, message, from_email, user.Email) This is the best solutions and it works well
{ "language": "en", "url": "https://stackoverflow.com/questions/27664175", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to run VS 2012 codedUI project solution remotely from command line? We have a simple codedUI test project solution of Visual Studio 2012. VS 2012 has the Test - Run - All Tests option on its GUI. We like to invoke that from command line for automation purpose. Is there a way to do it and not using Test Manager at all ? Thanks A: You need to install Visual Studio Test Agent first in your remote/test machine. Then using a remote access tool such as PsExec from PsTools you use MSTest.exe or VSTest.Console.exe to run a dll. You can script this in bat file on your own machine to trigger loading of test dlls to the remote machine and automated running. However setting up a good build-test environment using Visual Studio TFS will always be a better and more integrated solution.
{ "language": "en", "url": "https://stackoverflow.com/questions/27727062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How can I close the navbar clicking on the body? My navbar looks like this: <div id="mySidenav" class="sidenav"> <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a> <span class="d-flex mx-3"> <img src="{{ asset('images/logo-small.png') }}" width="30" height="30" alt="Deliveboo"> <h4 class="mx-3">Deliveboo</h4> </span> <hr class="mx-3"> <div class="d-flex justify-content-center p-3"> @if (Auth::guest()) <a class="btn btn-primary text-center" href="{{ route('login') }}" role="button">Accedi</a> <a class="btn btn-primary text-center" href="{{ route('register') }}" role="button">Registrati</a> @endif @if (Auth::check()) <a class="btn btn-primary" href="{{ route('restaurants.dashboard') }}" role="button">Vai alla tua dashboard</a> @endif </div> <hr class="mx-3"> </div> These are my scripts: <script> function openNav() { document.getElementById("mySidenav").style.width = "375px"; document.getElementById("root").style.overflow = "hidden"; } function closeNav() { document.getElementById("mySidenav").style.width = "0"; document.getElementById("root").style.overflow = "auto"; } </script> I want the navbar to close when I click outside of it. I'm new to JavaScript. The entire view: <body id="root"> {{-- HEADER --}} <header> <div id="nav-bg"> <nav class="navbar navbar-light d-flex justify-content-space-between container"> {{-- LOGO --}} <div> <a class="navbar-brand" href="#"> <span class="text-white"> <img src="{{ asset('images/logo-text.png') }}" width="100" height="40" class="d-inline-block align-top" alt="Logo"> </span> </a> </div> {{-- Navbar buttons --}} <div> @if (Auth::guest()) <a class="btn btn-light mx-3" href="{{ route('login') }}" role="button"><i class="fas fa-home mr-2"></i>Accedi o registrati</a> @endif @if (Auth::check()) <a class="btn btn-light" href="{{ route('restaurants.dashboard') }}" role="button">Vai alla tua dashboard<i class="fas fa-home"></i></a> @endif <a class="btn btn-light" href="#" role="button" onclick="openNav()"><i class="fas fa-bars mr-2"></i>Menu</a> </div> {{-- Sidebar --}} <div id="mySidenav" class="sidenav"> <a href="javascript:void(0)" class="closebtn" onclick="closeNav()">&times;</a> <span class="d-flex mx-3"> <img src="{{ asset('images/logo-small.png') }}" width="30" height="30" alt="Deliveboo"> <h4 class="mx-3">Deliveboo</h4> </span> <hr class="mx-3"> <div class="d-flex justify-content-center p-3"> @if (Auth::guest()) <a class="btn btn-primary text-center" href="{{ route('login') }}" role="button">Accedi</a> <a class="btn btn-primary text-center" href="{{ route('register') }}" role="button">Registrati</a> @endif @if (Auth::check()) <a class="btn btn-primary" href="{{ route('restaurants.dashboard') }}" role="button">Vai alla tua dashboard</a> @endif </div> <hr class="mx-3"> </div> </nav> </div> {{-- HERO --}} <div id="hero"> <div class="container"> <div class="row"> <div id="hero-text" class="col-6 mb-5 img-animation"> <h1>I piatti che ami, a domicilio.</h1> </div> </div> </div> </div> </header> {{-- MAIN --}} <main> {{-- DELIVEBOO SECTION --}} <section id="deliveboo-section" class="my-5"> <div class="container"> {{-- Section title --}} <h2 class="mb-3 font-weight-bold">La selezione di Deliveboo</h2> <div class="row"> {{-- Card Comfort Food --}} <div class="col-lg-6 col-md-12 d-flex py-3"> <div class="card flex-grow-1 shadow-sm" style="width: 18rem;"> <a class="text-decoration-none text-dark" href="{{ route('restaurants.index') }}"> {{-- Card image --}} <img src="{{ asset('images/comfortFood.png')}}" class="card-img-top" alt="Comfort-food"> <div class="mt-4 p-3"> {{-- Card title --}} <h5 class="card-title">Comfort food</h5> {{-- Description --}} <p class="card-text">I grandi classici che scaldano il cuore, perfetti in ogni momento.</p> <p>Scopri Comfort Food</p> </div> </a> </div> </div> {{-- Card Dessert --}} <div class="col-lg-6 col-md-12 d-flex py-3"> <div class="card flex-grow-1 shadow-sm" style="width: 18rem;" > <a class="text-decoration-none text-dark" href="{{ route('restaurants.index') }}"> {{-- Card image --}} <img src="{{ asset('images/dessert.png')}}" class="card-img-top" alt="dessert"> <div class="mt-4 p-3"> {{-- Card title --}} <h5 class="card-title">Dolci e dessert</h5> {{-- Description --}} <p class="card-text">Dolci piaceri per rendere la giornata ancora più gustosa.</p> <p>Scopri Dolci e dessert</p> </div> </a> </div> </div> {{-- Card Food To Share --}} <div class="col-lg-6 col-md-12 d-flex py-3"> <div class="card flex-grow-1 shadow-sm" style="width: 18rem;"> <a class="text-decoration-none text-dark" href="{{ route('restaurants.index') }}"> {{-- Card image --}} <img src="{{asset('images/toshare.png')}}" class="card-img-top" alt="food"> <div class="mt-4 p-3"> {{-- Card title --}} <h5 class="card-title">Perfetti da condividere</h5> {{-- Description --}} <p class="card-text">Serve una scusa per stare insieme? Ordina dai ristoranti che trasformeranno la tua serata in un vera festa.</p> <p>Scopri Perfetti da condividere</p> </div> </a> </div> </div> {{-- Card Exclusive Deliveboo --}} <div class="col-lg-6 col-md-12 d-flex py-3"> <div class="card flex-grow-1 shadow-sm" style="width: 18rem;" > <a class="text-decoration-none text-dark" href="{{ route('restaurants.index') }}"> {{-- Card image --}} <img src="{{ asset('images/exclusive.png')}}" class="card-img-top" alt="food" > <div class="mt-4 p-3"> {{-- Card title --}} <h5 class="card-title">Esclusiva deliveboo</h5> {{-- Description --}} <p class="card-text">I più famosi, i più buoni, i preferiti. Quelli che trovi solo su Deliveboo.</p> <p>Scopri Esclusiva Deliveboo</p> </div> </a> </div> </div> </div> </div> </section> {{-- DEFAULT SECTION --}} <section id="default-section" class="py-5"> <div class="container"> {{-- Section title --}} <h2 class="mb-4 font-weight-bold">I tuoi piatti preferiti, consegnati da noi</h2> <div class="row row-cols-1 row-cols-md-3 justify-content-center"> {{-- FOOD CARD --}} <div class="col-lg-4 col-md-6 mb-4"> <div> <a href="{{ route('restaurants.index') }}"> {{-- Card image --}} <img src="{{ asset('images/sushi.jpg')}}" class="card-img-top shadow-sm" alt="Sushi" > <div class="mt-2"> {{-- Card title --}} <h5 class="card-title text-capitalize">Sushi</h5> </div> </a> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div> <a href="{{ route('restaurants.index') }}"> {{-- Card Image --}} <img src="{{ asset('images/pokè.jpg')}}" class="card-img-top shadow-sm" alt="Pokè-bowl"> <div class="mt-2"> {{-- Card title --}} <h5 class="card-title text-capitalize">Pokè bowl</h5> </div> </a> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div> <a href="{{ route('restaurants.index') }}"> {{-- Card Image --}} <img src="{{ asset('images/tacos.jpg')}}" class="card-img-top shadow-sm" alt="Cucina-Messico"> <div class="mt-2"> {{-- Card title --}} <h5 class="card-title text-capitalize">Cucina messicana</h5> </div> </a> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div> <a href="{{ route('restaurants.index') }}"> {{-- Card image --}} <img src="{{ asset('images/fastfood.jpg')}}" class="card-img-top shadow-sm" alt="Fast-food"> <div class="mt-2"> {{-- Card title --}} <h5 class="mt-2">Fast Food</h5> </div> </a> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div> <a href="{{ route('restaurants.index') }}"> {{-- Card image --}} <img src="{{ asset('images/pizza.jpg')}}" class="card-img-top shadow-sm" alt="Pizza"> <div class="mt-2"> {{-- Card title --}} <h5 class="card-title text-capitalize">Pizza</h5> </div> </a> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div> <a href="{{ route('restaurants.index') }}"> {{-- Card Image --}} <img src="{{ asset('images/pasta.jpg')}}" class="card-img-top shadow-sm" alt="Pasta"> <div class="mt-2"> {{-- Card title --}} <h5 class="card-title text-capitalize">Cucina italiana</h5> </div> </a> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div> <a href="{{ route('restaurants.index') }}"> {{-- Card Image --}} <img src="{{ asset('images/pesce.jpg')}}" class="card-img-top shadow-sm" alt="Frittura-di-pesce"> <div class="mt-2"> {{-- Card title --}} <h5 class="card-title text-capitalize">Pesce</h5> </div> </a> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div> <a href="{{ route('restaurants.index') }}"> {{-- Card Image --}} <img src="{{ asset('images/kebab.jpg')}}" class="card-img-top shadow-sm" alt="Kebab"> <div class="mt-2"> {{-- Card title --}} <h5 class="card-title text-capitalize">Kebab</h5> </div> </a> </div> </div> <div class="col-lg-4 col-md-6 mb-4"> <div> <a href="{{ route('restaurants.index') }}"> {{-- Card Image --}} <img src="{{ asset('images/vietnamita.jpg')}}" class="card-img-top shadow-sm" alt="Cucina-Vietnam"> <div class="mt-2"> {{-- Card title --}} <h5 class="card-title text-capitalize">Cucina vietnamita</h5> </div> </a> </div> </div> </div> </div> </section> {{-- SECTION SUGGESTED --}} <section id="suggested" class="m-5"> <div class="container"> <h2 class="mb-4">Cerchi qualcos'altro?</h2> @foreach ($types as $type) <a href="{{ route('restaurants.index') }}" class="btn px-3">{{ $type->name }}</a> @endforeach </div> </section> </main> A: You need to add an event listener to the body and run the function. const body = document.querySelector('body'); const buttonToOpen = document.querySelector('#buttonSideNav') function closeNavBody(e) { if (e.target.id !== 'mySidenav' || e.target.id !== '#buttonSideNav') { closeNav(); body.removeEventListener('click', myClick); } } function openNav() { document.getElementById("mySidenav").style.width = "375px"; document.getElementById("root").style.overflow = "hidden"; body.addEventListener('click', closeNavBody) } function closeNav() { document.getElementById("mySidenav").style.width = "0"; document.getElementById("root").style.overflow = "auto"; } A: You can add an eventListener on the area that is not that element with event.target. But only do that when nav is open and remove the listener when is closed by removeEventListener() or it would be a load. A: Get references to the elements we're working with const mySideNav = document.getElementById("mySidenav"); const root = document.getElementById("root"); const body = document.getelementByTagName("body"); Define our functions function closeNav() { mySidenav.style.width = "0"; root.style.overflow = "auto"; body.onclick = undefined; } function openNav() { mySideNav.style.width = "375px"; root.style.overflow = "hidden"; body.onclick = closeNav; } A: You can attach a listener to body and call closeNav if sideBar nav is open Also attach click listener to stop propagation when clicked inside nav bar. <script> // variable of references to the dom node to avoid querying DOM again and again const sideNavBarElem = document.getElementById("mySidenav"); const rootElem = document.getElementById("root"); const bodyElem = document.querySelector('body'); function openNav() { sideNavBarElem.style.width = "375px"; rootElem.style.overflow = "hidden"; // delay attaching body listener to avoid calling body listener when nav has just opened setTimeout(function() { bodyElem.addEventListener('click', bodyNavListener); }, 0); } function closeNav() { sideNavBarElem.style.width = "0"; rootElem.style.overflow = "auto"; bodyElem.removeEventListener('click', bodyNavListener); } function bodyNavListener(){ // call closeNav fn if navbar is open if(sideNavBarElem.style.width !== "0"){ closeNav(); } } sideNavBarElem.addEventListener('click', function(event){ // stop event propagation to avoid closing nav bar due to body click listener event.stopPropagation(); }) </script> Sample Codepen
{ "language": "en", "url": "https://stackoverflow.com/questions/70038489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get id or pass id to datatables from serverside in Codeigniter? I am working on datatables server-side Processing in codeigniter. Everything is working fine, but I want to pass the id from the controller inside some columns. I've tried this code, but the id is not being received: MyController foreach($fetch_data as $row) { $sub_array = array(); $sub_array[] = $no++; $sub_array[] = "<td id='$row->id'>$row->program</td>"; $sub_array[] = $row->semester; $sub_array[] = $row->name; } After this the table column look like this.<td>Program</td> How to receive the id in the <td id="1">Program</td> form? A: update with $sub_array[] = "<td id=".$row->id.">".$row->program."</td>"; A: $sub_array[] = "<td id='$row->id'>$row->program</td>"; In the above code, you have wrapped $row->id in the single quote(') which causes a problem. Update your code with $sub_array[] = "<td id='".$row->id."'>".$row->program."</td>"; A: You can use onclick function for this task. When you click on the specific td the value get in function and perform ajax. $sub_array[] = "<td onclick='your_function(".$row->id.")'>".$row->program."</td>"; Than in jquery call the function function your_function(id='') { if(id!='') { //your ajax call here } }
{ "language": "en", "url": "https://stackoverflow.com/questions/59303268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Meta Viewport Dynamic Change on Android Default Browser (not Chrome) I'm trying to dynamically change <meta name="viewport">. I have it set by default like: <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> And when the screen resolution goes below 768px I want viewport to be change to: <meta name="viewport" content="width=768">. For this I use jQ code: var winW, initVP, newVP = "width=768"; $(document).on({ ready: function(){ winW = $(window).width(); } }); $(window).on({ load: function(){ if ( winW < 768 ) { setViewport( newVP ); } } }); function setViewport( content ) { $('meta[name=viewport]').attr('content',content); } But for some reason this change doesn't affect Google Nexus 7's Default browser (not Chrome but the lame one that was before) in any visible way. I can see that changes are made in the <head> section, and <meta name="viewport" content=" is changed to width=768">, but the browser doesn't seem to react to this change. Can anyone explain me what I am doing wrong here? Thanks! EDIT: as zsaat14 mentioned Nexus7 has 800px width according to the specs. Nevertheless browser always return 600px width (see the screenshot here). In my case of Android emulator it returns 602px though %) A: The Nexus 7 has a screen resolution of 1280X800 (source). It is somewhat surprising then that the meta tag is changing, but not surprising that your website stays the same. EDIT: Ok, so it's not the width then. You might try reading this article from MDN and make sure that the meta viewport can do what you are expecting. It is not quite clear what you want it to do, but the meta viewport tag does not make drastic changes, so you might just be missing it.
{ "language": "en", "url": "https://stackoverflow.com/questions/21165681", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Using TypeScript decorators and promises with proper typing? I wrote a buffered decorator, which works as expected by returning a Promise (during the execution). However, to make the tsc transpiler happy, I'm forced to cast the decorated function with any and then (in the example below) with Promise<number>. How can I avoid the extra casts? Is it even possible for a decorator to modify the signature of the decorated function? For example, how do I write an @buffered decorator, that takes a method function f (which returns number), while the decorated function @buffered f returns a Promise<number> (and not simply a number)?: import { decorator as buffered } from '@dizmo/functions-buffered'; class Class { @buffered(100) // i.e. 100ms delay public f1(t: Date): number { return new Date().getTime() - t.getTime(); } @buffered // i.e. defaults to 200ms delay public f2(t: Date): number { return new Date().getTime() - t.getTime(); } } const p: Promise<number> = new Class().f1(new Date()) as any; p.then((res: number) => { console.debug(res); }); I could write for example: const p: Promise<number> = new Class().f1(new Date()); p.then((res: number) => { console.debug(res); }); However, then I get the following output: [ts] Type 'number' is not assignable to type 'Promise<number>'. However, I should actually just be able to write: const p = new Class().f1(new Date()); p.then((res: number) => { console.debug(res); }); But then p is recognized as a number instead of a Promise: [ts] Property 'then' does not exist on type 'number'. The implementation of the @buffered decorator is available at: * *https://github.com/dizmo/functions-buffered/blob/master/lib/index.ts Please note that the implementation has additional complexity due to my desire to drop the parenthesis of the @buffered decorator, when I want to use a default delay of 200ms. A: Decorators can't change the structure of the class they are decorating. This is a design limitation. There is a proposal to change this but it does not seem to be a priority (maybe upvote the GitHub issue if it's important to you) We could use a mapped type if we want to transform all methods, but we can't apply a mapped type transformation to only decorated properties so this is not a viable solution in this case. A better option would be to actually have the corect return type directly in the class. We could do this with minimal changes to the code using async: class Class { @buffered(100) // i.e. 100ms delay // use async and return a promise instead of a number public async f1(t: Date): Promise<number> { return new Date().getTime() - t.getTime(); } @buffered // i.e. defaults to 200ms delay public async f2(t: Date) { // no need to specify the return type will be inferred correctly to Promise<number> return new Date().getTime() - t.getTime(); } } const p: Promise<number> = new Class().f1(new Date()); // works fine p.then((res: number) => { console.debug(res); });
{ "language": "en", "url": "https://stackoverflow.com/questions/51730805", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How do i parse results from a combine publisher I am new to the combine world and have written a query that returns the results I need correctly. It's multi-step, but basically makes an api call over the network, parses the returned json and creates an array of records I need. let results2: Publishers.Map<Publishers.ReceiveOn<Publishers.Decode<Publishers.Map<URLSession.DataTaskPublisher, JSONDecoder.Input>, Wrapper<Question>, JSONDecoder>, DispatchQueue>, [Question]> I'm trying to rewrite a portion of my code and realize that I still don't quite grasp the ins and outs of parsing the results. If you look at the datatype of results2 you will see the final portion contains an array of Question. How do I assign this array to a variable, as in: let finalAnswer: [Question] = turnThisIntoAnArray(results2) If possible, I'd prefer a general answer to this general question, rather than providing all the code needed to recreate this specific string of publishers. thanks A: In this working example, notice the variable results below: func runQuery() { let env = BespokeEnvironment(mainQueue: .main, networkQuery: NetworkQuestionRequestor()) results = env.networkQuery.reviewedQuestionsQuery(pageCount: 1) .sink( receiveCompletion: { print($0)}, receiveValue: { values in returnValues.append(contentsOf: values) }) } I originally had: let results = ... And was not getting any records. It turns out the method was completing and returning before the publisher had finished. In the non-working code, the cancellable was not being saved long enough for the publisher to complete. So I moved results into the parent view and made it a @State variable. Everything now works correctly. @State var results: AnyCancellable? = nil
{ "language": "en", "url": "https://stackoverflow.com/questions/71756471", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ADF: table was unable to show in page I have an ADF table defined in a .jsff file, in which the partialTrigger is bound to the id of the component containing class B: <af:table value="#{pageFlowScope.ManagedBeanName.nameList}" ... partialTriggers="::::it5"> ... </af:table> In the ManagedBeanName.java, we define the nameList and have a method to set value to the list named setNameList. When the nameList is set with value, it will show the table in the UI page. public void setNameList(){ ... nameList.add(name); } Now I have a Class B, in which we invoke setNameList, ManagedBeanName managedbean = new ManagedBeanName(); managedbean.setNameList(); Through the debugging process, we found setNameList can be invoked correctly and nameList can be set values. But after the invoking, nameList does not have values. And the table does not show. Could you please help to discover where the issue is? Thanks very much in advance! A: You have to put list of data in a scope try something like this: public List<String> getMyList() { myList.clear(); List<String> list = (List<String>) AdfFacesContext.getCurrentInstance().getProcessScope().get("myList"); if (list != null) { for (String var : list) { myList.add(var); } } return myList; } You can also see this question and answer : How to refresh table within a popup in dialog window in ADF Oracle 11gR1 A: The problem is that I define the setNameList() in managedbean and have to invoke setNameList() in another method in Class B. I new a fresh managedBean to call this method and the nameList in this instance is not the one bonded to the page. Solution: In class B, get the right instance as: ManagedBean managedBean = (ManagedBean)ADFUtil.evaluateEL("#{pageFlowScope.ManagedBean}"); The issue is gone.
{ "language": "en", "url": "https://stackoverflow.com/questions/48376230", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is there a way to limit the number of records for a user using Prisma? The simplest example I can give, is a User that can create multiple Posts. A one-to-many relationship where multiple posts can be tied to a single user. But what if I want the User to only be able to have a max of 10 Posts? Ideally there'd be some kind of query I can run when creating a new Post, and if the limit has been reached, to reject creating that Post (or possibly replace a Post). I'm kind of stumped on this. And I'm not sure if there is a way I can model this to create the desired outcome. Otherwise, the only real solution I see is to fetch all Posts for a User, and count them before trying to create a new Post. But that would require two calls to the db instead of one which is the problem I am trying to avoid. A: Have you considered a database trigger? Below example is taken from this StackExhange post: CREATE OR REPLACE FUNCTION check_number_of_row() RETURNS TRIGGER AS $body$ BEGIN IF (SELECT count(*) FROM your_table) > 10 THEN RAISE EXCEPTION 'INSERT statement exceeding maximum number of rows for this table' END IF; END; $body$ LANGUAGE plpgsql; CREATE TRIGGER tr_check_number_of_row BEFORE INSERT ON your_table FOR EACH ROW EXECUTE PROCEDURE check_number_of_row(); Unfortunately triggers don't seem to be supported in Prisma yet, so you will have to define it in SQL: https://github.com/prisma/prisma/discussions/2382 A: You can achieve it with interactive transaction, here's my example code: const createPost = async (post, userId) => { return prisma.$transaction(async (prisma) => { // 1. Count current total user posts const currentPostCount = await prisma.posts.count({ where: { user_id: userId, }, }) // 2. Check if user can create posts if (currentPostCount >= 10) { throw new Error(`User ${userId} has reached maximum posts}`) } // TODO // 3. Create your posts here await prisma.posts.create({ data: post }) }) }
{ "language": "en", "url": "https://stackoverflow.com/questions/74288790", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to call remote method in Invoke-command for a local variable in script block I am working on a PowerShell script that remotely gets veeam Backup reporting data from a backup server. I know we can pass variables usually with $Using: $object = Invoke-command -ComputerName serverName -ScriptBlock { Get-VBRBackup | Where-Object { $_.JobName -eq $Using:jobName }} but how can I call method of the object, I tried as below and doesn't work. $data=Invoke-command -ComputerName serverName -ScriptBlock { $($using:object).GetLocalStorages()} but if I do : $data=Invoke-command -ComputerName serverName -ScriptBlock { $(Get-VBRBackup | Where-Object { $_.JobName -eq $Using:jobName }}).GetLocalStorages()} it works: I am quite new to PowerShell and don't know much. How to encapsulate alocal objects in invoke-command and call its method?
{ "language": "en", "url": "https://stackoverflow.com/questions/71417209", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Changing css background image property by jquery setTimeout I want to change my header image (which I gave it's source in the css, not in HTML) every 10 seconds Using jQuery. I may have up to 15 16 images so the code I wrote may be too long for my js file. I wrote the code below , but I'm looking for much compact code , hopefully using arrays. $(function() { setTimeout(function() { changeHeaderImg3() }, 10000); setTimeout(function() { changeHeaderImg2() }, 20000); setTimeout(function() { changeHeaderImg1() }, 30000); setTimeout(function() { changeHeaderImg4() }, 40000); setTimeout(function() { changeHeaderImg3() }, 50000); }); function changeHeaderImg3() { $('header').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover'); $('footer').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover'); }; function changeHeaderImg2() { $('header').css('background', 'url(assets/img/bg2.jpg) center center').css('background-size', 'cover'); $('footer').css('background', 'url(assets/img/bg2.jpg) center center').css('background-size', 'cover'); }; function changeHeaderImg1() { $('header').css('background', 'url(assets/img/bg1.jpg) center center').css('background-size', 'cover'); $('footer').css('background', 'url(assets/img/bg1.jpg) center center').css('background-size', 'cover'); }; function changeHeaderImg4() { $('header').css('background', 'url(assets/img/bg4.jpg) center center').css('background-size', 'cover'); $('footer').css('background', 'url(assets/img/bg4.jpg) center center').css('background-size', 'cover'); }; function changeHeaderImg3() { $('header').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover'); $('footer').css('background', 'url(assets/img/bg3.jpg) center center').css('background-size', 'cover'); }; A: If you have an array of image urls, you can use setInterval to periodically update your header/footer images. Something like this: var imgUrls = [ 'assets/img/bg1.jpg', 'assets/img/bg2.jpg', 'assets/img/bg3.jpg', 'assets/img/bg4.jpg', // ... etc. ]; var currentImageIndex = 0; // Create a callback that will be invoked every 10 seconds setInterval(function() { var imgUrl = imgUrls[currentImageIndex++]; $('header').css('background', 'url(" + imgUrl + ") center center').css('background-size', 'cover'); $('footer').css('background', 'url(" + imgUrl + ") center center').css('background-size', 'cover'); // Make sure the currentImageIndex doesn't get too big if (currentImageIndex >= imgUrls.length) { currentImageIndex = 0; } }, 10000); A: Another solution : $(function() { let pictures = ["bg3.jpg", "bg2.jpg", "bg1.jpg"]; $.each(pictures, function(i,e) { setTimeout(function() { changeHeaderImg(e); }, i*10000); }); } function changeHeaderImg(pictureName: string) { $('header').css('background', 'url(assets/img/'+pictureName+') center center').css('background-size', 'cover'); $('footer').css('background', 'url(assets/img/'+pictureName+') center center').css('background-size', 'cover'); } A: This will work for any number of images as long as you keep following your 'assets/img/bg' + num + '.jpg' format. Just set the number of headers you have at the top and you're good to go. $(function() { var numHeaders = 4; var header = 0; setInterval(function() { header++; if (header > numHeaders) { header = 1; } $('header').css('background', 'url(assets/img/bg' + header + '.jpg) center center').css('background-size', 'cover'); $('footer').css('background', 'url(assets/img/bg' + header + '.jpg) center center').css('background-size', 'cover'); }, 10000); });
{ "language": "en", "url": "https://stackoverflow.com/questions/44359189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why Use 'new' When Using AsyncTask When using AsyncTask in android, I have to use like this, new MyAsyncTask().execute() I have to make new instance If I want to use AsyncTask. But I wonder why I have to do. I just want to use it like, private MyAsyncTask task; ... private void foo() { ... task.excute(); } BUT I can't. And I want to know why it doesn't work. If you give me answer, I'm very appreciated. A: execute() is a method of AsyncTask. If you want to invoke then you need to create an instance of Asynctask. If you want to execute a method of a class you need to instantiate and then call the appropriate methods. task.excute(); will give you NUllPointerException. task = new MyAsyncTask(); task.execute(); You may also want to check http://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html Look at the public methods as suggested by prosper k it is not a static method http://developer.android.com/reference/android/os/AsyncTask.html A: Java is not RAII. You always need to create an instance of a class, because you cannot execute methods on a class directly unless the method is static. But then still the syntax would be different. What you can do is more like this: private MyAsyncTask task; … private void foo() { task = new MyAsyncTask(); … task.execute(); } A: This is a matter of Java not Android. In java, something like: MyAsynkTask task; doesn't create an object. In this step you have only declared a variable. To use any method of your object (e.g. task.execute()) you have to instantiate an object (i.e. actually create one); like: task = new MyAsyncTask(); A: Check this link for basics of "new" keyword. Basically it is use for Instantiating a Class.The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor. Hope this helps you.
{ "language": "en", "url": "https://stackoverflow.com/questions/22034571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to save an blob in database - typeorm Generaly: can someone just give an example how to save a Blob object like in my example Blob {size:1996683, type: "image/png"} size: 1996683 type: "image/png" proto: Blob in a cordova typeorm database (with the data content)? Inital if i get the Blob i can work with it fine and can display the image direclty without any converting or something else. but when loading it out of the database its just a string with the object type.. (see long version) Long version of my problem: im currently building an ionic app with cordova and angular. for the database im using the typeorm module. which i initialize like this: await createConnection({ type: 'cordova', database: 'test.db', location: 'default', logging: false, synchronize: true, entities: [ User, QrCode, QrFile, QrOrder, SubItem, Property, ] }) my qrFile entity which contains the blob column looks like: @Entity('qrfile') export class QrFile{ ... @Column("blob", { nullable: true }) content: Blob; Here i tried a lot of other types instead of Blob e.g. Buffer, ArrayBuffer and so on... I added a few debug console logs in the "main" method which is managing the entity content: public async getFileContent(qrFile: QrFile) { if(!qrFile.content){ console.log("getFileBase64Content -> no content so load from server") let result = await this.loadContentFromServer(qrFile).catch(reject => { return null; }); qrFile.content = result;//await new Response(result).arrayBuffer()//new Buffer(result); qrFile = await this.saveQrFileToDB(qrFile); }else{ console.log("getFileBase64Content -> content found!") } console.log("IMPORTANT!!! content which will be used:") console.log(qrFile.content) return qrFile.content; } Now i'm loading the file from a server as octet stream (so the first if check is true and i have to load and then set the content) the content is a real Blob the first time, when i loaded it from the server: console output: IMPORTANT!!! content which will be used: main.js:6217 Blob {size:1996683, type: "image/png"} size: 1996683 type: "image/png" proto: Blob but the second time this method is called i have something in the content of the qrFile but it isn't a Blob... console output IMPORTANT!!! content which will be used: main.js:6217 [object Object] It's pretty strange, cause the saveToDB method is returning the "new/updated" entity and i ALWAYS use the content of that entity. Like i wrote i tried already a lot. like make different buffers out of the first Blob and set this as content. and then after loading out of the database convert the Buffer back to a Blob but nothing worked. i have always just the object Object with which a can't really work it seems like. ionic info: cli packages: (C:\Users#####\AppData\Roaming\npm\node_modules) @ionic/cli-utils : 1.19.3 ionic (Ionic CLI) : 3.20.1 global packages: cordova (Cordova CLI) : not installed local packages: @ionic/app-scripts : 3.1.9 Cordova Platforms : android 7.0.0 Ionic Framework : ionic-angular 3.9.2 System: Android SDK Tools : 26.1.1 Node : v10.15.3 npm : 6.4.1 OS : Windows 10 Environment Variables: ANDROID_HOME : D:\android_sdk Misc: backend : pro And package.json entry for typeorm: "typeorm": "^0.2.5", Edit: i now activated the logging for typeORM and did some more console logs: the update query is: query: UPDATE "qrfile" SET "content" = ? WHERE "id" = ? -- PARAMETERS: [{"size":1996683,"type":"image/png"},1] and a direct query after the save on the qrFile results in: content: "[object Object]" so there is a simple String with just [object Object] saved in the db?! so one more update from my side: created an extra method which updates the content value directly via a query: with this method i get as db select result "content: "[object Blob]" still a string it seems. also strange is that the parameter. to be honest i don't really like to convert the image to base64 and save it as string or something like that. i mean the doc of typeorm (https://github.com/typeorm/typeorm/blob/master/docs/entities.md) says that blob is a valid entity type - so it should work somehow.
{ "language": "en", "url": "https://stackoverflow.com/questions/57199241", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Table shows headers in a column not as a row I'm a little puzzled with this one. I've got my code to display how ever it will not display it in the format I wish, I want it to be: section serial bike time info1 info2 info3 info4 info1 info2 info3 info4 info1 info2 info3 info4 info1 info2 info3 info4 and so on.. however my code is displayed as: section serial bike time info1 info1 info1 info1 info2 info2 info2 info2 etc My code is as follows: <div class="table" style="width:100%;" > <?php # table 1 print '<div class="thead">'; #thead print ' <div class="th"><div class="spaced"></div>'; print 'Section'; print ' </div>'; print ' <div class="th"><div class="spaced"></div>'; print 'Serial'; print ' </div>'; print ' <div class="th"><div class="spaced"></div>'; print 'Bike'; print ' </div>'; print ' <div class="th"><div class="spaced"></div>'; print 'Time'; print ' </div>'; print '</div>'; #thead print '<div class="tbody">'; #tbody for ($i=1;$i<=$num_rows;$i++) { print '<div class="tr">'; for ($x=1;$x<=2;$x++) { if ($x == 1) $row_pos = $i; else $row_pos = $num_stations - $i; print '<div class="td">'; print '<div class="table">'; print ' <div class="tr" format me >'; print ' <div class="td"><div class="spaced"></div>'; print $station_detail[$row_pos]['station_name']; print ' </div>'; print ' <div class="td"><div class="spaced"></div>'; print $station_detail[$row_pos]['station_name'];; print ' </div>'; print ' <div class="td"><div class="spaced"></div>'; print $station_detail[$row_pos]['station_name']; print ' </div>'; print ' <div class="td"><div class="spaced"></div>'; print $station_detail[$row_pos]['station_name']; print ' </div>'; print ' </div></div>'; } print '</div>'; #tr print '</div>'; #tbody } ?> </div> </div><!-- close table --> and i know its a formatting issue my css: .table {display: table;width:600px;position:relative;margin:0 auto;} .tr {display: table-row;} .td {display: table-cell;} .table { border-collapse: collapse; width:auto; } .tr { border-collapse: collapse; float:left; text-align:left; height:auto; width:25%; } .th{ border-collapse: collapse; border: 1px solid black; font-size:20px; height:40px; vertical-align: middle; width:25%; } .thead{ border-collapse: collapse; border: 1px solid black; font-size:20px; height:40px; vertical-align: middle; width:25%; } .td{ border-collapse: collapse; border: 1px solid black; font-size:20px; height:40px; vertical-align: middle; width:25%; } .td1{ text-align:left; font-weight:bold; float:left; margin:15px; width:25%; } .screenpos{ width:100%; margin:0 auto; vertical-align: middle; } Can anyone guide where I've gone wrong? I'm new to putting my tables in div's and such. A: Your table structure should be something like this: <table> <tr> <th>Table heading 1</th> <th>Table heading 2</th> <th>Table heading 3</th> <th>Table heading 4</th> </tr> <tr> <td>cell 1</td> <td>cell 2</td> <td>cell 3</td> <td>cell 4</td> </tr> <tr> <td>cell 1</td> <td>cell 2</td> <td>cell 3</td> <td>cell 4</td> </tr> <tr> <td>cell 1</td> <td>cell 2</td> <td>cell 3</td> <td>cell 4</td> </tr> </table> JSFiddle Demo
{ "language": "en", "url": "https://stackoverflow.com/questions/21751510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Switch user from adaptive to desktop version of site I have a desktop and adaptive (with media query in css) design of site. How can I show desktop version of my site if user come to it from mobile gadget? There is only idea in my head: * *Set up cookie (for example siteVersion = mobile) previously. *If user choose desktop version (via clicking button, link...however) set up this cookie to "desktop" and after refresh page load css with desktop design. Does anyone have other ideas? Maybe someone has someexperience with it? A: So, what @jared gotte said - "adaptive" implies a web page that can adapt to the device capabilities without having to serve up different content from the server. So in that regard your question is a bit nonsensical. But, that said, the way most [large] sites handle serving different content to mobile .vs. desktop is by setting up different subdomains. For example Facebook uses www.facebook.com for the desktop version of the site, and m.facebook.com for the mobile version. When a user first hits the site, the server looks at the User-Agent header to decide what type of device they're using and redirects them appropriately. If/when you want to switch them between the two on the client, you can use JS to redirect their browser. The caveat to this is that you'll need to setup the DNS hostname(s), and make your server code aware of the Host header on incoming requests. A: Put your desktop CSS in one CSS file. Put your adaptive stuff in another CSS file. Serve both to the user. But then if a user says "show me the desktop version", stop serving them the adaptive CSS file.
{ "language": "en", "url": "https://stackoverflow.com/questions/19824896", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO) during mysql installation I have tried almost all related problems to this problem, but they all weren't working for me. It's my first time installing mysql onto my arch linux and it keeps asking me for root password as I don't have one. A: It was happening because I wasn't running my terminal in root.. I changed to root user and run the command and everything worked
{ "language": "en", "url": "https://stackoverflow.com/questions/72682333", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: microsoft sql server 2005 restoring .bak file I have a database hosted however the hosting expired. Need to restore my .bak file. Does the .bak file include the tables/procedures or only the data? How do I restore .bak file? Thanks A: The .bak file should have everything of the database it was made from - tables, sprocs and data. To restore it, right-click the Databases folder in the Object Explorer and choose Restore Database. Type in a name you wish to use for the restored database in the To database: field. Then select the From device: radio button and press the ... button to select your .bak file: in the window that appears press the Add button and select the correct file, then press OK.
{ "language": "en", "url": "https://stackoverflow.com/questions/6039669", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Netty server memory usage keep increasing and eventually crashes with io.netty.util.internal.OutOfDirectMemoryError Below is the code of my netty server. It is configured to release reference count on channelRead i.e wont be processing anything just drop the incoming data. Client is also netty based. Which starts 16 parallel connections with server and start sending data on each channel. However as soon as program starts, memory usage keep increasing and eventually it crashes with following exception. 08:41:15.789 [nioEventLoopGroup-3-1] WARN i.n.channel.DefaultChannelPipeline - An exceptionCaught() event was fired, and it reached a t the tail of the pipeline. It usually means the last handler in the pipeline did not handle the exception. io.netty.util.internal.OutOfDirectMemoryError: failed to allocate 100663296 byte(s) of direct memory (used: 3602907136, max: 369885184 0) at io.netty.util.internal.PlatformDependent.incrementMemoryCounter(PlatformDependent.java:640) ~[sosagent.jar:1.0-SNAPSHOT] at io.netty.util.internal.PlatformDependent.allocateDirectNoCleaner(PlatformDependent.java:594) ~[sosagent.jar:1.0-SNAPSHOT] at io.netty.buffer.PoolArena$DirectArena.allocateDirect(PoolArena.java:764) ~[sosagent.jar:1.0-SNAPSHOT] at io.netty.buffer.PoolArena$DirectArena.newUnpooledChunk(PoolArena.java:754) ~[sosagent.jar:1.0-SNAPSHOT] at io.netty.buffer.PoolArena.allocateHuge(PoolArena.java:260) ~[sosagent.jar:1.0-SNAPSHOT] at io.netty.buffer.PoolArena.allocate(PoolArena.java:231) ~[sosagent.jar:1.0-SNAPSHOT] at io.netty.buffer.PoolArena.reallocate(PoolArena.java:397) ~[sosagent.jar:1.0-SNAPSHOT] at io.netty.buffer.PooledByteBuf.capacity(PooledByteBuf.java:118) ~[sosagent.jar:1.0-SNAPSHOT] at io.netty.buffer.AbstractByteBuf.ensureWritable0(AbstractByteBuf.java:285) ~[sosagent.jar:1.0-SNAPSHOT] at io.netty.buffer.AbstractByteBuf.ensureWritable(AbstractByteBuf.java:265) ~[sosagent.jar:1.0-SNAPSHOT] at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1079) ~[sosagent.jar:1.0-SNAPSHOT] at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1072) ~[sosagent.jar:1.0-SNAPSHOT] at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1062) ~[sosagent.jar:1.0-SNAPSHOT] at io.netty.handler.codec.ByteToMessageDecoder$1.cumulate(ByteToMessageDecoder.java:92) ~[sosagent.jar:1.0-SNAPSHOT] at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:263) ~[sosagent.jar:1.0-SNAPSHOT] at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:362) [sosagent.jar:1.0- SNAPSHOT] NettyServerHandler public class AgentServerHandler extends ChannelInboundHandlerAdapter implements RequestListener { private Buffer buffer; private AgentToHost endHostHandler; private String remoteAgentIP; private int remoteAgentPort; private ChannelHandlerContext context; private float totalBytes; private long startTime; boolean called; @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { InetSocketAddress socketAddress = (InetSocketAddress) ctx.channel().remoteAddress(); log.debug("New agent-side connection from agent {} at Port {}", socketAddress.getHostName(), socketAddress.getPort()); this.context = ctx; remoteAgentIP = socketAddress.getHostName(); remoteAgentPort = socketAddress.getPort(); requestListenerInitiator.addRequestListener(this); if (this == null ) log.info("EHy nULLL "); // Utils.router.getContext().getAttributes().put("agent-callback", requestListenerInitiator); StatCollector.getStatCollector().connectionAdded(); startTime = System.currentTimeMillis(); } private boolean isMineChannel(RequestTemplateWrapper request, AgentServerHandler handler) { // if (handler == null) log.info("nULLLL"); else log.info("not null"); return request.getPorts().contains(((InetSocketAddress) handler.context.channel().remoteAddress()).getPort()); } /* Whenever AgentServer receives new port request from AgentClient. This method will be called and all the open channels will be notified. */ @Override public void newIncomingRequest(RequestTemplateWrapper request) { endHostHandler = getHostHandler(request); if (isMineChannel(request, this)) { endHostHandler.addChannel(this.context.channel()); log.debug("Channel added for Client {}:{} Agent Port {}", request.getRequest().getClientIP(), request.getRequest().getClientPort(), (((InetSocketAddress) this.context.channel().remoteAddress())).getPort()); this.buffer = bufferManager.addBuffer(request, endHostHandler); } endHostHandler.setBuffer(buffer); } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ReferenceCountUtil.release(msg); totalBytes += ((ByteBuf) msg).capacity(); } } Bootstrap private boolean startSocket(int port) { group = new NioEventLoopGroup(); AgentTrafficShaping ats = new AgentTrafficShaping(group, 5000); ats.setStatListener(this); try { ServerBootstrap b = new ServerBootstrap(); b.group(group) .channel(NioServerSocketChannel.class) .localAddress(new InetSocketAddress(port)) .childHandler(new ChannelInitializer() { @Override protected void initChannel(Channel channel) throws Exception { channel.pipeline() .addLast("agent-traffic-shapping", ats) .addLast("lengthdecorder", new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 0, 4, 0, 4)) // .addLast("bytesDecoder", new ByteArrayDecoder()) .addLast(new AgentServerHandler()) .addLast("4blength", new LengthFieldPrepender(4)) // .addLast("bytesEncoder", new ByteArrayEncoder()) ; } } ); ChannelFuture f = b.bind().sync(); log.info("Started agent-side server at Port {}", port); return true; // Need to do socket closing handling. close all the remaining open sockets //System.out.println(EchoServer.class.getName() + " started and listen on " + f.channel().localAddress()); //f.channel().closeFuture().sync(); } catch (InterruptedException e) { log.error("Error starting agent-side server"); e.printStackTrace(); return false; } finally { //group.shutdownGracefully().sync(); } } What could be possible cause here. I know netty uses reference count to keep track of Buffers. I am just releasing the reference as soon as I get a message so that shouldn't be problem ! A: There might be different reasons for OOM exception. One reason readily comes to my mind is is setting AUTO_READ option on the channel. The default value is true. you can get more information about this in stack overflow posts here and here If setting AUTO_READ option doesn't help, netty provides an option to check if any message to ChannelHandler is not released. Please set -Dio.netty.leakDetectionLevel=ADVANCED JVM option in the system properties. A: This happens because the client is writing faster than what the server can process. This ends up filling up the client buffer (memory) and eventual crash. The solution is to adjust the client send rate based on the server. One way to achieve this is that the server periodically reports the reading rate to the client and the client adjusts the write speed based on that.
{ "language": "en", "url": "https://stackoverflow.com/questions/51572490", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Python read file and write in another format I am trying to read a txt-file with many values of pairs in two colmns (X-Y values) and I wand them to be writen in another txt-file with 4 pairs X-Y at each row (8 values per row). So, from that: 0,038043 0,74061 0,038045 0,73962 0,038047 0,73865 0,038048 0,73768 0,03805 0,73672 0,038052 0,73577 0,038053 0,73482 0,038055 0,73388 0,038057 0,73295 0,038058 0,73203 0,03806 0,73112 0,038062 0,73021 0,038064 0,72931 0,038065 0,72842 0,038067 0,72754 0,038069 0,72666 to that: 0,038043 0,74061 0,038045 0,73962 0,038047 0,73865 0,038048 0,73768 0,03805 0,73672 0,038052 0,73577 0,038053 0,73482 0,038055 0,73388 0,038057 0,73295 0,038058 0,73203 0,03806 0,73112 0,038062 0,73021 0,038064 0,72931 0,038065 0,72842 0,038067 0,72754 0,038069 0,72666 I tried: import itertools files = [1, 2 ,3 ,4, 5, 6, 7, 8, 9, 10, 11, 12, 13] for k in files: print 'k =',k with open("deflag_G{k}.inp".format(k=k)) as f1: with open("deflag_G_{k}.inp".format(k=k),"w") as f2: f2.writelines(itertools.islice(f1, 4, None)) f2.close() f1.close() But I am not taking 4 pairs (8 values per line) in the new file. Any help is appreciated. A: One way to approach this is to spit the logic out. First get the data to a list of X-Y, then chunk the data to rows of 8 X-Y and then save the data (ie write data to another text file) The chunk method I've borrowed from another stack overflow answer. def chunks(lst, n): """Yield successive n-sized chunks from lst.""" for i in range(0, len(lst), n): yield lst[i:i + n] input = [ '0,038043, 0,74061', '0,038045, 0,73962', '0,038047, 0,73865', '0,038048, 0,73768', '0,03805, 0,73672', '0,038052, 0,73577', '0,038053, 0,73482', '0,038055, 0,73388', '0,038057, 0,73295', '0,038058, 0,73203', '0,03806, 0,73112', '0,038062, 0,73021', '0,038064, 0,72931', '0,038065, 0,72842', '0,038067, 0,72754', '0,038069, 0,7266' ] # Convert data to list of X-Y for x in list(chunks(input, 8)): # 8 is the number of chunk print(x) # This contains an array of 8 X-Y (e.g ['0,038043, 0,74061', '0,038045, 0,73962', '0,038047, 0,73865', '0,038048, 0,73768', '0,03805, 0,73672', '0,038052, 0,73577', '0,038053, 0,73482', '0,038055, 0,73388']) ... you could add your logic to save data to csv. A: If you have a generic batcher that will work on an iterable, you can use it directly on the file object to read lists of up to 4 lines. For example: def batcher(iterable, n): while True: vals = [] for i in range(n): try: vals.append(next(iterable)) except StopIteration: if vals: yield vals return yield vals with open("input.txt") as f1: with open("output.txt", "w") as f2: for lines in batcher(f1, 4): f2.write(' '.join((l.replace("\n", "") for l in lines)) + '\n') A: import itertools #i = 0 j = 0 for k in range (1,14): print 'k =',k with open("deflag_G{k}.inp".format(k=k)) as f1: with open("deflag_G_{k}.inp".format(k=k),"w") as f2: #lines = f1.readlines() for i, line in enumerate(f1): print i j = j + 1 print j b = line.split()[0] s = float(b) #print "b:", b d = line.split()[1] e = float(d) if j == 8: j = 0 # ('%s'%s + ' , ' + '%e'%e + '\n') f2.write(line.rstrip('\n') + ","+ '\n') else: print(repr(line)) #if line.startswith(searchquery): f2.write(line.rstrip('\n') + ", " ) #f2.write('%s'%listc + "\n") # i = i + 1 #else : # i = i+1 #os.close(f1) f1.close() f2.close()
{ "language": "en", "url": "https://stackoverflow.com/questions/62213917", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Seaborn Plot doesn't show up I am creating a bar chart with seaborn, and it's not generating any sort of error, but nothing happens either. This is the code I have: import pandas import numpy import matplotlib.pyplot as plt import seaborn data = pandas.read_csv('fy15crime.csv', low_memory = False) seaborn.countplot(x="primary_type", data=data) plt.xlabel('crime') plt.ylabel('amount') seaborn.plt.show() I added "seaborn.plt.show() in an effort to have it show up, but it isn't working still. A: You should place this line somewhere in the top cell in Jupyter to enable inline plotting: %matplotlib inline A: It's simply plt.show() you were close. No need for seaborn A: I was using PyCharm using a standard Python file and I had the best luck with the following: * *Move code to a Jupyter notebook (which can you do inside of PyCharm by right clicking on the project and choosing new - Jupyter Notebook) *If running a chart that takes a lot of processing time it might not have been obvious before, but in Jupyter mode you can easily see when the cell has finished processing.
{ "language": "en", "url": "https://stackoverflow.com/questions/33620940", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Logger level change for multi-tenant application as well as Package/Class logger level here we have a use cases, we are working on a web application that will host multiple companies (tenant). Currently, we have added company-specific log separation using MDC. It will separate the log files per company. We want the flexibility to change the logger level at runtime for a company (tenant) specific along with package/class logger level change, as we are getting a bulk number of unwanted logs in those files. Can anyone help me with this? We have achieved it partially either for the Company or Package level. · Company-specific logger level change using Turbo Filter. · Package/Class level using Admin Centre (using Actuator endpoints) Our question is if there is any way to change the logger level at run-time for a company-specific along with package/class. Eg: As Our application is Hosted for two companies ACOMP & BCOMP. Our requirement is ACOMP should log at INFO as root logger level, also user can set few packages like com.test.samplepackage to DEBUG level. Similarly, BCOMP should log at DEBUG as root logger level, also user can set few packages like com.test.samplepackage to ERROR level. Can anyone help me with this?
{ "language": "en", "url": "https://stackoverflow.com/questions/74992625", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Separate the elements I extracted from a web page by columns and print them in csv with python I am starting to learn Python, I have this code which works fine for web scraping, I already have the info that I want and I am sending that data to a CSV but it prints all the text in just one cell. Can you help me to fix it so I can print each element in a different column? This is my code: from bs4 import BeautifulSoup import csv with open('output_file_name', 'w', newline='') as csv_file: writer3 = csv.writer(csv_file, delimiter=';') file4 = open('hola4.csv', 'w', newline='') writer4 = csv.writer(file4) class Table: def __init__(self, driver): self.driver = driver def get_column_info(self): column_info = [] columns = self.driver.find_elements_by_xpath("/html/body/div[1]/main/div[2]/div[3]/div/div/div[5]/div[2]/table/thead/tr/th") for column in columns: column_info.append(str(column.text.replace("%",""))) writer2.writerow([column_info]) return column_info def get_results(self, index=None): columns = self.get_column_info() data = {} elements = self.driver.find_elements_by_xpath("//div[@id = 'resumen_mensual']/table/tbody[@id = 'body_tmes' ]/tr[contains(@class, 'ini')]{}" .format("[{}]".format(index) if index else "")) for elementos in elements: prueba = elementos.text.strip() for element in elements: current_index = elements.index(element) + 1 if not index else index parsed_data = {} for column in columns: value = element.find_element_by_xpath("//div[@id = 'resumen_mensual']/table/tbody[@id = 'body_tmes' ]/tr[contains(@class, 'ini')][{}]" "/td[{}]" .format(current_index,columns.index(column) + 1)).text parsed_data.update({column: str(value)}) data.update({current_index: parsed_data}) return data def get_number_of_results(self): return len(self.driver.find_elements_by_xpath("//div[@id = 'resumen_mensual']/table/tbody[@id = 'body_tmes' ]/tr[contains(@class, 'ini')]")) if "__main__" == __name__: table = Table(driver) writer4.writerow([table.get_column_info()]) writer3.writerow([table.get_results()]) table = Table(driver) print(table.get_column_info()) I have this as a result if I run it: ['DÍA', 'T. MEDIA', 'T. MÁX', 'T. MÍN', 'V. MEDIA VIENTO', 'RACHAS MÁX', 'PRESIÓN MEDIA', 'LLUVIA'] and in csv: A: I don't think you need writer2.writerow([column_info]). Set delimiters to \t (delimiter='\t'). Instead of: writer4.writerow([table.get_column_info()]) writer3.writerow([table.get_results()]) do: for info in table.get_column_info(): writer4.writerow(info) for result in table.get_results(): writer3.writerow(result)
{ "language": "en", "url": "https://stackoverflow.com/questions/63802047", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to create regexp which select digits between ()? I have a lot of string which can contain a digit sequence between () like: Some text 123 (some text in brackets, may contain digits) (12345678) Some text 123 - is required part (some text in brackets, may contain digits) - is not required (12345678) - is not required and must be deleted. Real exmple: "Project name - part name (stage2) (123123)" I have next regexp [(\d)] but it will delete "(2)" from (stage2) and "(123123)". I need to delete ONLY "(123123)". How I can modify my regexp for this? A: @Wiktor Stribizew is right. replace [(\d)] with \(\d+\) test it here: https://regex101.com/ A: I solve this problem, correct regexp is [ ][(][\d]*[)]
{ "language": "en", "url": "https://stackoverflow.com/questions/63303163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Handling the layout dynamically Below is the code I tried: <script type="text/javascript"> Ext.require(['*']); Ext.onReady(function() { Ext.Loader.setConfig({ enabled: true }); var totalScreenWidth = screen.availWidth; var totalScreenHeight = screen.availHeight; Ext.QuickTips.init(); var viewport = Ext.create('Ext.ViewPort', { id: 'border-example', layout: 'border', items: [ Ext.create('Ext.Component', { region: 'north', height: totalScreenHeight * 0.05, autoEl: { tag: 'div', html: '<p><center>UI Demo</center></p>' } }), { region: 'west', stateId: 'navigation-panel', id: 'west-panel', title: 'Tree View', split: true, width: totalScreenWidth * 0.2, collapsible: true, animCollapse: true, xtype: 'tabpanel', dockedItems: [{ dock: 'top', xtype: 'toolbar' }], minSize: 175, maxSize: 400, margin: '0 5 0 0', activeTab: 1, tabPosition: 'bottom', items: [{ title: 'Tree View', autoScroll: true }, { title: 'Graphical View', autoScroll: true }] }, Ext.widget('tabpanel', { id: 'tabWidgetPanel', region: 'center', items: [{ contentEl: 'Tabs1', title: 'Tab1', }, { contentEl: 'Tabs2', title: 'Tab2', }] })] }); ext.get("hideit").on('click', function() { var w = Ext.getCmp('west-panel'); w: collapsed ? w.expand() : w.collapse(); }); }); </script> When the west navigation panel is minimised, then the tabWidgetPanel is also moving towards left leaving the right side of the empty screen. What I want is when the west navigation panel is collapsed, I want the tabWidgetPanel to increase in size and occupy the entire screen. A: Remove the renderTo from it, add region: 'center', remove height and remove width. The Region can't adjust when you define this. You are also writing reion: 'west'.
{ "language": "en", "url": "https://stackoverflow.com/questions/12540640", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Remove duplicate spaces from string except new line character (\n) in Python I have a string and I want to remove duplicate spaces from that. But my string has a new line character \n and after doing this, this character also is deleted. Output of this: s = 'A B C D \n EF G' print(s) s = " ".join(s.split()) print(s) is as follows: A B C D EF G ------------ A B C D EF G But I do not want to remove this character. The desired output: A B C D EF G A: use filter. a='A B C D \n EF G' b=" ".join(list(filter(None,a.split(" ")))) print(b) A: You could use a pattern to match 2 or more whitespace chars without the newline, and in the replacement use a single space. [^\S\r\n]{2,} Regex demo | Python demo For example import re s = 'A B C D \n EF G' print(re.sub(r"[^\S\r\n]{2,}", " ", s)) Output A B C D EF G A: Try using regex. Split the string by '\n' and then combine multiple whitespace into 1 whitespace. import re comb_whitespace = re.compile(r"\s+") for i in s.split('\n'): print(comb_whitespace.sub(" ", i)) A B C D EF G A: It’s need to add \n split s = 'A B C D \n EF G' print(s) s = " ".join(s.split()) s = " ".join(s.split('\n')) print(s) Outs A B C D EF G A B C D EF G
{ "language": "en", "url": "https://stackoverflow.com/questions/64243383", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Cannot read file in uploaded path(used by another process) I upload a csv file to AppData folder in project solution and read the content with the code below: using (var fs = new FileStream(Path.Combine(uploadPath, name), chunk == 0 ? FileMode.Create : FileMode.Append)) { var buffer = new byte[fileUpload.InputStream.Length]; fileUpload.InputStream.Read(buffer, 0, buffer.Length); fs.Write(buffer, 0, buffer.Length); var reader = new StreamReader(System.IO.File.OpenRead(fs.Name));// I check path and file itself in AppData folder. its ok List<string> listA = new List<string>(); List<string> listB = new List<string>(); while (!reader.EndOfStream) { var line = reader.ReadLine(); var values = line.Split(';'); } But it throws IOException with message: The process cannot access the file 'c:\path\App_Data\o_1amtdiagc18991ndq1c1k1c2v1bama.csv' because it is being used by another process. I couldnt get it how and why it's being used I created this file from original uploaded file with unique name.. A: I couldnt get it how and why its being used Because you've not closed the stream that's writing to it: using (var fs = new FileStream(Path.Combine(uploadPath, name), ...) I would suggest you write the file, close the using statement so the handle can be released, then read it: string fullName = Path.Combine(uploadPath, name); using (var fs = ...) { // Code as before, but ideally taking note of the return value // of Stream.Read, that you're currently ignoring. Consider // using Stream.CopyTo } // Now the file will be closed using (var reader = File.OpenText(fullName)) { // Read here }
{ "language": "en", "url": "https://stackoverflow.com/questions/38202592", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Removing duplicates from DataFrame in R I have this data UserID Quiz_answers Quiz_Date 1 `a1,a2,a3`Positive 26-01-2017 1 `a1,a4,a3`Positive 26-01-2017 1 `a1,a2,a4`Negative 28-02-2017 1 `a1,a2,a3`Neutral 30-10-2017 1 `a1,a2,a4`Positive 30-11-2017 1 `a1,a2,a4`Negative 28-02-2018 2 `a1,a2,a3`Negative 27-01-2017 2 `a1,a7,a3`Neutral 28-08-2017 2 `a1,a2,a5`Negative 28-01-2017 I want to remove rows that are duplicates: Rules for rows being duplicates are: * *The word occuring after backtick(`) in Quiz_answers column are same *For such rows if the userID and Quiz_Date column values are also same then the row is duplicate` UserID<-c(1,1,1,1,1,1,2,2,2) Quiz_answers<-c("`a1,a2,a3`Positive","`a1,a4,a3`Positive","`a1,a2,a4`Negative","a1,a2,a3`Neutral","`a1,a2,a4`Positive","`a1,a2,a4`Negative","`a1,a2,a3`Negative","`a1,a7,a3`Neutral","`a1,a2,a5`Negative") Quiz_Date<-as.Date(c("26-01-2017","26-01-2017","28-02-2017","30-10-2017","30-11-2017","28-02-2018","27-01-2017","28-08-2017","28-01-2017"),'%d-%m-%Y') data<-data.frame(UserID,Quiz_answers,Quiz_Date) -I have written the below code data.removeDuplicates<- function(frames) { apply(frames[ ,c(grep("UserID", colnames(data)),grep("Quiz_answers", colnames(data)),grep("Quiz_Date", colnames(data)))],1,function(slice){ Outcome<-paste0("`",tail(strsplit(slice[2],split="`")[[1]],1)) cat("\n\n Searching for records: ",slice[1],Outcome,slice[3]) data<<-data[!( data$UserID == slice[1] & paste0("`",sapply(strsplit(as.character(data[,2]),'`'), tail, 1)) == c(Outcome) & data[,3]==c(slice[3])), ] }) print(frames) } data.removeDuplicates(data) print(data) [1] UserID Quiz_answers Quiz_Date <0 rows> (or 0-length row.names) I was expecting output UserID Quiz_answers Quiz_Date 1 `a1,a2,a3`Positive 26-01-2017 1 `a1,a2,a4`Negative 28-02-2017 1 `a1,a2,a3`Neutral 30-10-2017 1 `a1,a2,a4`Positive 30-11-2017 1 `a1,a2,a4`Negative 28-02-2018 2 `a1,a2,a3`Negative 27-01-2017 2 `a1,a7,a3`Neutral 28-08-2017 2 `a1,a2,a5`Negative 28-01-2017 Only the second row should get deleted from the DataFrame as per the rule its the only row which satisifies the condition of being duplicate. What am i doing wrong? A: Give this a try Your data df <- read.table(text="UserID Quiz_answers Quiz_Date 1 `a1,a2,a3`Positive 26-01-2017 1 `a1,a4,a3`Positive 26-01-2017 1 `a1,a2,a4`Negative 28-02-2017 1 `a1,a2,a3`Neutral 30-10-2017 1 `a1,a2,a4`Positive 30-11-2017 1 `a1,a2,a4`Negative 28-02-2018 2 `a1,a2,a3`Negative 27-01-2017 2 `a1,a7,a3`Neutral 28-08-2017 2 `a1,a2,a5`Negative 28-01-2017", header = TRUE, stringsAsFactors=FALSE) Solution & output library(dplyr) ans <- df %>% mutate(grp = sub(".*`(\\D+)$", "\\1", Quiz_answers)) %>% group_by(grp, UserID, Quiz_Date) %>% slice(1) %>% ungroup() %>% select(-grp) %>% arrange(UserID, Quiz_Date) # A tibble: 8 x 3 # UserID Quiz_answers Quiz_Date # <int> <chr> <chr> # 1 1 `a1,a2,a3`Positive 26-01-2017 # 2 1 `a1,a2,a4`Negative 28-02-2017 # 3 1 `a1,a2,a4`Negative 28-02-2018 # 4 1 `a1,a2,a3`Neutral 30-10-2017 # 5 1 `a1,a2,a4`Positive 30-11-2017 # 6 2 `a1,a2,a3`Negative 27-01-2017 # 7 2 `a1,a2,a5`Negative 28-01-2017 # 8 2 `a1,a7,a3`Neutral 28-08-2017 A: You can use sqldf package likes the following. First, find the group of Positive, Negative, and Neutral. Then, filter the duplicate using group by: require("sqldf") result <- sqldf("SELECT * FROM df WHERE Quiz_answers LIKE '%`Positive' GROUP BY UserID, Quiz_Date UNION SELECT * FROM df WHERE Quiz_answers LIKE '%`Negative' GROUP BY UserID, Quiz_Date UNION SELECT * FROM df WHERE Quiz_answers LIKE '%`Neutral' GROUP BY UserID, Quiz_Date") The result after running is: UserID Quiz_answers Quiz_Date 1 1 `a1,a2,a3`Neutral 30-10-2017 2 1 `a1,a2,a4`Negative 28-02-2017 3 1 `a1,a2,a4`Negative 28-02-2018 4 1 `a1,a2,a4`Positive 30-11-2017 5 1 `a1,a4,a3`Positive 26-01-2017 6 2 `a1,a2,a3`Negative 27-01-2017 7 2 `a1,a2,a5`Negative 28-01-2017 8 2 `a1,a7,a3`Neutral 28-08-2017 A: Here's a two line solution, using only base R: data[,"group"] <- with(data, sub(".*`", "", Quiz_answers)) data <- data[as.integer(rownames(unique(data[, !(names(data) %in% "Quiz_answers") ]))), !(names(data) %in% "group")]
{ "language": "en", "url": "https://stackoverflow.com/questions/46959590", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Python: Finding dictionaries in a list that have some keys of another list of dictionaries I have two list of dictionaries that are quite long. I want to find dictionaries in second list that have the keys in the first list of dictionaries and separate them based on another key. Some of the keys in the list one are values in the list two. Here is an example: students = [{'123': [{'course1': 2}, {'course2': 2}]}, {'124': [{'course1': 3}, {'course2': 4}]}, {'125': [{'course1': 24}, {'course2': 12}]}, {'126': [{'course1': 2}, {'course2': 24}]}, ...] finals = [{'student_number':'123', 'exam':'passed',...}, {'student_number':'124', 'exam':'ungraded',...}, {'student_number':'125', 'exam':'failed',...}, ...] Finding student_numbers in finals that exist in students and separate them based on 'exam' key: # Students who passed exam, 'exam' = 'passed' passed_students = ['123', ...] # Other Students other_students = ['124', '125', ...] A: I'm not too sure that your data is in the best format, but given what you have the following code will work: students = [{'123': [{'course1': 2}, {'course2': 2}]}, {'124': [{'course1': 3}, {'course2': 4}]}, {'125': [{'course1': 24}, {'course2': 12}]}, {'126': [{'course1': 2}, {'course2': 24}]}] finals = [{'student_number':'123', 'exam':'passed'}, {'student_number':'124', 'exam':'ungraded'}, {'student_number':'125', 'exam':'failed'}] studentIDs = [i.keys()[0] for i in students] passed_students=[] other_students=[] for row in finals: snum = row['student_number'] status = row['exam'] if status=='passed' and snum in studentIDs: passed_students.append(snum) elif status!='passed' and snum in studentIDs: other_students.append(snum) else: print 'Student ID {0} not found in list.'.format(snum) A: A little exercise for list comprehensions: students = [{'123': [{'course1': 2}, {'course2': 2}]}, {'124': [{'course1': 3}, {'course2': 4}]}, {'125': [{'course1': 24}, {'course2': 12}]}, {'126': [{'course1': 2}, {'course2': 24}]}] finals = [{'student_number':'123', 'exam':'passed',}, {'student_number':'124', 'exam':'ungraded',}, {'student_number':'125', 'exam':'failed',},] # Extract student id numbers. student_ids = set( student_data.keys()[0] for student_data in students) # Restrict finals to the students that exist in students. students_with_finals = [ final for final in finals if final['student_number'] in student_ids] passed_students = [ final['student_number'] for final in students_with_finals if final['exam'] == 'passed'] other_students = [ final['student_number'] for final in students_with_finals if final['exam'] != 'passed'] print('Passed students: {}'.format(passed_students)) print('Other students: {}'.format(other_students)) Result: Passed students: ['123'] Other students: ['124', '125'] It looks like that the data structures could be simplified by using dictionaries with the student ids as keys: students = { '123': [{'course1': 2}, {'course2': 2}], '124': [{'course1': 3}, {'course2': 4}], '125': [{'course1': 24}, {'course2': 12}], '126': [{'course1': 2}, {'course2': 24}], } finals = { '123': {'exam':'passed', 'points': 100}, '124': {'exam':'ungraded'}, '125': {'exam':'failed'}, } A: >>> students = {'123':{'name':'Bonnie','course_1':2, 'course_2':2}, ... '124':{'name':'Jerry', 'course_1':3, 'course_2':4}, ... '125':{'name':'Bob', 'course_1':24, 'course_2':12}, ... '126':{'name':'Jill', 'course_1':2, 'course_2':24}} >>> finals = [{'num':'123', 'exam':'passed'}, ... {'num':'124', 'exam':'ungraded'}, ... {'num':'125', 'exam':'failed'}] >>> student_results = {'passed':[], 'ungraded':[], 'failed':[]} >>> >>> for final in finals: ... student_results[final['exam']].append(students[final['num']]) >>> >>> # Print student results. >>> for result in ['passed', 'ungraded', 'failed']: ... print "Students %s:" % result ... for student in student_results[result]: ... print " " + student['name'] ... Students passed: Bonnie Students ungraded: Jerry Students failed: Bob
{ "language": "en", "url": "https://stackoverflow.com/questions/43567159", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Need to check the format of a string in c# I have a string that needs to be the following format: XX999900. XX has to be only character no decimal followed by 6 digits. So I thought of using regex in the following way: string sPattern = @"^\\[A-z]{2}\\d{6}$"; indexNumber = "ab9999.00"; if (Regex.IsMatch(indexNumber, sPattern) { // do whatever } It fails. Can somebody tell me what is wrong? A: I don't believe [A-z] is a valid character class. You certainly do not need \\ when using @. Try this: @"^[a-zA-Z]{2}\d{6}$" If you need the format to have 4 numerals followed by a . then two more numerals, try this: @"^[a-zA-Z]{2}\d{4}\.\d{2}$" (Note that for .NET, \d will match numerals in any script, so you may want to replace it with [0-9] if you want to only match those) A: You have way too many escape characters. Try: string sPattern = @"^[a-zA-Z]{2}\d{6}$"; A: A-z isn't valid (mixed case), and you don't have 6 consecutive digits. You have 4, a decimal, and then 2 more. Try ^[a-zA-Z]{2}\d{4}.\d{2}$ A: It fails because the value you are testing as a decimal in it and your regex pattern does not. Plus, your regex pattern is going to look at the entire string. That is ^ says start at the beginning of the string and $ says the end of the string. If you only want a "starts with", then drop the $ at the end of the pattern.
{ "language": "en", "url": "https://stackoverflow.com/questions/11870610", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Django NoReverseMatch I can't understand what's wrong? I tried to make a detail page of one item, like in example on http://tutorial.djangogirls.org/en/extend_your_application/index.html and It doesn't work in my project, but In exercises everything was good. Error message: NoReverseMatch at / Reverse for 'events.views.event_detail' with arguments '()' and keyword arguments '{u'pk': 3}' not found. 1 pattern(s) tried: ['$event/(?P<pk>[0-9]+)/$'] HTML(fragment) <div class="col-xs-6"><a class="btn btn-primary" href="{% url 'events.views.event_detail' pk=event.pk %}">Read more</a></div> </div> settings.py ROOT_URLCONF = 'mysite.urls' app urls.py from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^$', views.events_list), url(r'^event/(?P<pk>[0-9]+)/$', views.event_detail), ] app views.py from django.shortcuts import render, get_object_or_404 from django.utils import timezone from .models import Event def events_list(request): events = Event.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'events/events_list.html', {'events': events}) def event_detail(request, pk): event = Event.objects.get(pk=pk) return render(request, 'events/event_detail.html', {'event': event}) A: You haven't shown your mysite.urls, but from the error message it looks like you have done something like this: (r'^events/$', include('events.urls')), You need to drop the terminating $, since that means the end of the regex; nothing can match after that. It should be: (r'^events/', include('events.urls')), Note that you should also give your event URLs names, to make it easier to reference: url(r'^$', views.events_list, name='events_list'), url(r'^event/(?P<pk>[0-9]+)/$', views.event_detail, name='event_detail'), so that you can now do: {% url 'event_detail' pk=event.pk %}
{ "language": "en", "url": "https://stackoverflow.com/questions/31523791", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Can an AWS EventBridge Rule target a Kinesis Firehose Delivery Stream in another account? Imagine that there are two AWS accounts - Account-A and Account-B. Account-A has an EventBridge Event Bus and Account-B has a Kinesis Data Firehose. Is it possible for the event bus in Account-A to have a rule that targets the firehose in Account-B? A: At this time, no, the only type of cross-account resource you can target in an EventBridge Rule is another EventBridge bus. This is not really clearly stated anywhere I found while investigating the same question, but you can infer it from the PutTargets docs (since Event bus is the only target listed as supported in another account), or if you try it through CloudFormation you'll get an error "Only EventBus targets are allowed on cross-account PutTargets calls"). So currently they intend for you to set up another EventBridge bus in Account-B, and then attach a rule on it to target your firehose. Since there's no charge to receive events (the sender pays), this seems perfectly reasonable. This could all change of course as AWS routinely enhances their services. There's a nice diagram of this sort of cross-account event forwarding on Simplifying cross-account access with Amazon EventBridge resource policies:
{ "language": "en", "url": "https://stackoverflow.com/questions/69442280", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Compilation vs Execution in SAS This question was discussed on SAS forum, and participants finally agreed to disagree . The issue is simple : SAS assign a missing value to all variables at compile time UNLESS a variable shows up in a sum statement (in this case SAS assigns a value of 0 at compile time ) . Here is my simple proof data test; put _all_; var1+1; var2=5; put _all_; run; Log screen var1=0 var2=. _ERROR_=0 _N_=1 var1=1 var2=5 _ERROR_=0 _N_=1 NOTE: The data set WORK.TEST has 1 observations and 2 variables. var2 was assigned a missing value BUT var1 was assigned 0 because it is part of a sum statement (I believe so ) My question is WHY ? I was pretty sure that SAS assignes missing values to all variables at compilation . Why does it make an exception to a variable that will show up in a sum statement ? Are there any other exceptions ? A: I wouldn't call it sum statement. The statement var1+1; is equivalent of retain var1 0; var1 = var1 + 1; Nor the 'long' sum statement var1 = var1 + 1; nor var1 = sum(var1, 1); itself would do the RETAIN behavior nor initialization to zero. So to answer the question: initialization to zero is part of RETAIN behavior implicitly requested by a + b; syntax for variable a. I can't think of other exceptions.
{ "language": "en", "url": "https://stackoverflow.com/questions/24318484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Crashing in a for loop I'm trying to write to a text file. I can write fine when I don't use my for loop, but when I implement it to write all of my array to the file it crashes. Here's my code: void writeFile(void) { char *fileName[30]; cout << "enter a filename"; cin >> *fileName; ofstream myfile; myfile.open (*fileName); int p; for(p = 0; p <= i; p++) { myfile << right << setw(4) << setfill('0') << packet[i].getSource() << ":"; myfile << right << setw(4) << setfill('0') << packet[i].getDest() << ":"; myfile << right << setw(4) << setfill('0') << packet[i].getType() << ":"; myfile << right << setw(4) << setfill('0') << packet[i].getPort() << endl; } Any ideas where I'm going wrong? A: fileName is an array of 30 uninitialized pointers to char. *fileName is the same as filename[0], which is an uninitialized pointer to a char. You cannot use this pointer for anything but assigning it a valid value. You are not doing that, though, and instead you're trying to read data to it, with predictably catastrophic consequences. In short, you shouldn't be using any pointers in C++ at all, and instead use an std::string for your situation: std::string fileName; if (!(std::cin >> fileName)) { /* I/O error, die */ } // ... (Perhaps what you meant to do is to make fileName an array of 30 chars: char fileName[30];. But don't do that. Even though it might work, it's very terrible.) A: There is another thing slightly dodgy here: for(p = 0; p <= i; p++) you probably want for(p = 0; p < i; p++) so that you don't try to dereference off the end of your array probably better to write for (int p = 0; p != i; ++p) This is the recommended form according to Moo and Koenig: http://www.drdobbs.com/cpp/184402072 I would also not use char * to read from a cin, use std::string to store your string and inputs, you do not need to new the memory if it is not needed outside the scope of your main writeFile function. Strings support dynamic resizing also so you don't need to initialise it to any size, here is the first example I googled to help you understand A: Why are you using the "C way" to store your file name? And you're using it the wrong way: char**. It would be easier to just declare: std::string fileName; while(!std::cin >> fileName); ofstream myfile(fileName.c_str()); You also are using i inside of your loop but are iterating over p, I think that's not what you want to do ...
{ "language": "en", "url": "https://stackoverflow.com/questions/10474741", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: VS 2012 breaks on wrong thread I have a program which is multi-threaded, and in which I've set a number of breakpoints. Frequently, when the program hits a breakpoint, I see a line of code highlighted in green, indicating that it is the next line of code to be executed when the program returns from the current function. However, the breakpoint which has been hit is actually on another thread, in another source file. This line is not highlighted in yellow (or anything else), despite being the thread which actually caused the break. The only way I've found so far to fix the problem is to stop the program executing, clean the solution and rebuild the entire solution. This is about 70% effective, but I frequently have to do it several times. Additional info which may be relevant: The program is written in C#, and the code in question is a WCF service being called by an MVC web site. All this is running under IIS7 on my local machine. A: You can go from one thread to the other in debug. Debug \ Windows \ Threads [ctrl-alt-h] You'll have the list of thread. Be carefull, when stepping inside the code, you might alternate between threads. The best option is to freeze the other threads.
{ "language": "en", "url": "https://stackoverflow.com/questions/13691458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Start Spotify Radio with Android intent I know that you can start a specific song using the following: String uri = "spotify:track:308p4aUi2JKGC0i750B2JM"; Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri)); startActivity(intent); And I know that you can start a radio channel on the desktop app by searching for: spotify:radio:track:308p4aUi2JKGC0i750B2JM However when I try to start the radio by doing something similar: String uri = "spotify:radio:track:308p4aUi2JKGC0i750B2JM"; Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri)); startActivity(intent); Nothing happens... Does anyone know how to do this? Is it even possible? Thanks A: Disclaimer: I work for Spotify Upon examination of the Android app's source code, it seems that launching the radio is done with an internal intent. In other words, via an unpublished URI scheme which is unpublished because it is subject to change between versions. I'm not sure if this is a feature which is planned for the mobile clients, though I'll certainly ask around internally about it. I would encourage making a thread on the community forums (they do get read) pushing for it as well. Update: Apparently the reason for using an internal URI scheme is that when the radio feature was developed for the Android app, the URI scheme was not completely finalized. The team seems interested in fixing this behavior, and I've filed a JIRA ticket as a reminder for them.
{ "language": "en", "url": "https://stackoverflow.com/questions/14328048", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: 'Permission' instance expected, got ... Permission instance? I try to write data migration code for custom user type but when I try to apply migration I get this: TypeError: 'Permission' instance expected, got <Permission: my_app | Some Text | Can add some_model> Looks weird to me. Isn't that a Permission instance? Here is my custom user model: class Employee(AbstractUser): middle_name = models.CharField(max_length=60, null=True, blank=True) And here is a piece of code in migration which raises this error (I guess so): for user in User.objects.all(): employee = orm.Employee.objects.create( id=user.id, username=user.username, first_name=user.first_name, last_name=user.last_name, password=user.password, email=user.email, is_active=user.is_active, is_superuser=user.is_superuser, last_login=user.last_login, date_joined=user.date_joined, ) for perm in user.user_permissions.all(): employee.user_permissions.add(perm) A: When you create datamigration don't forget to use --freeze argument for all apps you somehow use in this migration, in my case it's auth: python manage.py datamigration my_app --freeze auth Then use orm['auth.User'].objects.all() instead of User.objects.all(). A: I am using user model as from django.contrib.auth.models import AbstractUser class MyProjectUser(AbstractUser): ... and i create migration for add new permissions to some groups of users: # -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import DataMigration from django.db import models permissions_codenames = ( 'can_action_1', ... 'can_action_10', ) class Migration(DataMigration): def forwards(self, orm): "Write your forwards methods here." permissions = orm['auth.Permission'].objects.filter(codename__in=permissions_codenames) for user in orm.MyProjectUser.objects.filter(groups__name__in=('GroupName1', 'GroupName2')): user.user_permissions.add(*permissions) def backwards(self, orm): "Write your backwards methods here." permissions = orm['auth.Permission'].objects.filter(codename__in=permissions_codenames) for user in orm.MyProjectUser.objects.filter(groups__name__in=('GroupName1', 'GroupName2')): user.user_permissions.remove(*permissions) models = { ... } complete_apps = ['users'] symmetrical = True in complete_apps = ['users'] 'users' is app name, where located MyProjectUser class.
{ "language": "en", "url": "https://stackoverflow.com/questions/21232978", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Position items below each other in one anchor item How do you position items below each other in a single<a></a> using angular material toolbar? I want the icon above the user name and both items need to be centered in the middle and not next to each other as in the stackblitz below: https://stackblitz.com/edit/angular-djay7v A: You are almost where near to answer Try below code in sidenav-autosize-example.html <mat-icon mat-list-icon style="font-size: 150px; height: 150px;color: rgba(244, 92, 27, 0.356);margin: 0 auto;">account_circle</mat-icon> <span style="position:relative;top:75px;right:20px">Current Username</span> <a mat-list-item href="#">Link 2</a> <a mat-list-item href="#">Link 3</a> </mat-nav-list> Live Demo Hope it will solve your problem
{ "language": "en", "url": "https://stackoverflow.com/questions/52914957", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: itunes file share restore deleted files My app uses iTunes File Share. I used the code to delete a single file: It worked the first time. On the second try, however, iTunes showed a empty share directory. It turns out all data files are gone. Can I recover those data files from the iPad? Thanks - (void) deleteFileFromDisk: (NSString*) fileName { if([self fileExists: fileName]) { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) ; NSString *documentsDirectory = [paths objectAtIndex: 0]; NSString* theFile = [documentsDirectory stringByAppendingPathComponent: fileName]; NSError *error; [[NSFileManager defaultManager] removeItemAtPath: theFile error: &error]; A: There's no "restore" feature on the iPad. But in all probability there's nothing to worry about. There's nothing about your code that would delete multiple files. It would delete just that file from the Documents directory that you supplied the name of as fileName. If you didn't call deleteFileFromDisk: multiple times, you didn't delete multiple files. Perhaps at some point you deleted the app. That would delete its entire sandbox and thus would take with it anything in the Documents directory. That sort of thing is perfectly normal during repeated testing.
{ "language": "en", "url": "https://stackoverflow.com/questions/30181626", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Getting "Expected 2 arguments but found 1" when getting the intExtra on the Activity result. Not sure what's wrong here I am doing the homework exercise from googles "Android fundamentals codelab" here -> https://codelabs.developers.google.com/codelabs/android-training-create-an-activity/index.html?index=..%2F..android-training#11 and I keep getting this: Expected 2 arguments but found 1 error when I try to get the intExtra on the Activity result method. I'll post the code below @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == TEXT_REQUEST) { if (resultCode == RESULT_OK) { count = data.getIntExtra(HelloActivity.EXTRA_REPLY); mTextView.setText(String.valueOf(count)); } } } The error occurs on line 40 (count = data.getIntExtra(HelloActivity.EXTRA_REPLY);). I know there are other questions here that ask something similar but I am a beginner on Android and java in general so it is difficult for me to understand those solutions in a way that is useful for my problem. a Layman's terms explanation would also be greatly appreciated. thank you! A: The method you are using requires 2 parameters: getIntExtra(String name, int defaultValue) So, just add a second int parameter, specifying the default value, in case the name is not found, something like this: int defaultValue = -1; count = data.getIntExtra(HelloActivity.EXTRA_REPLY, defaultValue);
{ "language": "en", "url": "https://stackoverflow.com/questions/63871435", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to form two sql insert statements from the JSON array I have got a JSON Array as shown below [{ "link_video": "123" }, { "link_video": "456" }] By parsing i want to create two insert sql as Insert into mytable values (123,456); Insert into mytable values (456,123);. I have started as shown below , could you please tell me how can i form two sql public class Testeee { public static void main(String[] args) throws JSONException, SQLException { String array = "[{\"link_video\":\"123\"},{\"link_video\":\"456\"}]"; JSONArray array_jsn = new JSONArray(array); PreparedStatement PstmtdeleteforLinkVideos = null; Connection con; String sql = "Insert into mytable values (?,?)"; con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sonoo", "root", "root"); PstmtdeleteforLinkVideos = con.prepareStatement(sql); for (int i = 0; i < array_jsn.length(); i++) { String id = array_jsn.getJSONObject(i).getString("link_video"); PstmtdeleteforLinkVideos.setInt(1,Integer.parseInt(id)); PstmtdeleteforLinkVideos.addBatch(); } PstmtdeleteforLinkVideos.executeBatch(); } } A: Your query is expecting two values. But your code below is assigning only one value. for (int i = 0; i < array_jsn.length(); i++) { String id = array_jsn.getJSONObject(i).getString("link_video"); PstmtdeleteforLinkVideos.setInt(1,Integer.parseInt(id)); PstmtdeleteforLinkVideos.setInt(2,Integer.parseInt(id)); PstmtdeleteforLinkVideos.addBatch(); } you have to set parameter index 2 also. Then it will work.
{ "language": "en", "url": "https://stackoverflow.com/questions/42643369", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: PyCharm console keeps "Getting Documentation from Python Runtime" I'm working (with pandas) in a Python Console in PyCharm, and while I'm typing commands it keeps hanging for 10-20 seconds while "Getting Documentation from Python Runtime." How do I prevent it from doing this?
{ "language": "en", "url": "https://stackoverflow.com/questions/75176820", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AJAX and Javascript: program leaves main page at form submission I'm just learning AJAX, so bear with me. I'm putting together a small program using AJAX that adds and retrieves information to and from a database using an HTML/Javascript file and a PHP file. I've tried several renditions but am not having any luck getting the page to stay on the main page and just resetting the form with a message indicating error or success. The PHP file is set up using mysqli to process the submission of a text field and a file and then echo that message. I'm using JQuery Cookbook as a guide for my latest version, but still the main page leaves and opens the PHP file in the browser, which of course is blank. However, it is adding a new row to the database, so at least that's working. I'm using PHPStorm and Firebug. Any thoughts on why my code isn't working? <!DOCTYPE html> <html> <head> <script src="jquery.min.js"></script> <script src="jquery.validate.js"></script> <script> $('addForm').validate(); $('addForm').submit(function(event){ event.preventDefault(); $('input[name="usingAJAX"]', this).val('true'); var $this=$(this); var url=$this.prop('action'); var dataToSend = $this.serialize(); var callback = function(dataReceived) { $this.hide(); //result message $('body').append(dataReceived) }; var typeOfDataToReceive = 'html'; $.get(url, dataToSend, callback, typeOfDataToReceive) }); </script> </head> <body> <form id="addForm" action="addActorInfo.php" enctype="multipart/form-data"> <input type="hidden" name="usingAJAX" value="false"/> <label for="aname">Actor Name: </label> <input type="text" name="aname" id="aname" class=required/> <br> <br> <label for="aimage">Actor Photo: </label> <input id="aimage" type="file" name="aimage" class="required"> <br> <br> <input type="submit" value="ADD"/> </form> </body> </html> A: A few issues. * *Your form's selector, $('addForm'), is missing the # as everyone is pointing out. *You're missing the $(document).ready() function since your form does not yet exist when the JavaScript is called, this is required. *You don't need another submit handler since the jQuery Validate plugin has a submitHandler callback function built in. As per docs, "The right place to submit a form via Ajax after it validated." Something like this: (assuming that the OP's .ajax function is already correct.) <script src="jquery.min.js"></script> <script src="jquery.validate.js"></script> <script> $(document).ready(function() { $('#addForm').validate({ //other options, submitHandler: function (form) { // your ajax code return false; // <-- stop form redirection since you used ajax } }); }); </script> A: There are several problems, most discussed in comments already: * *Your selector when you set up the "submit" handler was wrong. It should have been $('#addForm') *You're trying to use $.get() to process a form that includes a "file" <input> element. That can't be done. To upload a file, you can either: * *POST your form (has to be POST, not GET) and give it a "target" attribute of a hidden <iframe> element on the page. The response from the server should include JavaScript to update the parent page (the page with the form on it) as appropriate. *Use the HTML5 File API to grab the file contents and then upload via XHR. I've never tried to do this, but here is an older SO question about it.
{ "language": "en", "url": "https://stackoverflow.com/questions/14967262", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: C# How to read a binary file into int[] without a BinaryReader loop? As far as I know, the BinaryReader loop performance is poor. Another method I can think of is to first ReadAllBytes and then Buffer.BlockCopy into int[], but that would result in an additional copy. Is it possible to read a huge binary file directly into int[] efficiently? A: You can use MemoryMarshal.AsBytes to read all data: using var stream = new FileStream(...); var target = new int[stream.Length / 4]; stream.Read(MemoryMarshal.AsBytes(target.AsSpan())); No BinaryReader is used in that case. Be aware of endianness of int representation. This code above might cause problems if the file doesn't match to your hardware. A: If you want to read the array as another type, you can use MemoryMarshal.Cast. using System; using System.Runtime.InteropServices; class Program { public static void Main(string[] args) { byte[] arrayByte = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; Span<int> spanInt = MemoryMarshal.Cast<byte, int>(arrayByte); Console.WriteLine("0x{0:X8}", spanInt[0]); // For little endian it will be 0x44332211. Console.WriteLine("0x{0:X8}", spanInt[1]); // For little endian it will be 0x88776655. } } Another alternative is Unsafe.As. However, there are some problems, such as Length not reflecting the converted type value. I recommend using the MemoryMarshal class. using System; using System.Runtime.CompilerServices; class Program { public static void Main(string[] args) { byte[] arrayByte = { 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88 }; int[] arrayInt = Unsafe.As<byte[], int[]>(ref arrayByte); Console.WriteLine("Length={0}", arrayInt.Length); // 8!? omg... Console.WriteLine("0x{0:X8}", arrayInt[0]); // For little endian it will be 0x44332211. Console.WriteLine("0x{0:X8}", arrayInt[1]); // For little endian it will be 0x88776655. } }
{ "language": "en", "url": "https://stackoverflow.com/questions/75155160", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to get an alias icon WITHOUT the arrow? Using [[NSWorkspace sharedWorkspace] iconForFile:path] for an alias file returns an icon image with an arrow. How can I instead get the icon without the arrow? I don't want this arrow:
{ "language": "en", "url": "https://stackoverflow.com/questions/56087484", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Using boost to generate random numbers between 1 and 9999 How can i used boost library in C++ to generate random numbers between 1 and 9999 A: Did you try googling for "boost random number" first? Here's the relevant part of their documentation generating boost random numbers in a range You want something like this: #include <time.h> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int_distribution.hpp> std::time(0) gen; int random_number(start, end) { boost::random::uniform_int_distribution<> dist(start, end); return dist(gen); } edit: this related question probably will answer most of your questions: why does boost::random return the same number each time?
{ "language": "en", "url": "https://stackoverflow.com/questions/9156186", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-6" }