text
stringlengths
15
59.8k
meta
dict
Q: How to find the length of tuple inside a list? There is a list filled with tuples, like pairs = [('cheese', 'queso'), ('red', 'rojo'), ('school', 'escuela')] How do I find the length of, like, first tuple? len(pairs) returns me 3 and len(pairs[]) returns error. How do I get the length of a tuple inside the list? A: len(pairs[]) raises a SyntaxError because the square brackets are empty: >>> pairs = [('cheese', 'queso'), ('red', 'rojo'), ('school', 'escuela')] >>> pairs[] File "<stdin>", line 1 pairs[] ^ SyntaxError: invalid syntax >>> You need to tell Python where to index the list pairs: >>> pairs = [('cheese', 'queso'), ('red', 'rojo'), ('school', 'escuela')] >>> pairs[0] # Remember that Python indexing starts at 0 ('cheese', 'queso') >>> pairs[1] ('red', 'rojo') >>> pairs[2] ('school', 'escuela') >>> len(pairs[0]) # Length of tuple at index 0 2 >>> len(pairs[1]) # Length of tuple at index 1 2 >>> len(pairs[2]) # Length of tuple at index 2 2 >>> I think it would be beneficial for you to read An Introduction to Python Lists and Explain Python's slice notation.
{ "language": "en", "url": "https://stackoverflow.com/questions/24599207", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to increase numeric value present in a string I'm using this query in vb.net Raw_data = Alltext_line.Substring(Alltext_line.IndexOf("R|1")) and I want to increase R|1 to R|2, R|3 and so on using for loop. I tried it many ways but getting error string to double is invalid any help will be appreciated A: You must first extract the number from the string. If the text part ("R") is always separated from the number part by a "|", you can easily separated the two with Split: Dim Alltext_line = "R|1" Dim parts = Alltext_line.Split("|"c) parts is a string array. If this results in two parts, the string has the expected shape and we can try to convert the second part to a number, increase it and then re-create the string using the increased number Dim n As Integer If parts.Length = 2 AndAlso Integer.TryParse(parts(1), n) Then Alltext_line = parts(0) & "|" & (n + 1) End If Note that the c in "|"c denotes a Char constant in VB. A: An alternate solution that takes advantage of the String type defined as an Array of Chars. I'm using string.Concat() to patch together the resulting IEnumerable(Of Char) and CInt() to convert the string to an Integer and sum 1 to its value. Raw_data = "R|151" Dim Result As String = Raw_data.Substring(0, 2) & (CInt(String.Concat(Raw_data.Skip(2))) + 1).ToString This, of course, supposes that the source string is directly convertible to an Integer type. If a value check is instead required, you can use Integer.TryParse() to perform the validation: Dim ValuePart As String = Raw_data.Substring(2) Dim Value As Integer = 0 If Integer.TryParse(ValuePart, Value) Then Raw_data = Raw_data.Substring(0, 2) & (Value + 1).ToString End If If the left part can be variable (in size or content), the answer provided by Olivier Jacot-Descombes is covering this scenario already. A: Sub IncrVal() Dim s = "R|1" For x% = 1 To 10 s = Regex.Replace(s, "[0-9]+", Function(m) Integer.Parse(m.Value) + 1) Next End Sub
{ "language": "en", "url": "https://stackoverflow.com/questions/53914493", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: mysql: Update android variable from mysql using loop I try to update a string variable with data from a mysql database. Example: String str should grab a value from a mysql db using php. This is done and works perfectly. But str should grab these values every 10 seconds, so it has to run in a loop. And exactly this is the problem. Connecting via httppost and getting entities blocks the UI, so it skip frames. To solve this i used: Services, AsyncTasks and Runnables but always frame skipping. This is the latest thing i tried: public class AsyncStatus extends AsyncTask<String, String, String>{ HttpResponse response; String str; HttpPost httppost; HttpClient httpclient; List<NameValuePair> nameValuePairs; Handler mHandler=null; @Override protected String doInBackground(String... params) { // TODO Auto-generated method stub //Build the connection only once, to save performance getStrFirst(); //Loop started final Runnable mUpdateUI = new Runnable() { public void run() { System.out.println("called"); try { //to avoid "already consumed exceptions" response = httpclient.execute(httppost); //get the content str = EntityUtils.toString(response.getEntity()); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } str = str.replaceAll("\\D", ""); mHandler.postDelayed(this, 10000); // 10 seconds } }; mHandler.post(mUpdateUI); return null; } public void getStrfirst(){ nameValuePairs = new ArrayList<NameValuePair>(); try { httpclient = new DefaultHttpClient(); httppost = new HttpPost("http://lunation.square7.ch/msqlcount.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); response = httpclient.execute(httppost); str = EntityUtils.toString(response.getEntity()); LOGCAT: 09-11 12:12:41.185: I/System.out(10874): called 09-11 12:12:41.975: I/Choreographer(10874): Skipped 51 frames! The application may be doing too much work on its main thread. 09-11 12:12:51.990: I/System.out(10874): called EDIT: I call the AsyncTask with: AsyncStatus assi= new AsyncStatus(); assi.execute("nothing"); Why does this message appear, this isn't the main thread? Thank you for any advice
{ "language": "en", "url": "https://stackoverflow.com/questions/25784926", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: error installing rmagick gem on OSX - ERROR: Failed to build gem native extension I have installed about 40 other gems but this one can't install due to this error: Installing rmagick (2.13.1) with native extensions Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension. /Users/durrantm/.rvm/rubies/ruby-1.9.2-p290/bin/ruby extconf.rb checking for Ruby version >= 1.8.5... yes checking for /usr/bin/gcc-4.2... yes checking for Magick-config... no Can't install RMagick 2.13.1. Can't find Magick-config in /Users/durrantm/.rvm/gems/[email protected]_Abroad101/bin:/Users/durrantm/.rvm/gems/ruby-1.9.2-p290@global/bin:/Users/durrantm/.rvm/rubies/ruby-1.9.2-p290/bin:/Users/durrantm/.rvm/bin:/Library/PostgreSQL/9.1/bin:/usr/local/bin:/Library/PostreSQL/9.1/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/usr/local/sbin:/usr/local/mysql/bin:/Users/durrantm/.rvm/bin * extconf.rb failed * Could not create Makefile due to some reason, probably lack of necessary libraries and/or headers. Check the mkmf.log file for more details. You may need configuration options. Provided configuration options: --with-opt-dir --with-opt-include --without-opt-include=${opt-dir}/include --with-opt-lib --without-opt-lib=${opt-dir}/lib --with-make-prog --without-make-prog --srcdir=. --curdir --ruby=/Users/durrantm/.rvm/rubies/ruby-1.9.2-p290/bin/ruby Gem files will remain installed in /Users/durrantm/.rvm/gems/[email protected]_Abroad101/gems/rmagick-2.13.1 for inspection. Results logged to /Users/durrantm/.rvm/gems/[email protected]_Abroad101/gems/rmagick-2.13.1/ext/RMagick/gem_make.out An error occured while installing rmagick (2.13.1), and Bundler cannot continue. Make sure that gem install rmagick -v '2.13.1' succeeds before bundling. I tried this link https://github.com/maddox/magick-installer but it errored out at the end with: /usr/bin/install -c -m 644 ./builds/unix/freetype2.pc \ /usr/local/lib/pkgconfig/freetype2.pc tar: Unrecognized archive format tar: Error exit delayed from previous errors. Right now I am trying Veraticus' solution, then I will try Peters if necessary. A: What I found here perfectly works on Ubuntu: sudo apt-get install libxml2-dev libxslt1-dev imagemagick libmagickwand-dev and then, bundle install as usual. HTH A: Installing rmagick is always a pain... If you're having trouble, I'd step back and use Homebrew to reinstall Imagemagick. (This can usually be accomplished with brew install imagemagick.) Make sure to follow any follow-up instructions homebrew gives you, and then try installing the gem once again. A: I resolved the same issue by following these steps: * *Downgrade image-magics from 7 to 6 by running brew install imagemagick@6. *then run PKG_CONFIG_PATH=/usr/local/opt/imagemagick@6/lib/pkgconfig gem install rmagick. A: Be sure, you installed ImageMagick. If you have it, try to reinstall with that script
{ "language": "en", "url": "https://stackoverflow.com/questions/9407273", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: dynamically accessing datatemplates I have the following xaml: animationTemplate switches between template1 and template2. I would like to make this more reusable by putting the animationTemplate in the resource dictionary so multiple controls can use the same animationTemplate. The problem is that animation template has references to template1 and template2 so if I put the animationTemplate in the dictionary I get an error because animationTemplate cant find templates 1 and 2. <Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="Dictionary1.xaml" /> </ResourceDictionary.MergedDictionaries> <DataTemplate x:Key="template1" /> <DataTemplate x:Key="template2" /> <DataTemplate x:Key="animationTemplate" /> </ResourceDictionary> </Window.Resources> <ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource animationTemplate}" /> Is there a better way other then putting all of the template pairs in the dictionary and using a contentTemplateSelector to pick from them? I'd rather not do this (even if its possible because I have event handlers in the templates and I'm not sure how I would remove them)
{ "language": "en", "url": "https://stackoverflow.com/questions/12009268", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: extract similar terms Solr I want to extract from a data set, what all are the similar terms and then query with negation constraint on them. For example. for a the index set, how can i deduce that Blackberry and Nokia are two similar terms. Or say are 2 similar commodities. Can this be achieved through solr. ? This is not synonyms. but similarity constraint I need to achieve. A: Surely not the exact case you are looking for but you can check out Solr with Mahout. Mahout provides support for LDA for topic modeling, which will help you to group topics from your dataset A topic model is, roughly, a hierarchical Bayesian model that associates with each document a probability distribution over "topics", which are in turn distributions over words. For instance, a topic in a collection of newswire might include words about "sports", such as "baseball", "home run", "player", and a document about steroid use in baseball might include "sports", "drugs", and "politics". Note that the labels "sports", "drugs", and "politics", are post-hoc labels assigned by a human, and that the algorithm itself only assigns associate words with probabilities. The task of parameter estimation in these models is to learn both what the topics are, and which documents employ them in what proportions. So if within a dataset if you have documents for Mobiles, you would get a group of terms with blackberry, iphone, mobile and so on. These may not be similar terms but would relate to the same topic.
{ "language": "en", "url": "https://stackoverflow.com/questions/15538190", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Copy paste formulas verbatim Say I have a row of 100 cells, each with some formula. I want to copy them and paste them somewhere else, but with the formulas verbatim exactly the same, without changing the reference. Is there a quick way to do this (i.e. without macros, without having to add $ signs to the formulas, etc.)? One might have thought that there is some way to do this through Paste Special, but I don't seem to see any such option. A: The fastest way I usually do this is using find > replace... Do something like this: * *Select the cells that have the formulas you want *Use the find > replace feature in excel and replace all = with some other, unused character (I usually use #) - This will change them from formulas to plain text *Copy those cells and paste them where you want *Use the find > replace feature to replace that other character back to = In effect, you are changing the formula to text, copying and pasting it as the plain text (so preserving the cell references), then changing it back to the original formula. Hope this helps and makes sense.
{ "language": "en", "url": "https://stackoverflow.com/questions/21909970", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Replace character with preg replace I have been trying to replace/ remove any special characters when added in the form below. Characters like: +-()*&^%$#@!~ I have been trying to do this with preg replace but im not able to get it working. Code which i wrote is below. Am i missing something? <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> </head> <body> <form method="post" action="kenteken.php"> <input type="text" name="kenteken" /> <input type="submit" name="verzend" value="Check kenteken" /> </form> <?php // Include de benodigde classes include_once 'api/loader.php'; // Kijken of er een kenteken is ingevoerd. if(!isset($_POST["kenteken"])) { echo 'Geen kenteken ontvangen. Ga terug er probeer opnieuw!'; exit; } else { // Witte characters (spaties) weghalen $k = trim($_POST["kenteken"]); $k2 = preg_replace('/[^A-Za-z0-9\-]/', '', $k); // Kijken of kenteken leeg is met spaties if(empty($k2)) { echo 'Geen kenteken ingevoerd. Ga terug er probeer opnieuw!'; exit; } else { header("Location: http://domain.nl/kenteken/?kenteken=$k2"); } } ?> </body> </html> A: $k2 = preg_replace('/[^[:alnum:]]/', '', $k); simple and quick ;)
{ "language": "en", "url": "https://stackoverflow.com/questions/34778843", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How access a key of a array which is returned by a function I want to be able to access the array directly from the return value of the function. e.g. $arr = find_student(); echo $arr['name']; // I want to be able to do echo find_student()['name'] How can I accomplish the same ? Without another line of code ? A: You can't. The PHP syntax parser is limited and does not allow it in current versions. The PHP devs extended the parser for upcoming releases of PHP. Here's a link to a blog talking about it A: You cant :) function find_student() {return array('name'=>123);} echo find_student()['name']; Result: Parse error: syntax error, unexpected '[', expecting ',' or ';' A: You can do something similiar using ArrayObject. function find_student() { //Generating the array.. $array = array("name" => "John", "age" => "23"); return new ArrayObject($array); } echo find_student()->name; // Equals to $student = find_student(); echo $student['name']; Downside is you cant use native array functions like array_merge() on that. But you can access you data as you would on array and like on an object.
{ "language": "en", "url": "https://stackoverflow.com/questions/8819302", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Flutter Listview items not rendering What I do is fetching items from Firebase then saving them in a list and then I display them in a ListView. The Problem that I have now is that I check if the list has Items and if so it displays my ListView with the Items and if there are no items it displays a Text but even but even if there are items the text gets displayed but after pressing hot reload the items get shown. My guess was that there is a Problem with the State of the Widgets overall because stuff like SetState has no effect or a Refresh Indicator A: Is there a reason why the StreamBuilder is following your masterListStart().asStream as opposed to the masterList stream? I'm not saying it's wrong, its just not immediately obvious. Either way, it's not rebuilding automatically because the only part of your displayStory method that is reactive to the stream doesn't get built until after the non empty list condition is met. Without implementing a reactive state management solution there's nothing in your code that automatically notifies any listeners that the state of the storysList has changed, which means nothing is triggering a rebuild. Which is why you have to hot reload to see the changes. Without me getting too deep into your code, try returning the StreamBuilder at the top level of the displayStory method and putting all the conditionals inside its its builder method.
{ "language": "en", "url": "https://stackoverflow.com/questions/66216282", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Datastage:Split Parameter value I have a parallel job with parameter value "202203011537". I want to split this parameter value as "20220301" and "1537" and use it in SQL stage. Is there a way we can do it in Datastage parallel job? A: If you add Environment Variable in job properties? In this case, if you set a variable, you will can call a cuostom routine that calculated the split value.
{ "language": "en", "url": "https://stackoverflow.com/questions/72366405", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to let Flash app communicate with server? What's an easy and secure way to let my Flash app communicate with my back-end server? The Flash app, which is a video player, should retrieve the person's username and send back an ID. How would I do this? Note: Back-end is written in Javascript. A: If you want to connect flash with JS to actionscript use ExternalInterface. If you want to connect to e.g. PHP use NetConnection or UrlLoader A: I've used XML-RPC in a Flash client before. I've gotten it to work pretty well too. I've personally used this Action Script 3 implementation: http://danielmclaren.com/2007/08/03/xmlrpc-for-actionscript-30-free-library Of course, the server I was talking with was Java/Tomcat. However, I'm pretty sure there are XML-RPC implementations for JavaScript; a quick search found this: http://phpxmlrpc.sourceforge.net/jsxmlrpc/ Don't know how much setup/overhead it would be for you server-wise, but I've had success with that protocol.
{ "language": "en", "url": "https://stackoverflow.com/questions/6214495", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to extract a certain sentence in a paragraph? Python I want to extract certain sentences from a paragraph looking at a certain set of words Object C Statement:. The paragraph is as follows: Object A Statement: There was a cat with a bag full of meat. It was a red cat with a blue hat. Object B Statement: There was a dog with a bag full of toys. It was a blue dog with a green hat. Object C Statement: There was a dolphin with a bag full of bubbles. It was a purple dolphin with an orange hat. Object D Statement: There was a zebra with a bag full of grass. It was a white zebra with a blue hat. Object E Statement: There was a bear with a bag full of wood. It was a brown bear with a black hat. I want to extract Object C Statement: as follows: There was a dolphin with a bag full of bubbles. It was a purple dolphin with an orange hat. All examples that I have come across are with splitting a specific word etc. I tried this, but it doesn't work for me: word="Object A Statement: There was a cat with a bag full of meat. It was a red cat with a blue hat. Object B Statement: There was a dog with a bag full of toys. It was a blue dog with a green hat. Object C Statement: There was a dolphin with a bag full of bubbles. It was a purple dolphin with an orange hat. Object D Statement: There was a zebra with a bag full of grass. It was a white zebra with a blue hat. Object E Statement: There was a bear with a bag full of wood. It was a brown bear with a black hat." a, b, c, d, e = re.split(r"\B\s(?=[^\s:]+:)", word) regex = re.compile(r"""Object A Statement\s(.*?)Object B Statement\s(.*?)Object C Statement\s(.*?)Object D Statement\s(.*?)Object E Statement\s(.*)""", re.S|re.X) a, b, c, d, e = regex.match(word).groups() A: You can split the string with "\s*Object . Statement:\s*" import re word="Object A Statement: There was a cat with a bag full of meat. It was a red cat with a blue hat. Object B Statement: There was a dog with a bag full of toys. It was a blue dog with a green hat. Object C Statement: There was a dolphin with a bag full of bubbles. It was a purple dolphin with an orange hat. Object D Statement: There was a zebra with a bag full of grass. It was a white zebra with a blue hat. Object E Statement: There was a bear with a bag full of wood. It was a brown bear with a black hat." result = re.split(r"\s*Object . Statement:\s*", word) result = [r for r in result if len(r) > 0] print("\n".join(result)) I get the following result. There was a cat with a bag full of meat. It was a red cat with a blue hat. There was a dog with a bag full of toys. It was a blue dog with a green hat. There was a dolphin with a bag full of bubbles. It was a purple dolphin with an orange hat. There was a zebra with a bag full of grass. It was a white zebra with a blue hat. There was a bear with a bag full of wood. It was a brown bear with a black hat.
{ "language": "en", "url": "https://stackoverflow.com/questions/65908489", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Plotting two pie charts one beside another one (subplots) I would like to plot two pie charts one beside another. I am creating individually them as follows: pie chart 1: import matplotlib.pyplot as plt fig = plt.figure(figsize=(4,3),dpi=144) ax = fig.add_subplot(111) cts = df1.Name.value_counts().to_frame() ax.pie(cts.Name) pie chart 2: import matplotlib.pyplot as plt fig = plt.figure(figsize=(4,3),dpi=144) ax = fig.add_subplot(111) cts = df2.Name.value_counts().to_frame() ax.pie(cts.Name) I am not familiar with visualisation in python, but I think I should use subplot to create these two plots. An example of data is df1: Name water fire water fire fire fire df2 Name fire fire stones stones stones stones A: You need to create two subplots - one for each pie chart. The following code will do it (explanation in comments): import matplotlib.pyplot as plt # the same figure for both subplots fig = plt.figure(figsize=(4,3),dpi=144) # axes object for the first pie chart # fig.add_subplot(121) will create a grid of subplots consisting # of one row (the first 1 in (121)), two columns (the 2 in (121)) # and place the axes object as the first subplot # in the grid (the second 1 in (121)) ax1 = fig.add_subplot(121) # plot the first pie chart in ax1 cts = df1.Name.value_counts().to_frame() ax1.pie(cts.Name) # axes object for the second pie chart # fig.add_subplot(122) will place ax2 as the second # axes object in the grid of the same shape as specified for ax1 ax2 = fig.add_subplot(122) # plot the sencond pie chart in ax2 cts = df2.Name.value_counts().to_frame() ax2.pie(cts.Name) plt.show() This gives: A: This would do a job. You can defined subplots using fig.add_subplot(row, column, position). import matplotlib.pyplot as plt fig = plt.figure(figsize=(4,3),dpi=144) ax = fig.add_subplot(121) cts = df1.Name.value_counts().to_frame() ax.pie(cts.Name) ax = fig.add_subplot(122) cts = df2.Name.value_counts().to_frame() ax.pie(cts.Name) A: You can use subplots: import matplotlib.pyplot as plt colors = {'water': 'b', 'fire': 'r', 'stones': 'gray'} # same color for each name in both pie fig, axes = plt.subplots(1, 2, figsize=(4,3),dpi=144) plt.suptitle("Big title") for ax, df, title in zip(axes, (df1, df2), ('Title 1', 'Title 2')): count = df.Name.value_counts().to_frame().sort_index() ax.pie(count.Name, labels=count.index, colors=[colors[c] for c in count.index]) ax.set_title(title)
{ "language": "en", "url": "https://stackoverflow.com/questions/66359171", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iPhone app that talks to the server I need to build an iphone app that talks to a website. Logins, fetching data etc. I have built few apps that does these using website's api but the website I'm working with now does not have one. I don't have enough knowledge of PHP or RoR so I'm not sure if I could build a back-end API from scratch and then start on the ios development. I did some research and it looked like there are websites like parse.com or appactive where they help you with back-end api. Though, I looked around the website and read the about page but I'm still not sure how they work. Could those services help me if I already have a server/website running and I need an app that requires login and data exchanges? A: Jus a note, in 2016 Parse has closed (it's now open source and you run it on Heroku or whatever). There are many other "baas" such as Firebase etc. Since there seems to be some confusion, (a) your current service has no API. it is, thus, unfortunately essentially useless so your most absolutely time saving step from here would be just scrap it and use parse (or another baas) as the backend. you can have parse up and running in minutes. what previously took server developers man-years is now just like "a consumer product", just make a few clicks to add column-names (b) your current service has no API. assuming yo DO WANT TO continue to use it, you will have to somehow add an API, using php or whatever. there's no way to avoid this. IF you do that, then you could (if you wanted) make a "basic" API that parse can get the info from, and then use parse to actually connect to the ios/android builds (since that is so easy) TBC, here's literally how you do that in Parse, https://parse.com/docs/cloud_code_guide#networking "Cloud Code allows sending HTTP requests to any HTTP Server" it's that simple. As I mention above, it's far easier just to scratch your current backend and change to a bAAs (such as Parse). you have to "go with the times" you know? Note that the development and testing of an API on a service is incedibly time consuming, it is a huge job for a team. Here on this question you seem to be asking about bAAs and how they fit in the formula. the answers are: (1) if you simply scrap your current service, do everything on a baas: it is trivial. what used to take literally man-years is now a few clicks (2) in terms of "helping you ADD AN API to that service". bAAs cannot help you with that in any way and is irrelevant (3) if you DO have a service with an API, yes it is relatively easy to have bAAs "link in" to that. (i include literally the doco from pare on doing that above) Hope it helps!!!
{ "language": "en", "url": "https://stackoverflow.com/questions/26354072", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: SignalR hosted on iis works not stable I have a problem with signalr 2.2 hosted on iis 7.5 and windows server 2008r2. The problem is when I use my code on widows 7 and iis express signalr methods works perfect, but when I hosted in on this configuration sometimes methods works, but sometimes not. I can't detect any lows of that behavior. I use asp.net mvc3 with .net 4.5.1 Maybe somebody has such issues with signalR? The application is simply chat with sending text messages. Thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/28903696", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Android: Unable to download from play store I am developing an Android App. I was able test it on my device successfully. So I pushed the released version on Google Play store. Now I uninstalled the debug build from my device and tried to download it from the Play Store. But when I click on install button, I am getting this error. you cannot install this app because another user has already installed an incompatible version on this device... I am only using Google Play services. Not using any storage or anything that might be different for different users and Android L. What changes should I make in my app source to resolve this? Edit AndroidManifest <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.unary.untangleit" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.VIBRATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"> <activity android:name=".GameActivity" android:label="@string/app_name" android:screenOrientation="portrait" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <meta-data android:name="com.google.android.gms.games.APP_ID" android:value="@string/app_id" /> <meta-data android:name="com.google.android.gms.appstate.APP_ID" android:value="@string/app_id" /> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> </application> A: I solved this problem in this way: * *Go to Settings > Apps *Find your app and open the App Info *Open the overflow menu (3 vertical dots) *Choose Uninstall for all users. A: For Redmi or Mi Phones, the debug app was got installed on second space. * *Go To Setting -> Second Space -> Open Second Space. *Settings -> App - > downloaded app list. *Click on the application, You want to Uninstall. *Click on Uninstall. *Back to First space from setting. Or For Other Phones * *Go to settings -> apps -> downloaded app list *You can see the installed applications in the list *Click on the Application *Click on uninstall for all users options. A: I solved this issue by uninstalling debug version of the app and then clearing data of play store app. If this still doesn't work, you can follow these steps given in this site. Go to any root file manager, and navigate to directory: root >> data/data folder. Find the relevant folder of that app which you were installing from play store. Then delete that folder. [Note: Here you will loose all data related to that app]. Now go to play store, and try to install that app again. Check you have fixed your error. Hope this helps! Update: Thanks Abhishek, you can also try uninstalling the app using adb: adb shell pm uninstall com.packagename A: Somehow adb shell pm uninstall com.packagename did not work for me. I am not sure if this was because I was on a lollipop device. The answer suggested in this link did the trick. Hope this helps someone else. A: * *Go to settings > apps > downloaded app list *You can see the installed applications in the list (may be towards the very end) *Click on the application,go to the menu option *Click on uninstall for all users options
{ "language": "en", "url": "https://stackoverflow.com/questions/28522991", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "13" }
Q: Run multiple curl commands in parallel I have the following shell script. The issue is that I want to run the transactions parallel/concurrently without waiting for one request to finish to go to the next request. For example if I make 20 requests, I want them to be executed at the same time. for ((request=1;request<=20;request++)) do for ((x=1;x<=20;x++)) do time curl -X POST --header "http://localhost:5000/example" done done Any guide? A: You can use xargs with -P option to run any command in parallel: seq 1 200 | xargs -n1 -P10 curl "http://localhost:5000/example" This will run curl command 200 times with max 10 jobs in parallel. A: Using xargs -P option, you can run any command in parallel: xargs -I % -P 8 curl -X POST --header "http://localhost:5000/example" \ < <(printf '%s\n' {1..400}) This will run give curl command 400 times with max 8 jobs in parallel. A: Adding to @saeed's answer, I created a generic function that utilises function arguments to fire commands for a total of N times in M jobs at a parallel function conc(){ cmd=("${@:3}") seq 1 "$1" | xargs -n1 -P"$2" "${cmd[@]}" } $ conc N M cmd $ conc 10 2 curl --location --request GET 'http://google.com/' This will fire 10 curl commands at a max parallelism of two each. Adding this function to the bash_profile.rc makes it easier. Gist A: Add “wait” at the end, and background them. for ((request=1;request<=20;request++)) do for ((x=1;x<=20;x++)) do time curl -X POST --header "http://localhost:5000/example" & done done wait They will all output to the same stdout, but you can redirect the result of the time (and stdout and stderr) to a named file: time curl -X POST --header "http://localhost:5000/example" > output.${x}.${request}.out 2>1 & A: Wanted to share my example how I utilised parallel xargs with curl. The pros from using xargs that u can specify how many threads will be used to parallelise curl rather than using curl with "&" that will schedule all let's say 10000 curls simultaneously. Hope it will be helpful to smdy: #!/bin/sh url=/any-url currentDate=$(date +%Y-%m-%d) payload='{"field1":"value1", "field2":{},"timestamp":"'$currentDate'"}' threadCount=10 cat $1 | \ xargs -P $threadCount -I {} curl -sw 'url= %{url_effective}, http_status_code = %{http_code},time_total = %{time_total} seconds \n' -H "Content-Type: application/json" -H "Accept: application/json" -X POST $url --max-time 60 -d $payload .csv file has 1 value per row that will be inserted in json payload A: Update 2020: Curl can now fetch several websites in parallel: curl --parallel --parallel-immediate --parallel-max 3 --config websites.txt websites.txt file: url = "website1.com" url = "website2.com" url = "website3.com" A: This is an addition to @saeed's answer. I faced an issue where it made unnecessary requests to the following hosts 0.0.0.1, 0.0.0.2 .... 0.0.0.N The reason was the command xargs was passing arguments to the curl command. In order to prevent the passing of arguments, we can specify which character to replace the argument by using the -I flag. So we will use it as, ... xargs -I '$' command ... Now, xargs will replace the argument wherever the $ literal is found. And if it is not found the argument is not passed. So using this the final command will be. seq 1 200 | xargs -I $ -n1 -P10 curl "http://localhost:5000/example" Note: If you are using $ in your command try to replace it with some other character that is not being used. A: Based on the solution provided by @isopropylcyanide and the comment by @Dario Seidl, I find this to be the best response as it handles both curl and httpie. # conc N M cmd - fire (N) commands at a max parallelism of (M) each function conc(){ cmd=("${@:3}") seq 1 "$1" | xargs -I'$XARGI' -P"$2" "${cmd[@]}" } For example: conc 10 3 curl -L -X POST https://httpbin.org/post -H 'Authorization: Basic dXNlcjpwYXNz' -H 'Content-Type: application/json' -d '{"url":"http://google.com/","foo":"bar"}' conc 10 3 http --ignore-stdin -F -a user:pass httpbin.org/post url=http://google.com/ foo=bar
{ "language": "en", "url": "https://stackoverflow.com/questions/46362284", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "68" }
Q: SAS data step for array, errors and warnings I am getting the following errors/warnings: WARNING: Apparent symbolic reference ARRAY_MONTH_COUNT not resolved. ERROR: Too many variables defined for the dimension(s) specified for the array array1. ERROR 22-322: Syntax error, expecting one of the following: an integer constant, *. ERROR 200-322: The symbol is not recognized and will be ignored. for the following code: data demo_effective; set work.demo; array array1 [&array_month_count] $ 1 membsdemo_flag_&start_yrmo membsdemo_flag_&end_yrmo; length yrmo 6; do i=1 to &array_month_count; if array1[i] = 'N' then continue; if array1[i] = 'Y' then yrmo = substrn(vname(array1[i]),20,6); output; end; run; I didn't write this program, I am just trying to work with it, so I don't know why this isn't working (I made no changes, just ran the program in SAS and it was already broken), and I am still learning SAS and SQL, so half of this program is nonsense to me even after watching some videos and trying to find more information about it. If it helps, it looks like the warning/errors are occurring around array1 [&array_month_count]. A: &array_month_count is a macro variable. In SAS, this is a string that is substituted at compile time. Macros "write" code. It looks like all the errors you are getting are because that variable does not have a value. So somewhere in the code, there should be something that sets the value of array_month_count. Find that, fix it, and this step should work. A: A bit more detail than Dom's answer may be helpful, though his answer is certainly the crux of the issue. &array_month_count needs to be defined, but you also probably have a few other issues. array array1 [&array_month_count] $ 1 membsdemo_flag_&start_yrmo membsdemo_flag_&end_yrmo; This is probably wrong, or else this code is perhaps doing something different from what it used to: I suspect it is intended to be array array1 [&array_month_count] $ 1 membsdemo_flag_&start_yrmo - membsdemo_flag_&end_yrmo; In other words, it's probably supposed to expand to something like this. array array1 [6] $ 1 membsdemo_flag_1701 membsdemo_flag_1702 membsdemo_flag_1703 membsdemo_flag_1704 membsdemo_flag_1705 membsdemo_flag_1706; The 6 there isn't actually needed since the variables are listed out (in a condensed form). The dash tells SAS to expand numerically with consecutive numbers from the start to the end; it would only work if your yrmo never crosses a year boundary. It's possible -- is appropriate instead - it tells SAS to expand in variable number order, which works fine if you have consecutively appearing variables (in other words, they're adjacent when you open the dataset). The 6 is however needed for the second bit. do i=1 to &array_month_count; Unless you rewrite it to this: do i = 1 to dim(array1); *dim = dimension, or count of variables in that array; In which case you really don't even need that value. -- If it's actually intended to be the code as above, and only have 2 variables, then you don't need &array_month_count since it's known to be only 2 variables.
{ "language": "en", "url": "https://stackoverflow.com/questions/45551739", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: AWS lambda CLI 'update-function-code' does not update lambda_handler file update-function-code AWS CLI command updates all code files except the handler function file, lambda_function.py Specifically, I made a bash script that * *Downloads code zip from one lambda (source) *Uploads code zip to another lambda (dest) Everything works, except the main function file lambda_function.py does not get updated. Oddly, when I download the zip from a lambda, make a change, and then upload to the same lambda, it works (all files are updated). FYI, here is my bash script to download code from one lambda, and upload to another: #!/bin/sh SRC_LAMBDA_FUNCTION_NAME="$1" DEST_LAMBDA_FUNCTION_NAME="$2" export PYTHONIOENCODING=utf8 # get lambda function config LAMBDA_JSON=$(aws lambda get-function --function-name $SRC_LAMBDA_FUNCTION_NAME) export LAMBDA_JSON # parse the code zip file download URL (link expires 10 minutes after creation) ZIP_FILE_URL=$(python -c 'import json,sys,os;obj=json.loads(os.environ["LAMBDA_JSON"]);print(obj["Code"]["Location"])') # make temp dir mkdir -p download # download the code from src lambda curl -o "download/$SRC_LAMBDA_FUNCTION_NAME.zip" $ZIP_FILE_URL # upload the code to dest lambda aws lambda update-function-code --function-name $DEST_LAMBDA_FUNCTION_NAME --zip-file "fileb://download/$SRC_LAMBDA_FUNCTION_NAME.zip" A: I was verifying the code changes by navigating to the lambda code editor on the AWS web portal, and it appears this was just a client side issue in the web UI. It took about 5 minutes before the lambda_function.py was updated in the UI (despite refreshing), whereas the other code files did get updated immediately. It is very strange that other files got updated, but not lambda_function.py. This makes me think it is not just a browser caching issue, but maybe a bug. A: I believe you may need to publish the new code changes according to https://docs.aws.amazon.com/cli/latest/reference/lambda/update-function-code.html --publish | --no-publish (boolean) Set to true to publish a new version of the function after updating the code. This has the same effect as calling PublishVersion separately.
{ "language": "en", "url": "https://stackoverflow.com/questions/53600256", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: How to convert UTF-8 numbers into characters I have got a very big text file (~150 MB) encoded in UTF-8. The content of the text contains both UTF-8 readable characters and entity numbers. When displayed by a text editor (TextWrangler, NotePad++...), the text content is as below: zygoma <B><FONT SIZE='+1'>zygoma</FONT></B>/z&#652;&#618;/ (g&#601;&#650;m&#601;)</FONT> When this text file is read by a web browser, the content is correctly displayed as: * *zygoma zygoma/zʌɪ/ (gəʊmə) I want all the UTF-8 numbers (like g&#601;&#650;m&#601;)to be converted to readable characters (like gəʊmə) so that, when opened by a text editor, the text file will be like this: zygoma <B><FONT SIZE='+1'>zygoma</FONT></B>/zʌɪ/ (gəʊmə)</FONT> I have tried using encoding tools provided by TextWrangler and Notepad++... but there is no luck. (there are some online tools to do this task but my text file is too big for them). I wonder if there is a tool or a way to convert those UTF-8 numbers into their equivalent readable characters. Can you please help? Thank you. A: EditPad Pro can do this: Using the Convert - &#65535; and &#xFFFF; -> Character command (and assuming that the current file is set to UTF-8 and that you're using a font that contains the required glyphs), you get When you save that, you get a correctly UTF-8-encoded file with or without BOM, as you choose. Disclaimer: I am the translator for EPP's German version (but I'm doing this for free, because this editor is excellent). A: You could try this http://www.artlebedev.ru/tools/decoder/ tool (Russian lang). Translated version: http://bit.ly/15O0eQW (eng) updated: Try this script https://gist.github.com/Funfun/6839052
{ "language": "en", "url": "https://stackoverflow.com/questions/19196291", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-2" }
Q: CSS: Alternative method to positon absolute I have the following mark up: <div id="playArea" style="position: relative;"> <div style="position: absolute; left: 295px; top: -1px; width: 313px; height: 269px;">Hello</div> <div style="position: absolute; left: 63px; top: 35px; width: 80px; height: 42px;">World</div> <div style="position: absolute; left: 534px; top: 329px; width: 183px; height: 251px;">Bye</div> </div> But i would like to have a paragraph of text under the 'playArea' div, but because all the divs inside playArea is absolute, the text doesnt appear at the bottom of the last absolute positioned div. I have looked into this and found an alternative by using float:left and clear:left however after using this method on the first div, you cannot position the div correctly as the starting point of the second div is under the first div and not at (0,0). Any ideas of how i can get by this. Thanks A: If I understood correctly, you just have to give the "playArea" div the right height. Edit: I mean, the combined height of everything inside it. A: But i would like to have a paragraph of text under the 'playArea' div, but because all the divs inside playArea is absolute, the text doesnt appear at the bottom of the last absolute positioned div. As you seem to know all the dimensions and positions already, just add another absolutely positioned div to it and put the relative content in it. I have looked into this and found an alternative by using float:left and clear:left however after using this method on the first div, you cannot position the div correctly as the starting point of the second div is under the first div and not at (0,0). Any ideas of how i can get by this. You need to remove position: absolute to get the floats right. Just width and height are enough. A: Float the three inner divs left, put overflow: hidden; on the playArea div and put your <p> under the three inner divs with clear: both; A: After reading the comment thread between you and "BalusC", it appears that you have modified your CSS and are now trying to float your items, and use margin-top and margin-left for positioning. You are totally able to do it that way, but you are forgetting that you can also use negative margins to position your elements as well. For example if you use margin-top:-10px; then it will pull the element up (instead of pushing it down, like a normal positive valued margin). The same goes for all of your other margins. That seems to be the missing ingredient for you now.
{ "language": "en", "url": "https://stackoverflow.com/questions/1957894", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: HTML + JS + CSS converter I have a HTML file with JS (jQuery) and CSS. I want a converter that converts all the files, minimizes it and just puts it all in a index.html for example. Google seems to be using this, they have no external files, not even the image, everything is just in one file and I'm sure pre-compiled before release. Also is this a good idea? A: This is not a good idea, in general. Splitting out your CSS and JavaScript files means that they can be cached independently. You will likely be using a common CSS and JavaScript across many pages. If you don't allow those to be cached, and instead store them in each page, then the user is effectively downloading a new copy of those files for every page they visit. Now, it is a good idea to served minified versions of these files. Also make sure to add gzip or deflate transfer encoding so that they are compressed. Text compresses nicely... usually around a ratio of 1/8. (I should note that there has been one occasion where I have loaded everything into a single file. I was working on a single-page web application for the Nintendo Wii, which had no caching capability at all. This is about the only instance where putting everything into a single file made sense. Even then, it is only worth the effort if you automate it server-side.) A: I don't recommend to concat CSS with JS. Just put your css at the top of the page and js at the bottom. To minify your CSS and JS you have to use gruntjs Also I recommend you to read this article: Front-end performance for web designers and front-end developers A: If your intention is to load the pages faster: * *For images: try to use image sprites or images from different domains because browsers love downloading resources from different domains instead of just one domain. *For scripts as well as css: use online minifiers that can reduce white-spaces and reduce the size (if you are on a web hosting, your host may be already compressing the scripts for you using gzip etc) *For landing pages like index pages: If you have less styles then try inserting them inside the <style></style> tag, this will make the page load very fast, Facebook mobile does it that way. A: If it wasn't a good idea, google wasn't be using it! If you put everything in single file, you'll get less HTTP requests when the browser will check if the newer version of file is available. You also get read of the problem that some resources are not refreshed, which is the headache for 'normal' developers, but it's a disaster in AJAX applications. I don't know of any publicly available tool doing it all, surely Google is having its own. Note also that, for example in GWT, many such embedding was done by compiler. What you can do is to search for: CSS image embedder - for encoding images into CSS CSS and JS minifier - for building single CSS/JS and minimizing it And you need some simple tool that will embed it into HTML.
{ "language": "en", "url": "https://stackoverflow.com/questions/14539930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Nearest-neighbor algorithm with directions (left / right / top / bottom) Having n random points in 2D geometry, for each point p I need to find 4 (or less if not exists) closest points (qa,qb,qc,qd), where qa is the closest left-top point, qb is the closest right-top point, qc is the closest left-bottom point and qd is the closest right-bottom point to point p. Having same x coordinate is considered as left, having same y coordinate is considered as bottom. What would be the best data structure to store point coordinates and their nearest-neighbor references? What algorithm would be the fastest or the most performed? Note: This issue is far more then nearest-neighbor algorithm, as for each point 4 neighbor points are needed. A: You can try a space filling curve and a quadtree data structure. A space filling curve reduces the 2 dimension to 1 dimension and it works best with power of 2 grids. A quadtree divides the plane into 4 quads. A space filling curve is mathematical function taking 2 variables and gives 1 number as result. It can have also 3,4,5 variables but the most simple is with 2. Because it gives 1 number and takes 2 variables it can help for questions with 2 dimensions or more. * *http://social.technet.microsoft.com/wiki/contents/articles/9694.tuning-spatial-point-data-queries-in-sql-server-2012.aspx *https://www.google.com/search?q=nearest+neigbor+search+space+filling+curve A: Use a k-dim tree index (in this case k=2) so a quad tree. This should allow you to efficiently search the space to the left,right,up and down of your point. You can probably formulate a query in a dmbs for this but conceptually I would search the points own "quad" and then depending on the position of the point in the quad we can know if we found the nearest point in one direction or not. Then we know which quads to search for the rest of the points. Since you are doing this for each point you know there exists symmetry i.e. point P1 has P2 as nearest left neighbor so P2 has P1 as nearest right neighbor. So update the point objects accordingly.
{ "language": "en", "url": "https://stackoverflow.com/questions/11551263", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Date range picker does not show next arrow but shows previous arrow I am working with DateRangePicker and I am not shown the following arrow, I don't know what I have configured wrong. As we see the image should have on the right side an arrow too, this time I went back to 2020 so you can see that I don't have the arrow My input <input type="text" id="daterange" name="daterange"/> My script <script src="https://code.jquery.com/jquery-migrate-3.0.0.min.js"></script> <script type="text/javascript" src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" /> <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.min.js"></script> <script> $(function() { $('input[name="daterange"]').daterangepicker({ "minDate": "01-01-2018", "maxDate": '0', "autoUpdateInput": false, "locale": { "cancelLabel": 'Limpiar', "applyLabel": 'Aplicar', "fromLabel": "Desde", "toLabel": "Hasta", "daysOfWeek": [ "Do", "Lu", "Ma", "Mi", "Ju", "Vi", "Sa" ], "monthNames": [ "Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Setiembre", "Octubre", "Noviembre", "Diciembre" ], } }); $('input[name="daterange"]').on('apply.daterangepicker', function(ev, picker) { $(this).val(picker.startDate.format('MM/DD/YYYY') + ' - ' + picker.endDate.format('MM/DD/YYYY')); }); $('input[name="daterange"]').on('cancel.daterangepicker', function(ev, picker) { $(this).val(''); }); }); </script> A: you need to set the "maxDate". it cannot be "maxDate": '0',
{ "language": "en", "url": "https://stackoverflow.com/questions/65623163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Recursive HTTP request: How to prevent a page from calling itself I'm looking for a good way to prevent the scenario of the page calling itself repeatedly. I have a page, that to be rendered needs to make an HTTP request to an RSS feed. If the URL to that RSS feed happens to be the current page, it will fire off a request to itself. The new request would start off another request to the page, which would start another request... This continues until the site grinds to a halt when all available connections are busy in this recursive loop. A few notes: * *The URL to the RSS is entered by the user. *This is a page in a CMS, the URL of the page could be almost anything and could change after the RSS URL is entered. *In this case, the user entered a URL to a remote server that lead to a redirect back to the page. A few ideas: * *I could just deny all requests from the localhost IP before rendering. *Before sending the request, I could track in a common location which requests are active and not even send it if it's already in the middle of another request to the same address. *Maybe add a custom user-agent to the request header and deny the request if that user agent is seen? A: Does the page being rendered know it's own address/URL (it should), if so can't it just check to ensure it's address doesn't match the RSS one?
{ "language": "en", "url": "https://stackoverflow.com/questions/5263084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: overflow numbers to another cell in excel Here is what is going on. I am needing to simplify my payroll worksheet. What I want to do for Column D is input actual hours worked with D15 summing all hours up to 40 hours. After 40 hours of course overtime is applied to our employees pay, so is there any way that when 40 is reached in D15, that when I input hours let’s say in D10, that the difference is automatically flowed over to E10? Column E would still auto sum to E15. Please refrain from editing my question. A: Put this in E2 and copy/drag down: =IF(D2<>"",IF(SUM($D$1:D2)>40,MIN(D2,SUM($D$1:D2)-40),0),"")
{ "language": "en", "url": "https://stackoverflow.com/questions/40048003", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: scanner delimiter to get tokens separated by " " and "\n" java I am trying to read tokens from a file that looks like this 4 2 3 1 2 3 So I want these tokens to be delimited by " " or by enter (\n). How do I achieve this? I tried something, but with no success. in = new FileInputStream("input.txt"); scan = new Scanner(in); scan.useDelimiter(" \\n"); System.out.println("I get here"); t = new Translator(Integer.parseInt(scan.next()), Integer.parseInt(scan.next())); System.out.println("I don't get here"); int temp = Integer.parseInt(scan.next()); while(temp > 0){ m.final_states.add(Integer.parseInt(scan.next())); temp--; } I can't seem to find any relevant information about the kind of delimiters that I want. I've seen a couple of examples, I've read the example in the documentation too, but I am confused. The error I get is java.lang.NumberFormatException A: A very common issue is you forget to trim the string. Try this: m.final_states.add(Integer.parseInt(scan.next().trim())); and t = new Translator(Integer.parseInt(scan.next().trim()), Integer.parseInt(scan.next().trim())); A: The good thing about Scanner is that it allows to read primitive types w/o explicit casting. You may try the following approach: try (FileInputStream source = new FileInputStream(PATH)) { Scanner scanner = new Scanner(source); Translator translator = new Translator(scanner.nextInt(), scanner.nextInt()); while(scanner.hasNextInt()){ m.final_states.add(scanner.nextInt()); } } Please note that with the help of the scanner.hasNextInt() you don't need to count # of your inputs in the second line.
{ "language": "en", "url": "https://stackoverflow.com/questions/42728569", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flutter Contacts bug - doesn't work for 1 icloud account, works when that account isn't logged in we are testing an app that uses flutter_contacts. We maintain a user database that also contains phone numbers. We use this call on the package to get contacts: contacts = await FlutterContacts.getContacts( withProperties: true, withPhoto: true, sorted: true, ); We then are creating a different list from users in our app userbase (all gave phone number), and intersecting the two lists to get the displayed list of contacts in the app (i.e. you see users who are both in your contacts and members of the app). This works for around 15 people who have tested it. However, one tester observes the following behaviour: when their icloud is logged in, they see no contacts in app. When their icloud is logged out on same phone, they see correct contact list in app. Have done: * *factory reset of iphone *tested same icloud account on different device with same results *contacts privacy setting for app is on *icloud sync fully done *ios fully updated Any help much appreciated.
{ "language": "en", "url": "https://stackoverflow.com/questions/73823935", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: XAMPP - quick way to restart apache? I have XAMPP installed on Windows 7. I need to stop and start Apache many times every day. Currently, I do this by opening up the Xampp control panel, clicking 'Stop' (next to 'Apache'), waiting for it to stop, then clicking 'Start'. Ideally I would like to be able to do this more quickly - something like right click the Xampp icon, and choosing 'Restart Apache'. Or, even better, just a shortcut key that restarts Apache. I know that there are two bat files with Xampp - apache_stop.bat and apache_start.bat. I've tried utilising these to get want I want. However, when you run apache_start.bat, you get a cmd window that you can't get rid of. I couldn't find a way to start Apache silently in this way. So, basically I want to be able to quickly restart Apache (one click/shortcut key), completely silently. Thanks in advance. A: If you have the Apache service monitor in your system tray, you can just open that (right click, I think?) and click "restart Apache". If it's not in your system tray, you can find it in the /bin folder of the Apache installation (called ApacheMonitor.exe). I'd recommend making a shortcut to it in the "Startup" folder. A: Copy apache_start.bat and rename it to apache_restart.bat. Change the line apache\bin\httpd.exe to apache\bin\httpd.exe -k restart Voila, there you go with your restart script. and you can also give it a shortcut. A: For me, with the version 3.2.2 the first answer didn't work. I've put together a script from the two apache_start.bat and apache_stop.bat files. @echo off cd /D %~dp0 echo Apache 2 is stopping... apache\bin\pv -f -k httpd.exe -q if not exist apache\logs\httpd.pid GOTO exit del apache\logs\httpd.pid echo Apache 2 is re-starting ... apache\bin\httpd.exe if errorlevel 255 goto finish if errorlevel 1 goto error goto finish :error echo. echo Apache konnte nicht gestartet werden echo Apache could not be started pause :finish A: @adrianthedev's version didn't work for (XAMPP v3.2.4) me but helped me find a solution. It's a lot less sophisticated as I don't know much about scripting but here it is and it worked for me: @echo off C:/xampp/apache/bin/httpd -k stop C:/xampp/apache/bin/httpd -k start Note: apache\logs\httpd.pid doesn't need to be deleted as it's done already by the httpd -k stop command.
{ "language": "en", "url": "https://stackoverflow.com/questions/11557101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "20" }
Q: plot how many times each list entry is repeated using pyplot I have list containing votes (smth like this votes = [1, 2, 3, 4, 1, 1, 3, 4, 4, 4]). How to use pyplot to plot a graph showing the count of each vote (i.e. 1 -> 3 votes, 2 -> 1 vote, 3 -> 2 votes, 4 -> 4 votes) Here is how I am doing it: from collections import Counter import matplotlib.pyplot as plt votes = [1,1,1,2,3,3,4,4,4,4,4] tmp_votes_count = Counter (votes) votes_count = [] for i in tmp_votes_count: votes_count.append ([i, tmp_votes_count[i]]) plt.plot([row[0] for row in votes_count], [row[1] for row in votes_count]) plt.axis([0,4,0,20]) plt.show() Is there a more optimized way to do it? Also how to style the graph as bar chart instead of the continuous line? I mean smth similar to this: instead of what I am getting right now: A: Just do plt.bar([row[0] for row in votes_count], [row[1] for row in votes_count]) A: If you know pandas , it will be very easy. votes=pd.DataFrame(data=votes,columns=['List']) votes.List.hist()
{ "language": "en", "url": "https://stackoverflow.com/questions/43826168", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: angular 2 to display and hide a component on mouse enter and leave I have created a component for filter in angular 2 which I have added inside my table header. I want to display when mouse is on span and when out i want to hide <th> <span class="headColor" >{{componentContents.dlHead}}</span> <app-data-filter [dataObject]="responseData" [filterBy]="'storeCatelogue'" (filteredArray)="filterByArray($event,'storeCatelogue')"></app-data-filter> </th> <th > <span class="headColor">{{componentContents.titleHead}}</span> <app-data-filter [dataObject]="responseData" [filterBy]="'title'" (filteredArray)="filterByArray($event,'title')" ></app-data-filter> </th> But i want to display this filter component on mouse over and hide on mouse out and this should not display all the app-data-filter component i want to display it for that particular header. filter is different for each header so i should display one at a time. I don't have any idea about host listener that how can i use that here as i'm still learning angular 2 so it would be really helpful if i get some guidance or is there any other way A: You can use the css :hover selector.. Since you didn't specify the exact structure of your html its hard for me to say how exactly you should implement it. Lets say for this matter that you want to show the on table mouse hover, and you table class is 'my-table'. .my-table:hover{ th{ display:none; } } You can read about the :hover selector here. Edit: If your html strauctre is something like: <span class='my-toggle-span'>Toggle app filter!</span> <app-filter class='my-app-filter'></app-filter> Then your css will be .my-toggle-span:hover +.my-app-filter{ display:none; } The plus selector Selects all element that are placed immediately after it. Edit 2: As opener requested, A javascript based solution: I don't recommend this approach and any way, Your toggle logic should be handled in your component and not in your html. <span class='my-toggle-span' (mouseenter)="toggle=true;" (mouseleave)="toggle=false;">Toggle app filter!</span> <app-filter *ngIf="toggle" class='my-app-filter'></app-filter>
{ "language": "en", "url": "https://stackoverflow.com/questions/47049993", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: hrtimer signal handler in user space? I've set up multiple hrtimers for a satellite I'm building as part of my research group. Ideally, I'd like the access to these timers in the user space, so I'm wondering if there's a way to have the hrtimer generate a signal that can be handled in user space. Is that possible?
{ "language": "en", "url": "https://stackoverflow.com/questions/44313930", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: string.Contains() and IndexOf() throw FormatException Why would myString.Contains(" ") or myString.IndexOf(' ') throw a FormatException "Invalid name format"? This exception is only thrown when there is a space in myString. A: Looking at the MSDN pages for the string.Contains and string.IndexOf methods clearly shows that neither of these methods ever throws a FormatException. I can only conclude that it must be another part of the code (possibly a call to string.Format?) throwing this exception. Perhaps posting the relevant section of code would help?
{ "language": "en", "url": "https://stackoverflow.com/questions/3388998", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Condition in Linq Expression I have a LINQ expression that joins two tables. I want to conditionally check another boolean value: (notice text between ********* below) bool status = testfunc(); var List = from t in Houses join k in Tbl_HouseOwner on t.HouseCode equals k.HouseCode where k.ReqCode== t.ReqCode *********** if (status) { where k.Name.Contains(Name) } ********** select new { ... name = k.Name, ... }; A: You can use status to mask the condition, like this: where k.ReqCode == t.ReqCode && (!status || k.Name.Contains(Name)) If the status is false, the OR || will succeed immediately, and the AND && will be true (assuming that we've got to evaluating the OR ||, the left-hand side of the AND && must have been true). If the status is true, on the other hand, the k.Name.Contains(Name) would need to be evaluated in order to finish evaluating the condition. A: An alternative option to dasblinkenlight's answer (which should work fine) is to build up the query programmatically. In this case you're effectively changing the right hand side of the join, so you could use: IQueryable<Owner> owners = Tbl_HouseOwner; if (status) { owners = owners.Where(k => k.Name.Contains(Name)); } Then: var query = from t in Houses join k in owners on t.HouseCode equals k.HouseCode where k.ReqCode == t.ReqCode select new { ... }; Which approach is the most suitable depends on your scenario. If you want to add a variety of different query filters, building it up programmatically can be cleaner - and make the final SQL easier to understand for any given query. For a one-off, dasblinkenlight's approach is simpler. Also note that in LINQ to Objects at least, it would be more efficient to join on both columns: var query = from t in Houses join k in owners on new { t.HouseCode, t.ReqCode } equals new { k.HouseCode, k.ReqCode } select new { ... }; In any flavour of LINQ which translates to SQL, I'd expect this to be optimized by the database or query translation anyway though. A: I do it this way: IQueryable<X> r = from x in Xs where (x.Status == "Active") select x; if(withFlagA) { r = r.Where(o => o.FlagA == true); } To fit this to your example, firstly you could do this: IQueryable<YourOwnerType> filteredOwners = Tbl_HouseOwner; if( status ) { filteredOwners = filteredOwners.Where( o => o.Name.Contains(Name) ); } Then substitute Tbl_HouseOwner with filteredOwners. var List = from t in Houses join k in filteredOwners on t.HouseCode equals k.HouseCode where k.ReqCode== t.ReqCode //Nothing here select new { ... name = k.Name, ... }; Now, you may know this, but the point here is that the initial .Where does not 'reach out' to the database. Your query doesn't get executed either until you start enumerating it (e.g. foreach) or call a method like ToList(), First(), FirstOrDefault(). This means you can call .Wheres after your selects if you prefer and the final query will still be efficient.
{ "language": "en", "url": "https://stackoverflow.com/questions/11406463", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Converting a xml file into jrxml file Is there a way I can convert a xml file to jrxml file? I am doing a project where I need to write data from the database in a MS Word file that is already designed with the required template. I have converted that document file into xml format. I am using iReport to generate the resultant doc file. But it requires a jrxml file. It fails to read from xml file. A: Bijil, JRXML is a template that contains the format for the content that is shown on the report. And from what i understand the xml is containing the input data. How jasper reports work is, you create JASPER file by compiling the JRXML file (this can be done using iReport or through your java code). To this JASPER file you will attach a object from your java code that contain data for filling the JASPER. Please see this link for details Edited: iReport is a designer tool for creating jasper reports, I am not sure if there any tool that can convert xml to jrxml. jrxml will contain the syntax with respect to jasper report. What we used to do, were try to create a similar report(by comparing the look and feel) as the one client has given using iReport and get the final jrxml. Compile jrxml in iReport check the look and feel with the sample word doc with the generated sample report Then use the compiled jasper file in the application directly. The use of jasper has 2 advantages, * *you can use unicode characters in your report *you reduce the overhead of compiling your code every time before generating report. disadvantage * *you need to keep separate track of jrxml, to fix any defect on previous jasper file. A: Save your MS WORD file (Template) in report directory and using Apache POI, Do necessary edits to your template. Then save your file to any place you like. Apache POI tutorials Link 01: To print save your edited file in temp directory and call Desktop.getDesktop().print(file) using desktop Link 02: Wish you good luck.
{ "language": "en", "url": "https://stackoverflow.com/questions/13024147", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Extracting .bdf from Matlab generated .set file Excuse if this is more a file format conversion question rather than programming, but I can't find anyone who can help extract the embedded .bdf (bio signals format) data from this .set file http://statigrafix.com/temp/EEG-set/Target_1.set Which seems from the header to have been generated from MATLAB 5. I've asked colleagues at San Diego Supercomputing Center and CALIT2 but no luck yet. Can someone somewhere in the world figure it out? A: That looks like an EEGLAB dataset file, which is simply a regular MAT-file with a structure variable stored inside. This structure contains various info about the biosignals. You could manually load the data using LOAD function, or use the provided GUI to open the dataset. >> load Target_1.set -mat >> EEG EEG = setname: 'Target_1' filename: 'Target_1.set' filepath: '/home/julie/FiveBox_JO' subject: '' group: '' condition: '' session: [] comments: [1x803 char] nbchan: 238 trials: 1 pnts: 99129 srate: 256 xmin: 0 xmax: 387.22 times: [] data: [238x99129 single] icaact: [] icawinv: [238x238 double] icasphere: [238x238 double] icaweights: [238x238 double] icachansind: [1x238 double] chanlocs: [1x238 struct] urchanlocs: [] chaninfo: [1x1 struct] ref: 'common' event: [1x616 struct] urevent: [1x18879 struct] eventdescription: {'' '' '' ''} epoch: [] epochdescription: {} reject: [1x1 struct] stats: [1x1 struct] specdata: [] specicaact: [] splinefile: '' icasplinefile: '' dipfit: [1x1 struct] history: [1x1022 char] saved: 'yes' etc: [] A: You can add a plug-in of inporting( about BDF) in eeglab, then load your data to eeglab and export as .bdf file. after that you will obtain a .bdf file. But this file can not be uesed still, you need to add file extension as '*.dbf'. Finally, the bdf can be loaded into another software to analysis.
{ "language": "en", "url": "https://stackoverflow.com/questions/11142962", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: aws apigateway lambda authorizer added, getting 500 error Created a lambda authorizer for AWS HTTP API Gateway * *Payload Format: 2.0 *Response Mode: IAM Policy *Identity sources: $request.header.Authorization *Invoke Permission: Automatically grant API Gateway permission to invoke your Lambda function And here is the lambda function which has API Gateway as trigger exports.handler = function(event, context, callback) { var token = event.authorizationToken; switch (token) { case 'allow': callback(null, generatePolicy('user', 'Allow', event.methodArn)); break; case 'deny': callback(null, generatePolicy('user', 'Deny', event.methodArn)); break; case 'unauthorized': callback("Unauthorized"); // Return a 401 Unauthorized response break; default: callback("Error: Invalid token"); // Return a 500 Invalid token response } }; var generatePolicy = function(principalId, effect, resource) { var authResponse = {}; authResponse.principalId = principalId; if (effect && resource) { var policyDocument = {}; policyDocument.Version = '2012-10-17'; policyDocument.Statement = []; var statementOne = {}; statementOne.Action = 'execute-api:Invoke'; statementOne.Effect = effect; statementOne.Resource = resource; policyDocument.Statement[0] = statementOne; authResponse.policyDocument = policyDocument; } // Optional output with custom properties of the String, Number or Boolean type. authResponse.context = { "stringKey": "stringval", "numberKey": 123, "booleanKey": true }; return authResponse; } I am getting response as follows: {"message":"Internal Server Error"} Here is the log from CloudWatch for API Gateway { "requestId":"TpdEqgAZhcwEJtg=", "ip": "103.121.69.2", "requestTime":"29/Sep/2020:21:35:00 +0000", "httpMethod":"POST", "routeKey":"POST /auth/otp", "status":"500","protocol":"HTTP/1.1", "responseLength":"35" } How I do I resolve this error 500?
{ "language": "en", "url": "https://stackoverflow.com/questions/64128116", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Android/JAVA: Inner AsyncTask in a seperate file This is the given situation: public class MainActivity extends BaseActivity Implements Foo, Bar { ... not so much code ... private class GetSomeStuff extends AsyncTask<String, Integer, Boolean> { ... lot of code ... } private class GetOtherStuff extends AsyncTask<String, Integer, Boolean> { ... more code ... } } This situation makes my MainActivity very unreadable. This is a single activity app with many fragments, so the main activity only does the navigation and fragment management stuff. Is it possible to define these AsyncTask classes in another file so my code is more readable, keeping the accessibility? thanks!
{ "language": "en", "url": "https://stackoverflow.com/questions/62555077", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: GMT DateTime Conversion between different TimeZones Web application is hosted on a server with (UTC+10.00)Canberra,Sydney,Melbourne TimeZone. When a user from Melbourne creates an event it saves the datetime to database in GMT format. if the user selection is 23/12/2015 3:30:00 AM value saved to the DB will be 2015-12-22 16:30:00.000 Now when a user from (UTC+10.00)Brisbane visits the application it's still shows the same datetime but they are one hour behind from Melbourne time. So they are suppose to view 23/12/2015 2:30:00 AM There could be users from different parts of Australia. How to convert this datetime to logged in users TimeZone? A: Check this. TimeZone.CurrentTimeZone.ToLocalTime(date); https://msdn.microsoft.com/en-in/library/system.datetime.touniversaltime(v=vs.110).aspx Convert UTC/GMT time to local time A: You can get the timezone offset from the clients browser using Javascript. function returnTimeDiff(postDateTime, spanid) { var offset =(new Date().getTimezoneOffset() / 60) } Convert UTC time to Client browser's timezone using JavaScript in a MVC View
{ "language": "en", "url": "https://stackoverflow.com/questions/34427095", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Ansible Cant extract json from URL but Curl can. What am I missing? Im having some trouble with Ansible URI module when pulling json from a specific web site. Ansible Code: - name: check for Tenable Agent updates. uri: url: https://www.tenable.com/downloads/api/v1/public/pages/nessus-agents follow_redirects: none validate_certs: false return_content: yes body_format: json register: tenable_result Ansible output when run: TASK [agent-check : check for Tenable Agent updates.] *************************************************************************************************************************** fatal: [testhost.local]: FAILED! => {"cf_cache_status": "DYNAMIC", "cf_ray": "66e527b55f742542-SJC", "changed": false, "connection": "close", "content": "Bad Request", "content_length": "11", "content_type": "text/plain; charset=utf-8", "date": "Tue, 13 Jul 2021 20:10:30 GMT", "elapsed": 0, "expect_ct": "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\"", "msg": "Status code was 400 and not [200]: HTTP Error 400: Bad Request", "redirected": false, "server": "cloudflare", "set_cookie": "AWSALB=mjbt0/pPG5uYbItH6JZZsMNU31tfIYcjN3EzGUGGwe0yh1IyClNI3QZwwaIsvvxTBsxAtONNkX5ikvZUQxB/3m5RsPKsZKCs9GC/shJpEAmAiRTvDFgzMdSEsBl2; Expires=Tue, 20 Jul 2021 20:10:30 GMT; Path=/, AWSALBCORS=mjbt0/pPG5uYbItH6JZZsMNU31tfIYcjN3EzGUGGwe0yh1IyClNI3QZwwaIsvvxTBsxAtONNkX5ikvZUQxB/3m5RsPKsZKCs9GC/shJpEAmAiRTvDFgzMdSEsBl2; Expires=Tue, 20 Jul 2021 20:10:30 GMT; Path=/; SameSite=None; Secure, __cf_bm=cf4aba5cd769c19f68e8a6b84448295bb7acca50-1626207030-1800-AcDXU5VzEKMNjpyeGluMOFzCeIfWcxvrpS8wIms3LQHysBisfPjp051BUkVGysLvq7pPwEfXNDrNwGV7VV2GPbI=; path=/; expires=Tue, 13-Jul-21 20:40:30 GMT; domain=.tenable.com; HttpOnly; Secure; SameSite=None", "status": 400, "strict_transport_security": "max-age=31536000", "url": "https://www.tenable.com/downloads/api/v1/public/pages/nessus-agents", "x_content_type_options": "nosniff"} QUESTION: How do I tell Ansible to anticipate this redirect and satisfy whatever the cloudflare needs in order for me to move on to the file & ID data over on tenable.com? I know the URL works & can output the needed json data because I can parse the Filename & download ID via Curl and jq like so: $ curl -s https://www.tenable.com/downloads/api/v1/public/pages/nessus-agents| jq '.downloads[] | "\(.file) \(.id)"' "Agent_plugins_expires_2021-07-15.tgz 13183" "NessusAgent-8.3.0-x64.msi 13130" "NessusAgent-8.3.0-Win32.msi 13131" "NessusAgent-8.3.0.dmg 13132" "NessusAgent-8.3.0-debian6_amd64.deb 13134" "NessusAgent-8.3.0-debian6_i386.deb 13135" "NessusAgent-8.3.0-amzn.x86_64.rpm 13133" "NessusAgent-8.3.0-es5.x86_64.rpm 13136" "NessusAgent-8.3.0-es5.i386.rpm 13137" "NessusAgent-8.3.0-es6.x86_64.rpm 13138" "NessusAgent-8.3.0-es6.i386.rpm 13139" "NessusAgent-8.3.0-es7.x86_64.rpm 13140" "NessusAgent-8.3.0-amzn2.aarch64.rpm 13149" "nessus-agent-updates-8.3.0.tar.gz 13150" "NessusAgent-8.3.0-es8.x86_64.rpm 13141" "NessusAgent-8.3.0-fc20.x86_64.rpm 13142" "NessusAgent-8.3.0-suse11.x86_64.rpm 13143" "NessusAgent-8.3.0-suse11.i586.rpm 13144" "NessusAgent-8.3.0-suse12.x86_64.rpm 13145" "NessusAgent-8.3.0-suse15.x86_64.rpm 13146" "NessusAgent-8.3.0-ubuntu1110_amd64.deb 13147" "NessusAgent-8.3.0-ubuntu1110_i386.deb 13148" "tenable-2048.gpg 7000" "tenable-1024.gpg 6998" Any idea what I'm missing in my Ansible code?
{ "language": "en", "url": "https://stackoverflow.com/questions/68383703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it safe converting a Mat to itself with different type? Suppose I want to use a Mat as float. The following code can be compiled without error. However, is it safe doing this? Mat im = imread('test.jpg', CV_LOAD_IMAGE_GRAYSCALE); im.convertTo(im, CV_32F1); I want to do this because it's written more compact, otherwise I need to create a temporary Mat. The documentation of Mat::convertTo() doesn't give much information about the memory usage of the function. A: Mat::convertTo function should be safe to use when using inplace calls (i.e. same input and output Mat objects). According to OpenCV DevZone, this function did have a bug when using inplace calls, but it was fixed a few years ago.
{ "language": "en", "url": "https://stackoverflow.com/questions/36820387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to make array of inherited objects - Java I have abstract class Animal and inheritance classes Fish and Dog. I need to create various objects of fish and dogs and give them names and breeds and also make methods of the way they move. Finally i need to create an array of them and do 4 random prints that will show their name and breed. Main Class: public class JavaApplication38 { public static void main(String[] args) { Animal[] arr = new Animal[20]; arr[0] = new Fish("Riby", "Sea Fish"); arr[1] = new Dog("Any", "Great Dane"); arr[2] = new Fish("Ribytsa", "River fish"); arr[3] = new Dog("Jackie", "Pug"); arr[4] = new Fish("Bobi", "Mix"); arr[5] = new Dog("Ruby", "Labrador"); } } Animal class public abstract class Animal { public Animal(String name, String breed){ } public Animal(){ } public abstract void moving(); } Dog class Public class Dog extends Animal{ private String breed; private String name; public Dog(){ } public Pas(String name, String breed){ this.name = name; this.breed =breed; } @Override public void moving() { System.out.print("Walk\n"); } } Fish class public class Fish extends Animal { private String breed; private String name; public Fish(){ } public Fish(String name, String breed){ this.name = name; this.breed= breed; } @Override public void moving(){ System.out.print("Swims\n"); } } The question is, what do i have to write in a loop to print names and breeds via array? A: The problem was that you defined name and breed separately in each subclass of Animal. You need to make name and breed instance variables in Animal. That way, Java knows that every single Animal has a name and breed. public abstract class Animal { private String name; private String breed; public Animal(String name, String breed) { this.name = name; this.breed = breed; } public getName() { return name; } public getBreed() { return breed; } public abstract void moving(); } public class Dog extends Animal { public Dog(String name, String breed) { super(name, breed); } @Override public void moving(){ System.out.print("Walks\n"); } } public class Fish extends Animal { public Fish(String name, String breed) { super(name, breed); } @Override public void moving(){ System.out.print("Swims\n"); } } Now you can print the name and breed for any Animal, whether it's a Dog or Fish. Animal[] arr = new Animal[6]; arr[0] = new Fish("Riby", "Sea Fish"); arr[1] = new Dog("Any", "Great Dane"); arr[2] = new Fish("Ribytsa", "River fish"); arr[3] = new Dog("Jackie", "Pug"); arr[4] = new Fish("Bobi", "Mix"); arr[5] = new Dog("Ruby", "Labrador"); for (Animal a : arr) { System.out.println(a.getName() + " " + a.getBreed()); a.moving(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/53548100", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: xcode 4.2 iOS 5 and OAuth 2.0 - can you suggest a tutorial? can you suggest a tutorial or detailed description how to obtain authorization with OAuth 2.0 for iOS 5. Or perhaps you can help me with starting point. A: I decided to answer my question, hope it can help someone else. For OAuth 2 I found this solution: http://code.google.com/p/gtm-oauth2/ There are sample projects for mac and iOS.
{ "language": "en", "url": "https://stackoverflow.com/questions/7893836", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Problem with implement a 4-D Gaussian Processes Regression through GPML I refer to the link https://stats.stackexchange.com/questions/105516/how-to-implement-a-2-d-gaussian-processes-regression-through-gpml-matlab and create a 2-d Gaussian Process regression. I want to create a 4-d Gaussian Process regression, however the 'meshgrid' only allows 3 inputs([X,Y,Z] = meshgrid(x,y,z)); how do I add another input into meshgrid? The 3-d code is like: X1train = linspace(-4.5,4.5,10); X2train = linspace(-4.5,4.5,10); X3train = linspace(-4.5,4.5,10); X = [X1train' X2train' X3train']; Y = [X1train + X2train + X3train]'; %Testdata [Xtest1, Xtest2, Xtest3] = meshgrid(-4.5:0.1:4.5, -4.5:0.1:4.5, -4.5:0.1:4.5); Xtest = [Xtest1(:) Xtest2(:) Xtest3(:)]; % implement regression [ymu ys2 fmu fs2] = gp(hyp, @infExact, [], covfunc, likfunc, X, Y, Xtest); If I create an X4train, that means I need an Xtest4, how do I add Xtest4 into meshgrid? The GPML code is from http://www.gaussianprocess.org/gpml/code/matlab/doc/ A: You may create n- dimensional grids using ndgrid, but please keep in mind that it does not directly create the same output as meshgrid, you have to convert it first. (How to do that is also explained in the documentation)
{ "language": "en", "url": "https://stackoverflow.com/questions/69673457", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Is it possible to delay iPhone from detecting motion until a view fades from the screen? I have a crystal ball (single view) application that I need a fix for. There is a UILabel, which shows brief instructions, that appears upon the first launch of the application. I would like to disable the motion detection until the user taps the screen to dismiss the instructions. As of now, while the instructions are displayed, the user can shake the device, which displays the prediction. Is there a way to disable the motionBegan method until the user dismisses the instructions? A: Declare a BOOL instance variable and use it as a flag to indicate if the instructional view has been dismissed yet. Then, add a check inside your motionBegan method to see if it should do anything or not. Something like this: //.h BOOL instructionsDoneShowing; //.m //Wherever your instructions screen is dismissed instructionsDoneShowing = TRUE; //Inside your motionBegan method if (instructionsDoneShowing) { //Do your stuff here } A: After initiation of your view, say [yourView resignFirstResponder]; When user dismisses the instructions say - [yourView becomeFirstResponder];
{ "language": "en", "url": "https://stackoverflow.com/questions/25372665", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: matplotlib set stacked bar chart labels I am trying to create a stacked bar chart that groups data by operating system. I'm having trouble creating an individual label for each component in each bar. What I'm trying to do is different from the example in the docs because in my data each category appears in only one bar, whereas in the example each bar contains one member of each category. Currently I have this code plt.cla() plt.clf() plt.close() def get_cmap(n, name='hsv'): '''Returns a function that maps each index in 0, 1, ..., n-1 to a distinct RGB color; the keyword argument name must be a standard mpl colormap name.''' return plt.cm.get_cmap(name, n) fig = plt.figure(figsize=(18, 10), dpi=80) # group by the prefixes for now prefixes = [] indices = [] bars = [] legend = {} cmap = get_cmap(len(os_counts.index) + 1) k = 0 for i, prefix in enumerate(d): indices.append(i) if len(d[prefix]["names"]) == 1: prefixes.append(d[prefix]["names"][0]) else: prefixes.append(prefix) #colors = [next(cycol) for j in range(len(d[prefix]["names"]))] colors = [cmap(k + j) for j in range(len(d[prefix]["names"]))] k += len(colors) bar = plt.bar([i] * len(d[prefix]["names"]), d[prefix]["values"], color=colors, label=d[prefix]["names"]) bars.append(bar) plt.xticks(rotation=90) plt.ylabel("Frequency") plt.xlabel("Operating System") plt.xticks(indices, prefixes) plt.legend() plt.show() Which produces this result. As you can see, the legend is created for the first colour within the bar and shows an array. A: I think that each call to plt.bar gets one label. So, you are giving it a list as a label for each plt.bar call. If you want a label for every color, representing every operating system then I think the solution is to call plt.bar once for each color or os.
{ "language": "en", "url": "https://stackoverflow.com/questions/50651069", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Initially i connect to phonegap's database but when i move to the second html page i can;t connect I am using phonegap's database API in my html/css/js code and i have a problem.Although in the index page i manage to create tables,insert data,select and display them,when i proceed to my second html file i can't access anything from the database.I get SQL error 0.Here is my javascript file for the second html page.Any ideas? var db; function ondevre (){ alert('a1'); $.ajaxSetup({ crossDomain: true, xhrFields: { withCredentials: true } }); $.support.cors = true; $.mobile.allowCrossDomainPages = true; signsql(); function signsql(){ db = window.openDatabase("Database", "1.0", "Cordova Demo", 2*1024*1024); db.transaction(selectDB, errorCB, successCB); function errorCB(err) { alert("Error processing SQL: "+err.code); } function successCB() { alert("YEAH!!!!"); } function selectDB (tx) { myname=escape(window.localStorage["myname"]); var stre='SELECT User_Mail FROM table1 WHERE User_Name="'+myname+'"'; tx.executeSql(stre, [], mnme, function er(e) {alert("error "+e)}); function mnme (tx,result) { if (result != null && result.rows != null) { alert(result.rows.length); for (var i = 0; i < result.rows.length; i++) { var row = result.rows.item(i); }; us_mail=row.User_Mail; } } } }; } $("#ii").ready (function () { $("#whole").fadeIn(2500); ondevre(); }); app.initialize(); A: You have likely lost all the plugins - you want to code your app to be a single page app that never as such leaves "index.html" but loads data and page elements into it with Ajax / local templates etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/33926134", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to define global in XSD I would like to define TEST as global in XSD <xs:element name="TEST"> <xs:complexType> <xs:sequence> <xs:element name="TEST_LOGIN" type="xs:string" /> <xs:element name="DOCUMENT" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> A: Top-level (children of xs:schema) component definitions are inherently globally available. Nested definitions are only locally available – not referenceable elsewhere. See also * *How to reference global types in XSD? *How to define a local type in XSD?
{ "language": "en", "url": "https://stackoverflow.com/questions/69665687", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Problems with itemRollOver and itemRollOut events on List component I have set the itemRollOver and itemRollOut event listeners on a List component, but whenever I roll the mouse over a list item, both the over and out events of the same list item fire in succession right after each other. My list uses a custom itemRenderer. Any ideas why this might be? The Adobe documentation doesn't provide much insight into this (not surprisingly...). A: In my opinion this is a bug. The ListBase.mouseOverHandler now sets a variable called lastHighlightItemRendererAtIndices when it dispatches an ITEM_ROLL_OVER event, which is then used (together with lastHighlightItemIndices) when dispatching an ITEM_ROLL_OUT event in ListBase.clearHighlight (called by the mouseOutHandler). The problem is that when you mouse from row-to-row the mouseOverHandler is called first, setting the lastHightlight... variables, and then when the mouseOutHandler gets called subsequently, it uses the lastHighlight... values that were just set with the result that you get consecutive 'roll over' and 'roll out' events for the same renderer. Frankly I don't know why ListBase.clearHighlight just doesn't use the passed in renderer when dispatching the ITEM_ROLL_OUT event (which is how it used to work in SDK 2) as this is the actual renderer that is being 'rolled out of'. A: Are they coming from the same object? If not you will it is likely so that you will get an itemRollOut from the "item" you just left and a itemRollOver from the new one you entered, depending on their spacing and such these may fire very close to each other. A: Make sure you are setting super.data in your item renderer if you are overriding set data(). ListBase listens for MOUSE_OVER and then figures out the item underneath it based on coordinates of mouse and the position of the item renderer. You could check ListEvent.itemRenderer to see which renderer's roll over and roll out are firing and in what order. Worst case, you could listen for rollOver and rollOut inside your item renderer. A: Had the same problem. super.data was already being set, and the item is the same for the rollOut and rollOver event. I ended up opting for anirudhsasikumar's worst case scenario, and listened for rollOver and rollOut inside the item renderer. Seems to work fine. A: I was having this same issue. I ended up subclassing the mx.controls.List class and overriding the clearHighlight function. As far as I can tell, the lastHighlightItemIndices variable is only ever read in that function. So doing something like the following fixed this issue: import mx.core.mx_internal; use namespace mx_internal; public class List extends mx.controls.List { public function List() { super(); } override mx_internal function clearHighlight( item:IListItemRenderer ):void { var uid:String = itemToUID( item.data ); drawItem( UIDToItemRenderer( uid ), isItemSelected( item.data ), false, uid == caretUID ); var pt:Point = itemRendererToIndices( item ); if( pt ) { var listEvent:ListEvent = new ListEvent( ListEvent.ITEM_ROLL_OUT ); listEvent.columnIndex = item.x; listEvent.rowIndex = item.y; listEvent.itemRenderer = item; dispatchEvent( listEvent ); } } } Then just use this List class instead of the Adobe one and you'll have the behavior you expect. I tested this against Flex SDK 3.2 and it works. <mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:controls="com.example.controls.*"> [ other code ... ] <controls:List itemRollOver="onItemRollOver( event )" itemRollOut="onItemRollOut( event )" /> </mx:Canvas> Thanks to Gino Basso for the idea in the post above. Hope that helps. A: Thanks for the solution. That really solved the problem! Small correction, though: listEvent.columnIndex = item.x; listEvent.rowIndex = item.y; should be listEvent.columnIndex = pt.x; listEvent.rowIndex = pt.y; item.x and y hold the coordinate of the renderer in pixels.
{ "language": "en", "url": "https://stackoverflow.com/questions/331105", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Issue validating App using Sphero SDK in Xcode 7.1 beta (7B75) I'm having an issue validating an iOS 9 app (via the Organizer window) in Xcode 7.1 beta (7B75) that links to the latest RobotKit and RobotUIKit frameworks available from the Sphero Developer site. The validation fails with a message, and here's contents of the IDEDistribution.critical.log: 2015-10-06 21:55:03 +0000 [MT] Failed to generate distribution items with error: Error Domain=DVTMachOErrorDomain Code=0 "Found an unexpected Mach-O header code: 0x72613c21" UserInfo=0x7fb9a236fb40 {NSLocalizedDescription=Found an unexpected Mach-O header code: 0x72613c21, NSLocalizedRecoverySuggestion=} 2015-10-06 21:55:03 +0000 [MT] Presenting: Error Domain=DVTMachOErrorDomain Code=0 "Found an unexpected Mach-O header code: 0x72613c21" UserInfo=0x7fb9a236fb40 {NSLocalizedDescription=Found an unexpected Mach-O header code: 0x72613c21, NSLocalizedRecoverySuggestion=} As a test, I deleted both Sphero embedded frameworks from the .xcarchive file that is being validated, so the issue points to something in those underlying frameworks. Does anyone have any pointers? A: I have an update. The issue turned out to be simple in hindsight. I added both the RobotUIKit and RobotKit frameworks to the "Embedded Binaries" section of the General tab for my target app in Xcode. They should ONLY be added to the "Linked Frameworks and Libraries" section. The Sphero framework is a pre-iOS 8 framework and thus appears to be statically linked.
{ "language": "en", "url": "https://stackoverflow.com/questions/32980504", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Create lists of nodes from rows of matching pairs Not sure if this can be done with pandas or if I need to write a loop with some logic. I have some data representing chains of pairs of nodes: pairs = [ # A1 -> B1 -> C1 {'source': 'A1', 'target': 'B1'}, {'source': 'B1', 'target': 'C1'}, # A1 -> D1 {'source': 'A1', 'target': 'D1'}, # C2 -> A2 -> B2 {'source': 'C2', 'target': 'A2'}, {'source': 'A2', 'target': 'B2'}, ] And I want to resolve those chains to create the list of nodes they contain: results = [ ['A1', 'B1', 'C1', 'D1'], ['C2', 'A2', 'B2'], ] So far I have this code which does allow me to match some of those nodes together: def pair_nodes(df, src, tgt): df = df.groupby([src]).agg({tgt: 'unique'}).reset_index() df['nodes'] = df.apply(lambda r: np.append(r[src], r[tgt]), axis=1) return df df1 = pair_nodes(df, 'source', 'target') df2 = pair_nodes(df, 'target', 'source') print(df1) print(df2) Which gives me: source target nodes 0 A1 [B1, D1] [A1, B1, D1] 1 A2 [B2] [A2, B2] 2 B1 [C1] [B1, C1] 3 C2 [A2] [C2, A2] target source nodes 0 A2 [C2] [A2, C2] 1 B1 [A1] [B1, A1] 2 B2 [A2] [B2, A2] 3 C1 [B1] [C1, B1] 4 D1 [A1] [D1, A1] And I'm a stuck there. What I guess I'm missing is to merge rows from df1 and df2 whenever source or target is found in nodes I had a look at df.merge but it only seems to work for exact key match. Can this be achieved with pandas or do I need to write a custom loop/logic to do this? A: Creating the desired result with merging dataframes can be a complicated process. The above used login of merging will not be able to satisfy all types of graphs. Have a look at the below method. # Create graph graph = {} for pair in pairs: if pair['source'] in graph.keys(): graph[pair['source']].append(pair['target']) else: graph[pair['source']] = [pair['target']] # Graph print(graph) { 'A1': ['B1', 'D1'], 'B1': ['C1'], 'C2': ['A2'], 'A2': ['B2'] } # Generating list of nodes start = 'A1' # Starting node parameter result = [start] for each in result: if each in graph.keys(): result.extend(graph[each]) result = list(set(result)) # Output print(result) ['A1', 'B1', 'C1', 'D1']
{ "language": "en", "url": "https://stackoverflow.com/questions/56241829", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: iTunes connect update limited to some countries? I have an app available for multiple countries; and now I need to release an update only to some of this countries. Example An app available for the whole world, is going to get an update, but it should only be available for USA users for instance. Is it possible to release this update only to the USA store, or somehow limit it? Thanks in advance. A: If you limit the app to any geographical extent, then current users will be able to use it, but it won't appear to anyone on iTunes. So, if you wanted an update for some region while having the previous version available, the answer is no, there's no way to do that. @skorulis I find many reasons why you could want to do so, e.g. incremental release of the app update amongst many others.
{ "language": "en", "url": "https://stackoverflow.com/questions/30333029", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: UIImageView.image not loading I have a strange issue with loading an imageview into a UITableViewCell during: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath here is my code: UIImageView *title = [[[UIImageView alloc] initWithFrame:CGRectMake(0,10,300,150)] autorelease]; title.image = [UIImage imageNamed:@"featured_graphic.png" ]; title.contentMode = UIViewContentModeScaleAspectFill; title.alpha = 1.0; cell.selectionStyle = UITableViewCellSelectionStyleNone; its inside this: if( [indexPath isEqual:[NSIndexPath indexPathForRow:0 inSection:0]] ) { } I verified that featured_graphic.png is in my application. A: You make the title but you don't actually add it to the view. [cell.contentView addSubview:title];
{ "language": "en", "url": "https://stackoverflow.com/questions/8108458", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to update column name after finding the table names from information schema I have run a script to find the table names with a specific column name from a database using the information schema here is the query use IMS_SCMS_DIGITAL_POWER select * from information_schema.columns where column_name like 'COMPANY_ID%' after finding the table names now i would like to update the specific column values of all the database. Need solutions. A: Run following query to get all tablenames with specific column name SELECT t.name AS TableName FROM sys.columns c JOIN sys.tables t ON c.object_id = t.object_id WHERE c.name LIKE '%COMPANY_ID%' just use in forward only cursor with tablenames to update the specific table.
{ "language": "en", "url": "https://stackoverflow.com/questions/23774704", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Angular PWA implementation on a specific component of angular Successfully converted my app into PWA but what I wanted to achieve is, I wanted that install option start visible from localhost/employee/dashboard not from localhost/. What I tried so far is: I put the URL (employee/dashboard/) in the starting URL of menifest.json, but what I achieve by this is it still showing the install option from the localhost/ but on installing it start PWA screen from localhost/employee/dashboard which is not what I wanted. What I wanted: I know to achieve this what I have to do is to put in the index.html of that component, but my project is not in simple html,css,js where every component have a tag where I put and it starts giving install option from there. It is angular, can I somehow achieve this.
{ "language": "en", "url": "https://stackoverflow.com/questions/74637522", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: np.transpose behavior different for different array constructions I came across this weird behavior with np.transpose wherein it works differently when used on an numpy array and array constructed from a list. As an MWE following code is presented. import numpy as np a = np.random.randint(0, 5, (1, 2, 3)) print(a.shape) # prints (1, 2, 3) b = np.transpose(a, (0, 2, 1)) print(b.shape) # prints (1, 3, 2), which is expected # Constructing array from list of arrays c = np.array([np.random.randint(0, 5, (2, 3)), np.random.randint(0, 5, (2, 3)), np.random.randint(0, 5, (2, 3)), np.random.randint(0, 5, (2, 3))]) print(c.shape) # prints (4, 2, 3) d = np.transpose(c, (2, 0, 1)) print(d.shape) # prints (3, 4, 2), whereas I expect it to be (2, 3, 4) I do not understand this behavior. Why is it that the array constructed from the list has the dimensions mixed up? Any help is appreciated. A: np.transpose() picks the dimensions you specify in the order you specify. In your first case, your array shape is (1,2,3) i.e. in dimension->value format, it is 0 -> 1, 1 -> 2 and 2 -> 3. In np.transpose(), you're requesting for the order 0,2,1 which is 1,3,2. In the second case, your array shape is (4,2,3) i.e. in dimension->value format, it is 0 -> 4, 1 -> 2 and 2 -> 3. In np.transpose(), you're requesting for the order 2,0,1 which is 3,4,2.
{ "language": "en", "url": "https://stackoverflow.com/questions/70741320", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How can Apache Camel be used to monitor file changes? I would like to monitor all of the files in a given directory for changes, ie an updated timestamp. This use case seems natural for Camel using the file component, but I can't seem to find a way to configure this behavior. A uri like: file:/some/directory will consume the files in the provided directory but will delete them. A uri like: file:/some/directory?noop=true consumes each file once when it is added or when the route is started. It's surprising that there isn't an option along the lines of consumeOnChange=true Is there a straightforward way to monitor file changes and not delete the file after consuming? A: You can do this by setting up the idempotentKey to tell Camel how a file is considered changed. For example if the file size changes, or its timestamp changes etc. See more details at the Camel file documentation at: https://camel.apache.org/components/latest/file-component.html See the section Avoiding reading the same file more than once (idempotent consumer). And read about idempotent and idempotentKey. So something alike from("file:/somedir?noop=true&idempotentKey=${file:name}-${file:size}") Or from("file:/somedir?noop=true&idempotentKey=${file:name}-${file:modified}") You can read here about the various ${file:xxx} tokens you can use: http://camel.apache.org/file-language.html A: Setting noop to true will result in Camel setting idempotent=true as well, despite the fact that idempotent is false by default. Simplest solution to monitor files would be: .from("file:path?noop=true&idempotent=false&delay=60s") This will monitor changes to all files in the given directory every one minute. This can be found in the Camel documentation at: http://camel.apache.org/file2.html. A: I don't think Camel supports that specific feature but with the existent options you can come up with a similar solution of monitoring a directory. What you need to do is set a small delay value to check the directory and maintain a repository of the already read files. Depending on how you configure the repository (by size, by filename, by a mix of them...) this solution would be able to provide you information about news files and modified files. As a caveat it would be consuming the files in the directory very often. Maybe you could use other solutions different from Camel like Apache Commons VFS2 (I wrote a explanation about how to use it for this scenario: WatchService locks some files? A: I faced the same problem i.e. wanted to copy updated files also (along with new files). Below is my configuration, public static void main(String[] a) throws Exception { CamelContext cc = new DefaultCamelContext(); cc.addRoutes(createRouteBuilder()); cc.start(); Thread.sleep(10 * 60 * 1000); cc.stop(); } protected static RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("file://D:/Production" + "?idempotent=true" + "&idempotentKey=${file:name}-${file:size}" + "&include=.*.log" + "&noop=true" + "&readLock=changed") .to("file://D:/LogRepository"); } }; } My testing steps: * *Run the program and it copies few .log files from D:/Production to D:/LogRepository and then continues to poll D:/Production directory *I opened a already copied log say A.log from D:/Production (since noop=true nothing is moved) and edited it with some editor tool. This doubled the file size and save it. At this point I think Camel is supposed to copy that particular file again since its size is modified and in my route definition I used "idempotent=true&idempotentKey=${file:name}-${file:size}&readLock=changed". But camel ignores the file. When I use TRACE for logging it says "Skipping as file is already in progress...", but I did not find any lock file in D:/Production directory when I editted and saved the file. I also checked that camel still ignores the file if I replace A.log (with same name but bigger size) in D:/Production directory from outside. But I found, everything is working as expected if I remove noop=true option. Am I missing something? A: If you want monitor file changes in camel, use file-watch component. Example -> RECURSIVE WATCH ALL EVENTS (FILE CREATION, FILE DELETION, FILE MODIFICATION): from("file-watch://some-directory") .log("File event: ${header.CamelFileEventType} occurred on file ${header.CamelFileName} at ${header.CamelFileLastModified}"); You can see the complete documentation here: Camel file-watch component
{ "language": "en", "url": "https://stackoverflow.com/questions/20086532", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "19" }
Q: What is helperGrowEdges function in MATLAB I was following a tutorial in matlab documentation at http://www.mathworks.com/help/vision/examples/automatically-detect-and-recognize-text-in-natural-images.html There they use a function helperGrowEdges but I it is not being recognized right now. I verified that I have Computer Vision System Toolbox. I am unable to figure how to implement it. It says it 'Grow the edges outward by using image gradients around edge locations', but I am unable to figure out how to implement is well. A: As hinted out by Naveh, It works those functions are present only in MATLAB 2014 version and not in older versions. Older versions do not have that example as well when I try to open edit TextDetectionExample A: This example first appears in release R2014a. helperGrowEdges is a helper function, which goes with the example. Unfortunately it does not get published in the documentation. The only way for you to see it is to get access to an installation of MATLAB R2014a with the Computer Vision System Toolbox, and do edit helperGrowEdges.
{ "language": "en", "url": "https://stackoverflow.com/questions/23142176", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Lightweight pickle for basic types in python? All I want to do is serialize and unserialize tuples of strings or ints. I looked at pickle.dumps() but the byte overhead is significant. Basically it looks like it takes up about 4x as much space as it needs to. Besides, all I need is basic types and have no need to serialize objects. marshal is a little better in terms of space but the result is full of nasty \x00 bytes. Ideally I would like the result to be human readable. I thought of just using repr() and eval(), but is there a simple way I could accomplish this without using eval()? This is getting stored in a db, not a file. Byte overhead matters because it could make the difference between requiring a TEXT column versus a varchar, and generally data compactness affects all areas of db performance. A: personally i would use yaml. it's on par with json for encoding size, but it can represent some more complex things (e.g. classes, recursive structures) when necessary. In [1]: import yaml In [2]: x = [1, 2, 3, 'pants'] In [3]: print(yaml.dump(x)) [1, 2, 3, pants] In [4]: y = yaml.load('[1, 2, 3, pants]') In [5]: y Out[5]: [1, 2, 3, 'pants'] A: Maybe you're not using the right protocol: >>> import pickle >>> a = range(1, 100) >>> len(pickle.dumps(a)) 492 >>> len(pickle.dumps(a, pickle.HIGHEST_PROTOCOL)) 206 See the documentation for pickle data formats. A: If you need a space efficient solution you can use Google Protocol buffers. Protocol buffers - Encoding Protocol buffers - Python Tutorial A: Take a look at json, at least the generated dumps are readable with many other languages. JSON (JavaScript Object Notation) http://json.org is a subset of JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data interchange format. A: There are some persistence builtins mentioned in the python documentation but I don't think any of these is remarkable smaller in the produced filesize. You could alway use the configparser but there you only get string, int, float, bool. A: "the byte overhead is significant" Why does this matter? It does the job. If you're running low on disk space, I'd be glad to sell you a 1Tb for $500. Have you run it? Is performance a problem? Can you demonstrate that the performance of serialization is the problem? "I thought of just using repr() and eval(), but is there a simple way I could accomplish this without using eval()?" Nothing simpler than repr and eval. What's wrong with eval? Is is the "someone could insert malicious code into the file where I serialized my lists" issue? Who -- specifically -- is going to find and edit this file to put in malicious code? Anything you do to secure this (i.e., encryption) removes "simple" from it. A: Luckily there is solution which uses COMPRESSION, and solves the general problem involving any arbitrary Python object including new classes. Rather than micro-manage mere tuples sometimes it's better to use a DRY tool. Your code will be more crisp and readily refactored in similar future situations. y_serial.py module :: warehouse Python objects with SQLite "Serialization + persistance :: in a few lines of code, compress and annotate Python objects into SQLite; then later retrieve them chronologically by keywords without any SQL. Most useful "standard" module for a database to store schema-less data." http://yserial.sourceforge.net [If you are still concerned, why not stick those tuples in a dictionary, then apply y_serial to the dictionary. Probably any overhead will vanish due to the transparent compression in the background by zlib.] As to readability, the documentation also gives details on why cPickle was selected over json.
{ "language": "en", "url": "https://stackoverflow.com/questions/532934", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "7" }
Q: React get metamask latest transaction status I am using this, to make a function call in smart contract via metamask in react: export default class EthereumForm1 extends Component { constructor (props) { super (props); const MyContract = window.web3.eth.contract(ContractABI); this.state = { ContractInstance: MyContract.at('ContractAddress') } this.doPause = this.doPause.bind (this); } doPause() { const { pause } = this.state.ContractInstance; pause ( { gas: 30000, gasPrice: 32000000000, value: window.web3.toWei (0, 'ether') }, (err) => { if (err) console.error ('Error1::::', err); console.log ('Contract should be paused'); }) } What I want is to run jQuery code with loading gif: $(".Loading").show(); while transaction is being processed and remove it after. Also, it would be good to add transaction status in div after, like in metamask(either passed or rejected). A: What helped me was checking every few seconds if my transactiopn finished, and if yes hiding the loader. if (latestTx != null) { window.web3.eth.getTransactionReceipt(latestTx, function (error, result) { if (error) { $(".Loading").hide(); console.error ('Error1::::', error); } console.log(result); if(result != null){ latestTx = null; $(".Loading").hide(); } }); } A: You don't need jquery to do this. React state can manage the status of the progress automatically. All you have to do is to call setState function. class EthereumFrom1 extends React.Component { state = { loading: false }; constructor(props) { super(props); this.doPause = this.doPause.bind(this); } doPause() { const {pause} = this.state.ContractInstance; pause( { gas: 30000, gasPrice: 32000000000, value: window.web3.toWei(0, 'ether') }, (err) => { if (err) console.error('Error1::::', err); this.setState({loading: true}); }) } render() { return ( <div> {this.state.loading ? <div className="Loading"> Loading... </div> : <div>done</div> } </div> ) } }
{ "language": "en", "url": "https://stackoverflow.com/questions/49310555", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: my server it looking for a file, but i have a string, How would i simulate a fileupload via jquery i was curious if there was a way for me to set up an ajax call such that a string would be recognized as a file. i essentially created a XML via javascript that is in string format, and want to upload it, but the server looks for a file. I was thinking that i would have to post it to a webservice such that it would post to a iframe as file contents or something and then upload it that way or some other hack around it. EDIT: I was thinking this might be a solution? Creating a fake file? How to upload string as file with jQuery or other js framework A: After looking at the same for how to upload a string as a file with Jquery and then looking at how the server processed the information. I determined that the data saved doesnt nessicarily have to be that of a file. When looking at responsees, all that information was in the string the next time it was pulled. I actually just removed the data and pushed it up and it returned what i wanted. var myData = { user: top.USERNAME, pass: top.PW_HASH, secure: true, url: top.BASE_URL, ext: "foo", data:saveXML }; which as you can see, the data being passed in the object to my $.ajax wrapper was just the saveXML.
{ "language": "en", "url": "https://stackoverflow.com/questions/18596697", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: X Axis on graph in Power BI does not display full date range I am new at Power BI and created a column chart to display events for every month in a 13 month period. The X axis is displaying all the data, but the naming of the months is not correct as it skips every second month. Does anyone know where I can change this as I suspect it might only be a format change. I have attached a screenshot to show the x axis. Thank you! enter image description here A: Please go to X-axis in format tab in Visualizations and change type from Continuous to Categorical. Type as Categorical Create a calculated column as follows and sort it using Date field MonthLabel = CONCATENATE(CONCATENATE(LEFT([Date].[Month],3)," "),Right([Date],4)) Hope this helps! Best Regards, Shani Noorudeen
{ "language": "en", "url": "https://stackoverflow.com/questions/62296862", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Here the class Main is throwing DERIVED without declaring Main as THROWS but it works, can anyone explain this Here the class Main is throwing DERIVED without declaring Main as THROWS but it works, can anyone explain this. class Base extends Exception {} class Derived extends Base {} public class Main {//main class throwing DERIVED public static void main(String args[]) { // some other stuff try { // Some monitored code throw new Derived(); } catch(Base b) { System.out.println("Caught base class exception"); } catch(Derived d) { System.out.println("Caught derived class exception"); } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/50809166", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to find a substring in a cell array I am trying to use regexp in MATLAB to search for two words in strings in cell arrays. My cell array contains strings={'1abc_2def_ghi_AB_12A','1abc_2def_ghi_BD_19A','1abc_2def_ghi_CD_16A',} How would I go about constructing the expression to search the cell array for the string that contains both 'ghi' and '12'? Thanks in advance for any assistance. A: How about this? result = find(~cellfun(@isempty, regexp(strings, 'ghi')) & ... ~cellfun(@isempty, regexp(strings, 'AB'))); Or, using a single regular expression, result = find(~cellfun(@isempty, regexp(strings, '(ghi.*AB|ghi.*AB)')));
{ "language": "en", "url": "https://stackoverflow.com/questions/29357541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: addHTMLImage not working I am working on a project that sends out HTML emails to people after a forum is filled out, I have gotten the HTML portion of the code to work but for some reason cannot get the banner image to appear at the top when embedding the image into my code. I had it work before when I was working on the latest version of PHP but had to downgrade to PHP 5.3 in order for my scripts to run on our server. Since then I used the same code and it resulted in failure. I have tried many different methods and none have proven effective. Here is my code require_once('Mail.php'); require_once('Mail/mime.php'); $smtp_credentials = array('host' => 'smtp.postmarkapp.com', 'port' => 25, 'auth' => TRUE, 'username' => '*', 'password' => '*'); $headers = array('From' => '*', 'To' => $email, 'Subject' => $subject); $mime = new Mail_mime(array('eol' => PHP_EOL)); $file = '/*/*/*/dls.jpg'; $mime->addHTMLImage(file_get_contents($file),'image/jpeg',basename($file),false, "blackstone"); #I used this code to fish out the cid out of mime I tried echoing this out and # it returned blackstone which I defined as the 5th parameter of addHTMLImage which # sets the cid. $cid=$mime->_html_images[count($mime->_html_images)-1]['cid']; $banner = '<span style="color:#1f497d"> <img width = "623" height = "85" src = "cid:' . $cid . '" /> </span>'; $message_text = $banner; $mime->setHTMLBody($message_text); $mime->setTXTBody($body_text); $mail = Mail::factory('smtp', $smtp_credentials); try { $send = $mail->send($email, $mime->headers($headers), $mime->get()); } catch (Exception $e) { echo $e->getMessage(); die; } echo 'mail sent!'; I have tried many different things, like not using cids at all which I would prefer since a lot of mail clients do not work well with cids, but on the PEAR manual it is suggested to use cid in the src attribute. I am using gmail, but I do not think this is the problem since it worked when I was running the newer version of php. whenever I open the email, the html portion of it works. Where the image should be there is a little image icon but no image is displayed. A: The image url is supposed to be an absolute url.. not a path (relative or absolute).. it can't be a path, it must be a complete url to the image. So you need to use a valid url such as the one below. http://www.example.com/images/image-name.jpg Something like the below would not work. ../path/to/images/image-name.jpg and the same goes for below (it won't work): /root/public/path/to/images/image-name.jpg so make sure you are specifying a valid url to your image.
{ "language": "en", "url": "https://stackoverflow.com/questions/14879266", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to set element invisible with animation? I have this toggle button that when it is on, calls an animation method that sets several elements visible. But when I turn it off, the elements remain visible, although the opposite instruction. How can I make them disapear with the same logic? Do I have to create another method? Thanks, here's the code: drum.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { key1.setVisibility(View.VISIBLE); key1.startAnimation(fadeInAnimation()); key2.setVisibility(View.VISIBLE); key2.startAnimation(fadeInAnimation()); key3.setVisibility(View.VISIBLE); key3.startAnimation(fadeInAnimation()); rocking.setLooping(true); rocking.start(); Toast.makeText(getApplicationContext(), "Rock and Rolling!", Toast.LENGTH_SHORT).show(); } else { rocking.setLooping(false); key1.setVisibility(View.INVISIBLE);// These instrucions are ignored... key2.setVisibility(View.INVISIBLE); key3.setVisibility(View.INVISIBLE); Toast.makeText(getApplicationContext(), "Can't keep up? Try the tamborine!", Toast.LENGTH_SHORT).show(); } } }); And the animation method: private Animation fadeInAnimation() { Animation animation = new AlphaAnimation(0f, 1.0f); animation.setDuration(1000); animation.setFillEnabled(true); animation.setFillAfter(true); return animation; } A: Change the fadeInAnimation and pass a boolean argument, if true do fade-In animation else fade-out animation. Code sample is given below. Usage fadeAnimation(true) for fadeIn animation and fadeAnimation(false) for fadeOut animation. Hope this helps. private Animation fadeAnimation(boolean fadeIn) { Animation animation = null; if(fadeIn) animation = new AlphaAnimation(0f, 1.0f); else animation = new AlphaAnimation(1.0f, 0f); animation.setDuration(1000); animation.setFillEnabled(true); animation.setFillAfter(true); return animation; } A: Checkout below code viewObject.animate() .alpha(0.0f) .setStartDelay(10000) .setDuration(2000) .setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); // do your stuff if any, after animation ends } }).start(); A: possible duplicate of View.setVisibility(View.INVISIBLE) does not work for animated view. visibility are not honoured as long as an animation is performed even though animation is cancelled
{ "language": "en", "url": "https://stackoverflow.com/questions/40616506", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: what does allowLossyConversion mean in ios I am using the dataUsingEncoding(encoding: NSStringEncoding, allowLossyConversion: Bool = default) -> NSData? function to convert String to NSData, but I don't get what allowLossyConversion actually means. Is it similar to Lossy compression? Can anybody help me understand this? A: If flag is YES and the receiver can’t be converted without losing some information, some characters may be removed or altered in conversion. For example, in converting a character from NSUnicodeStringEncoding to NSASCIIStringEncoding, the character ‘Á’ becomes ‘A’, losing the accent.
{ "language": "en", "url": "https://stackoverflow.com/questions/29256216", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How can I set different session lifetime for each role? How can I set different session lifetime for each symfony role? Is there a built-in option for doing this? We're using different roles, one for our clients and one for each department within our company. We'd like to increase session lifetime for company roles without increasing it for the clients role. A: You would have to set the session lifetime for the role that has the highest, and then, saving dates on your database, log users out after the amount of time that you want.
{ "language": "en", "url": "https://stackoverflow.com/questions/52253521", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-4" }
Q: Angular component has click listener attribute How can I know within my-component, if the parent listens to the click event (A) or not (B). Case A: <my-component (click)="onClick()"></my-component> Case B: <my-component></my-component> Definition: @Component({ selector: 'my-component', templateUrl: './my-component.component.html', }) export class MyComponent { @???() hostHasClickListener: boolean; // I want to know this within my component } Thank you! A: You can achieve this by using an @Output with click as the name. This forces the consumers to bind their function to this click when they use (click)="Blah()" in the HTML. this.click.observed return true when click is used in the HTML. mycomponent.component.ts @Component({ ... }) export MyComponent implements OnInit { @Output() public click = new EventEmitter(); private _hasClick = false; public ngOnInit() { this._hasClick = this.click.observed; if(this._hasClick) { // do something here. } } }
{ "language": "en", "url": "https://stackoverflow.com/questions/74281925", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: replace columns in hive I have created a table in hive, now I am trying to replace the columns name using REPLACE COLUMNS. Alter query is: **ALTER TABLE emp1 REPLACE COLUMNS ( id INT eid int, name STRING ename string, sal INT esal int, city string ecity string, country string ecountry string);** MismatchedTokenException(26!=301) at org.antlr.runtime.BaseRecognizer.recoverFromMismatchedToken(BaseRecognizer.java:617) at org.antlr.runtime.BaseRecognizer.match(BaseRecognizer.java:115) at org.apache.hadoop.hive.ql.parse.HiveParser.alterStatementSuffixAddCol(HiveParser.java:9898) at org.apache.hadoop.hive.ql.parse.HiveParser.alterTblPartitionStatementSuffix(HiveParser.java:8524) at org.apache.hadoop.hive.ql.parse.HiveParser.alterTableStatementSuffix(HiveParser.java:8139) at org.apache.hadoop.hive.ql.parse.HiveParser.alterStatement(HiveParser.java:7190) at org.apache.hadoop.hive.ql.parse.HiveParser.ddlStatement(HiveParser.java:2602) at org.apache.hadoop.hive.ql.parse.HiveParser.execStatement(HiveParser.java:1589) at org.apache.hadoop.hive.ql.parse.HiveParser.statement(HiveParser.java:1065) at org.apache.hadoop.hive.ql.parse.ParseDriver.parse(ParseDriver.java:201) at org.apache.hadoop.hive.ql.parse.ParseDriver.parse(ParseDriver.java:166) at org.apache.hadoop.hive.ql.Driver.compile(Driver.java:462) at org.apache.hadoop.hive.ql.Driver.compileInternal(Driver.java:1276) at org.apache.hadoop.hive.ql.Driver.runInternal(Driver.java:1393) at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1205) at org.apache.hadoop.hive.ql.Driver.run(Driver.java:1195) at org.apache.hadoop.hive.cli.CliDriver.processLocalCmd(CliDriver.java:220) at org.apache.hadoop.hive.cli.CliDriver.processCmd(CliDriver.java:172) at org.apache.hadoop.hive.cli.CliDriver.processLine(CliDriver.java:383) at org.apache.hadoop.hive.cli.CliDriver.executeDriver(CliDriver.java:775) at org.apache.hadoop.hive.cli.CliDriver.run(CliDriver.java:693) at org.apache.hadoop.hive.cli.CliDriver.main(CliDriver.java:628) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.apache.hadoop.util.RunJar.run(RunJar.java:221) at org.apache.hadoop.util.RunJar.main(RunJar.java:136) FAILED: ParseException line 2:7 mismatched input 'eid' expecting ) near 'INT' in add column statement Please help me. I am learning hive A: REPLACE is used when you want to have an altogether different columns to your table.If not it is better to rename the column_name with the CHANGE option in the alter statement. A: The ALTER TABLE <TableName> REPLACE COLUMNS removes all existing columns and adds the new set of columns. ALTER TABLE <TableName> REPLACE COLUMNS (EID INT, EName STRING); REPLACE COLUMNS For your scenario you can make use of ALTER TABLE <TableName> CHANGE <ColumnName> ALTER TABLE <TableName> CHANGE ID EID INT; This page will give you a lots of information ALTER COLUMNS
{ "language": "en", "url": "https://stackoverflow.com/questions/46967456", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Why, in Python, a dictionary does not need to be nonlocal to be seen in an inner function I am learning Python and while I was doing exercises with decorators, I found a case that I don't understand. The code bellow, inspired by the tutorial I use, is working: >>> def maxExeTime(absMax,printMax=False): ... def decorFun(toDo): ... storeInfo = {"exeMax":0} ... def modified(*p,**pp): ... startTime = time.time() ... returnValue = toDo(*p,**pp) ... exeTime = time.time() - startTime ... if exeTime > storeInfo["exeMax"]: ... storeInfo["exeMax"] = exeTime ... if printMax: ... print("max execution time = {}".format(storeInfo["exeMax"])) ... if exeTime > absMax: ... raise Exception("Max exe time reached: {}".format(exeTime)) ... return returnValue ... return modified ... return decorFun ... >>> @maxExeTime(15,printMax=True) ... def mul(x,y): ... input("Press Enter...") ... return x*y ... >>> >>> mul(3,4) Press Enter... max execution time = 1.1439800262451172 12 >>> mul(3,5) Press Enter... max execution time = 2.1652064323425293 15 >>> mul(3,7) Press Enter... max execution time = 2.1652064323425293 21 >>> mul(3,10) Press Enter... max execution time = 21.074586629867554 Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 13, in modified Exception: Max exe time reached: 21.074586629867554 >>> But I don't understand why the dictionary storeInfo is persistent and can be re-used from one call to the other. If I try to store the information directly in a variable (ie exeMax=0) and adapt the code accordingly, I get the behavior that I was expecting with an exception at run time: UnboundLocalError: local variable 'exeMax' referenced before assignment when I try to compare the current execution time with the actual max value (if exeTime > exeMax:) Why does the dictionary persists out of the scope of the maxExeTime function execution? Thanks to the links an the redirection to duplicate questions, I discovered closure which was a concept I never see before. Good. And I understand why it does not work in my test with the local variable exeMax since I didn't declare it as nonlocal. But I didn't do it either for the dictionary storeInfo, and it is working. Why does this type of object have a different behavior? Edit @kindall what you say explains why it is necessary to use nonlocal when I use and integer directly since it seems that integers have a different behavior/rules than other objects, and I want to modify the value in the inner function. But I still don't understand why if exeTime < exeMax: fails when exeTime < storeInfo["exeMax"] does not, and then why the next code is valid. >>> a = 12 >>> def m(x): ... return a*x ... >>> m(3) 36 >>> a = 15 >>> m(3) 45 For the moment, all these differences in behavior make the variable scope definition looking fuzzy for me. I need to find a clear definition of it, with, I hope, a small set of rules and no exception.
{ "language": "en", "url": "https://stackoverflow.com/questions/69662678", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: TypeGuards for optional property while filtering array of objects I've got the following interfaces in typescript: interface ComplexRating { ratingAttribute1?: number; ratingAttribute2?: number; ratingAttribute3?: number; ratingAttribute4?: number; } export interface Review { rating: ComplexRating | number; } I'd love to calculate an average rating for say ratingAttribute1 for sake of simplicity. So given these reviews: const reviews: Review[] = [ { rating: { ratingAttribute1: 5 } }, { rating: { ratingAttribute1: 10 } }, { rating: { ratingAttribute2: 15 } }, { rating: 5 } ] I can filter down the reviews to the ones I'm interested in i.e.: const calculateAverageRating = (reviews: Review[]): number => { const reviewsWithRating = reviews.filter( (review) => typeof review.rating === 'object' && typeof review.rating['ratingAttribute1'] === 'number' ); return ( reviewsWithRating.reduce((acc, review) => { let newValue = acc; if (typeof review.rating === 'object') { const rating = review.rating['ratingAttribute1']; if (rating) { newValue += rating; } } return newValue; }, 0.0) / reviewsWithRating.length ); }; Now, what's annoying is that Typescript does not know that by running the reviews.filter function I type guarded the Reviews only to a subset of the Reviews that have rating of type ComplexType and also the ones that have ratingAttribute1: number; rather than ratingAttribute?: number. What I'd love to end up with is not having to repeat the type checks in the calculation effectively ending up with: const calculateAverageRating = (reviews: Review[]): number => { const reviewsWithRating = reviews.filter( (review) => typeof review.rating === 'object' && typeof review.rating['ratingAttribute1'] === 'number' ); return ( reviewsWithRating.reduce( (acc, review) => acc + review.rating['ratingAttribute1'], 0.0 ) / reviewsWithRating.length ); }; but that does not work out of the box: Is there any way of achieving this level of type guarding? Or is there a neater of way doing this type of stuff? A: The .filter() function will always return an array of the same type that was given as the argument. That is why reviewsWithRating is still a Review[], even after you filter it. To change this, you can add a type guard to the callback: const reviewsWithRating = reviews.filter( (review): review is { rating: Required<ComplexRating> } => typeof review.rating === 'object' && typeof review.rating['ratingAttribute1'] === 'number' ); Now TypeScript will know that reviewsWithRating is of type { rating: Required<ComplexRating> }[].
{ "language": "en", "url": "https://stackoverflow.com/questions/72292351", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Connection Error in SQL Server Compact with ASP.Net I am trying to access a database, using a DataSet. I am using Visual Studio for Web Express 2013, ASP Web Forms project with SQL Server Compact 4.0. I created the database from Database Explorer, added 3 tables, now my code has getData, setData methods which will use Dataset to get data. But the SqlConnection object is throwing exception at runtime. [SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)] I guess this is due to connection string since error is at line: SLQCon.Open(); I have tried more than one method but none of them has worked yet. These are few of them, msdn link Connection Strings The other things work fine (web form controls), only problem is when I do something related to database, any fixes? My code is as follows: void setData(string tableName) { string ConString = @"Data Source=" + "F:\\Github\\JournalClassifier\\WebApplication1\\WebApplication1\\App_Data\\KeywordsDB.sdf" + ";Connect Timeout=30"; SQLCon.ConnectionString = ConString; SQLCon.Open(); // Exception here // insertion code } A: Make sure your database inside App_Data folder on your root application. and change the connection string to this one <add name="ConnectionStringName" providerName="System.Data.SqlServerCe.4.0" connectionString="Data Source=\KeywordsDB.sdf;Connection Timeout=30" /> things you need to concern is you are using SQL Server Compact, so the provider name need use System.Data.SqlServerCe.4.0 otherwise it will confused with SQL Server Client
{ "language": "en", "url": "https://stackoverflow.com/questions/34632951", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to detect corner "joints" that connect elements on images? I'm using OpenCV via Python 3.7. I have a set of monochrome images that look like this: I'd like to find all "joint points" on these images, where a "joint point" - is a center (1 pixel) of every intersection of two planks. These "joints" are roughly represented by red cicrles on the image below: The first idea was to skeletonize the image and then find all connected edges algorythmically, but all skeletonizations technques gave me wiggly or round corners and extra "sprouts". import cv2 import numpy as np from skimage.morphology import skeletonize image = cv2.imread("SOURCE_IMAGE.jpg", cv2.IMREAD_GRAYSCALE) binary_image = cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 91, 12) skeleton = (skeletonize(binary_image//255) * 255).astype(np.uint8) Result: The second idea was to find inner contours, approximate them to bounding points, find closest neighbours and then somehow calculate centers, but, again, Canny edge detection method gave me wiggly corners and extra points. import cv2 image = cv2.imread("SOURCE_IMAGE.jpg", cv2.IMREAD_GRAYSCALE) edged = cv2.Canny(image, 100, 200) Result: Are there any reliable approcahes to this problem? A: This is my approach to solve this issue: * *Determine vertical lines *Determine horizontal lines *Find their intersections which are joints For first step check each column and determine thin lines and make them black(0). The result will be only vertical lines. For the second step do reverse. At the end compare vertical line image with the horizontal line image. The pixels which are white(255) in both are the intersection points. Note: Please do not blame me because of coding in C++. I am not familiar with python I just wanted to show my approach and results. Here is the code and results: Source: Vertical Lines: Horizontal Lines: Result: The code: #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> using namespace std; using namespace cv; int main() { Mat img = imread("/ur/image/directory/joints.jpg",1); imshow("Source",img); int checker = 1,checker2 = 1; int begin_y,finish_y2,finish_y,begin_y2; Mat vertical_img = img.clone(); Mat horizontal_img = img.clone(); cvtColor(vertical_img,vertical_img,CV_BGR2GRAY); cvtColor(horizontal_img,horizontal_img,CV_BGR2GRAY); int finish_checker = 0,finish_checker2=0; for(int i=0;i<horizontal_img.rows;i++) { for(int j=0;j<horizontal_img.cols;j++) { if(horizontal_img.at<uchar>(Point(j,i))>100 && checker) { begin_y = j; checker = 0; } if(horizontal_img.at<uchar>(Point(j,i))<20 && checker==0) { finish_y = j; checker = 1; finish_checker = 1; } if(finish_checker) { if((finish_y-begin_y)<30) { for(int h=begin_y-2;h<=finish_y;h++) { horizontal_img.at<uchar>(Point(h,i)) = 0; } } finish_checker = 0; } } } imshow("Horizontal",horizontal_img); for(int i=0;i<vertical_img.cols;i++) { for(int j=0;j<vertical_img.rows;j++) { if(vertical_img.at<uchar>(Point(i,j))>100 && checker2) { begin_y2 = j; checker2 = 0; } if(vertical_img.at<uchar>(Point(i,j))<50 && checker2==0) { finish_y2 = j; checker2 = 1; finish_checker2 = 1; } if(finish_checker2) { if((finish_y2-begin_y2)<30) { for(int h=begin_y2-2;h<=finish_y2;h++) { vertical_img.at<uchar>(Point(i,h)) = 0; } } finish_checker2 = 0; } } } imshow("Vertical",vertical_img); for(int y=0;y<img.cols;y++) { for(int z=0;z<img.rows;z++) { if(vertical_img.at<uchar>(Point(y,z))>200 && horizontal_img.at<uchar>(Point(y,z))>200) { img.at<cv::Vec3b>(z,y)[0]=0; img.at<cv::Vec3b>(z,y)[1]=0; img.at<cv::Vec3b>(z,y)[2]=255; } } } imshow("Result",img); waitKey(0); return 0; } A: Here's a slight modified version of @YunusTemurlenk's approach using Python instead of C++. The idea is: * *Obtain binary image. Load image, convert to grayscale, Gaussian blur, then Otsu's threshold. *Obtain horizontal and vertical line masks. Create horizontal and vertical structuring elements with cv2.getStructuringElement then perform cv2.morphologyEx to isolate the lines. *Find joints. We cv2.bitwise_and the two masks together to get the joints. *Find centroid on joint mask. We find contours then calculate the centroid. Horizontal/vertical line masks Detected joints in green Results import cv2 import numpy as np # Load image, grayscale, Gaussian blur, Otsus threshold image = cv2.imread('1.jpg') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (3,3), 0) thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1] # Find horizonal lines horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10,1)) horizontal = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, horizontal_kernel, iterations=2) # Find vertical lines vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1,10)) vertical = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, vertical_kernel, iterations=2) # Find joints joints = cv2.bitwise_and(horizontal, vertical) # Find centroid of the joints cnts = cv2.findContours(joints, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnts = cnts[0] if len(cnts) == 2 else cnts[1] for c in cnts: # Find centroid and draw center point M = cv2.moments(c) cx = int(M['m10']/M['m00']) cy = int(M['m01']/M['m00']) cv2.circle(image, (cx, cy), 3, (36,255,12), -1) cv2.imshow('thresh', thresh) cv2.imshow('horizontal', horizontal) cv2.imshow('vertical', vertical) cv2.imshow('joints', joints) cv2.imshow('image', image) cv2.waitKey()
{ "language": "en", "url": "https://stackoverflow.com/questions/60633334", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Convert POJO into JSON I have a POJO. @Data @AllArgsConstructor @Builder public class Emp { private String position; private String name; } Suppose, we have created an object Emp emp = new Emp("Manager", "Bob"); How can I convert it to a list and save it in a database in JSON format? The data should be stored in the database in the format below: { list:[ { position: Manager name: Bob } ] } Are there any ready solutions for that? I converted an object into a list and then I called the .toString() method on it: Collections.singletonList(emp); But when I store it in the database, the next save goes to the database: [Emp(position=Manager, name=Bob)] But I need to store the record in a different way A: How can I convert it to a list and save it in a database in JSON format? The data should be stored in the database in the format below: { "list": [ { "position": "Manager" "name": "Bob" } ] } Since the serialized JSON is required to have a property "list" you can't simply serialize the List as is. Instead, you can define a POJO wrapping this list. That's how it might look like (I've made it generic in order to make it suitable for serializing any type of list): @Data @AllArgsConstructor public static class ListWrapper<T> { private List<T> list; } And that's how it can be serialized using Jackson's ObjectMapper and ObjectWriter: List<Emp> emps = List.of(new Emp("Manager", "Bob")); ListWrapper<Emp> listWrapper = new ListWrapper<>(emps); ObjectMapper mapper = new ObjectMapper(); ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter(); String json = writer.writeValueAsString(listWrapper); System.out.println(json); Output: { "list" : [ { "name" : "Manager", "position" : "Bob" } ] } A: If you need to store the object list as JSON in DB then you need Convert the list of object to JSON string using Jackson ObjectMapper. Store the converted string to DB.
{ "language": "en", "url": "https://stackoverflow.com/questions/74423399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: testing sails.js with mocha: can't find /api/services/myService consider this mocha test: var Sails = require('sails'); describe("Foo Model creation:", function() { // create a variable to hold the instantiated sails server var app; // Global before hook before(function(done) { // Lift Sails and start the server Sails.lift({ log: { level: 'error' } }, function(err, sails) { app = sails; done(err, sails); }); }); // Global after hook after(function(done) { app.lower(done); }); describe("new foo", function() { var foo; before(function (cb) { var fooData = { name: "test foo to be removed after test" }; Foo.create(fooData, function (err, newFoo) if (err) return cb(err); foo = newFoo; cb(); }); }); it("must show the name", function() { foo.must.have.property('name'); }); after(function (cb){ foo.destroy(function (err) { cb(err); }); }); }); }) This would work except that the Foo model depends on a sails service i.e. library code defined in /api/services. Sails, when lifted here, can't find those services. Is there a way to instruct Sails during a mocha test to also load the services? A: I had a similar issue, and indeed, Sails should be loading services, controllers, etc. There were some debug tools that helped when lifting Sails: Sails.lift({ log: { level: 'verbose' }, appPath: '../', // explicitly load almost everything but policies //loadHooks: ['moduleloader', 'userconfig', 'orm', 'http', 'controllers', 'services', 'request', 'responses', 'blueprints'] } I also did a live debug of Mocha (though I won't go into steps on that here). What I found out through debugging and a log level of verbose (you could also try silly if verbose doesn't answer a question) is that I was loading Sails from the wrong directory - the test directory. Once I changed appPath to '../', I could tell from the log messages that it was loading the proper content, and voila, my sails.services.myService object was now there! Hope that helps!
{ "language": "en", "url": "https://stackoverflow.com/questions/21883944", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: How to capture file save as cancel respond I followed this post http://www.the-art-of-web.com/php/dataexport/ and successfully create an export to csv file from DB, base on user current search view. But to prevent hit to db while export is happening so I disable the export unless there is change within the view or user query. The issue I face with is when user hit on export a file save as confirm dialog pop up and if user changed her mind click on cancel. The export button remain disable. The only way for user to get back is to change query and come back again. My question is there anyway I could capture the cancel click respond on file save as confirm dialog. Thanks The code is very similar to http://www.the-art-of-web.com/php/dataexport/ Where as the view would be a grid with bunch of customer information from given date range. If user like the view they choose. They would click on export button. sample code export.php function exportCSV(){ document.getElementById("exportCSV").src = "test1.php"; document.getElementById("exportBtn").disabled = true; } function performSearch(){ //perform search get result and display //if resultset length > 0 document.getElementById("exportBtn").disabled = false; } Grid display right here <button id="search" onclick="performSearch()">Search <button id="exportBtn" onclick="exportCSV()"> Export <iframe id="exportCSV" style="display:none"/> test1.php $data = array( array("firstname" => "Mary", "lastname" => "Johnson", "age" => 25), array("firstname" => "Amanda", "lastname" => "Miller", "age" => 18), array("firstname" => "James", "lastname" => "Brown", "age" => 31), array("firstname" => "Patricia", "lastname" => "Williams", "age" => 7), array("firstname" => "Michael", "lastname" => "Davis", "age" => 43), array("firstname" => "Sarah", "lastname" => "Miller", "age" => 24), array("firstname" => "Patrick", "lastname" => "Miller", "age" => 27) ); # filename for download $filename = "website_data.xls"; header("Content-Disposition: application/octet-stream; filename=\"$filename\""); header("Content-Type: application/vnd.ms-excel"); $flag = false; foreach($data as $row) { if(!$flag) { # display field/column names as first row echo implode("\t", array_keys($row)) . "\n"; $flag = true; } array_walk($row, 'cleanData'); echo implode("\t", array_values($row)) . "\n"; } exit; function cleanData(&$str) { $str = preg_replace("/\t/", "\\t", $str); $str = preg_replace("/\r?\n/", "\\n", $str); if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"'; } A: There's no way to capture the browser event for canceling a save file. Using a confirm in an if statement(or something similar) is probably the best ux for that situation: if(confirm('are you sure you want to export?')) { //export code } else { //cancel code } If you want your export button to become re-enabled I would call a re-enable function whenever your user's search(or whatever action they make to change data) is called. Or you can also use setTimeout() after the export button is hit and re-enable it after a certain time period. A: Maybe you can send the dump file through a php script. There you (again: maybe, I dont know, if it really works) can test the connection status with connection_status(). But if you send the file through a php-script, you dont need to know the status, because if the script shutdown properly, it doenst matter, if the transmission were completed, if you just want to unlock the database. Usually a normal database dump is safe anyway. So if you let the database dump the data it contains and save it to a file, there is no reason to lock the database while someone downloads a file.
{ "language": "en", "url": "https://stackoverflow.com/questions/4198567", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Better solution to data storage and passing I'm trying to find a more elegant solution for some code I'm working on at the moment. I have data that needs to be stored then moved around, but I don't really want to take up any more space than I need to for the data that is stored. I have 2 solutions, but neither seem very nice. Using inheritance and a tag enum class data_type{ first, second, third }; class data_base{ public: virtual data_type type() const noexcept = 0; }; using data_ptr = data_base*; class first_data: public data_base{ public: data_type type() const noexcept{return data_type::first;} // hold the first data type }; // ... Then you pass around a data_ptr and cast it to the appropriate type. I really don't like this approach because it requires upwards casting and using bare pointers. Using a union and storing all data types enum class data_type{ first, second, third }; class data{ public: data(data_type type_): type(type_){} data_type type; union{ // first, second and third data types stored }; }; But I don't like this approach because then you start wasting a lot of memory when you have a large data type that may get passed around. This data will then be passed onto a function that will parse it into a greater expression. Something like this: class expression{/* ... */}; class expr_type0: public expression{/* ... */}; // every expression type using expr_ptr = expression*; // remember to 'delete' expr_ptr get_expression(){ data_ptr dat = get_data(); // interpret data // may call 'get_data()' many times expr_ptr expr = new /* expr_type[0-n] */ delete dat; return expr; } and the problem arrises again, but it doesn't matter in this case because the expr_ptr doesn't need to be reinterpreted and will have a simple virtual function call. What is a more elegant method of tagging and passing around the data to another function? A: It's difficult to envisage exactly what you're looking for without more information. But if I wanted some framework that allowed me to store and retrieve data in some structured way, in as-yet-unknown storage devices this is the kind of way I'd be thinking. This may not be the answer you're looking for, but I think there'll be concepts here that will inspire you in the right direction. #include <iostream> #include <tuple> #include <boost/variant.hpp> #include <map> // define some concepts // bigfoo is a class that's expensive to copy - so lets give it a shared-handle idiom struct bigfoo { struct impl { impl(std::string data) : _data(std::move(data)) {} void write(std::ostream& os) const { os << "I am a big object. Don't copy me: " << _data; } private: std::string _data; }; bigfoo(std::string data) : _impl { std::make_shared<impl>(std::move(data)) } {}; friend std::ostream& operator<<(std::ostream&os, const bigfoo& bf) { bf._impl->write(os); return os; } private: std::shared_ptr<impl> _impl; }; // all the data types our framework handles using abstract_data_type = boost::variant<int, std::string, double, bigfoo>; // defines the general properties of a data table store concept template<class...Columns> struct table_definition { using row_type = std::tuple<Columns...>; }; // the concept of being able to store some type of table data on some kind of storage medium template<class IoDevice, class TableDefinition> struct table_implementation { using io_device_type = IoDevice; using row_writer_type = typename io_device_type::row_writer_type; template<class...Args> table_implementation(Args&...args) : _io_device(std::forward<Args>(args)...) {} template<class...Args> void add_row(Args&&...args) { auto row_instance = _io_device.open_row(); set_row_args(row_instance, std::make_tuple(std::forward<Args>(args)...), std::index_sequence_for<Args...>()); row_instance.commit(); } private: template<class Tuple, size_t...Is> void set_row_args(row_writer_type& row_writer, const Tuple& args, std::index_sequence<Is...>) { using expand = int[]; expand x { 0, (row_writer.set_value(Is, std::get<Is>(args)), 0)... }; (void)x; // mark expand as unused; } private: io_device_type _io_device; }; // model the concepts into a concrete specialisation // this is a 'data store' implementation which simply stores data to stdout in a structured way struct std_out_io { struct row_writer_type { void set_value(size_t column, abstract_data_type value) { // roll on c++17 with it's much-anticipated try_emplace... auto ifind = _values.find(column); if (ifind == end(_values)) { ifind = _values.emplace(column, std::move(value)).first; } else { ifind->second = std::move(value); } } void commit() { std::cout << "{" << std::endl; auto sep = "\t"; for (auto& item : _values) { std::cout << sep << item.first << "=" << item.second; sep = ",\n\t"; } std::cout << "\n}"; } private: std::map<size_t, abstract_data_type> _values; // some value mapped by ascending column number }; row_writer_type open_row() { return row_writer_type(); } }; // this is a model of a 'data table' concept using my_table = table_definition<int, std::string, double, bigfoo>; // here is a test auto main() -> int { auto data_store = table_implementation<std_out_io, my_table>( /* std_out_io has default constructor */); data_store.add_row(1, "hello", 6.6, bigfoo("lots and lots of data")); return 0; } expected output: { 0=1, 1=hello, 2=6.6, 3=I am a big object. Don't copy me: lots and lots of data }
{ "language": "en", "url": "https://stackoverflow.com/questions/31227838", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Application is getting crash while using gridview in Android In my app i want to use a gridView in fragment of navigation drawer but my application is getting crash. this is my code: public class HomeFragment extends Fragment { GridView gridView; private String[] categoryHomeGridView; private Integer[] icon={R.drawable.cat_offer_women,R.drawable.cat_offer_men, R.drawable.cat_offer_food_and_drink,R.drawable.cat_offer_electronics}; private ArrayList homeGridViewItems; private HomeGridViewListAdapter adapter; public HomeFragment(){} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_home, container, false); init(); return view; } private void init() { // TODO Auto-generated method stub gridView=(GridView) getActivity().findViewById(R.id.homeGridView); categoryHomeGridView=getActivity().getResources().getStringArray(R.array.category_array); homeGridViewItems=new ArrayList(); homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[0], icon[0])); homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[1], icon[1])); homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[2], icon[2])); homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[3], icon[3])); // iconHomeGridView.recycle(); adapter=new HomeGridViewListAdapter(getActivity().getApplicationContext() ,homeGridViewItems); gridView.setAdapter(adapter); } } and this is crash log 03-26 14:50:56.524: E/AndroidRuntime(2355): FATAL EXCEPTION: main 03-26 14:50:56.524: E/AndroidRuntime(2355): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.couponoffer/com.example.couponoffer.MainActivity}: java.lang.NullPointerException 03-26 14:50:56.524: E/AndroidRuntime(2355): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059) 03-26 14:50:56.524: E/AndroidRuntime(2355): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 03-26 14:50:56.524: E/AndroidRuntime(2355): at android.app.ActivityThread.access$600(ActivityThread.java:130) 03-26 14:50:56.524: E/AndroidRuntime(2355): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 03-26 14:50:56.524: E/AndroidRuntime(2355): at android.os.Handler.dispatchMessage(Handler.java:99) 03-26 14:50:56.524: E/AndroidRuntime(2355): at android.os.Looper.loop(Looper.java:137) 03-26 14:50:56.524: E/AndroidRuntime(2355): at android.app.ActivityThread.main(ActivityThread.java:4745) 03-26 14:50:56.524: E/AndroidRuntime(2355): at java.lang.reflect.Method.invokeNative(Native Method) 03-26 14:50:56.524: E/AndroidRuntime(2355): at java.lang.reflect.Method.invoke(Method.java:511) 03-26 14:50:56.524: E/AndroidRuntime(2355): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 03-26 14:50:56.524: E/AndroidRuntime(2355): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 03-26 14:50:56.524: E/AndroidRuntime(2355): at dalvik.system.NativeStart.main(Native Method) 03-26 14:50:56.524: E/AndroidRuntime(2355): Caused by: java.lang.NullPointerException 03-26 14:50:56.524: E/AndroidRuntime(2355): at fragments.HomeFragment.init(HomeFragment.java:57) 03-26 14:50:56.524: E/AndroidRuntime(2355): at fragments.HomeFragment.onCreateView(HomeFragment.java:34) 03-26 14:50:56.524: E/AndroidRuntime(2355): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:829) 03-26 14:50:56.524: E/AndroidRuntime(2355): at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1035) 03-26 14:50:56.524: E/AndroidRuntime(2355): at android.app.BackStackRecord.run(BackStackRecord.java:635) 03-26 14:50:56.524: E/AndroidRuntime(2355): at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1397) 03-26 14:50:56.524: E/AndroidRuntime(2355): at android.app.Activity.performStart(Activity.java:5017) 03-26 14:50:56.524: E/AndroidRuntime(2355): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2032) 03-26 14:50:56.524: E/AndroidRuntime(2355): ... 11 more A: Place this line gridView=(GridView) getActivity().findViewById(R.id.homeGridView); in onCreate and do it like this gridView=(GridView) view.findViewById(R.id.homeGridView); because your gridview is part of your View. Or pass the View view to init(); like this: @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_home, container, false); init(view); return view; } private void init(View rootView) { // TODO Auto-generated method stub gridView=(GridView) rootView.findViewById(R.id.homeGridView); categoryHomeGridView=getActivity().getResources().getStringArray(R.array.category_array); homeGridViewItems=new ArrayList(); homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[0], icon[0])); homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[1], icon[1])); homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[2], icon[2])); homeGridViewItems.add(new HomeGridViewItem(categoryHomeGridView[3], icon[3])); // iconHomeGridView.recycle(); adapter=new HomeGridViewListAdapter(getActivity().getApplicationContext() ,homeGridViewItems); gridView.setAdapter(adapter); } A: The gridView probably belongs to the fragment layout So you need to change this gridView=(GridView) getActivity().findViewById(R.id.homeGridView); to @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_home, container, false) gridView=(GridView) view.findViewById(R.id.homeGridView); A: Change this: gridView=(GridView) getActivity().findViewById(R.id.homeGridView); to this: View view = inflater.inflate(R.layout.fragment_home, container, false); gridView=(GridView) view .findViewById(R.id.homeGridView);
{ "language": "en", "url": "https://stackoverflow.com/questions/22657929", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Viewing outstanding requests Is there any way to view what requests Protractor are waiting on? I'm trying to debug flaky state testing, but it is hard to tell whether a button didn't trigger a response or if Protractor didn't bother to wait. TL;DR: How can I view the remaining promises on the Protractor control flow? A: The usual approach is to start protractor in a debug mode and put browser.debugger() breakpoint before the problem block of code. See more information at Debugging Protractor Tests. On the other hand, you can catch the chromedriver service logs that look like: [2.389][INFO]: COMMAND FindElement { "sessionId": "b6707ee92a3261e1dc33a53514490663", "using": "css selector", "value": "input" } [2.389][INFO]: Waiting for pending navigations... [2.389][INFO]: Done waiting for pending navigations [2.398][INFO]: Waiting for pending navigations... [2.398][INFO]: Done waiting for pending navigations [2.398][INFO]: RESPONSE FindElement { "ELEMENT": "0.3367185448296368-1" } Might also give you a clue of what is happening. For this, you need to start chrome with --verbose and --log-path arguments: { browserName: "chrome", specs: [ "*.spec.js" ], chromeOptions: { args: [ "--verbose", "--log-path=/path/to/the/log/file" ] } } (not tested) For firefox, you can turn on and view logs by setting webdriver.log.driver and webdriver.log.file firefox profile settings. See also: * *Monitoring JSON wire protocol logs *How to change firefox profile
{ "language": "en", "url": "https://stackoverflow.com/questions/27626803", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Trying to create composite unique index with partialFilterExpression I'm trying to create an unique index for my collection with composite keys, but some documents might have null on the fields of the index. Going by the documentation it seems I should be able to do it with partialFilterExpression. I tried it as following: db.collection.createIndex( { a: 1, b: 1, c: 1 }, { "background":true, "unique": true, "partialFilterExpression": { "a": { "$exists": true }, "b": { "$exists": true }, "c": { "$exists": true } } }) but that gave me the following error: exception: E11000 duplicate key error collection: schema.collection index: a_1_b_1_c_1 dup key: { : null, : null, : null } I even tried changing the partial filter criteria to this: db.collection.createIndex( { a: 1, b: 1, c: 1 }, { "background":true, "unique": true, "partialFilterExpression": { "a": { "$exists": true, "$ne": null }, "b": { "$exists": true, "$ne": null }, "c": { "$exists": true, "$ne": null } } } ) But still returned the same error. Did I misunderstand the use or am using it wrongly? A: Just figured out what was my issue. The version of my monogo is 3.0.12 and partialFilterExpression was introduced in version 3.2
{ "language": "en", "url": "https://stackoverflow.com/questions/44550777", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Why does Crashlytics go into an infinite loop for an unhandled exception? I have just updated to the latest Crashlytics. I tried testing it by throwing an unhandled exception. It did not send a bug report. The app simply froze. Checking the debugger, it appears to be in an infinite loop. If I pause threads in the debugger, it looks like the picture. enter image description here That is absolutely unacceptable. I can't ship an app like this. This is in build.gradle at the app level. // Recommended: Add the Firebase SDK for Google Analytics. implementation 'com.google.firebase:firebase-analytics:17.1.1' // Add the Firebase Crashlytics SDK. implementation 'com.google.firebase:firebase-crashlytics:17.1.1' This in build.gradle at the project level: // Add the Crashlytics Gradle plugin. classpath 'com.google.firebase:firebase-crashlytics-gradle:2.2.0'
{ "language": "en", "url": "https://stackoverflow.com/questions/63067054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Checkbox with PHP and MYSQL I have two checkboxes <form action="" method="post" enctype="multipart/form-data"> <input type="checkbox" name="file_type" value="1"> Filer<br /> <input type="checkbox" name="file_type" value="1"> Statistik </form> and i have two rows on my database table das_custermer_files. row 1 = files row 2 = statistic how can i check one of them an put the value into my rows. i have try with this code if($_POST['file_type'] == 1){ mysql_query("INSERT INTO das_custermer_files (url, das_file_categories_id, das_custermers_id, name) VALUE('$fileurl', 1, $user_custermers_id, '$name')" ) or die(mysql_error()); } elseif($_POST['statistik_type'] == 1){ mysql_query("INSERT INTO das_custermer_files (url, das_custermer_upload_id, das_custermers_id, name) VALUE('$fileurl', 1, $user_custermers_id, '$name')" ) or die(mysql_error()); } else{ echo "no choices"; } But if i only check one of them it stil put value 1 in both of my rows. Hope people understand. If not. ask i have done it. the finel code: html <form action="" method="post" enctype="multipart/form-data"> <input type="radio" name="file_type" value="1"> Filer<br /> <input type="radio" name="file_type" value="2"> Statistik </form> PHP $field = false; switch($_POST['file_type']) { case 1: $field = 'das_file_categories_id'; break; case 2: $field = 'das_custermer_upload_id'; break; default: $field = false; } if($field) { mysql_query("INSERT INTO das_custermer_files (url, $field, das_custermers_id, name) VALUE('$fileurl', 1, $user_custermers_id, '$name')" ) or die(mysql_error()); } A: My approach would be like this: I would use radio buttons instead, to ensure a type is selected. Form Bits: <input type="radio" name="file_type" value="0" checked="checked"> None<br /> <input type="radio" name="file_type" value="1"> Filer<br /> <input type="radio" name="file_type" value="2"> Statistik PHP Bits: $field = false; // set the field name based on the file type selected in the form switch($_POST['file_type']) { case 1: $field = '`das_file_categories_id`'; break; case 2: $field = '`das_custermer_upload_id`'; break; default: $field = false; } // if a field has been set ( i.e file_type != 0 ) then build and run the query if($field) { $query = "INSERT INTO `das_custermer_files` (`url`, " . $field . ", `das_custermers_id`, `name`) "; $query .= "VALUES ('" . $fileurl . "', 1, " . $user_custermers_id . ", '" . $name . "')"; mysql_query($query); echo "Inserting to db: " . $query; } else { echo "No field set: "; print_r($_POST); } Things worth noting * *You're using mysql_query which is outdated, see here: http://php.net/manual/en/function.mysql-query.php *Even though you are using $fileurl, $user_custermers_id,$name i cannot see these being set, so i am assuming they are set somewhere higher in the file A: your check_box names should be different. yours the same. <input type="checkbox" name="file_type" value="1"> Filer<br /> <input type="checkbox" name="file_type" value="1"> Statistik A: Html code : <form action="test.php" method = 'post'> <input type="checkbox" name="file_type[]" value="1"> Filer<br /> <input type="checkbox" name="file_type[]" value="2"> Statistik <input type="submit" value="submit" /> checkbox will contain its value in array $_POST['file_type'] and you may inter its value to db as follows :- if(isset($_POST['file_type'])){ foreach($_POST['file_type'] as $keys) { mysql_query("INSERT INTO das_custermer_files (url, das_file_categories_id, das_custermers_id, name) VALUE('$fileurl', $keys, $user_custermers_id, '$name')" ) or die(mysql_error()); } } else if(isset($_POST['statistik_type'])){ mysql_query("INSERT INTO das_custermer_files (url, das_custermer_upload_id, das_custermers_id, name) VALUE('$fileurl', 1, $user_custermers_id, '$name')" ) or die(mysql_error()); } else{ echo "no choices"; } this maybe your requirement... A: Try this .Should work. if(isset($_POST['file_type'])){ mysql_query("INSERT INTO das_custermer_files (url, das_file_categories_id, das_custermers_id, name) VALUE('$fileurl', 1, $user_custermers_id, '$name')" ) or die(mysql_error()); } else if(isset($_POST['statistik_type'])){ mysql_query("INSERT INTO das_custermer_files (url, das_custermer_upload_id, das_custermers_id, name) VALUE('$fileurl', 1, $user_custermers_id, '$name')" ) or die(mysql_error()); } else{ echo "no choices"; } A: You approach is totally wrong. You should follow this structure <form action="test.php" method = 'post'> <input type="checkbox" name="file_type" value="1"> Filer<br /> <input type="checkbox" name="file_type" value="2"> Statistik <input type="submit" value="submit" /> </form> Now with php $query = ''; if($_POST['file_type'] == 1){ $query = "INSERT INTO das_custermer_files (url, das_file_categories_id, das_custermers_id, name) VALUE ('$fileurl', 1, $user_custermers_id, '$name')"; }else if($_POST['file_type'] == 2){ $query = "INSERT INTO das_custermer_files (url, das_custermer_upload_id, das_custermers_id, name) VALUE ('$fileurl', 1, $user_custermers_id, '$name')"; } mysqli_query($query); A: You probably forgot to <form action = "..." method = "POST"> </form>. First step, you should do the test: print_r($_POST); What you get by this test? If the first step is correct (not empty array), we can finish: if (isset($_POST['file_type'])) { ... }; // OR use alternative if ($_POST['file_type'] == 1) { ... }; A: Clicking on a checkbox doesen't change the value attribute but adds "checked" in the dome like this: <input type="checkbox" name="file_type" value="1" checked> Filer<br /> So the submitted value of the checked box will stay forever at "1" EDIT When you replace the values with strings you can check against it in php. HTML <form action="" method="post" enctype="multipart/form-data"> <input type="checkbox" name="file_type" value="Filer"> Filer<br /> <input type="checkbox" name="file_type" value="Statistik"> Statistik </form> PHP if($_POST['file_type'] == "Filer"){ mysql_query("INSERT INTO das_custermer_files (url, das_file_categories_id, das_custermers_id, name) VALUE('$fileurl', 1, $user_custermers_id, '$name')" ) or die(mysql_error()); } elseif($_POST['file_type'] == "Statistik"){ mysql_query("INSERT INTO das_custermer_files (url, das_custermer_upload_id, das_custermers_id, name) VALUE('$fileurl', 1, $user_custermers_id, '$name')" ) or die(mysql_error()); } else{ echo "no choices"; }
{ "language": "en", "url": "https://stackoverflow.com/questions/16439247", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: File upload validation - to unlink from tmp or not Just a quick question on best practice. If my website visitors are uploading files that fail file validation (too large, wrong filetype etc.) is it safer/ more efficient to programatically delete the file from the servers tmp directory? Or do I just let the purge cycle performed by the server take care of it? Many thanks Phill A: From the manual: The file will be deleted from the temporary directory at the end of the request if it has not been moved away or renamed. So, you could omit it, however: Whatever the logic, you should either delete the file from the temporary directory or move it elsewhere. ... it's always nice to be explicit in your script. In short: you don't have to, but I would.
{ "language": "en", "url": "https://stackoverflow.com/questions/25388231", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Scrapping memory issue (Out Of Memory) Good day, I have cameras that are saving videos by clips on a cloud service, with a limit on N clips. In order to save more clips, I made a scrapping script that gets all my video links from the website where I can preview them. (to be executed on page load with a JS extension) Note that these are M3U8 files. Here is my script: var cameraScrapper = { playerReady: false, videos: {}, cameraCurrent: 0, cameras: [ 'cid1', // #1 'cid2', // #3 'cid3', // #2 ], gui: function() { return { calendarPreviousMonth: document.getElementById( 'event_calendar_section' ).getElementsByClassName( 'navigation' )[0].getElementsByClassName( 'prev' )[0], calendarNextMonth: document.getElementById( 'event_calendar_section' ).getElementsByClassName( 'navigation' )[0].getElementsByClassName( 'next' )[0], calendarSelectedDate: document.getElementById( 'event_selected_date' ), calendarMonthDays: document.getElementById( 'event_calendar_section' ).getElementsByClassName( 'month' )[0].children, cameras: document.getElementById( 'camera_list_dropdown' ).children, dayClips: document.getElementById( 'event_clips_wrap' ).children, noRecords: document.getElementsByClassName( 'no_recording' )[0] }; }, init: function() { document.getElementById( 'hls_player' ).addEventListener( 'canplay', function() { this.playerReady = true; }.bind( this ) ); for( let i = 0; i < this.cameras.length; i++ ) { if( window.location.href.includes( '=' + this.cameras[i] + '&' ) ) { this.cameraCurrent = i; break; } } while( !this.gui().calendarPreviousMonth.children[0].classList.contains( 'disabled' ) ) { this.gui().calendarPreviousMonth.click(); } this.scrap(); }, getVideo: function( pCamera, pTimeStamp ) { let performance = window.performance || window.mozPerformance || window.msPerformance || window.webkitPerformance || {}; let requests = ( performance.getEntries() || {} ); for( let i = 0; i < requests.length; i++ ) { if( requests[i].name.includes( '.ts?' ) ) { if( this.videos[encodeURIComponent( requests[i].name )] === undefined ) { this.videos[encodeURIComponent( requests[i].name )] = { 'camera': pCamera, 'timestamp': this.formatDate( pTimeStamp ) }; } } } if( Object.entries( this.videos ).length > 25 ) { this.save(); this.videos = {}; performance.clearMarks(); performance.clearMeasures() performance.clearResourceTimings(); } }, formatDate( pTimestamp ) { let date = pTimestamp.split( ' ' )[0]; let time = pTimestamp.split( ' ' )[1]; let month = { JAN: '01', FEB: '02', MAR: '03', APR: '04', MAY: '05', JUN: '06', JUL: '07', AUG: '08', SEP: '09', OCT: '10', NOV: '11', DEC: '12' } return date.split( '.' )[2] + '-' + month[date.split( '.' )[1]] + '-' + date.split( '.' )[0] + ' ' + time; }, sleep: function( pMs ) { return new Promise( resolve => setTimeout( resolve, pMs ) ); }, scrap: async function() { let scrapDays = true; while( scrapDays ) { for( let i = 0; i < this.gui().calendarMonthDays.length; i++ ) { if( !this.gui().calendarMonthDays[i].classList.contains( 'is-disabled' ) && !this.gui().calendarMonthDays[i].classList.contains( 'is-expired' ) && !this.gui().calendarMonthDays[i].classList.contains( 'is-future' ) ) { // console.log( 'day ' + this.gui().calendarMonthDays[i].innerText ); this.gui().calendarMonthDays[i].click(); let clipsLoaded = false; if( this.gui().noRecords !== undefined ) { clipsLoaded = !this.gui().noRecords.classList.contains( 'displayOff' ) } while( !clipsLoaded && ( this.gui().dayClips.length == 0 ) ) { await this.sleep( 99 ); if( this.gui().noRecords !== undefined ) { clipsLoaded = !this.gui().noRecords.classList.contains( 'displayOff' ) } } // console.log( 'clips ' + this.gui().dayClips.length ); for( let j = 0; j < this.gui().dayClips.length; j++ ) { this.playerReady = false; this.gui().dayClips[j].children[0].click(); while( !this.playerReady ) { await this.sleep( 99 ); } this.getVideo( ( '' + this.cameraCurrent ), this.gui().calendarSelectedDate.innerText + ' ' + this.gui().dayClips[j].children[0].children[1].children[1].innerText ); } } } if( !this.gui().calendarNextMonth.children[0].classList.contains( 'disabled' ) ) { this.gui().calendarNextMonth.click(); } else { scrapDays = false; } } this.save(); this.sleep( 4999 ); let cameraNext = this.cameraCurrent + 1; if( this.cameras.length >= cameraNext ) { cameraNext = 0; } window.location.href = 'https://cloudcamerasservice.com/camera?no=' + this.cameras[cameraNext] + '&model=CAM'; }, save() { let xhr = new XMLHttpRequest(); xhr.open( 'POST', 'http://localhost/videomonitoring/stack.php', true ); xhr.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded' ); xhr.onload = ( e ) => { /* console.log( 'saved' ); */ }; xhr.onerror = ( e ) => {}; xhr.send( 'stack=' + encodeURIComponent( JSON.stringify( this.videos ) ) ); } }; setTimeout( function() { cameraScrapper.init() }.bind( this ), 4999 ); stack.php will handle file download from provided list, my script is mainly about getting the video links and date of recording. But when launching my script, my browser run out of memory after 75-100 clips saved. Can you help me with this? Not sure if it's comming from my script, indeed, I have the feeling this is due to preloading many videos on the same page.
{ "language": "en", "url": "https://stackoverflow.com/questions/73704541", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Scrollbar in textarea Css is like: ::-webkit-scrollbar,::-moz-scrollbar { -webkit-appearance: none; width: 6px; /* for vertical scrollbars */ height: 8px; /* for horizontal scrollbars */ } ::-webkit-scrollbar-track,::-moz-scrollbar-track { background: rgba(0, 0, 0, 0.1); border-radius:4px; } ::-webkit-scrollbar-thumb,::-moz-scrollbar-thumb { background: rgba(0, 0, 0, 0.5); border-radius:4px; } but it works only in chrome ..in other browser it display default scrollbar and second doubt is it start appears in ipad after I scrolldown..how to display vertical scroll if it has max text on hover of the textarea? jsfiddle A: You can use mouseout and mouseover events to hide or show the scroll bar using css. A: For a cross browser solution you should use javascript/jquery. There are many successful scrollbar plugins that you can use
{ "language": "en", "url": "https://stackoverflow.com/questions/31807340", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Button isn't displayed in RelativeLayout below GridView I have the next problem: when a gridview content doesn't fit into device display and scrolling begins then a button below the gridview is not shown. Here is my code: <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="16dp" android:paddingRight="16dp"> <GridView android:id="@+id/generated_number_gridview" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:columnWidth="90sp" android:horizontalSpacing="10sp" android:stretchMode="columnWidth" android:verticalSpacing="10sp" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/generated_number_gridview" android:layout_centerHorizontal="true" android:onClick="proceed" android:text="@string/proceed" android:textSize="25sp" /> </RelativeLayout> Would be very thankful for your help ! A: Remove this line from Button Layout properties. android:layout_below="@id/generated_number_gridview" This means that It should be below the GridView. And your GridView size is not fixed. Since the renderer shows the GridView with multiple elements it fills the screen and your Button goes below that. That's why it's not visible. I hope this is the UI that you are looking for. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="16dp" android:paddingRight="16dp"> <GridView android:id="@+id/generated_number_gridview" android:layout_width="match_parent" android:layout_height="wrap_content" android:columnWidth="90sp" android:horizontalSpacing="10sp" android:stretchMode="columnWidth" android:verticalSpacing="10sp" android:layout_above="@+id/proceedButton" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_alignParentBottom="true" android:id="@+id/proceedButton" android:onClick="proceed" android:text="proceed" android:textSize="25sp" /> </RelativeLayout> Hope it helps. A: Try this. Just replace this with your XML code. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="16dp" android:paddingRight="16dp"> <GridView android:id="@+id/generated_number_gridview" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@+id/btnProceed" android:layout_centerHorizontal="true" android:columnWidth="90sp" android:horizontalSpacing="10sp" android:stretchMode="columnWidth" android:verticalSpacing="10sp" /> <Button android:id="@+id/btnProceed" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:onClick="proceed" android:text="Proceed" android:textSize="25sp" /> </RelativeLayout> Here is the Screen shot. A: You can use this layout.. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="16dp" android:paddingRight="16dp"> <GridView android:id="@+id/generated_number_gridview" android:layout_width="match_parent" android:layout_height="wrap_content" **android:layout_above="@+id/btn_proceed"** android:layout_centerHorizontal="true" android:columnWidth="90sp" **android:horizontalSpacing="10dp**" android:stretchMode="columnWidth" **android:verticalSpacing="10dp"** /> <Button android:id="@+id/btn_proceed" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:onClick="proceed" android:text="@string/proceed" android:textSize="25sp" /> </RelativeLayout>
{ "language": "en", "url": "https://stackoverflow.com/questions/36668101", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to ignore code when data does not contain necessary values? I'm very new to R and here as well and need some help fixing my code because sometimes my data gets weird So I have data similar to this Random Price 11.23 0.68 66.77 0.51 68 0.46 78 0.51 88 0.32 89 0.51 90 0.27 91 0.65 This is my code so far: newdata <- data[ which(data$Random>=30 & data$Random < 50), ] Pvalue<- lapply(1:length(dat), function(i){ if(length(dat[[i]][[4]])>1){ t.test(newdata$Price,dat[[i]][[4]])$p.value }else 'not enough observation' }) My code basically does a t.test between the data from 'newdata' and another set of data called 'dat' But there are times when I don't have data from 30 to 50 similar to my example data above. So instead of my code returning an error, how could I change it so that it just returns NA . A: You already know how to use the if/else construct. All you have to do is add one testing nrow(newdata), or maybe combine both as follows: newdata <- subset(data, Random >= 30 & Random < 50) Pvalue <- lapply(dat, function(x){ if (length(x[[4]]) > 1 & nrow(newdata) > 1) { t.test(newdata$Price, x[[4]])$p.value } else NA }) You could also replace lapply(...) with sapply(...) or vapply(..., numeric(1)) to get a numeric vector instead of a list. For that, it is recommended to replace 'not enough observation' with NA like I did, or you could end up with a character vector.
{ "language": "en", "url": "https://stackoverflow.com/questions/15718684", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: SQLITE: SELECT between timestamps doesnt work my goal is it to search between two time stamps of a certain time span all of this is stored in an array of an dynamic amount of time stamps depending on how much days i want to search in the past. Originally they looked like that 2020-07-30T08:41:22.164Z but i removed the unimportant parts of it and now it looks like that 07-30. So i just filtered the time stamp to its month and day. Now to my problem: I am trying to bring that command to work: "SELECT status FROM database WHERE timeStamp BETWEEN '%datesStored[datesStored.length -1]%' AND '%datesStored[0]%'". Ignore the fact that i used JS where the time stamps should be. The whole SQLite statement is in fact a String I've built that i am trying to send to SQLite node in nore-red. But that is not important. They only thing i need is the certain command that would work. Thank you for any responses. var datesSaved = msg.payload; var daysBack = global.get("maxDaysBack"); var min = datesSaved[0]; var max = datesSaved[datesSaved.length-1]; msg.topic = "SELECT status, dateTime FROM database WHERE dateTime BETWEEN '%07-28%' AND '%07-29%';"; msg.labels = msg.payload; msg.payload = []; return msg; A: I don't know exactly what your search strategy is here, but if you want to see all records going back 7 days to the past, you may use: SELECT status, dateTime FROM database WHERE dateTime >= date('now', '-7 day');
{ "language": "en", "url": "https://stackoverflow.com/questions/63169703", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How do I safely lock an ASP.NET MVC3 Session? I want to modify the Session variable in an ASP.NET MVC3 Controller (that has SessionState required) in a thread-safe manner. What object should I lock on?
{ "language": "en", "url": "https://stackoverflow.com/questions/10089686", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Where do I start with developing a Silverlight app using Windows Workflow Foundation? We are starting out with the development of a Silverlight app that will make use of Windows Workflow Foundation (WF4). Our workflows are long-running. We plan to use the tracking and persistence functionality of WF. We will probably need to also store data related to each workflow instance in another DB (I suspect running reporting against the workflow persistence store would be tricky). Our workflows may change with time so we would probably also need some strategy to implement versioning on them. So specifically, are there any resources you can point me to or direction you can give me on where to start, taking into account that we need to implement tracking, persistence and versioning of workflows? A: Based on your question, I'm assuming that you already have experience with WWF and are really just asking about how it interacts with Silverlight. The short answer is that it would not be noticeably different from how you would implement a WWF-enabled application in traditional ASP.NET. Remember that Silverlight is only a UI client that usually lives on top of a traditional ASP.NET web application. Your WWF-related logic and code would live in the ASP.NET layer -- not in Silverlight at all. So if you already know how to make a WWF-enabled application in ASP.NET, all you really need to learn is how to wire up a shiny Silverlight interface to an ASP.NET web app. For that, you of course only need to hit up http://silverlight.net/, which you're probably already doing. Good luck!
{ "language": "en", "url": "https://stackoverflow.com/questions/6308652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Why is Serilog(.Extras.)Web's ApplicationLifecycleModule.Init() called twice? I'm hosting a Web API in IIS (7.5) as an Application under "Default Web Site", and am using several of the Enrichers from Serilog.Extras.Web (I'll be upgrading soon to the SerilogWeb.Classic package). I noticed in my logs that ApplicationLifecycleModule.LogRequest() was being called twice for each request, and I'm trying to understand why. What I noticed is that ApplicationLifecycleModule.Init() is being called twice, thus registering two event handlers. The first callstack: Serilog.Extras.Web.dll!Serilog.Extras.Web.ApplicationLifecycleModule.Init(System.Web.HttpApplication context) System.Web.dll!System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(System.IntPtr appContext, System.Web.HttpContext context, System.Reflection.MethodInfo[] handlers) System.Web.dll!System.Web.HttpApplication.InitSpecial(System.Web.HttpApplicationState state, System.Reflection.MethodInfo[] handlers, System.IntPtr appContext, System.Web.HttpContext context) System.Web.dll!System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(System.IntPtr appContext, System.Web.HttpContext context) System.Web.dll!System.Web.Hosting.PipelineRuntime.InitializeApplication(System.IntPtr appContext) [AppDomain Transition] And the second: Serilog.Extras.Web.dll!Serilog.Extras.Web.ApplicationLifecycleModule.Init(System.Web.HttpApplication context) System.Web.dll!System.Web.HttpApplication.InitModulesCommon() System.Web.dll!System.Web.HttpApplication.InitInternal(System.Web.HttpContext context, System.Web.HttpApplicationState state, System.Reflection.MethodInfo[] handlers) System.Web.dll!System.Web.HttpApplicationFactory.GetNormalApplicationInstance(System.Web.HttpContext context) System.Web.dll!System.Web.HttpApplicationFactory.GetApplicationInstance(System.Web.HttpContext context) System.Web.dll!System.Web.HttpRuntime.ProcessRequestNotificationPrivate(System.Web.Hosting.IIS7WorkerRequest wr, System.Web.HttpContext context) System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) System.Web.dll!System.Web.Hosting.PipelineRuntime.ProcessRequestNotification(System.IntPtr rootedObjectsPointer, System.IntPtr nativeRequestContext, System.IntPtr moduleData, int flags) Am I doing something wrong? Or is this a bug in the ApplicationLifecycleModule?
{ "language": "en", "url": "https://stackoverflow.com/questions/29546391", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Insert to all cells when records are more than one PHP here is my big program! note: all codes are in one page. freinds, all thing is ok but problem is in 'while' line and when i have more than one record. here we connect to database and fetch information about users that got service of another users. <form name="form2" method="post" action="" accept-charset='UTF-8'> <?php $id=$fgmembersite->UserID(); echo "$id"; ?> <?php $db_host = 'localhost'; $db_name= 'site'; $db_table= 'action'; $db_user = 'root'; $db_pass = ''; $con = mysql_connect($db_host,$db_user,$db_pass) or die("خطا در اتصال به پايگاه داده"); $selected=mysql_select_db($db_name, $con) or die("خطا در انتخاب پايگاه داده"); mysql_query("SET CHARACTER SET utf8"); $dbresult=mysql_query("SELECT tablesite.name, tablesite.family, tablesite.username, tablesite.phone_number, tablesite.email, action.service_provider_comment, action.price, action.date, job_list.job_name, relationofaction.ind FROM $db_table INNER JOIN job_list on job_list.job_id=action.job_id INNER JOIN relationofaction on relationofaction.ind=action.ind INNER JOIN tablesite on tablesite.id_user=action.service_provider_id AND action.customer_id='$id'",$con); here prints all times that current user got service of another user. it may be 0 or n. problem is here. when services are more that 1 and when i am trying to insert informations to table, first choose of vote and explain inserts to all cells. each button must send information to a seprated field not all fileds! while($amch=mysql_fetch_assoc($dbresult)) {?> <?php echo'<div dir="rtl">'; echo "نام خدمت دهنده: "."&nbsp&nbsp&nbsp".$amch["name"]." ".$amch["family"]."&nbsp&nbsp&nbsp"."شماره تماس: ".$amch["phone_number"]."&nbsp&nbsp&nbsp"."ایمیل: ".$amch["email"].'<br>'. "شغل انجام شده: ".$amch["job_name"].'<br>' ."تاریخ انجام عملیات: ".$amch["date"].'<br>' ."هزینه ی کار: ".$amch["price"]." تومان".'<br>' .$amch["service_provider_comment"].'<hr/>'; echo'<label for="explain">اگر توضیحاتی برای ارائه در این باره دارید، ارائه دهید</label> <br />'; echo'<textarea name="explain" id="explain" cols="" rows="" style="width:300 ;height:300"></textarea>'.'<br/>'; echo'<label for="rate">امتیاز این عملیات را ثبت نمایید: </label> <br />'; echo '<select name="vote">'; echo '<option value="عالی">عالی</option>'; echo '<option value="عالی">خوب</option>'; echo '<option value="عالی">متوسط</option>'; echo '<option value="عالی">بد</option>'; echo '</select>'; echo'<br/>'; echo '<input type="submit" name="submit" value="ارسال نظر شما"/>'; echo'<hr/>'; echo'<hr/>'; echo'</div>'; } ?> here we say if user clicked on button, send informations to table. once again i say all thing for one record is ok, problem when occure that we have more than one record and i now problem is in 'while' but i do not know how fix this problem. <?php if(isset($_POST['submit'])) { $db_host = 'localhost'; $db_name= 'site'; $db_table= 'action'; $db_user = 'root'; $db_pass = ''; $con = mysql_connect($db_host,$db_user,$db_pass) or die("خطا در اتصال به پايگاه داده"); mysql_query("SET NAMES 'utf8'", $con); mysql_query("SET CHARACTER SET 'utf8'", $con); mysql_query("SET character_set_connection = 'utf8'", $con); $selected=mysql_select_db($db_name, $con) or die("خطا در انتخاب پايگاه داده"); $ins ="UPDATE $db_table SET customer_comment='" . mysql_escape_string($_POST['explain']) . "', vote='" . mysql_escape_string($_POST['vote']) . "' WHERE ind=ind"; $saved=mysql_query($ins ); mysql_close($con); echo '<script language="javascript">'; echo 'alert("نظر شما با موفقیت ثبت شد")'; echo '</script>'; echo '<script>window.location.href = "action_perfomed_agree.php";</script>'; } ?> this is a forms of a person that have 3 forms and here is my table after sending as you see we have repetetive records but where customer_id=37 there is not a problem because that user hasve just a record. tables: tablesite: 1 id_user int(11) 2 name varchar(128) utf8mb4_persian_ci 3 family varchar(128) utf8mb4_persian_ci 4 email varchar(64) utf8mb4_persian_ci 5 phone_number varchar(16) utf8mb4_persian_ci 6 username varchar(16) utf8mb4_persian_ci 7 password varchar(32) utf8mb4_persian_ci 8 confirmcode varchar(32) utf8mb4_persian_ci relation 1 user_name varchar(255) utf8mb4_persian_ci 2 job_id int(255) 3 comments varchar(255) 4 user_id int(255) RelationOfaction 1 service_provider_id int(20) 2 customer_id int(20) 3 ind int(20) action 1 job_id int(11) 2 service_provider_id int(10) 3 customer_id int(10) 4 date date 5 price int(255) 6 vote varchar(255) utf8mb4_persian_ci 7 service_provider_comment varchar(255) utf8mb4_persian_ci 8 customer_comment varchar(255) 9 ind int(10) A: I would advise wrapping each portion in its own form: <?php $id = $fgmembersite->UserID(); echo "$id"; $db_host = 'localhost'; $db_name= 'site'; $db_table= 'action'; $db_user = 'root'; $db_pass = ''; $con = mysql_connect($db_host,$db_user,$db_pass) or die("خطا در اتصال به پايگاه داده"); $selected=mysql_select_db($db_name, $con) or die("خطا در انتخاب پايگاه داده"); mysql_query("SET CHARACTER SET utf8"); $dbresult=mysql_query("SELECT tablesite.name, tablesite.family, tablesite.username, tablesite.phone_number, tablesite.email, action.service_provider_comment, action.price, action.date, job_list.job_name, relationofaction.ind FROM $db_table INNER JOIN job_list ON job_list.job_id=action.job_id INNER JOIN relationofaction ON relationofaction.ind=action.ind INNER JOIN tablesite ON tablesite.id_user=action.service_provider_id AND action.customer_id='$id'", $con); $i = 1; while($amch=mysql_fetch_assoc($dbresult)){ echo "<form id='form_$i' method='post' action='{$_SERVER['PHP_SELF']}' accept-charset='UTF-8'>\r\n"; echo '<div dir="rtl">'; echo "نام خدمت دهنده: "."&nbsp&nbsp&nbsp".$amch["name"]." ".$amch["family"]."&nbsp&nbsp&nbsp"."شماره تماس: ".$amch["phone_number"]."&nbsp&nbsp&nbsp"."ایمیل: ".$amch["email"].'<br>' ."شغل انجام شده: ".$amch["job_name"].'<br>' ."تاریخ انجام عملیات: ".$amch["date"].'<br>' ."هزینه ی کار: ".$amch["price"]." تومان".'<br>' .$amch["service_provider_comment"].'<hr/>'; echo '<label for="explain">اگر توضیحاتی برای ارائه در این باره دارید، ارائه دهید</label> <br />'; echo '<textarea name="explain" id="explain" cols="" rows="" style="width:300 ;height:300"></textarea>'.'<br/>'; echo '<label for="rate">امتیاز این عملیات را ثبت نمایید: </label> <br />'; echo '<select name="vote">'; echo ' <option value="عالی">عالی</option>'; echo ' <option value="عالی">خوب</option>'; echo ' <option value="عالی">متوسط</option>'; echo ' <option value="عالی">بد</option>'; echo '</select>'; echo '<br/>'; echo '<input type="submit" name="submit" value="ارسال نظر شما"/>'; echo '<hr/>'; echo '<hr/>'; echo '</div>'; echo "</form>\r\n"; $i++; } ?> You will find a number of little fixes in this code. This will result in a number of forms, each with a unique ID, posting to the same place. A: With respect to @Twisty answer, I would like to come with my final solution to your submission problem. First of all we need to define which raw to be updated, therefore you need to tell your update statement which ind to be updated. To do that we need to pass ind in out submission form to out update statement, we added a hidden input field and pass out ind value like this. <input type="hidden" name="ind" value="' . $amch["ind"] . '">; Next we need to fetch the value and update our data by adding following: ($_POST['ind']) So the final solution will look like this: echo '</select>'; echo '<input type="hidden" name="ind" value="' . $amch["ind"] . '">'; //new line echo '<br/>'; echo '<input type="submit" name="submit" value="ارسال نظر شما"/>'; echo '<hr/>'; echo '<hr/>'; and in your update statement: $ins = "UPDATE $db_table SET customer_comment='" . mysql_escape_string($_POST['explain']) . "', vote='" . mysql_escape_string($_POST['vote']) . "' WHERE ind=".($_POST['ind']); // to define the ind value And wala, it works. NOTE: Just be a ware of, I used the updated code of @Twisty and the final solution on it.
{ "language": "en", "url": "https://stackoverflow.com/questions/33550554", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Symfony, How to pass a variable to the path? I need to pass the var 'busqueda' for the path, if instead of using the var I put text if it works, but to shove the variable tells me there. JavaScript code in twig. var busqueda = document.getElementById('search_keywords').value; xmlhttp.open("GET","{{path('searchCorreos', {'page': thisPage, 'search': busqueda } )}}",true); xmlhttp.send(); A: Since it's a GET request, this should work: var busqueda = document.getElementById('search_keywords').value; xmlhttp.open("GET","{{ path('searchCorreos', {'page': thisPage}) }}&search=" + busqueda,true); xmlhttp.send(); A: If you run into this problem more often (needing to append javascript variables to symfony generated paths/urls) you can make use of the FOSJsRoutingBundle: https://github.com/FriendsOfSymfony/FOSJsRoutingBundle This allows you to do the following in your javascript source: var busqueda = document.getElementById('search_keywords').value; var path = Routing.generate('searchCorreos', { page: 'thisPage', search: busqueda }); xmlhttp.open("GET", path, true); xmlhttp.send();
{ "language": "en", "url": "https://stackoverflow.com/questions/37481308", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Casting DataRow value into float I'm working with DataRow and I want to divide every value in the row with a number(taken from a cell from the same row). I've been searching ways to convert the values into float, like from this thread, but casting gives me "Specified cast is not valid" error. List<DataTable> tblsol = new List<DataTable>(); DataTable now = tblsol.Last(); while (true) { DataRow fb = now.Rows[v]; DataRow fb2 = now.Rows[w]; float akun = (float)fb[fb.Table.Columns.Count - 1] / (float)fb[u]; if (akun > (float)fb2[fb2.Table.Columns.Count - 1] / (float)fb2[u]) { if (w == now.Rows.Count - 1) { v = w; break; } else { v++; w++; } } else { if (w == now.Rows.Count - 1) { break; } else { w++; } } } DataRow bk = now.Rows[v]; float angkun = Convert.ToSingle(bk[u]); for (int dc = 1; dc < now.Columns.Count;dc++) { bk[dc] = Convert.ToSingle(bk[dc]) / angkun; } I used 2 methods to convert the value into float (using Convert.toSingle and casting), but both ways gave me error. Is there anything else I can do? Or maybe is there something wrong in my code? p.s. tblSol is not empty and all variables are already declared. A: try float.Parse, but you need to convert the datarow to dynamic/string type for it to be compatible: var test = (dynamic)fb[fb.Table.Columns.Count - 1]; float boat = float.Parse(test); Or something similar using float.Parse A: You can try after converting it to String like this, float akun = float.Parse(fb[fb.Table.Columns.Count - 1].ToString()) / float.Parse(fb[u].ToString()); A: As noted in my comment, try casting the relevant columns to Decimal first. It is one of the explicitly supported DataTypes when accessing data from columns of DataRow instances; the valid types are listed in the MSDN DataColumn Reference page
{ "language": "en", "url": "https://stackoverflow.com/questions/31258941", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: What is the scope of a namespace alias in C++? Does a C++ namespace alias defined inside a function definition have a block, function, file, or other scope (duration of validity)? A: It's a block duration of validity. E.g If you define a namespace alias as below, the namespace alias abc would be invalid outside {...} block. { namespace abc = xyz; abc::test t; //valid } abc::test t; //invalid A: The scope is the declarative region in which the alias is defined. A: It would have the scope of the block in which it was defined - likely to be the same as function scope unless you declare the alias inside a block within a function. A: I'm fairly certain that a namespace alias only has scope within the block it's created in, like most other sorts of identifiers. I can't check for sure at the moment, but this page doesn't seem to go against it. A: As far as I know, it's in the scope it's declared. So, if you alias in a method, then it's valid in that method, but not in another. A: Take a look at http://en.wikibooks.org/wiki/C++_Programming/Scope/Namespaces A: It is valid for the duration of the scope in which it is introduced. Take a look at http://en.cppreference.com/w/cpp/language/namespace_alias, I trust the explanation of cppreference, it's much more standard.
{ "language": "en", "url": "https://stackoverflow.com/questions/1495649", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "22" }
Q: Find position of a node using xpath using attributes How can I get the position of a node based on a certain attribute value? The following post shows how to do this with elements: Find position of a node using xpath So if we change the example xml in the post mentioned above to: <a> <b val="zyx" /> <b val="wvu" /> <b val="tsr" /> <b val="qpo" /> </a> How would I get the position of a/b[@val = 'tsr']? A: Should be almost exactly the same: count(a/b[@val='tsr']/preceding-sibling::*)+1 Example usage... XSLT 1.0 <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <xsl:value-of select="count(a/b[@val='tsr']/preceding-sibling::*)+1"/> </xsl:template> </xsl:stylesheet> Output: 3
{ "language": "en", "url": "https://stackoverflow.com/questions/9589469", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: get_the_terms issue on foreach loop I want to show taxonomy name in post. I use foreach loop but it does not show any thing to me. here is my code. <?php global $post; $foo_home_url = site_url(); $url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; if(strpos($url, 'foo_cat')){ $foo_bc_cat = get_the_terms( $post->ID , FOO_POST_TAXONOMY ); ?> <ul> <li><a href="<?php echo $foo_home_url; ?>">Home</a></li> <?php foreach($foo_bc_cat as $foo_tax_cat){ ?> <li><a href="<?php echo get_term_link($foo_tax_cat->slug, FOO_POST_TAXONOMY) ?>"><?php echo $foo_tax_cat->name ?></a></li> <?php } ?> </ul> <?php } ?> Any idea. A: use this code <?php global $post; $foo_home_url = site_url(); $url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; if(strpos($url, 'foo_cat')){ $foo_bc_name = get_queried_object()->name; ?> <ul> <li><a href="<?php echo $foo_home_url; ?>">Home</a></li> <li><a href="<?php echo get_term_link($foo_tax_cat->slug, FOO_POST_TAXONOMY) ?>"><?php echo $foo_bc_name; ?></a></li> </ul> <?php } ?> instead of this code <?php global $post; $foo_home_url = site_url(); $url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; if(strpos($url, 'foo_cat')){ $foo_bc_cat = get_the_terms( $post->ID , FOO_POST_TAXONOMY ); ?> <ul> <li><a href="<?php echo $foo_home_url; ?>">Home</a></li> <?php foreach($foo_bc_cat as $foo_tax_cat){ ?> <li><a href="<?php echo get_term_link($foo_tax_cat->slug, FOO_POST_TAXONOMY) ?>"><?php echo $foo_tax_cat->name ?></a></li> <?php } ?> </ul> <?php } ?>
{ "language": "en", "url": "https://stackoverflow.com/questions/24435730", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Expo thows error that I need to run pod install I get an error message when trying to " import Realm from "realm" " The error message: Error: Missing Realm constructor. Did you run "pod install"? Please see https://realm.io/docs/react-native/latest/#missing-realm-constructor for troubleshooting Running on Android 13 SDK (latest from Android Studio) through the command "expo start". I get the error, but I cant fix it since im not on Mac, and it also shouldnt require pods, since Im also running it on Android and not iOS. (iOS throws the same error). The error message also refers to a non-existing website which is very helpful :) Thank you MongoDB team... Expo SDK v. 44.0.0 realm v. 10.17.0 (latest?) My goal is to make an offline-first database application and its not going so well...
{ "language": "en", "url": "https://stackoverflow.com/questions/72288066", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }