text
stringlengths
70
452k
dataset
stringclasses
2 values
XF + DryIoc: Unable to select single public constructor from implementation type Xamarin.Forms.NavigationPage I just created a XF + Prism + DryIoc project using Prism template in VS2017. I updated an app XF and Prism to latest: XF: <IP_ADDRESS>934 Prism: <IP_ADDRESS>6-pre Without adding any of more code (except fixing breaking changes with latest Prism 7), when running the app I get: Unable to select single public constructor from implementation type Xamarin.Forms.NavigationPage I search a bit and I found https://github.com/PrismLibrary/Prism/issues/889 but issue is supposed to be resolved with latest DryIoc. Any ideas? As Brian indicated this was fixed and is on MyGet. This was actually a bit of a regression that was caused by our move to unify the API and abstract the IOC containers in Prism 7. You'll notice this was reported: Issue 1304 Issue 1309 Issue 1311 And was fixed in PR 1305. The fix is available in <IP_ADDRESS>0-ci or later.
common-pile/stackexchange_filtered
Is there a name for the un-integrated Lagrangian? The "action" is a functional of fields and their derivatives integrated over a space-time volume. A Lagrangian is just integrated over the space dimensions. But what is the name of the thing to be integrated? e.g. $$S=\int L[\phi](t) dt = \int {\cal L}[\phi](x,y,z,t)dx dy dzdt.$$ What is the name of ${\cal L}$ if it has one? e.g. for the Klein-Gordon action it might be: $${\cal L}[\phi] = \eta^{\mu\nu}\partial_\mu \phi(x)\partial_\nu \phi(x) + m^2 \phi(x)^2.$$ It's just an expression of fields and first deriviatves. Does this have a name? In field theory, the quantity which is integrated over spacetime to obtain the action is usually called the Lagrangian density. But since you can create a different lagrangian density by doing integration by parts, this means two lagrangigan densities will have the same Lagrangian??? Two lagrangian densities which only differ by a total derivative will effectively give you the same Lagrangian, since the total derivative ends up cancelling when performing the integration due to the Euler-Lagrange equations. The factor you integrate over spacetime is called Lagrangian density. A similar case happens when you calculate the hamiltonian, where you can integrate a Hamiltonian density.
common-pile/stackexchange_filtered
android tabs are too big Rephrasing an old question as suggested by a group of mods. Why are android tabs too big ,specially on a device that small? Eg. http://developer.android.com/resources/tutorials/views/hello-tabwidget.html I am converting a java Swing application to android and tabs are giving me the most trouble. Besides looking ugly, each page seem to require a separate activity too. I mean with a JtabbedPane all I did was to put whatever components on a separate JPanel and add them to the host pane. Thanks First I believe both of my questions are stated clearly in the above post but i will rephrase anyway a) Why are the default android tabs so big compared to other components. It takes up a lot of space of the limited available space. If it is to make it comfortable for the user why aren't the other components equally big ? b) [ANSWERED]Why does each page requires starting a separate activity. In my app for example I just need to display some chats. This is already answered i.e use of Fragments. Hope it is clear enough now Android's UI and Java's Swing have little to nothing in common. The reason for this is BECAUSE the screen is so small. If the tabs were the same size as in a Swing application, you would have trouble trying to select them. The screen size is what made it necessary to do something completely different If anything you save space by making them smaller so I disagree. I have noted many apps using buttons and handling the switching themselves than using default tabs. Unfortunately for me I have used tabs everywhere in views of the java app. Then this sounds like a personal problem. If it's such a big deal, use buttons. Make a new TabActivity class that draws things the way you want them. You're never required to use the tabs they offer you, so by all means do whatever you want. Just be aware you'll probably run into countless problems along the way, specifically here and here Do you realize the keyboard buttons have much smaller size than the tabs and yet you don't complain about difficulty of selecting them ? That's because there's a software behind it accounting for inaccuracy. Well why not use that for the other components too ? It is part of the OS I suppose. Facts is the tabs do have a strangely bigger size than what one would expect compared to other components. Your reasoning that it is because the screen is small is simply wrong. You can't use the autocorrect software for tabs. It wouldn't work, the user would get frustrated. By all means, do it your own way, but that's way more work. Just make sure you keep it pure. And in the future, don't come on SO just to complain that Android's UI doesn't look the way you want it to. You are not making any sense at all and stop using capital letters to try and convince me. My objection to your post was that your emphatic "BECAUSE it is so small" is wrong. If that was the reason the other controls should be equally big too. Why is it that the tabs are the only one which are x-large ? There is definitely a reason to it but you certainly don't seem to know. about the multiple activities problem , check out the fragments solution that google has offered since android 3.x. they also have a compatability package for older android devices (requires android API4+ , which is the vast majority) . they even have a tabs example which is very similar to the android market app (aka "play store") , so all you need is to check out the sample. about tabs sizes , you can customize it however you wish (example here) , but do note that this requires the user to actually be able to touch it , even with large fingers... :) Thanks. I should be able to use the fragments solution since I am targeting a galaxy nexus android. I will have to decrease the height of the tabs because I am creating them everywhere dynamically (multiple chats with users). It might not be the best app with this one-to-one translation but I will try it anyway. P.S you mean the phone Google invented on april 1st that uses the morse code :) i don't understand the morse code question . anyway , are you sure you wish to target phones with android ICS (API 14+) ? they are only 5% of the market currently . look : : http://www.appbrain.com/stats/top-android-sdk-versions http://developer.android.com/resources/dashboard/platform-versions.html most devices currently use version 2.1 and above . I can switch to 2.1 or 2.3 I guess since I do not use much of the new features anyway. I use the galaxy nexus because the app I am developing really needs all the space it can get. The gmail tap is an april 1st joke that uses morse code for people with fat fingers. http://www.huffingtonpost.com/2012/04/01/gmail-tap-google-april-fools-day_n_1394635.html i know the morse code app , i just didn't understand what it has to do with anything i've written about . about the space , do you mean screen space or storage space ? if it's screen space , consider using a scrollView for smaller screens (or something similar) , and if it's storage space , consider using android expansion library : http://developer.android.com/guide/market/expansion-files.html Sigh.. it was not a question really. You said people with large fingers should touch the keys and then put a smiley on it. I interpreted that as a joke. Why so dense? Well thanks for the rest of your post anyway.. sorry . i didn't mean it . anyway , do you know that this app actually exists : https://play.google.com/store/search?q=morse+keyboard&c=apps I actually didn't know it existed and took it as a joke when I read it. Thanks.
common-pile/stackexchange_filtered
Omniauth mock up not working in rails rspec. Google Login button not getting clicked After following tutorials from internet of integration test of Google Login in Rails. I came to this. But it's not working. # frozen_string_literal: true require "rails_helper" def stub_omniauth OmniAuth.config.test_mode = true OmniAuth.config.mock_auth[:google_oauth2] = OmniAuth::AuthHash.new({ provider: "google_oauth2", uid: "12345678910", info: { email<EMAIL_ADDRESS> first_name: "Sam", last_name: "Lim" }, credentials: { token: "abcdefg12345", refresh_token: "abcdefg12345", expires_at: DateTime.now, } }) end RSpec.feature "user logs in" do scenario "using google oauth2" do visit login_path stub_omniauth Rails.application.env_config["omniauth.auth"] = OmniAuth.config.mock_auth[:google_oauth2] expect(page).to have_css("a.google-login-button") find("a.google-login-button").click expect(page.current_path).to eq(dashboard_path) end end I am supposing that after running the test my page content would change but they are same as before.
common-pile/stackexchange_filtered
Sharing result response API without state and outside then() var a = getdata() a.then((result) => { console.log(result.data.data); this.setState({ items: result.data.data }); }) console.log(result.data.data); I want to share result.data.data to outside then(). New to React and JS in general so I apologize for the simplistic nature of this question. I'm attempting to store a single child's name from my API in React's state but I must be doing something incorrectly with the JSON as this state is never updated. If someone could explain what I'm doing incorrect and the best way to accomplish this, I'd very much appreciate it. My code almost mirrors this but I can't seem to figure out whats wrong here. It will be useful if you could share more code. You cannot access result variable outside your callback function. So you have to save it to the state variable and access it outside or anywhere else as this.state.items i already do that's, but i want to callback result if can do that.
common-pile/stackexchange_filtered
Spark never finishes jobs and stages, JobProgressListener crash We have a Spark application that process continuously a lot of incoming jobs. Several jobs are processed in parallel, on multiple threads. During intensive workloads, at some point, we start to have this kind of warnings : 16/12/14 21:04:03 WARN JobProgressListener: Task end for unknown stage 147379 16/12/14 21:04:03 WARN JobProgressListener: Job completed for unknown job 64610 16/12/14 21:04:04 WARN JobProgressListener: Task start for unknown stage 147405 16/12/14 21:04:04 WARN JobProgressListener: Task end for unknown stage 147406 16/12/14 21:04:04 WARN JobProgressListener: Job completed for unknown job 64622 Starting from that, the performance of the app plummet, most of Stages and Jobs never finish. On SparkUI, I can see figures like 13000 pending/active jobs. I can't see clearly another exception happening before with more info. Maybe this one, but it concerns another listener : 16/12/14 21:03:54 ERROR LiveListenerBus: Dropping SparkListenerEvent because no remaining room in event queue. This likely means one of the SparkListeners is too slow and cannot keep up with the rate at which tasks are being started by the scheduler. 16/12/14 21:03:54 WARN LiveListenerBus: Dropped 1 SparkListenerEvents since Thu Jan 01 01:00:00 CET 1970 This is a very annoying problem, because it's not a clear crash, or clear ERROR message we could catch to relaunch the app. UPDATE: Problem occurs with Spark 2.0.2 and Spark 2.1.1 Most probably related to SPARK-18838 What bugs me most is that I would expect this to happen on large configurations (a large cluster would DDOS the driver with task results more easily), but it's not the case. Our cluster is kind of small, the only particularity is that we tend to have a mix of small and large files to process, and small files generate many tasks that finish quickly. did you find the reason ? I may have found a workaround : Changing value of spark.scheduler.listenerbus.eventqueue.size (100000 instead of default 10000) seems to help, but it may only postpone the problem. Spark 1.4.1 here. Increasing this setting seem to delay the onset of this error. :) repartitioning to a smaller number, you can avoid this error, before using the base df/rdd, do base_df.coalesce(<some smaller number. like 10>).
common-pile/stackexchange_filtered
What is the use case for -M gcc option? gcc's -M option gives makefile compatible list of dependencies. I've tried it on one of my projects *.c files and I got very long list of various system headers: $ gcc -I/home/marko/foo/local/include -I/home/marko/foo/src/misc.git -M src/foo.c | wc -l 65 What is the use case for this? Why would anyone need such long list of not so useful dependencies? Or is it somehow used in autotools and not intended for manual use? Why would that be useless? Just let make include it and decide what's useful for it. It's mainly used in conjunction with other options. Have a look at the -M* options I think it is primarily a pedantic thing. You might want to track system dependencies for some reason. For example, you might be using -isystem or --sysroot or something like that, and want your dependency tracking to work properly when you update the files in the sysroot. Less likely, you might want your project to rebuild properly after you update the operating system. I would hazard a guess that using -M is generally harmless.
common-pile/stackexchange_filtered
How to find out programmatically if a contact is editable in android In the application I am building I am accessing the contacts of the mobile, but I need to know whether those contacts are editable (like the ones of the google account) or not (like the ones coming from Skype). I haven't found anything related to this topic anywhere, but I see that the contacts application from Samsung is able to distinguish between them, so it has to be possible. Any help or guide would be very appreciated. Thanks a lot!! Well, it seems that maybe what I am asking is not completely clear. This is my specific use case: I am building an app that has a map. From it you can access the contact list and when you select a contact, this will be shown in a balloon on the map. If that contact is writeable, you will have a button in that bubble to edit that contact. But if that contact is not writeable, that button will not appear. Hey, there were many discussion went through on this topic. Please go through following links. here, here and here Thanks, but none of those discussions make reference to the problem I am asking for (to know whether a contact is writeable or not). You need to have following permissions which will enable write/read authority on contacts. When you have write permission, it implicitly means that you have edit permission on contacts. <uses-permission android:name="android.permission.READ_CONTACTS"></uses-permission> <uses-permission android:name="android.permission.WRITE_CONTACTS"></uses-permission> For complete list of available permissions, please go through developer reference To edit contacts please refer the this discussion. For sample code please go through this and this. Thanks again, but that is not exactly what I need. Maybe I didn't explain myself properly. In the contact list on your mobile there are some that you can't edit (like the ones coming from Skype) and that is ok, it is the way it should be (and it is the way it works manually or programmatically). What I need is that when I get the information of a contact, know whether it is writeable or not, because depending on that, I will perform different actions. I am sorry for that, let me think. Please describe actual use case, so that we may suggest appropriate solution. elaborate your question and be specific. Well, basically, I am building an app that has a map. From it you can access the contact list and when you select a contact, this will be shown in a balloon on the map. If that contact is writeable, you will have a button in that bubble to edit that contact. But if that contact is not writeable, that button will not appear.
common-pile/stackexchange_filtered
Can't free linked list This is the struct: typedef struct listeEle { int pos; struct listeEle *next; } ListEle; this is where I create the list: ListEle *mokli(int n){ if(n<=0) { fprintf(stderr, "Falscher Parameter für mokli... Programm beendet."); exit(0); } else { ListEle *lst; lst = malloc(sizeof(ListEle)); lst->next = NULL; lst->pos = 1; int i; ListEle *new; ListEle *ptr; ptr = lst; for(i=1; i<n; i++) { new = NULL; new = malloc(sizeof(ListEle)); new->next = NULL; new->pos = i+1; ptr->next = new; ptr = ptr->next; } return lst; } } and this is where I try to free it void unmokli(ListEle *lst) { if(lst->next == NULL) { free(lst); lst = NULL; printList(lst); printf("1 > Liste vollständig gelöscht.\n"); } else { ListEle *head; head = lst; int del = 0; while(head) { ListEle *temp = head; head = head->next; free(temp); del+=1; } free(lst); lst = NULL; printf("2 > Liste deleted (%d).\n", del); } } This is how I print it void printList(ListEle *anfang){ if(anfang == NULL) { printf("List not av...\n"); } else { ListEle *ptr; ptr = anfang; int i = 1; while(ptr) { printf("Element %i -> ListeEle pos=%i\n", i++, ptr->pos); ptr = ptr->next; } } } The problem is in the main method. The list I create here won't be freed, although I pass it correctly to the freeing function. int main(void){ ListEle *liste; liste = mokli(6); printList(liste); unmokli(liste); printList(liste); return 0; } After unmokli it should be freed completely, but the list inside the main function is still allocated. How can I completely free the list? When you do lst = NULL; in the function unmokli you are only making the local copy lst NULL. Remember that arguments are passed by value, i.e. they are copied. You need to pass lst by reference, which can be done by passing a pointer (to the pointer): void unmokli(ListEle **lst) { ... *lst = NULL; ... } You then call this by using the address-of operator: unmokli(&liste); The method signatures have to stay like this. This is an assignment. @IMX Then you simply have to set the liste pointer to NULL in main, or simply not use the pointer any more. Using the pointer when you have freed what it points to will cause undefined behavior. Right, I'll delete my comment. It's freed, but data still remains after calling free, so you just accessing deleted data by printing list after delete. (which you mustn't do actually) Also, if you want to set 'liste' pointer to NULL inside free-function, you should pass pointer to a pointer. The following code in unmokli is useless: free(lst); // Already freed in a loop before lst = NULL; // Takes effect only inside this function Either pass reference of liste to unmokli() or take return parameter from it as you have done in mokli(). In your case, its getting freed, but variable liste in main() is not set to NULL and still references old memory. This is may cause you crash. Update your code as void unmokli(ListEle **lst_ref) { ListEle *lst = *lst_ref; ... //your code freeing list //set to null after freeing *lst_ref = NULL; } From main() call it as unmokli(&liste); Typically, I would free (& NULL assign) the linked list as below: void unmokli(ListEle **lst) { ListEle* nxt; if(lst==NULL) return; // printList(*lst); // not required by the free-list logic as such... while(*lst) { nxt=(*lst)->next; // printList(*lst); // not required by the free-list logic as such... You can test free code with this. free(*lst); *lst=nxt; } } //usage unmokli(&list_head);
common-pile/stackexchange_filtered
Compression Level Mksquashfs Here I'm trying to create a squashfs filesystem but the resulting image is bigger than the original version and not because I added a file or anything as I only modified some configuration files. What I'm trying to do is modify the existing squashfs filesystem on a live usb and delete some info to start the OS in a login shell. Since I fixed an amount of space to the EXT4 partition I need the modified squashf to have the same size as the original. I can do the changes while the live system is running but since I'm making a script to automate this process I need to do it before creating the live usb itself. The problem comes when recreating the image as the resulting file is about 400mb larger than the original and when I use the -b 4096/1Mbyte option the image is about 800mb larger when the original file is about 2.2gb. I did the same before to add my script to the filesystem and it worked great but now I can't understand what happen this time. I searched my backup of .bash_history but with no luck How can I reduce the image size?? What I'm doing wrong, anyone?? Edit: # Create Directories mkdir /mnt/kali-iso mkdir /mnt/squash mkdir /tmp/squash_mod # Mount ISO And Squashfs Image mount /root/kali.iso /mnt/kali-iso mount /mnt/kali-iso/live/filesystem.squashfs /mnt/squash -o loop # Copy All Files To A Temp Directory To Modify Them cp -rf /mnt/squash/* /tmp/squash_mod cp /root/foo.sh /tmp/squash_mod/root/Desktop/ # Create Squashfs mksquashfs /tmp/squash_mod filesystem.squashfs Or # mksquashfs /tmp/squash_mod filesystem.squashfs -b 4096 # or 1Mbyte Results from "du" command: du -ch /mnt/squash | grep "total" = 6.6G total du -ch /tmp/squash_mod | grep "total" = 7.2G total There are some discrepancies between the same folders, their size are different: "/tmp/squash_mod/sbin = 8.8mb" "/mnt/squash/sbin = 8.5mb" "/tmp/squash_mod/var = 309mb" "/mnt/squash/var = 282mb" "/tmp/squash_mod/bin = 7.0mb" "/mnt/squash/bin = 6.8mb" Can you provide the full command you're using to generate the file? Check my edit for complete process but by only copying a file instead of modifying a file Your cp -rf won't preserve hardlinks, so hard linked files will take up twice as much space as before. Not sure if this is the issue, but worth trying. Use rsync -Ha /mnt/squash/. /tmp/squash_mod/ instead. You can also use du to compare /mnt/squash with /tmp/squash_mod to see where the difference in space is. Well I did as you said but the size of the 2 directories are way too different. I'll post the results for a better understanding. Cannot comment so I'm writing an answer: 1) I agree with Patrick that the most probably source of your problems is hardlink 'multiplication'. With a normal cp you create as many copies of a hardlinked file as the hardlink count was. Use rsync or cp -a instead. 2) An even better solution would be to simply unsquashfs the image so you can skip the loop mount step. 3) Digging even deeper, you can play around with aufs or unionfs :)
common-pile/stackexchange_filtered
index.html index.php redirection + Internal Server Error I'm using a mac, FTP is with Transmit. I am doing a website for a client on Wordpress. The site is finished but my client wanted to add another page in front of the website so when you click on the URL in Google, you have a page with their logo which you click and then access to the wordpress website. So : I created a index.html with dreamweaver pointing to "http://www...." and I uploaded it in the FTP. The index.php of the wordpress site points also to that same address. I added this code here in the .htaccess file: DirectoryIndex index.html index.php I then had to replace the index.html by another one (same but the content image is just bigger to have full width) and removing the old one. And now nothing seems to point, or there a duplicate problem! I have the "Internal Server Problem, error 500". So there, the word is out! Thank You! Just so you know, we call those sorts of things "splash pages," and they're generally accepted to be a bad idea. It may be worth trying to convince the client not to do it. ya, you should definitely point out the usability issue's to your client. All right. I thought so myself... so does anyone have an idea of how I can put it back the way it was? Meaning, do I just delete the index.html and write in the .htaccess : DirectoryIndex index.php ?? how do I put it back the way it was? You can simply remove the line with the directory index (or comment it out using # at the beginning of the line) and you should also remove the index.html file (or rename it to something like index_old.html) What exactly is wrong is hard to tell without knowing the error. If you have access to any apache log files, the error.log will tell you why it's outputting an error. A HTTP 500 status can be any kind of error, but in my experience it is most commonly due to: Incorrect file permissions on some files syntax error in the .htaccess file or httpd.conf (which I'm guessing you don't have access to) If you are on a shared host and you do not have access to the apache error.log file or you don't know where it is, it would probably be a good idea to contact the sys admin or support and ask why you're getting the error or ask where you can find the error.log file I've read everywhere that you can find what's wrong from the apache error.log but I have no idea where to access them. In my log file for example its only access.log.05 or any number... Thank you for your time! Then you might have to contact the system administrator / support to find out what the error is. It might even be that they've disabled overriding the DirectoryIndex directive. That could cause a 500 error. Ok Thank you so much, I think I'll do that!
common-pile/stackexchange_filtered
How do I automatically select the first panel in a declarative dojo wizard? I have created a declarative dojo wizard in dojo 1.5 that is embedded in a dojo dialog like this: <div dojoType="dijit.Dialog" id="genWizardDialog" jsId="genWizardDialog" refreshOnShow="true" preventCache="true" title="Title"> <div dojoType="dojox.widget.Wizard" style='height: 375px; width:400px' hideDisabled="true" doneButtonLabel="someLabel"> <div id="wizard1" dojoType="dojox.widget.WizardPane" canGoBack="false" passFunction="panelOneDriver"></div> <div id="wizard2" dojoType="dojox.widget.WizardPane" passFunction="validateBoxes" style="padding:8px; height:100%;"></div> ....I have some more panels. </div> <!-- Here I have setup the cancel method. --> <script type="dojo/method" event="cancelFunction"> //dijit.byId("genWizardDialog").onSelected(0); dijit.byId("genWizardDialog").hide(); </script> </div> Everything pretty much works. However, I have 4 panels. If I proceed to panel three and hit cancel. When I then click the button to start the dojo dialog I am already at panel 3! I want to start back at panel 1. As I have already invested time into the declarative approach I am hoping to avoid doing this programmatically. I found site that mentioned an onSelected() method to accomplish this -> http://dojo-toolkit.33424.n3.nabble.com/resetting-wizard-pane-and-contents-on-reopening-wizard-td158660.html, however, this didn't work and stands to reason since looking in the Wizard.js I don't see this method defined! In your pasted code, you have the cancelFunction event in the dialog's div, not the wizard's. So move the <script> tag inside the div that has dojoType=dojox.widget.Wizard. To select a specific wizard pane, you can use the selectChild function. <script type="dojo/method" event="cancelFunction"> dijit.byId("genWizardDialog").hide(); dijit.byId("genWizard").selectChild("wizard1", false); </script> In the above, I've assumed that your wizard has an id "genWizard", so you'd have to add that to the wizard's div. Now the wizard will jump to the first wizard pane when you click its cancel button. It will not jump to the first wizard pane if you just click the dialog's X button. If you want that too, you need to use the dialog's onHide event. <script type="dojo/method" event="onHide"> dijit.byId("genWizard").selectChild("wizard1", false); </script> This script tag has to be in the dialog's div, not the wizard's, make sure you get that right. Hi Frode, Thx for the response. That did the trick. I actually just messed up the copy/paste of the cancelFunction, it was in the right place on my server just not in the above. But, your point was valid. Thx again.
common-pile/stackexchange_filtered
Is there a known limit to the number of CREATE TABLE I can run in parallel with Cassandra? I'm wondering whether I can have all my clients send a "CREATE TABLE ..." to the same Cassandra cluster at pretty much the same time. Is that expected to work? I can always increase the timeout to make sure that I don't get such an error, but I'm wondering whether this is something that could cause problems, outside of some slowness. Would it be slower/faster as we increase the number of clients & Cassandra nodes? Yes, 1. Do not run schema changes in parallel. After each run make sure schema is in agreement before running next (ie java driver: resultset.getExecutionInfo().isSchemaInAgreement()) They are slow but you should be conservative and patient with them. Its not worth the risk of divergent schemas that can exist with some known race conditions. This may improve in future releases but with all existing versions since the schemas were made dynamic (0.7 - 3.11) this operation should be run one at a time. If your application is dependent on constantly changing and dynamic tables you should re-evaluate your implementation. No. Not really dynamic tables. An installation may add plugins at a later time and these plugins may make use of their own tables. So they need to be created at that time. It's a one time event at the time you add those plugins and then it's there forever. Only, it would be simpler if I could have any computer in the cluster create tables that are still missing. Anyway... it will require a little more synchronization work. Nothing to worry about really. Does isSchemaInAgreement() work for keyspace creation and altering, too? The Javadoc says "After a successful schema-altering query (ex: creating a table)" so I'm sort of assuming that keyspace management is also considered schema-altering, but I can't find anything to prove me right or wrong. yes, it will tell you when the cluster is in schema agreement or if theres some nodes with different versions.
common-pile/stackexchange_filtered
Vue.js not being recognised with CDN Hi I am currently learning Vue.js and I have an issue with it, I am calling Vue using a CDN. I have followed instructions but it does not seem to be recognising that Vue exists. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Vue Basics</title> <link href="https://fonts.googleapis.com/css2?family=Jost:wght@400;700&display=swap" rel="stylesheet" /> <link rel="stylesheet" href="styles.css" /> <script src="https://unpkg.com/vue@3"></script> <script src="app.js" defer></script> </head> <body> <header> <h1>Vue Course Goals</h1> </header> <section id="user-goal"> <h2>My Course Goal</h2> <p>{{coarseGoal}}</p> </section> </body> </html> This is the simple js file It does not output the code from the Vue object. Would really appreciate any help on this. const app = vue.createApp({ data () { return { coarseGoal: 'This is the best', }; } }); app.mount('#user-goal'); It should be Vue.createApp instead of vue.createApp. Working Fiddle const app = Vue.createApp({ data() { return { coarseGoal: 'This is the best', }; } }); app.mount('#user-goal'); <title>Vue Basics</title> <link href="https://fonts.googleapis.com/css2?family=Jost:wght@400;700&display=swap" rel="stylesheet" /> <link rel="stylesheet" href="styles.css" /> <script src="https://unpkg.com/vue@3"></script> <body> <header> <h1>Vue Course Goals</h1> </header> <section id="user-goal"> <h2>My Course Goal</h2> <p>{{coarseGoal}}</p> </section> </body>
common-pile/stackexchange_filtered
How to find/delete duplicate items in stack The items inside the stack should be unique. Is there a way I can delete the duplicate item inside the stack? And inform the user that his input is already inside the stack? Here is my code: class Node: def __init__(self, key): self.left = None self.right = None self.val = key def printPreorder(root): if root: print(root.val), printPreorder(root.left) printPreorder(root.right) class stack: def __init__(self): self.items = [] def push(self, item): return self.items.append(item) def pop(self): return self.items.pop() print ("Create 3 words using the letters:") root = Node('n') root.right = Node('o') root.left = Node ('w') printPreorder(root) print("-----------------------------------") s1 = stack() while (s1.size() <3): FirstList = (input("Enter the word you created: ")).lower() if FirstList == 'won' or FirstList == 'own' or FirstList == 'now': s1.push(FirstList) print(s1.items) else: print('Try another word!') One way to do this is to store a copy of the stack's contents in a list and search there, but it's not good if your stack has a lot of elements Ideally no you cannot traverse through a stack to find duplicate elements. But since you are using a list for your stack implementation, you can traverse through it and find duplicate elements but this is not a good idea. Instead, you can use another data structure, for example, a set can be used to keep track of all the unique elements you have seen so far. Every time .push() is called, you can check if the element is already present in the set. If it is not present, then you can add it to both the stack and set. If present, you can inform the user that it is already present in stack. And remember to remove the element from the set when you pop from the stack. You can use set to store unique values. A simple way to check if the stack has unique elements is to compare the size of the set of stack elements and the list of stack elements (since your implementation of a stack is a list). def isDuplicate(self): return len(set(self.items())) != len(self.items()) To check if there's a duplicate element in the stack (implemented as a list), you can write an implementation that inserts your elements into a set, and at every step checks whether the element already exists inside the list. def removeDuplicate(self): temp_set = set() for item in self.items(): if item in temp_set: return item return None And then you can remove that duplicate element from the stack using self.items().pop(self.removeDuplicate())
common-pile/stackexchange_filtered
I want to display all related posts for a selected tag in WordPress I want to display all the related posts for a selected tag, my purpose is I display all the tag at my posts, if someone clicks on the tag, then it should be re-direct to my tag template tag.php. But I am unable to display all the posts related to the tag (which i have clicked at post). my tag <div class="single_detail"> <div class="single_text"> <?php //GET THE TAG NAME FORM THE QUIRED OBJECT $term = get_queried_object(); $tag_name = $term->name; $args=array('posts_per_page'=>5, 'tag' => $tag_name); $wp_query = new WP_Query( $args ); if( $wp_query->have_posts()) : while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?> <div class="blog_box"> <a href="<?php the_permalink(); ?>"> <span class="blog_author">By <strong><?php echo get_the_author(); ?></strong> Posted <strong><?php the_time('F j, Y') ?></strong></span> <h3><?php the_title(); ?></h3> <p><?php echo substr(get_the_excerpt(), 0,100); ?></p> <span class="read_more">Read more</span> </a> </div> <?php endwhile; endif; ?> </div> <!-- end of posts details --> How can I get all the post of my selected tag? You're limiting your query via posts_per_page to five results, to get all possible results use -1. Don't use $wp_query as variable name, as it is associated to a global variable with the same name, which can lead to interferences. But that said, you absolutely don't need a custom query in your tag.php. You are already querying for a specific tag, with ?tag=abc or /tag/abc in your URL. WordPress catches that and selects the correct template, and limits the query to that tag. There is a hierarchy on how tag template (codex page; read it for more information) files get selected: tag-slug.php tag-id.php tag.php archive.php index.php If available then the order is first to fifth, if not WordPress is looking for the next one. Additionally I would recommend to give the Theme Developer Handbook a good read, especially the section about Template Files. In the end you just need a template file to fit your needs. Below a exemplary template file. <?php /** * The template for displaying tag pages. * * @package WordPress * @subpackage Theme */ ?> <?php get_header(); ?> <!-- tag | start --> <div class="row"> <div class="col-xs-12"> <?php the_archive_title( '<div class="page-header"><h1 class="page-title">', '</h1></div>' ); ?> </div> </div> <div class="row"> <div class="col-xs-12"> <?php if ( have_posts() ) : ?> <?php $description = get_the_archive_description(); ?> <?php if ( ! empty( $description ) ) :?> <div class="archive-description"> <?php echo $description; ?> </div> <?php endif; ?> <?php while ( have_posts() ) : the_post(); ?> <!-- tag loop | start --> <div id="content" <?php post_class(); ?>> <div class="row"> <div class="col-xs-12"> <?php the_title( '<div class="post-header"><h2 class="post-title">', '</h2></div>' ); ?> <?php if ( has_post_thumbnail() ) : ?> <div class="entry-thumbnail"> <?php the_post_thumbnail(); ?> </div><!-- .entry-thumbnail --> <?php endif; ?> <div class="entry-content"> <?php the_excerpt(); ?> </div><!-- .entry-content --> </div> </div> </div><!-- #content --> <!-- tag loop | end --> <?php endwhile; ?> <?php endif; ?> </div> </div> <!-- tag | end --> <?php get_footer(); ?>
common-pile/stackexchange_filtered
How to make this simple landing page flex box work in all relevant browsers? For hours I have been trying to make a simple landing box banner layout work in all relevant browsers using flexbox, but without luck. In the following there is a sketch of the layout I want to realize. Basically just two boxes for an image and a title next to each other. Reaching a certain minimum width of the title box, the layout should wrap to a stacked layout: This is my HTML code: <div class="landing_page_box"> <div class="landing_page_box_left"> <h2>Title</h2> </div> <div class="landing_page_box_right"> <figure>...</figure> </div> </div> And this is the CSS code: div.wp-block-columns.landing_page_box { display: flex; flex-direction: row; flex-wrap:wrap-reverse; } div.landing_page_box_left { flex: 1 0 33.33%; min-width: 300px; padding: 30px; background: #cccccc; display: flex; flex-direction: column; justify-content: center; } div.landing_page_box_right { flex: 2 0 66.66%; } While this seems to work in Firefox V70 and Chrome V78 there are Problems in Internet Explorer 11: The two boxes are always stacked, even if the browser window is big enough for the boxes placed to each other. Could you please help me with that issue? Thanks in advance! I would argue IE11 is not relevant and I think it’s supported by edge getting chromium and IE not I agree, IE11 has very buggy flexbox support: https://caniuse.com/#search=flexbox use css media queries? I've tested gman's solution and it works well. You need to use media query in IE 11 and set flex-direction value to column-reverse to make the title column at the bottom when wrap to a stacked layout. If you want to auto-resize an image to fit a <div>, you can't apply an explicit width or height to the image tag. You could apply: max-width:100%; max-height:100%; And apply overflow:hidden; to the <div> to prevent the image overflowing. I think your approach to center vertically is good enough. You could check my sample below: .landing_page_box { display: flex; } .landing_page_box_left { flex: 1 1 auto; padding: 30px; background: #ccc; display: flex; flex-direction: column; justify-content: center; /*align-items: center;*/ } .landing_page_box_right { flex: 2 1 auto; background: #ddd; overflow: hidden; } img { max-width: 100%; max-height: 100%; } @media (max-width: 500px) { .landing_page_box { flex-direction: column-reverse; } } <div class="landing_page_box"> <div class="landing_page_box_left"> <h2>Title</h2> </div> <div class="landing_page_box_right"> <figure><img src="https://i.sstatic.net/SF9SU.jpg"></figure> </div> </div> Once again thank you very much for your helpful answer! I upvoted your answers, but my votes aren't shown since I do not have enough posts yet... @Stooky You're welcome. You could mark the most helpful suggestion as an answer if you have solved the issue. It can help other community members in future in similar kind of issues. Thanks for your understanding. Thanks a lot for your suggestions! Indeed, in this simplified example your approach works pretty well. However, if an image is added to the right column , you get some errors: <figure><img src="..." sizes="(max-width: 1024px) 100vw, 1024px"></figure> Firefox V70: The left title column is much smaller than 33%. To correct this, I changed "flex: 1 1 auto;" and "flex: 2 1 auto;" to "flex: 1 1 33.33%;" and "flex: 2 1 66.66%;", respectively. IE11: After the change above I tested the effect of adding an image to the right column in IE11. Sadly, the image is too big and overflows significantly to the right side. Obviously, IE11 is not able to scale the image correctly to the width of the right column. Is there a workaround? Things get even worse if I shrink the browser window until the media query is triggered. Then, the whole flex box is messed up and overflown by the running text of the website. Don't get me wrong, I would love to ignore IE11. However, as far as I know the market share of this browser still is about 10%. Isn't that too large a number to be ignored? Besides the errors, I want the title in the left column to be centered vertically, too. In my code I've already posted I realized this by adding the following lines to the respective css class: display: flex; flex-direction: column; justify-content: center; Although this works in all 3 browsers (even in IE11, yay!) I think that's more a workaround than a robust solution. Is there a better way to do this? Thanks in advance for your answers!
common-pile/stackexchange_filtered
What does status "Undisclosed" means for a conference paper I had sent a paper in a reputed conference. The status changed from "Under review" to "Decision pending" to "Undisclosed". What is the meaning of status "Undisclosed" ? Does it indicate something? It indicates that the conference system has a tendency to provide useless information that will, at best, send some of the authors round the bend. "Undisclosed" means that the conference chair (or the in-charge of decisions) has already made a decision based on the comments received from the reviewers, but the decision is not yet made visible to the authors. Wait for the decision notification date. You can see it on that date.
common-pile/stackexchange_filtered
Import errors when debugging Python unit tests in VSCode I'm trying to debug a Python unit test inside Visual Studio Code, but am getting an error while importing dependencies at the top of the file: import unittest from scipy.io import loadmat # exception thrown here I get a lengthy exception message: Exception has occurred: ImportError (note: full exception trace is shown but execution is paused at: <module>)` IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE! Importing the numpy C-extensions failed. This error can happen for many reasons, often due to issues with your setup or how NumPy was installed. ... This happens only when debugging. Any ideas why? How can I fix this? Are you using any virtualenvs/multiple Python versions, is your terminal/vscode running in the right one? Yep, I'm using an anaconda virtual environment and the terminal is set to it. Do I need to configure this in some other places as well for debugging sessions? Possibly related https://stackoverflow.com/questions/43700354/conda-and-visual-studio-code-debugging Thanks @mikulatomas, of all the ideas suggested on that SO, the solution that worked was to open a cmd window, do conda activate, navigate to my project folder and start code . from that folder. I'm uneasy about accepting this hack as a solution. I feel there should be a more permanent way of doing this. Seems like the way around is to open Anaconda Powershell and type: cd <my project folder> conda activate <myenv> code . This starts VSCode with the correct configuration. It's an ugly hack, but allows me to run and debug my unit tests.
common-pile/stackexchange_filtered
The strange behavior of let and var in Javascript case 1 var a // ===> undefined let a // ===> SyntaxError: Identifier 'a' has already been declared case 2 a = 1 // ===> 1 var a // ===> undefined let a // ===> undefined Why case 2 does not throw an exception? On my Chrome I get the same syntax error for the bottom example. Welcome to SO!! Please have a look at this. Case 2 also throws error. @ggorlen: There's a difference between console mode and regular script execution here, see my answer for more details. @Mandy8055: With Node 14.x or the Chrome 81 console, case 2 indeed does not throw an error. See my answer for the explanation why. V8 developer here. The first thing worth pointing out is that there are differences between regular script execution and "console mode" (a.k.a. "REPL mode"). The former is specified by the JavaScript standard, so all engines should behave the same there; otherwise it's a bug. The latter is not specified; it should obviously be similar to the former, but due to the interactive usage it turns out that it makes sense to have some minor differences. Let's look at a few concrete examples and explain what's going on. (1) Re-declaring a let-variable is invalid in regular script. In the DevTools console, that turns out to be annoying though: > let a = 42j // typo: I meant "42" < Uncaught SyntaxError: Invalid or unexpected token > let a = 42 // Let's try that again < Uncaught SyntaxError: 'a' has already been declared // Aaaargh!!! So a while ago Chrome made some changes to special-case the behavior around let-redeclarations for the console, which is why you can now see the following difference: > let a; let a; // One script: redeclaration error > let b > let b // Separate evaluations: OK, no error. If you executed the last two lines as part of regular script execution, you'd get the same error as when putting both declaration on the same line in DevTools. (2) var declarations vs. implicit global variables: there is a small difference between c = 1 and var d = 1: the former creates a configurable property on the global object, the latter creates a non-configurable property, so while the two are almost equivalent, they can still be distinguished afterwards. Now, in regular script execution, var declarations are hoisted, so if you have an explicit declaration following an implicit use of the same variable: e = 1; var e = 2; then this gets transformed internally to: var e; e = 1; e = 2. So in this case, you can't observe the configurability difference. In console mode, the exact same behavior isn't possible: when you execute e = 1, the engine can't know yet that you're going to type var e = 2 next. So it creates e as a configurable property of the global object. When var e follows, it doesn't do anything, because the e property already exists. (3) let variables vs. global object properties: variables declared with let do not create properties on the global object, they are in their own scope, shadowing the global property. Here's how you can observe that effect (both in regular script and in the console): f = 1 let f = 2 console.log(window.f, f) // prints "1 2" (4) Limitations to redeclarations in REPL mode: when REPL mode with its loosened restrictions on normally-invalid redeclarations was built for V8, the team decided to (continue to) disallow redeclarations that would change the kind (var, let, const) of a variable, as well as redeclaration of consts: > var g > var g // OK > let g // error: already declared > const g = 1 // error: already declared > let h > let h // OK (REPL-mode special case) > var h // error: already declared > const h = 1 // error: already declared > const i = 1 > const i = 2 // error: already declared > var i // error: already declared > let i // error: already declared (So there's only one difference to regular script execution here, see the comment on that line above.) Armed with this knowledge, we can now get back to your original question: var a // Creates a variable of `var` kind. let a // Redeclaration -> error a = 1 // Creates global object property. var a // Does nothing, because `a` already exists. let a // Creates a variable of `let` kind, shadowing global property. TL;DR: Use let for everything, and your code will behave reasonably. var has weird semantics that can't be fixed because it would break backwards compatibility with existing websites. Forgetting the keyword entirely gives even weirder behavior, especially once functions are involved. I was unaware about the point 4 mentioned in your answer. Thanks for the enlightenment @jmrk. When you define a variable without var, let, or const, it is entered into the global scope. Try this: In the JS interpreter of your choice, do this: >>> a = 5 >>> global You'll see a bunch data, and at the very bottom, you'll see a = 5. Now, enter >>> var a = 7 >>> global You'll see the same thing, but now a is 7. Restart your interpreter and enter >>> a = 5 >>> let a = 7 >>> global You'll see a still equals 5! This gives us a hint that var and let aren't using the same scope. Restart your interpreter. >>> a = 5 >>> let a = 6 >>> var a = 7 // Syntax Error! Now, try this: >>> var b = 6 >>> var b = 7 Notice how there's no syntax error? We've discovered that global variables will not throw syntax errors if you redeclare them at the global level. However, you cannot redeclare a variable at the global level that is already declared at a lower level. let creates a variable in a scope below var, which declares it in the global scope. That's why when you run var twice, nothing happens, but when you run let then var (or let then let), you get a syntax error. However, as we can see from the other answers, this is actually not true of all interpreters. My local version of Node has the same results you do, while some other interpreters will throw a Syntax Error for case 2. I am using node version v12.16.3. This also shows the syntax error for the second case. I am using v8.10.0 Case 2 does not throw an exception because of the a = 1. Remember that let variables are not initialized until their value is evaluated. In comparison to var, var is initialized with undefined unlike let variables It throws a syntax error. Please check once yep because let variables can't be referenced before assignment But in your answer you wrote Case 2 doesn't throws it.
common-pile/stackexchange_filtered
How specify field type for query select when using alias in cakephp? I'm using Cakephp 3.2.7 as a framework and create a query with select alias. $posts = $this->Posts->find() ->select(['id' => 'Posts.id','userid'=>"Posts.user_id"])->toArray(); I want to get id as string not integer (the column type in mysql is integer) and get the userid as integer (the column type in mysql is also integer) but use alias convert it to string. Is there any way to fetch all of Id columns in all of model as string or at least can define data type in query? Why do you need to change the type? PHP is a loosely typed language so it doesn't make a massive difference whether you have an integer or a string. Converting the id to a string in your code whilst maintaining the column as an integer in the database is likely to lead to issues with saving! if you use id or *_id words as alias and field type is integere then cakephp auto converts it into integer values. try with use author_id instead of userid then check. and let me know its working or not http://stackoverflow.com/questions/35650306/cakephp-3-x-how-to-change-the-data-type-of-a-selected-alias @drmonkeyninja I want to use it in the response of API for mobile and change it to string to prevent issues in data type definition in different OS. Finally I found the solution. I add a mutator to entity of post class. protected function _getId() { return (string)$this->_properties['id']; } that force id to return as string. Actually I agree with @drmonkeyninja and I don't know why you want to do this. Also I don't guarantee that what I'm about to write is safe and is a clean way to achieve what you are trying to do. Anyway you can modify the table schema and change the column type. See the manual $this->Posts->schema()->addColumn('userid', [ 'type' => 'integer', ]) ->addColumn('id', [ 'type' => 'string', ]); thanks for your response. I haven't ever used schema and I am not sure weather it change anything in database or just it convert column type after data fetch from database?
common-pile/stackexchange_filtered
NSTimer never fires I've been having problems getting an NSTimer to fire, and I assumed it had to with multi-threading issues. Just to be sure I was creating the timer correctly, I created the following test code and I placed it into my main view controller's initWithNibName. Much to my surprise, it also failed to fire there. NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(timerTest:paramTwo:paramThree:)]]; NSString *a = @"a"; NSString *b = @"b"; NSString *c = @"c"; [invocation setArgument:&a atIndex:2]; //indices 0 and 1 are target and selector respectively, so params start with 2 [invocation setArgument:&b atIndex:3]; [invocation setArgument:&c atIndex:4]; [[NSRunLoop mainRunLoop] addTimer:[NSTimer timerWithTimeInterval:5 invocation:invocation repeats:NO] forMode:NSDefaultRunLoopMode]; Any clues as to what is wrong with this code? It seems to do exactly what the documentation specifies for using an NSInvocation with an NSTimer. NSInvocations also have to have a target and a selector in addition to a method signature and arguments: NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(timerTest:paramTwo:paramThree:)]]; NSString *a = @"a"; NSString *b = @"b"; NSString *c = @"c"; [invocation setArgument:&a atIndex:2]; //indices 0 and 1 are target and selector respectively, so params start with 2 [invocation setArgument:&b atIndex:3]; [invocation setArgument:&c atIndex:4]; [invocation setTarget:self]; [invocation setSelector:@selector(timerTest:paramTwo:paramThree:)]; [[NSRunLoop mainRunLoop] addTimer:[NSTimer timerWithTimeInterval:1 invocation:invocation repeats:NO] forMode:NSDefaultRunLoopMode]; I was under the impression that the method signature contained the target and selector information; if not, what is its purpose? Nope. Method signatures are just a string describing the format of the selector and a little bit of useless information as to the stack alignment of the arguments. NSInvocation needs it in order to make the message forwarding mechanism work in case the invocation on the original target fails.
common-pile/stackexchange_filtered
How do I get TypeScript Array.map() to return the same as VanillaJS? Within my Angular6 App, I am making Conway's Game of Life. I am trying to generate an n x m two dimensional array of class instances. In vanillaJS, I got this to work as: generateInitialState(bias) { return [...Array(this.rows)] .map((a, i) => [...Array(this.columns)] .map((b, j) => new Cell(j, i, (Math.round(Math.random() * 1000) < (1000 * bias)) ? 'alive' : 'dead'))); } This generates an Array of length this.rows containing Arrays populated by (n = this.columns) instances of the Cell class. E.g. when this.rows = this.columns = 4 (from the console): [ [ Cell { x: 0, y: 0, state: 'alive' }, Cell { x: 1, y: 0, state: 'dead' }, Cell { x: 2, y: 0, state: 'alive' }, Cell { x: 3, y: 0, state: 'dead' } ], [ Cell { x: 0, y: 1, state: 'alive' }, Cell { x: 1, y: 1, state: 'alive' }, Cell { x: 2, y: 1, state: 'dead' }, Cell { x: 3, y: 1, state: 'dead' } ], [ Cell { x: 0, y: 2, state: 'alive' }, Cell { x: 1, y: 2, state: 'alive' }, Cell { x: 2, y: 2, state: 'alive' }, Cell { x: 3, y: 2, state: 'dead' } ], [ Cell { x: 0, y: 3, state: 'dead' }, Cell { x: 1, y: 3, state: 'alive' }, Cell { x: 2, y: 3, state: 'alive' }, Cell { x: 3, y: 3, state: 'alive' } ] ] In vanillaJS this works fine and generates the Array as needed. However, the above code in Typescript only returns an empty array of length this.rows. TypeScript appears to compile it down to: function generateInitialState(bias) { var _this = this; return Array(this.rows).slice().map(function (a, i) { return Array(_this.columns).slice().map(function (b, j) { return new Cell(j, i, (Math.round(Math.random() * 1000) < (1000 * bias)) ? 'alive' : 'dead'); }); }); } How would I get it to work in TypeScript? Full Code class Game { constructor(columns, rows, randomBias){ this.columns = columns; this.rows = rows; this.randomBias = randomBias; this.cells = this.generateInitialState(this.randomBias); } /* Content omitted for brevity */ generateInitialState(bias) { return [...Array(this.rows)] .map((a, i) => [...Array(this.columns)] .map((b, j) => new Cell(j, i, (Math.round(Math.random() * 1000) < (1000 * bias)) ? 'alive' : 'dead'))); } } class Cell{ constructor(x, y, state){ this.x = x; this.y = y; this.state = state; } } let a = new Game(4, 4, 0.5); console.log(a.cells); The problematic place is how you initialize array of specified size. When you do this: [...Array(this.rows)] it gets compiled to Array(this.rows).slice() which doesn't produce any values, because the array is filled with "holes", which is not the same as array filled with undefined values, which you get in original (uncompiled) version. Holes are not processed by map. Try Array.from({ length: this.rows }) instead: function generateInitialState(bias) { return Array.from({ length: this.rows }) .map((a, i) => Array.from({ length: this.columns }) .map((b, j) => new Cell(j, i, (Math.round(Math.random() * 1000) < (1000 * bias)) ? 'alive' : 'dead'))); }
common-pile/stackexchange_filtered
Display smiley button at right bottom on Android keyboard I need to show smileys button by default when user input in my EditText. Now keyboard for my EditText looks like: Look at the right bottom, you will see done button. In same time in sms app keyboard looks like: [ At the right bottom displays smiles button. How do I display smile button in keyboard for my EditText? Now I have next ExitText layout: <EditText ... // some layout params android:inputType="textCapSentences|textAutoCorrect|textAutoComplete"/> You can try by adding following attributes in your EditText. Missing property in you code is textShortMessage. So you can try by adding same. android:inputType="textShortMessage|textAutoCorrect|textCapSentences|textMultiLine" android:imeOptions="actionSend|flagNoEnterAction" It works. Thanks. It looks strange, but I couldn't find solution in Internet during one hour. You just have to add imeOption textShortMessage. <EditText ... // some layout params android:inputType="textShortMessage|textCapSentences|textAutoCorrect|textAutoComplete"/>
common-pile/stackexchange_filtered
Why i cant populate the chef's document? I have 3 collections: recipe, chef, and food category. Im trying to populate the chef collection, and I cant; what is the problem? const recipeSchema = new mongoose.Schema({ chef: { type: mongoose.Schema.Types.ObjectId, ref: 'Chef', required: true }, foodCategory: { type: mongoose.Schema.Types.ObjectId, ref: 'FoodCategory', required: true }, }) const recipes = await Recipe.find({ chef: '608ed57e58e54d4b9486dae4' }) .select("-__v") .sort({ name: 1 }) .populate("Chef", 'name status filePath'); You're trying to populate Chef not chef, fix the typo It doesn't work, my friend. could you try const recipes = await Recipe.find({ chef: '608ed57e58e54d4b9486dae4' }).select("-__v").sort({ name: 1 }).populate({path: "chef"}); and console.log(recipes) OMG, you are my saver! What was the problem? It's the typo you had .populate("Chef") not chef I only fixed that and the syntax change was because of my linter. by the way you specify your selection like this .populate({path: "chef", select: 'name status filePath'});
common-pile/stackexchange_filtered
How to create a tree from multi-parent / children? I am actually running through a problem. I have a Step (a Doctrine Entity) that has a self-referencing Many-To-Many relation. So a Step can have many parents, and many children, building some sort of a tree. The problem is I'm trying to render this tree, like this: I would like to be able to link the "root" step to "step_4_2", too so it draws a line from root to step_4_2. It seems like it is a "Directed Acyclic Graph", does anyone have an idea of how to manage this with PHP / Symfony2 / Doctrine ? What is the problem? I don't really see what could stop you from simply linking root with step_4_2 if you mean the structure. But if you mean something else, like rendering itself, then you need to specify. Yeah that is the problem. I need some function that can allow me to render correctly this design. For now it works as seen in the image above. However if I link rootto step_4_2, step_4_2 moves up between step_1_1and step_1_2, which is incorrect So... how to you want us to fix your code? Just guess what your current code is? I was always curious what people expect asking such questions to fix their code without providing any current one. I wasn't asking for a code fix, but rather a correct algorithm to create a DAG. I moved on to ArangoDB which supports storing complex graphs in a NoSQL database Previously you said that the tree itself is not a problem, you just don't know how to render it. Now you say you can't create the tree. You need to specify what you expect if you want to get any answer here.
common-pile/stackexchange_filtered
the simplest interface to let subprocess output to both file and stdout/stderr? I want something have similar effect of cmd > >(tee -a {{ out.log }}) 2> >(tee -a {{ err.log }} >&2) in python subporcess without calling tee. Basically write stdout to both stdout and out.log files and write stderr to both stderr and err.log. I knew I could use a loop to handle it. But since I have lots of Popen, subprocess.run calls in my code already and I do not want to rewrite the entire thing I wonder is there any easier interface provided by some package could just allow me to do something like: subprocess.run(["ls", "-l"], stdout=some_magic_file_object(sys.stdout, 'out.log'), stderr=some_magic_file_object(sys.stderr, 'out.log') ) Possible duplicate: https://stackoverflow.com/questions/19425736/how-to-redirect-stdout-and-stderr-to-logger-in-python @Tzane that is completely different question. We are talking about subprocess's stdout/stderr. That question about python logger Sure, but the point was to pipe the subprocess output to stdout/stderr and use the logger to log that. I see the solution here was more elegant than that though. No simple way as far as I can tell, but here is a way: import os class Tee: def __init__(self, *files, bufsize=1): files = [x.fileno() if hasattr(x, 'fileno') else x for x in files] read_fd, write_fd = os.pipe() pid = os.fork() if pid: os.close(read_fd) self._fileno = write_fd self.child_pid = pid return os.close(write_fd) while buf := os.read(read_fd, bufsize): for f in files: os.write(f, buf) os._exit(0) def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): self.close() def fileno(self): return self._fileno def close(self): os.close(self._fileno) os.waitpid(self.child_pid, 0) This Tee object takes a list of file objects (i.e. objects that either are integer file descriptors, or have a fileno method). It creates a child process that reads from its own fileno (which is what subprocess.run will write to) and writes that content to all of the files it was provided. There's some lifecycle management needed, as its file descriptor must be closed, and the child process must be waited on afterwards. For that you either have to manage it manually by calling the Tee object's close method, or by using it as a context manager as shown below. Usage: import subprocess import sys logfile = open('out.log', 'w') stdout_magic_file_object = Tee(sys.stdout, logfile) stderr_magic_file_object = Tee(sys.stderr, logfile) # Use the file objects with as many subprocess calls as you'd like here subprocess.run(["ls", "-l"], stdout=stdout_magic_file_object, stderr=stderr_magic_file_object) # Close the files after you're done with them. stdout_magic_file_object.close() stderr_magic_file_object.close() logfile.close() A cleaner way would be to use context managers, shown below. It would require more refactoring though, so you may prefer manually closing the files instead. import subprocess import sys with open('out.log', 'w') as logfile: with Tee(sys.stdout, logfile) as stdout, Tee(sys.stderr, logfile) as stderr: subprocess.run(["ls", "-l"], stdout=stdout, stderr=stderr) One issue with this approach is that the child process writes to stdout immediately, and so Python's own output will often get mixed up in it. You can work around this by using Tee on a temp file and the log file, and then printing the content of the temp file (and deleting it) once the Tee context block is exited. Making a subclass of Tee that does this automatically would be straightforward, but using it would be a bit cumbersome since now you need to exit the context block (or otherwise have it run some code) to print out the output of the subprocess. Thanks a lot! I actually would like to see the output ASAP so write out immediately won't really be a problem. However, this approach seems have performance problem when the process output lots of data, it can even lock up at some extreme situation. It use a python for loop to read 1 byte per loop. I guess we have to implement something like subprocess.PIPE with some configurable buffer size (maybe just use the io.open()) and readout all bytes from the buffer every time we have the chance. @Wang I originally processed a single byte at the time to provide immediate feedback, rather than waiting until the stream ends to output data in the buffer. I added a bufsize keyword argument to Tee that can be set higher (e.g. 4096). This will result in less immediate feedback, as the last 4095 bytes won't be output until the stream ends, but the throughput should be much higher. Not sure exactly what would cause it to lock up. If you have more details then maybe I could improve the solution.
common-pile/stackexchange_filtered
MySQL query to SQL-Server I have a mysql query that I have to convert to sql server syntax, I am novice and perhaps someone can help me. Here is my code: SELECT id, nick, mobile, name, description, direction, date, image FROM mytable WHERE number=1 ORDER BY date desc LIMIT 1, 10; Is there some tool to try sql server querys or some online converter Thanks for all select top 10 ... and remove the LIMIT yes but if I want to put limit 15, 30? For SQL 2012, you have the rather unwieldy syntax: SELECT id, nick, mobile, name, description, direction, date, image FROM mytable WHERE number=1 ORDER BY date desc OFFSET 100 ROWS FETCH NEXT 5 ROWS ONLY; For SQL 2005, you generally need to adopt a 2-step approach to pagination via a derived table, e.g. SELECT * FROM ( SELECT ROW_NUMBER() OVER(ORDER BY date desc) As RowID, id, nick, mobile, name, description, direction, date, image FROM mytable WHERE number=1 ) As RowResults WHERE RowID BETWEEN 101 AND 106; SqlFiddle here UPDATED : select * FROM ( select ROW_NUMBER() OVER (ORDER BY ID) as RowNumber , * FROM mytable ) tmp where tmp.RowNumber between 15 AND 30 Yes but if I want to put limit 15, 30 in order to 1,10 to only show from 15 to 30? thanks I'll Update the answer
common-pile/stackexchange_filtered
use of collections to group nested form records - accessing proper index Rails form helpers can call upon a a collection to be used. Class Event has_many :equipments, has_many :equipment_maintenanceitems Class Equipment has_many :maintenanceitems and, as events are created they inherit attributes of maintenanceitems (but not a relationship, i.e. they don't get updated) However, when I employ the collection as follows @event.equipments.each do |eq| eq.title @maintenance_for_eqs = @maintenanceitems.select{ |i| i.equipment_id == eq.id } @maintenance_for_eqs do |eq_maintenance| eq_maintenance.name f.fields_for :equipment_maintenanceitems, eq_maintenance do |equipment_maintenanceitem| equipment_maintenanceitem.object.id equipment_maintenanceitem.check_box :executed While the object call is returning the proper id, the check_box is being identified with the array of counters starting at '0', as if it were a new build. <input name="event[equipment_maintenanceitems_attributes][0][executed]" type="hidden" value="0" /> while equipment_maintenanceitem.object.id returns "2". As per documentation Note that #fields_for will automatically generate a hidden field to store the ID of the record. this is clearly not happening. How can the check_box reference the attributes of the proper object? Equipment is a mass noun. So its equipment in plural - not equipments. http://english.stackexchange.com/questions/70828/what-is-the-plural-of-equipment Fine. But that is not at the root of the problem. I actually put that term in so as not to confuse readers with a foreign language, but get the gist... Rails' pluralization is not always the most convenient thing. The issue is that an improper index is being accessed by fields_for I still think this is very confusing - I think for this to be understandable you should create a proper verifiable example. And state what the desired outcome is in form of a params hash. Also if the names are just figured a least be consistent maintenance_items. I'm guessing the main problem is modeling though you should most likely be doing an inderect relationship: Event has_many :equipment, has_many :maintenance_items, though: :equipment instead of duplicating it. You also seem confused about how rails handles arrays of nested records in params - it enumerates them from 0. The index is not based on the id. I can understand the perceived confusion, given the data model. I understand rails enumerates builds of nested items from 0. But what I am after is fields_for recode that are already created; thus they have to reference the child record id, not the array enumeration.
common-pile/stackexchange_filtered
drop rows with multiple conditions based on multiple column in python I have a dataset (df) as below: I want to drop rows based on condition when SKU is "abc" and packing is "1KG" & "5KG". I have tried using following code: df.drop( df[ (df['SKU'] == "abc") & (df['Packing'] == "10KG") & (df['Packing'] == "5KG") ].index, inplace=True) Getting following error while trying above code: NameError Traceback (most recent call last) <ipython-input-1-fb4743b43158> in <module> ----> 1 df.drop( df[ (df['SKU'] == "abc") & (df['Packing'] == "10KG") & (df['Packing'] == "5KG") ].index, inplace=True) NameError: name 'df' is not defined Any help on this will be greatly appreciated. Thanks. What is confusing about "NameError: name 'df' is not defined?" You never defined the variable df. Are you sure your DataFrame is called df? Can you print df.head() to validate? Welcome to StackOverflow! The problem here is that you have not defined df. Please see how to create a [mre], and [ask]. Among other things, these tutorials will tell you not to include an image of your dataframe. Instead, copy and paste it formatted as code or, even better, see this answer on how to include a good pandas example. As the others above have mentioned, it doesn't see you have df defined. Further, the boolean AND operation in Python is and. I think & is a bitwise-AND operation. I suggest trying this: df = df.loc[~((df['SKU'] == 'abc') & (df['packing'].isin(['1KG', '5KG']))] The .loc is to help define the conditions and using ~ basically means 'NOT' those conditions.
common-pile/stackexchange_filtered
Oracle query monitoring - I have Java Code that contain oracle insert,update,etc statement , while executing java program oracle statement executed . I need to Know what is happing in oracle database. How can I achieve It..? try { sql = "SELECT DISTINCT Enquiry_PrimaryDetailsId\n" + "FROM enquiry_revisiondetails erevision\n" + "WHERE ActiveCode=1 AND Enquiry_RevisionDetailsId NOT IN (SELECT Enquiry_RevisionDetailsId FROM quotationprimary );"; proc = dao.prepareCall(sql); System.out.println(proc); rs = dao.executePreparedCall(proc); while (rs.next()) { Enquiryentry enquiryentry = new Enquiryentry(); enquiryentry.setEnquiry_primarydetailsid(rs.getString("Enquiry_PrimaryDetailsId")); enquirylist.add(enquiryentry); } } catch (Exception e) { e.printStackTrace(); } finally { dao.releaseAll(); } This my Java Coding , I have to know the statement which is runs on oracle. What do you mean .. "what is happening"? A lot of things happen in the database, what do you want to look for? What do you want to understand? Actually I am looking query is currently executing on database (ORACLE) .The query is sent through Java (JDBC) .
common-pile/stackexchange_filtered
Is it possible for a genin to become a jonin? In Naruto, by the end of Shippuden (ignoring the epilogue), neither Naruto nor Sasuke had ever passed the chunin exams. Given that the chunin exams seem to be held sporadically (two years between the ones in Naruto Part 1 and the ones being shown in the anime currently), it seems possible that other genin would end up in this situation. Is it possible for those genin to go directly to being jonin, or do they have to wait for possibly dozens of years (depending on how sporadically the chunin exams are held) to become a chunin first? In the Road to Ninja movie, Naruto tried to get a recommendation from Iruka for promotion to Jōnin, but was refused. Iruka said that Naruto had to become a Chūnin before he could become a Jōnin. Iruka: so, what did you want to talk about? Naruto: Um, Iruka-sensei, uh, listen, you think you can submit a Jonin application for me? Iruka: What? Naruto: It's just that all of my other classmates are going to have their parents fill out applications for them, and, well, I, uh... Iruka: Nope, sorry. I won't. Naruto: But why not? Iruka: Because that step is supposed to come after you become a chunin. Sure you saved us from Pain, and everyone calls you the "Hero of the Hidden Leaf", but I can't give you special treatment. I mean, even your Dad worked his way up through the ranks - from Genin, to Chunin, to Jonin, to become Hokage. Then he went on to became a Hero. Naruto: hmm, to become just a face carved into a rock. Update: In the Naruto Shippuden anime, Episode 413 - Hopes Entrusted to the Future shows that it is possible for a Genin to be promoted to Jōnin under special circumstances. Lee, Tenten, and Negi did not complete the original requirements of the second Chūnin Exam. They returned with 2 "Heaven" scrolls instead of "Heaven" and "Earth" scrolls: Lee: [places two heaven scrolls on the table] Please accept these. Proctor: Two "Heaven" scrolls are not acceptable! Lee: Oh, but that's--! [slaps table] Proctor: No, no, no! Lee: I can't reveal any details, but there were extraordinary circumstances that prevented us from collecting scrolls! Please ask Lord Kazekage! Proctor: It doesn't matter what circumstances there were. No means no! Gaara later rescinded that requirement when he cancelled the Third exam after he and Fū were attacked in an attempt to steal their tailed beasts: Temari: Cancel the Third exam? Gaara: I'm sorry. I can't go into details, but this is a domestic matter within the Sand. Shikamaru: Then how do we determine who passed the Chunin Exams? Gaara: We've prepared detailed reports about each team's performance in the Second Exam. I'd like the respective villages to use them to decide whether their participants should be promoted to chunin. [later, when addressing the exam participants...] Gaara: Therefore, I deem the Third Exam unnecessary... Furthermore, I am rescinding part of the requirements for the Second Exam... For each of you standing here right now, a detailed report of your performance will be sent to your respective villages. Your Kage will make the final decision on your promotion. Based on that report, Lady Tsunade "double-promotes" Negi to Jōnin: Tsunade: I've gone over your Second Exam reports. And... Hinata, Shino, Kiba, Choji, Ino, and Sakura... You six passed with flying colors and are promoted to chunin! [cheers] ... Tsunade: [looking at Tenten, Negi, and Lee] Finally, although they did not collect two scrolls, they performed admirably... and are more than qualified for promotion. Lee and Tenten, you are now chunin. Lee: Lady Tsunade! Team Guy is one for all, all for one! How can Neji not be included...?! Tsunade: Just let me finish! Neji Hyuga is given a special double promotion to jonin! The Kazekage himself noted, "In particular, Neji's performance was most impressive and due consideration has been given in this report." He's already proven himself to be more than capable as a chunin. First of all, it's not exactly known how a Chunin becomes Jonin. From Jonin article on Naruto wiki: The villagers may send their recommendations for a jōnin appointment. The Kage reads said recommendations and may consider appointing an individual a jōnin if his or her qualities are recognised as adequate by enough people and himself. and However, there was mention of a Jōnin Exam in the anime's Kurama Clan Arc. But we don't know what the requirements for this exam are. It also seems that the article/series doesn't mention anything about the general requirements for becoming a Jonin. From the Jonin article, it is safe to assume that becoming a Jonin is matter of experience, reputation and most importantly, skill. So, is it possible for a Genin to become Jonin? Yes. Provided: They are highly talented. They are respected and well-known in his/her village. They have high level of experience. They have unique skill set. But whether to become a Jonin also depends on personal beliefs of the person. As we can see from the Genin article: Kosuke Maruboshi, who is called the Eternal Genin (万年下忍, Mannen Genin) has the skills of a jōnin-level shinobi, but is officially a genin — a rank he had consciously decided to remain at, due to personal reasons. He shares the epithet with Might Duy, who in his twenty years as a genin mastered the Eight Gates. After the fourth great ninja war, Kakashi gives Naruto a giant stack of books to study and say that when he finishes those book then he can become a Jonin. Yes, it is quite possible, but very unlikely. In the anime, during the arc of the second Naruto Shippuden Chunin Exams, it was revealed that Neji was directly granted the Jonin rank from Genin. However, this came under extraordinary circumstances, in which he led Tenten, Lee, Matsuri of Sunagakure, and two Genin of Takigakure to fight Hōichi of Sunagakure, who had captured Gaara and Fū, the Jinchūriki of the Seven-Tails. Neji had actually passed the Chunin Exams, but also got a good recommendation from the Kazekage Gaara for his performance, so he was also raised to a Jonin. It was possible only after the exam. @ArunA.S: Negi, Tenten, and Lee did not actually "pass" the Second exam (they did not collect the correct scrolls), but were given special consideration after Gaara cancelled the Third exam and sent a performance report about the Second exam to the villages. Yes. Rank in the shinobi world is traditionally appointed by superiors based on skill, maturity and leadership ability. Prior to Tobirama's creation of the ninja academy, novices were given to a an experienced shinobi to train and s/he decided when they were ready to start taking missions (i.e. equivalent to genin) and all further rank was earned in the field. Field promotion to chūnin, tokubetsu jōnin and even jōnin was still common during the third shinobi war. In peacetime, field promotions became harder to attain, as there were fewer opportunities for shinobi to prove themselves in combat. The villages therefore created their own evaluations/exams for genin who had ben in the field for a while to assess whether they were ready for promotion. Some time after the third great shinobi war, the joint chūnin exams were instituted to promote inter-village cooperation as well as to provide a spectacle to entertain the lords, attract customers and showcase the skills of the young ninja. By the opening of the Naruto manga, most genin only attain chūnin rank through the semi-annual joint chūnin exams. Field promotion to chūnin is rare, though theoretically possible. In contrast, promotion to tokubetsu jōnin and jōnin was still by appointment rather than examination (although the Kurama filler arc mentions a jōnin exam, this is not reflected in the manga canon) and can theoretically be given to any shinobi, even genin. From what we see in the manga, promotion from genin straight to jōnin rarely happens in reality, though. It isn't completely impossible, however, as there is mention of independent ninja and small clans joining a village and their ninja being assigned various ranks based on their skills and/or reputations. In theory, the whole 4th shinobi war should have lead to many field promotions, but this didn't seem to happen, looking at the vrious flashbacks and stuff in Boruto, so yeah ... yes, this was the case with shikamaru, who was promoted immediately to jonin after his fight against temari, even though he forfeited the fight because he ran out of chakra. Hi, it'd be better if you could also provide the chapter/episode number as a reference, thanks! Nope. He was only promoted to chunin at that time. Reread the chappie (115 or 116 not sure)
common-pile/stackexchange_filtered
Refresh to display content from Firebase + Angular 4 I created a web app in angular 4 with data read from firebase (via angular fire 2), but on the pages where firebase data is displayed, I have to refresh the page once or twice before the data displays. This is not new data, its existing data. Also when I am writing data to firebase I have run the function twice from the front end before it actually writes anything. What could be the problem? Controller import { Component, OnInit } from '@angular/core' //import api service import { FreeAgentApiService } from '../free-agent-api.service' //import list item object import { ListItem } from './listitem' //import search componenet import { SearchComponent } from '../search.component' //import router import { Router, ActivatedRoute, ParamMap } from '@angular/router' //import animations import { moveIn, fallIn, moveInLeft } from '../router.animations' @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.css'], animations: [moveIn(), fallIn(), moveInLeft()], //host: {'[@moveIn]': ''} }) export class DashboardComponent implements OnInit { //user name name: any //state state: string = '' //search string search: String; //declare filter filterOptions = ["Status: Active", "Status: Completed", "Status: Cancelled", "Status: Hidden"] filter = "Status: Active" //projects array projects = []; //inject api service and router into component constructor(private freeAgentApi: FreeAgentApiService, private router: Router){ this.freeAgentApi.afAuth.authState.subscribe( auth => { if(auth){ this.name = auth } }) } ngOnInit(){ //init projects array on page load this.projects = this.freeAgentApi.getAllProjects() //console.log(this.projects) } //function to go to project openProject(projectName, projectUrl, projectEndDate, clientName){ //router with parameters this.router.navigate(['project'], { queryParams: { projectName: projectName, projectUrl: projectUrl, projectEndDate: projectEndDate, clientName} }) } } View <!-- header section --> <div class="header"> <div class="headerItem"> <img class="logo" alt="logo" src="../../assets/images/now-boarding-logo.svg"/> </div> <div class="headerItem"> <my-search (onSearchChange)="search = $event"></my-search> </div> <div class="headerItem"> <a class="navTop">projects</a> <a class="navTop">reporting</a> </div> </div> <!-- main section --> <div class="main" > <select class="statusfilter" [(ngModel)] = "filter"> <option *ngFor="let f of filterOptions">{{f}}</option> </select> <div class="listentry" *ngFor="let p of projects | statusFilter: filter | searchPipe:'projectName':search" (click) = "openProject(p.projectName,p.projectUrl,p.endsOn, p.clientName)"> <div class="listentryitem"> <div class="userNameCircle">ML</div> <p class="project-title">{{p.projectName}}</p> </div> <div class="listentryitem-2"> <p class="note-grey">{{ p.clientName }} </p> </div> <div class="listentryitem-3"> <input class="dateListItem field" type="text" value="{{p.endsOn | date: 'EEE d MMM'}}" disabled="true"/> <input class="budgetTimeInput" name="budgetTime" type="text" value="{{p.taskBudgetTime}}" disabled="true"> <progress class="budgetProgressBar" value="{{p.totalTimeLogged}}" max="{{p.taskBudgetTime}}"> {{ p.taskBudgetTime - p.totalTimeLogged }} </progress> </div> </div> </div> Provider for api calls import { Injectable } from '@angular/core'; //import http modules import { Http, Headers, Response, RequestOptions } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/catch'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/toPromise'; import 'rxjs/add/operator/mergeMap'; //import firebase modules import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database'; import { AngularFireAuth } from 'angularfire2/auth' import * as firebase from 'firebase/app' //import list item component import { ListItem } from './dashboard/listitem' //import project item object import { ProjectItem } from './project/projectItem' @Injectable() export class FreeAgentApiService { //inject Http constructor(private http: Http, public afAuth: AngularFireAuth, public af: AngularFireDatabase) { } //function to populate authorization header createAuthorizationHeader(headers: Headers) { headers.append('Authorization', 'Bearer 19wUDe8bnIsfuLsa1MhJfblztRj4WIZYCpnc_NQGG'); } //project item //project = new ProjectItem() //array to store projects //projects = [] //declare array to store tasks //tasks = [] //decalare array of expenses //expenses = []; //declare total tracked time * hourly rate //totalTracked = 0 //function to get all projects getAllProjects(): ListItem[]{ let projects = [] //declare headers let headers = new Headers(); //add headers this.createAuthorizationHeader(headers); //make api call and return promise array this.http.get('https://api.freeagent.com/v2/projects?sort=-updated_at&per_page=100', { headers: headers }) .map((result: Response) => { //iterate projects list result.json().projects.forEach(element => { //varaible to hold single project let project = new ListItem(); //assign values to list item object, named 'project' here project.projectName = element.name; project.status = element.status; project.endsOn = element.ends_on; project.clientUrl = element.contact; //use string to get client name project.projectUrl = element.url; //use string to get timeslipt //add current project to projects array projects.push(project); }) }) //get contacts .flatMap(() => this.http.get('https://api.freeagent.com/v2/contacts', {headers: headers}) ) .map((res: Response) => res.json() ) .subscribe( (res) => { //iterate projects array projects.forEach((project,index) => { //iterate contacts array res.contacts.forEach(r => { //match contact id with project if(project.clientUrl == r.url){ //assign client name to organisation name project.clientName = r.organisation_name } }) }) }) //get timeslips /*this.http.get('https://api.freeagent.com/v2/timeslips', {headers: headers }) .map( (res: Response) => res.json()) .subscribe((res) => { //iterate projects array projects.forEach(element => { element.timeLogged = 0 //iterate timeslips res.timeslips.forEach(element2 => { //check if project url matches if(element2.project == element.projectUrl){ //assign remaining time slip (increment) element.timeLogged += parseFloat(element2.hours) } }) }) })*/ this.getFromFirebase(projects) return projects } //function to save projects to firebase getFromFirebase(projects: any[]){ //get firebase list let storedProjects = this.af.list('/projects/') .subscribe((res) => { //console.log(res) //check if results array contains values if(res.length != 0){ //iterate firebaselist projects.forEach(p => { //iterate projects arrays res.forEach( r => { //check if project is stored in firebase if(r.projectUrl == p.projectUrl){ //assign time logged if(r.taskBudgetTime != undefined && r.taskBudgetTime != null) { p.taskBudgetTime = r.taskBudgetTime } if(r.totalTimeLogged != undefined && r.totalTimeLogged != null){ p.totalTimeLogged = r.totalTimeLogged } } }) }) } }) return projects; } //function to sync firebase object with local object loadProjectToFromFireBase(project){ //specify key, key is last four characters of url let key = project.projectUrl.substring(project.projectUrl.length - 4) //get firebase object, user project url as query parameter let currentProject = this.af.list('projects/', { query: { orderByChild: 'projectUrl', equalTo: project.projectUrl, limitToFirst: 1, } }) .subscribe((res) => { //check if any fields are undefined and assign value for(let field in project){ if(typeof project[field] == 'undefined'){ console.log(field + " -> " + project[field]) if(field == 'clientName'){ project[field] = 'n/a' } else { project[field] = '' } } } console.log(project) //if no results are returned, write object to firebase if (res.length == 0){ //write project object to firebase let ref = this.af.list(`projects/`) .update(key,project) } else { project.taskBudgetTime = 0 //get expenses from firebase //iterate expenses array project.expenses.forEach(expense => { //init expense expense.expenseBudget = 0 //iterate expenses array res[0].expenses.forEach(ex => { if(expense.url == ex.url){ expense.expenseBudget = ex.expenseBudget } }) }) //get tasks from firebase //iterate project tasks array project.tasks.forEach(task => { //iterate results array and match task res[0].tasks.forEach(r => { //check if task exists if(task.url == r.url){ //load task budget in time if(r.budgetTime != undefined && r.budgetTime != null){ task.budgetTime = r.budgetTime } } }) //incement billing rate * task budget time project.totalRateBudgetTime += Math.round(task.billing_rate * task.budgetTime) //incement total task budget time project.taskBudgetTime += Math.round(task.budgetTime) } )} }) } //function to get tasks getTasks(projectUrl: string){ let project = new ProjectItem() //declare headers let headers = new Headers() //add headers this.createAuthorizationHeader(headers) //get tasks from project this.http.get('https://api.freeagent.com/v2/tasks?project=' + projectUrl, {headers: headers }) .map((res: Response) => { res.json().tasks.forEach(t => { //map to local variable if(t.is_billable){ let task task = t project.tasks.push(task) } }) }) .flatMap( () => this.http.get('https://api.freeagent.com/v2/timeslips?project=' + projectUrl, {headers: headers })) .map((res: Response) => res.json()) .subscribe((res) => { //init task budget time project.taskBudgetTime = 0 //init total budget rate * total budget time project.totalRateBudgetTime = 0 //iterate tasks array project.tasks.forEach((task, index) => { //add time logged field task.timeLogged = 0 //load budget time from firebase or init to zero if not exists task.budgetTime = 0 //iterate timeslips res.timeslips.forEach(timeslip => { //check if task url mathes if(task.url == timeslip.task){ //increment time logged task.timeLogged += parseFloat(timeslip.hours) } }) //increment total tracked time * task billing rate project.totalTracked += Math.round(task.timeLogged * task.billing_rate) //increment total time logged for all tasks project.totalTimeLogged += Math.round(task.timeLogged) }) }) //console.log(project) return project } //function to get bills (not expenses) getExpenses(projectUrl: string){ //declare headers let headers = new Headers(); //add headers this.createAuthorizationHeader(headers) //get expenses from project return this.http.get('https://api.freeagent.com/v2/bills?project=' + projectUrl, {headers: headers }) .map((res) => res.json()) } //function to get invoices getInvoices(projectUrl: string){ //declare total invoices let invoiceTotal = 0; //declare headers let headers = new Headers(); //add headers this.createAuthorizationHeader(headers) //get invoices from project return this.http.get('https://api.freeagent.com/v2/invoices?project=' + projectUrl, {headers: headers }) .map((res) => res.json()) } //funtion to get estimates getEstimates(projectUrl: string){ //declare headers let headers = new Headers() //add headers this.createAuthorizationHeader(headers) //get approved estimates return this.http.get('https://api.freeagent.com/v2/estimates?project=' + projectUrl, {headers: headers}) .map((res) => res.json()) } //function to extract promise data private extractData(res: Response) { let body = res.json(); return body; } //function to handle promise errors private handleErrorPromise (error: Response | any) { console.error(error.message || error); return Promise.reject(error.message || error); } } When asking a question about a problem caused by your code, you will get much better answers if you provide code people can use to reproduce the problem. That code should be… Minimal – Use as little code as possible that still produces the same problem. The more code there is to go through, the less likely people can find your problem. See How to create a Minimal, Complete, and Verifiable example. The problem is you are expection an async resource to be synchronous. Basicallt this is what is happening: getAllProject(){ let projects = []; doAsyncStuffThatTakes30Seconds.subscribe(result => projects = result) return projects; } At the point where you return you projects, the async stuff hasn't completed. That's is why you are not seeing data. That probably makes you wonder why you do see data sometimes. That is because firebase caches the result until it has changed. So the async stuff is completed before the processing. The solution would be to return an observable and do all the processing in the stream. Now you can subscribe in your component to get the data. I understand what you are saying but I have no clue how to structure the code. There is an http request getting info from the 'free agent api', I have to first return that info before making a call to firebase because the firebase info to be loaded is linked to that. How would I achieve that in an observable?? You can use switchMapfor that. Eg: http.get('someUrl1).switchMap(someValue => http.get(someValue))
common-pile/stackexchange_filtered
Copy Activity with stored procedure rounds up decimals I am using an Azure Data Factory to get data from an on prem database to an Azure sql database. I am doing it in 2 steps: Copy to blob Insert into azure using a copy activity that runs a stored procedure. The problem i have is the decimal is rounded up and the destination values are different than source. For the entire process i have defined 3 datasets: SQLDataset - the structure node is {... "name" : "MyColumn", "type":"Decimal"}. BlobDataset - the structure node is the same as above AzureSQLDataset - the structure node is the same On the SQL database, i have a user defined table type as follows: CREATE TYPE dbo.myType TABLE (...MyColumn decimal(28,10) null) The stored procedure does an insert or an update and no data transformation. However, when i query for MyColumn value, the values end up being rounded up. If source had a value of<PHONE_NUMBER>94.019990000 , target has a value of<PHONE_NUMBER>94.0200000000 Am i missing something ? I have investigated this with Microsoft support and we have identified it as a bug. There are issues when converting decimals with high precision and loads of numbers. If you want to a precise numeric value, your best bet is to ship the numeric value out as a string.
common-pile/stackexchange_filtered
Writing an object to the file What I am trying to do is writing a HashMap to a file. The code below correctly when run at once. However when i try to run just writing the object to the file and try to just run reading the written object to file individually it throws the following exception. import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.HashMap; public class FileIo { String fileName; FileOutputStream fos; FileInputStream fis; ObjectOutputStream oos; ObjectInputStream ois; public FileIo(String fileName) { this.fileName = fileName; File file = new File(fileName); try { if (!file.exists()) { file.createNewFile(); System.out.println("created"); } fos = new FileOutputStream(fileName); fis = new FileInputStream(fileName); oos = new ObjectOutputStream(fos); ois = new ObjectInputStream(fis); } catch (IOException e) { e.printStackTrace(); } } public void writeToFile(Object obj) { try { oos.writeObject(obj); oos.flush(); oos.close(); } catch (IOException e) { e.printStackTrace(); } } public Object readFromFile() { try { return ois.readObject(); } catch (ClassNotFoundException | IOException e) { e.printStackTrace(); } return null; } @SuppressWarnings("unchecked") public static void main(String args[]) { HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>(); FileIo fi = new FileIo("tex.txt"); //Only write to the file ArrayList<String> a = new ArrayList<>(); a.add("test"); map.put("testput", a); fi.writeToFile(map); //Only write to the file try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } //Only read from the file map = null; map = (HashMap<String, ArrayList<String>>) fi.readFromFile(); System.out.println(map.toString()); } } //Exception java.io.EOFException at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2608) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1319) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:371) at FileIo.readFromFile(FileIo.java:49) at FileIo.main(FileIo.java:73) The only thing happening different is instead of directly writing and instantaneously reading it. I first write the object program finishes then run the program runs to read the object. You need to create the FileInputStream after the data has been written to the file. You can't create it before and assume it will show subsequently written data. add that as an answer @AndyTurner :D @AndyTurner the code works fine when I run it as it is. But when I slightly modify the code such that at any given time I am either writing to the file or reading from it. So in what I tried doing was first run the program to only write to the file and then re-run the program to read from it, throws the above exception. So in that case FileInputStream would always be created after the data has been written to the file. are you commenting stuff out every time you read/write? because your main keeps modifying the content. try andy's solution, moving your filestream/objectstream constructors into just the read/write methods instead of creating them in the constructor. The exists/createNewFile block is a complete waste of time and space. new FileOutputStream already creates a new file, and deletes it if it exists, or rather the OS does that when the FileOutputStream is constructed. You're just tripling the work required. @JohnGardner Thank you it seems to work. But I don't understand why would it throw an exception in the previous case. Thank you for help though. @EJP thank you for informing me!!! You need to create the FileInputStream after the data has been written to the file. You can't create it before and assume it will show subsequently written data. the general problem here is that you should create your streams and read from them at the last possible instant. so instead of creating them in the constructor, you should create them when you actually need to write/read from them. (that way you also don't waste opening them if nobody writes or reads, like if you were to write once but read many times)
common-pile/stackexchange_filtered
How to render the data after the API Call? (Vue.js) So the following template is rendered immediately, and it does not wait for the API call. The solution I found is using v-if in order to keep the elements from rendering until the data is there. This seems counterintuitive to the DRY principle if I have to wrap my elements with v-if. Is there another approach to this problem? Another way of coding this? <template> <div id="app"> <div v-if="obj"> <h2>{{ obj[0].item }}</h2> </div> <div v-if="obj"> <h5>{{ obj[0].id }}</h5> </div> </div> </template> <script> export default { name: 'app', data() { return { obj: [] } }, mounted: function() { axios.get(URL) .then(response => this.obj = response }); } } </script> Yes there is if you are using Vue Router - https://router.vuejs.org/en/advanced/data-fetching.html So data would be fetched immiteately after the route is activated by watching the $route object Check my similar answer here Check permissions before vue.js route loads
common-pile/stackexchange_filtered
Can $\mathbb{R}$ be written as an ascending union of proper additive subgroups? Can the group $\mathbb{R}$ be written as countable ascending union of proper subgroups? (i.e. does there exists a series of proper subgroups $H_1\leq H_2\leq \cdots $ such that $\cup {H_i}=\mathbb{R}$?) You want this to be a countable union, presumably? @Sammy: We expect countable union. Otherwise, as $\mathbb{R}$ is ordered set, we can certainly find a chain of subgroups, ordered according to the order in $\mathbb{R}$, with union equal to $\mathbb{R}$. (Thanks for suggestion; I have edited question) Nice problem.${}$ It may help to realize that every proper subgroup of $;\Bbb R;$ is either cyclic or dense (wrt the usual Euclidean topology)...It can't be an ascending union of cyclic ones because of Baire's Theorem, and I doubt it is a union of the second kind, or a mix of both...nice little bastard problem! +1 I wonder whether the OP's nick comes from Marshall (Hall) and (Aleksander Gennadievich) Kurosh, two monsters of group theory from the last century... @DonAntonio: yes! And the problem I was raised myself, while reading the first volume of Kurosh on group theory. Is $\mathbb R$ a countable ascending union of proper subfields? Does this work: let $S$ be a maximal set of algebraically independent (over $\mathbb Q$) transcendental real numbers; let $S=\bigcup_{n\in\mathbb N}S_n$ be a partition of $S$ into nonempty sets $S_n$; let $F_n$ be the algebraic closure of $S_1\cup\dots\cup S_n$? The real numbers $\mathbb{R}$ is a vector space over $\mathbb{Q}$. By axiom of choice there is a basis $B$. Let $S_i$ be the set of all rational numbers $a/b$ where the prime factors of $b$ are among the $i$ first primes. The set of real numbers with coordinates (for the basis $B$) from $S_i$ is a subgroup $G_i$. It is clear from the definition that $G_i\subset G_{i+1}$. Now $B$ is a basis and hence for every real number there is some $G_i$ containing it. Or am I misunderstanding the question? Neato. ${}{}{}$ Wouldn't it be simpler to partition the basis $B$ into a countable infinity of disjoint nonempty sets $B_n(n\in\mathbb N)$ and define $G_n$ to be the vector space over $\mathbb Q$ spanned by $B_1\cup\dots\cup B_n$? Yes you are right! The constructions in the other answers use the axiom of choice, and this can't be avoided. The subgroups in question have to be pathological. It is impossible to construct such a series of subgroups, all of which have the Baire property. By the Baire category theorem, one of them $G_n$ would have to be nonmeager. A result due to Pettis says that for any nonmeager set $A \subset \mathbb{R}$ (or any Polish group) which has the Baire property, $A - A$ contains an open neighborhood of 0. So $G_n = G_n - G_n$ contains an open neighborhood of 0; hence it must equal $\mathbb{R}$. It is consistent with the axiom of dependent choice that every subset of $\mathbb{R}$ has the Baire property (Shelah's model). It is impossible to construct such a series of subgroups, all of which are Lebesgue measurable. By countable additivity, one of them $G_n$ would have to have positive measure. A theorem of Steinhaus says that for any measurable set $A$ of positive Lebesgue measure, $A - A$ contains an open neighborhood of 0. So as before, we would have to have $G_n = \mathbb{R}$. It is consistent with the axiom of dependent choice, together with some large cardinal axioms, that every subset of $\mathbb{R}$ is Lebesgue measurable. (Solovay's model.) (Disclaimer: I'm parroting some set theory that I've heard about but not studied deeply. An actual expert is welcome to correct mistakes or fill gaps.) Taking a cue from the other answer, if $M$ is the $\Bbb Z$-submodule of $\Bbb R$ spanned by a $\Bbb Q$-vector space basis and $n_1, n_2,\cdots$ any increasing cofinal sequence in the naturals ordered by divisibility (for example factorials as $n_k=k!$), then we have $M\subseteq n_1^{-1}M\subseteq n_2^{-1}M\subseteq\cdots$ with union $\Bbb R$.
common-pile/stackexchange_filtered
Default argument for partial specialization [Clang yes, GCC no] Why does the following compile with clang but not with g++ 4.9 #include <array> template< typename T1, typename T2 , typename T3 = int> struct A; template<typename T, unsigned int N, typename T2, typename T3> struct A< std::array<T,N>, T2, T3 > { int a; }; int main() { A< std::array<int,10>, double> a; a.a +=3; } http://coliru.stacked-crooked.com/a/c7800f49ba5aac43 g++ does not find a suitable specialization and complains with "incomplete type". I am wondering since, the default argument typename T3 = int should apply for the specialization (or does it only apply for full specialization?) Because you're using unsigned int instead of std::size_t. With the latter, both compilers accept the program. Related: http://stackoverflow.com/q/21740896/ Could be https://llvm.org/bugs/show_bug.cgi?id=16279 The templates A<T1, T2, T3> and A<T1, T2> are not complete defined so you can't use your members, you can solve the problem defining this templates at this way: #include <array> template< typename T1, typename T2 , typename T3 = int> struct A { int a; }; template<typename T, unsigned int N, typename T2, typename T3> struct A< std::array<T,N>, T2, T3 > { int a; }; int main() { A< std::array<int,10>, double> a; a.a +=3; } Another fine example of specialization more simple: template<typename T, unsigned int N> struct A { T a = N; }; template<unsigned int N> struct A<int, N> { int a = 2*N; }; #include <iostream> using namespace std; main() { A<float, 30> af; A<int, 30> ai; cout << af.a << endl << ai.a << endl; } Like @dys say's on your comment using std::size_t instead unsigned int works: template< typename T1, typename T2 , typename T3 = int> struct A; template<typename T, std::size_t N, typename T2, typename T3> struct A< std::array<T,N>, T2, T3 > { T3 a = N; int b; }; int main() { A< std::array<int,10>, double> a; a.a +=3; A< std::array<int,10>, double, int> b; b.b +=3; } I dont think thats the answer, the asnwer should be @dyp's comment. The problem is that it matches the first prototype (which is incomplete yes) because the template matching is obviously pedantic about the used types -> template<typename T, std::size_t> std::array @dyp are really right, using std::size_t instead unsigned int works fine.
common-pile/stackexchange_filtered
How to use input() as a name for object in Python? I'm new to python and I've been trying new things. I made this class: class Student(object): def __init__(self,school,gpa,age): self.school=school; self.gpa=gpa; self.age=age; def stu_info(self): print("School: ",self.school) print("GPA:", self.gpa) print("Age:",self.age) and then I typed this code to create objects of the class. The problem is taht I wish to use the input() function to enter the name of the object. Here is the code I wrote (which does not work). School=input("What is your school's name? \n") Gpa=input("What is GPA? \n") Age=input("How old are you? \n") StudentName=input("Name: ") StudentName=Student(School,Gpa,Age) print("Saved") You can see that my problem is in these lines: Name=input("Name: ") Name=Student(School,Gpa,Age) An object with the name (StudentName) is always created and I can get the information by using StudentName.stu_info(). Do you have any ideas on how I can use the value of StudentName as a name of an object? thank you in advance Have you learned about dictionaries yet? This is basically what they're for. I have a used dictionaries before but how could I use it in here? d = {}; name = input(); d[name] = Student(School,Gpa,Age);. Then you just lookup in d. When I lookup d I get this: {'Mazen': <__main__.Student at 0x2919c75a550>} and if I use Mazen.stu_info() I get name 'Mazen' is not defined d["Mazen"].stu_info(). Don't try to create arbitrary variables. It'll make your life difficult later. Store the "variables" in a dictionary. name = input("Name: ") locals()[name] = Student(School,Gpa,Age) But don't do that. Instead use a dictionary: students = {} students[name] = Student(School,Gpa,Age) I used the first method and worked just fine for me.. why shouldn't I use it? And I reall didn't get the dictionary method.. Because it's a hack. locals is a mutable dictionary of available variable names. When you access some_variable, it's looked up from locals. You're polluting locals by putting all your students in there. Less polluting will be to use a dictionary
common-pile/stackexchange_filtered
Regarding static collision resolution between two circles I have some code that resolves the positions of two circles when they collide: float fDist = sqrtf((c2->m_pos.x - c1->m_pos.x) * (c2->m_pos.x - c1->m_pos.x) + (c2->m_pos.y - c1->m_pos.y) * (c2->m_pos.y - c1->m_pos.y)); float fOverlap = 0.5f * (fDist - c1->m_radius - c2->m_radius); c1->m_pos.x -= fOverlap * (c1->m_pos.x - c2->m_pos.x) / fDist; c1->m_pos.y -= fOverlap * (c1->m_pos.y - c2->m_pos.y) / fDist; c2->m_pos.x += fOverlap * (c1->m_pos.x - c2->m_pos.x) / fDist; c2->m_pos.y += fOverlap * (c1->m_pos.y - c2->m_pos.y) / fDist; However, I'm having the issue that, on large numbers of simulated circles, as the program "detection rate" slows down, fDist approaches (or even becomes) 0. As a result, the circles in question are blasted off into infinity, rather than "glide" apart from each other as I intend on doing. Is there an alternative method of achieving this effect? Or does my simulation simply run too slowly? For more context, I am following javidx9's tutorial on circle collisions. Are you taking delta time into account? You can set an arbitrary minimum delta time to prevent small values. Also, are you filtering your radius overlaps to see if a collision can even exist before running your sqrt? You can do the radius check without doing the sqrt. Thanks for the suggestions! I will apply and play around with these ideas
common-pile/stackexchange_filtered
Logging user activities in applications The problem I'm here to talk about and (ask about of course) is not new. I searched web and stack overflow and I got ideas to many part of this problem (pros and cons) but there is still some part missing in my mind. So I thought it would be a good idea to share in one place (of course it will be more complete with others' ideas) and ask for it. The problem is clear: "We Want to log every single action of user" - probably when we solve the big problem, smaller ones (like logging only one action would be piece of cake). First from what I read over the web and stack overflow: Use DB instead of File: That's a good advice although it always depends on situation. But because of many benefits of DB, in long term and in general, it's the better solution. DB Layer or Application Layer: Actually it depends. For example If you want really monitor everything(I mean really every single rows that changes in Database, it seems we will have one choice "Using Database Triggers". Although there are many discussions around MySQL that says, triggers slowdown DB and they advised not to use it. So it depends on the level of details you need, you can put your logging system in DB Layer or Application Layer(for exam some common function call $logClass->logThis()). Use Observers: Clean codes are always better. If you are familiar with observers, you can use them to do things for you when an action is happened so you don't have to add $logClass->logThis() every time a CRUD happens in your application. What To Log: Simple and short answer is: Based on your needs, but there are some common fields you will need: user_id (if a unique user ID is available) timestamp (unix maybe) ip (not everyone know how to fake it in first place so use it, even faking it give you some insight about user behavior) action_id (should be predefined actions for better unifying in queries and reports) object_id (the unique row ID of a record that changes had made on) action (which my question is about this part) and etc... I would appreciate if anyone correct me if I made mistake in any part or add other useful information to this post, so it would become one of good references for other users. And now my question: How to Store actions?. For better understanding, consider following scenario. I have a table named "product" and a table named "companies". From the business logic we want to assign products to companies, which we ended up in a table "company_product". Now when a user insert new product and simultaneously assign it's companies, 2 table will be affected (the same goes for delete and update): "product" and "company_product" and we want to know: what's inserted? what's deleted? what's updated to what? For performance issue and because I don't have enough knowledge about triggers, I want to use logging in Application Layer, so I ended up with this idea that I can, save action fields of database in array or json structure. But as I developed my solution I encountered a problem: How to make this log understandable for non technical users? Because for example I want to save something like this in action field of database when delete(insert) product with id 20: action : [{id: 20, product_id:2, company_id: 1},{id: 21, product_id:2, company_id: 2}] And this is not something easy for every one to read and understand. Actually I can use this json more readable and make it something like this: action : {'Product A Deleted From Company X', 'Product A Deleted From Company Y'} and save the previous action in technical_action field for further diagnose, But it needs additional works and more query to run for something that is not always needed to be considered(log) I would appreciate any additional information on this article (I'm definitely sure that there exist other criteria that can be discussed), and answer to my question. Please make comment on -1 on the post so I know what is wrong with the post or the content. thanks :) I was wondering is this subject so obvious for everyone, or we don't consider logging in our projects?? 2 days and no participation from community! You are actually going to gather details for analytics kind of stuffs. It will be good if you go for flat tables rather than going to relational tables. Because if you want to do more analysis your relational table will not be a good choice as it lacks in performance. The log table is flat, relation between example tables of product and company was relational that actually is irrelevant to discussion and considered as an example. If you mean Flat Databases like NoSQL variants, it can be discussed seperately
common-pile/stackexchange_filtered
Why do browsers treat requests in an iframe as cross-site requests as it relates to cookies, but same-site for the request itself? If a run an application containing an iframe on <IP_ADDRESS>:5500 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <script> document.addEventListener("DOMContentLoaded", () => { // This here is to demonstrate that the a request to localhost:3000 will // give a CORS error fetch("http://localhost:3000/req1").then((res) => { console.log(res); }); }) </script> <body> <h1>I am the outer application</h1> <iframe src="http://localhost:3000" width="100%" height="500px"></iframe> </body> </html> And the application at localhost:3000 makes requests to /req1, /req2 /req3, and these will return some data, as well as setting a cookie, and no cross origin headers. eg. //req1 export async function GET() { const x = NextResponse.json({ error: 'I am req 1 data' }, { status: 200 }) x.cookies.set("my-cookie-1", "hello world"); return x; } //req2 export async function GET() { const x = NextResponse.json({ error: 'I am req 2 data' }, { status: 200 }) x.cookies.set("my-cookie-2", "hello world", { "sameSite":"none", "secure": true, }); return x; } What I observe is that the iframe is able to make the requests and the data and cookies are retrieved fine. They're considered same-site requests in this sense. However, unless we add secure: true and sameSite: "none" the cookies are not attached on subsequent requests. In Chrome's devtools we see the message: The cookie didn't specifiy a "SameSite" attribute when it was sotred and was defaulted to "SameSite=Lax," and was blocked because the request was made from a different site and was not initiated by a top-level navigation. The cookie had to be set with "SameSite=None" to enable cross-site usage. Why does the cookie treat this as a cross-site request, when the request itself does not? I have a reproduction for this here: https://github.com/dwjohnston/cookies-and-iframes I wonder if this happens without localhost in the equation, since that occasionally gets special treatment. Does this also happen if you edit your hosts file to create e.g. one.test and two.test and run your applications from there? @Siguza I did test this. Unfortunately it's becomes a less trivial reproduction as you now encounter HTTPS errors. // Why does the cookie treat this as a cross-site request, when the request itself does not? These are fundamentally two different security mechanisms (Cookies same-site vs CORS same-origin) with related but different security motivations. Cookies - Same-Site In your reproduction, cookies determine a cross-site status from the context of the top level document vs the iframe document. Noting that <IP_ADDRESS>:5500 is not considered to be the same-site as localhost:3000 The spec ensures that only Same-Site: None secure cookies are set/attached in cross-site contexts which includes iframes. I assume the motivation for browsers applying it to iFrame subresources like this is some form of defence in depth (In addition to X-Frame-Options/CSP). For example, if a malicious actor was able to craft an XSS exploit via URL, the user could embed this url into an iframe as one delivery mechanism. CORS - Same-Origin In the context of CORS, same-origin status is determined from the current document origin & the origin of the resource that is being requested. In comparison to cookies, there is no special distinction around the top level document visible URL (which is why your sub-iframe requests operate as expected). What I observe is that the iframe is able to make the requests and the data and cookies are retrieved fine. They're considered same-site requests in this sense. This is because the server is not responsible for determining if something is considered same-site or not. The browser has the job of determining if the cookies should be set/not set based off the context of how the request was made. Note that this is the same as CORS, the browser is responsible for actually enforcing CORS policies. To summarise, There is no CORS in play for the sub iframe (as the API request is on the same origin as the iframe document). But there is a cross-site cookie usage (As the top level document uri is a different site to the iframe uri). Side note, if you want to limit the scope that a Same-Site: None cookie has, it's worth looking into partitioned cookies. They limit the scope to the top level site, which would have been a much saner default. Thanks - it seems like a lot of the confusion comes from my conflating cross-origin and cross-site. We should note that SameSite=None won't allow a cookie to be sent to a different origin - that's what the Domain is property for. This all boils down to cookie policy that browsers strictly implement in their core as a security and privacy measures. For example, embedding aaa.com on an iframe inside bbb.com, the requests in the iframe (aaa.com) will go to the bbb.com. however, browser's cookie policy have a cross-site rules because aaa.com is treated as an outside entity residing inside bbb.com. This prevents users from certain types of attacks like CSRF attacks where hackers sends outside requests from an already authenticated website. However, unless we add secure: true and sameSite: "none" the cookies are not attached on subsequent requests. By default, browsers block third party cookies unless explicitly the SameSite attributes are used SameSite=Lax, SameSite=Strict, and SameSite=None
common-pile/stackexchange_filtered
Opencsv How to Parse and Process Individual Row? When I parse my csv file of 20k rows using CsvToBeanBuilder my app runs out of memory. So I now want to parse each individual row into my pojo and then process them one by one. Can I do that with CsvToBeanBuilder? The Reading into beans documentation indicates CsvToBean#iterator() does what you want.
common-pile/stackexchange_filtered
reclassify vector data from multiple source data fields (ArcGIS) (ModelBuilder) I am using ArcGIS 10.1 and ModelBuilder. I am not familiar with Python. My question is very similar to ReClassify Vector Data Between Values using ArcGIS Desktop? . However that question is about reclassification using the values from one other field. I have experience of using this type of reclassification within the Calculate Value Tool. However I wish to base a reclassification on the values from more than one source data field. For example from two fields - "Land" and "WellYield". ideally I'd like to be able to run classifications from 2 or 3 source fields. I know the following code is wrong because i have not defined the "Land" field. e.g. parser: Python Expression: Reclass(!WELL_YIELD!, !Land!) Code Block: def Reclass(WellYield, Land): if (WellYield == 'Make'and Land == 'Natural'): return 'Greenspace' elif (WellYield =='Multiple' and Land == 'Natural'): return 'Not Greenspace' Any help or tips on the correct code would be much appreciated. I have just been testing some outputs by trial and error. The above code seems to work now for classifying by different data fields. I will test further by three fields. Any insights or advice would still be appreciated. You might want to and an else statement in case there are instances where land is natural but wellyield isn't make or multiple. Other than @Paul comment (+1) the code looks fine to me. In Model Builder You can use Insert -> Iterators -> Feature selection where you select "group by" fields. It works like combine function for raster data. As output you have Value that you can use as a name of the output : outputlayer_%Value%. It creates layers like : outputlayer_Make_Natural outputlayer_Multiple_Natural ...
common-pile/stackexchange_filtered
DataTables Jquery JSON I am new to DataTables/JSON and I am running into a coding issues. The issue is trying to pull data information from one set of object array into another one; if I'm not explaining this correctly, please forgive me. I can currently only pull data from the "courses" objects, but not the "schools". I need to render information from schools into courses. The plan is not to put the school names in multiple places but in one set of object arrays and pull the data that is needed depend on the id given under "courses" > "school" JSON txt file example { "courses" : [ { "course_id" : "1", "course_title" : "Mathematics", "school" : [ "1", "3" ] "cost" : "$100" }, { "course_id" : "2", "course_title" : "Science", "school" : [ "2", "3" ] "cost" : "$50" } ], "schools" : [ { "school_id" : "1", "school_name" : "School of Mathematics", "school_info" : "You will learn more about math in this school", }, { "school_id" : "2", "school_name" : "School of Social Studies", "school_info" : "You will learn more about geography and how it plays a role in science", }, { "school_id" : "3", "school_name" : "School of Science", "school_info" : "You will learn more about math and science and how it relates to one another", } ] } JQUERY - DataTables The plan is to grab the numbers that are listed under "courses" (data) > "schools" to render out the name of the schools depending on the id number given $(document).ready(function() { var table = $('#example').DataTable( { "ajax": { "url": "data/data.txt", "dataSrc" : "courses" }, "columns": [ { "className": 'details-control', "orderable": false, "data": null, "defaultContent": '' }, { "data": "course_id"}, { "data": "course_title"}, { "data": "cost" }, { "data": "school" } ], "order": [] } ); HTML <!-- DataTable Layout --> <table id="example" cellspacing="0" width="100%"> <thead> <tr> <th></th> <th>Course ID</th> <th>Course Title</th> <th>Cost</th> <th>Schools</th> </tr> </thead> </table> ADDITIONAL JQUERY Datatables dropdowns based off Datatable child rows My additional task is to render the schools information on the dropdown verses the columns. So, when the user clicks on the course they can click the dropdown to get additional information about the school. Currently, the format (d) is only reading the first object courses, however, I want it to read both main objects such as courses and schools and render the school information depending on the ids. (Similar to how Tim Harker answered just within the dropdowns this time) /* Formatting function for row details - modify as you need */ function format ( d) { // `d` is the original data object for the row return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+ '<tr>'+ '<td>Course Title:</td>'+ '<td>'+d.course+'</td>'+ '</tr>'+ '<tr>'+ '<td>School:</td>'+ '<td>'+d.schools+'</td>'+ '</tr>'+ '</table>'; } // Add event listener for opening and closing details $('#example tbody').on('click', 'td.details-control', function () { var tr = $(this).closest('tr'); var row = table.row( tr ); if ( row.child.isShown() ) { // This row is already open - close it row.child.hide(); tr.removeClass('shown'); } else { // Open this row row.child( format(row.data() )).show(); tr.addClass('shown'); } } ); This should get your fairly close: $(document).ready(function() { var source = { "courses": [{ "course_id": "1", "course_title": "Mathematics", "school": [ "1", "3" ], "cost": "$100" }, { "course_id": "2", "course_title": "Science", "school": [ "2", "3" ], "cost": "$50" } ], "schools": [{ "school_id": "1", "school_name": "School of Mathematics", "school_info": "You will learn more about math in this school" }, { "school_id": "2", "school_name": "School of Social Studies", "school_info": "You will learn more about geography and how it plays a role in science" }, { "school_id": "3", "school_name": "School of Science", "school_info": "You will learn more about math and science and how it relates to one another" } ] }; var table = $('#example').DataTable({ "data": source.courses, "columns": [{"data": "course_id"}, {"data": "course_title"}, {"data": "cost"},              {                 "data": "school",  render: function(data, type, row) {  var schools = ''; $.each(data, function(index, value) { schools += ', ' + source.schools[value - 1].school_name; }); return schools.substring(2);                 }            } ], "order": [] }); }) <link href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css " rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js "></script> <table id="example" cellspacing="0" width="100%"> <thead> <tr> <th>Course ID</th> <th>Course Title</th> <th>Cost</th> <th>Schools</th> </tr> </thead> </table> UPDATE: Courses that belong to school... $(document).ready(function() { var source = { "courses": [{ "course_id": "1", "course_title": "Mathematics", "school": [ "1", "3" ], "cost": "$100" }, { "course_id": "2", "course_title": "Science", "school": [ "2", "3" ], "cost": "$50" } ], "schools": [{ "school_id": "1", "school_name": "School of Mathematics", "school_info": "You will learn more about math in this school" }, { "school_id": "2", "school_name": "School of Social Studies", "school_info": "You will learn more about geography and how it plays a role in science" }, { "school_id": "3", "school_name": "School of Science", "school_info": "You will learn more about math and science and how it relates to one another" } ] }; var table = $('#example').DataTable({ "data": source.schools, "columns": [ {"data": "school_id"}, {"data": "school_name"}, {"data": "school_info"},              {                 "data": "courses",  render: function(data, type, row) {  var courses = ''; $.each(source.courses, function(index, course) { if (course.school.indexOf(row.school_id) > -1) courses += ', ' + course.course_title; }); return courses.substring(2);           }            } ], "order": [] }); }) <link href="https://cdn.datatables.net/1.10.13/css/jquery.dataTables.min.css " rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdn.datatables.net/1.10.13/js/jquery.dataTables.min.js "></script> <table id="example" cellspacing="0" width="100%"> <thead> <tr> <th>School ID</th> <th>School Name</th> <th>School Info</th> <th>Courses</th> </tr> </thead> </table> Let me know if you have any further questions, happy to help more. Nice! That definitely helps me get to the right direction. I have a question are we able to make var source contain the ajax call to the script verses adding it in on the same page? I figured it out. I appreciate your assistants! What I did was add $.getJSON(url, function(data)) and included my datatable script inside with the function variable data having a var source = data . I had to do it that way because it was giving me a null or undefined otherwise. Thanks I do have another question. I am actually using this type of DataTables: [https://www.datatables.net/examples/api/row_details.html] and I noticed my dropdowns aren't working, I will try to fix that issue. But the real question is if I wanted to add the school names on the dropdown section how would I go about doing it that way? Also, if there is a better way to include the JSON txt data verses doing it the way I solved it, feel free to share :) Thanks! Fixed the dropdown issue. I just added the needed javascript into the getJSON as well :) @TimHarker now I am working on the schools into the drop down. Thanks again. Keep going, sounds like you are working through it nicely. I'll keep my eye out for another question should you have it... just include tag 'datatables' if/when you create another. Keep up the good work! I have another question: Based off the info above. Say if I was to create another page to list the schools, but this time I want to list the courses that belong to that school on one column. How would I loop through the JSON? I updated my answer above. If you find it useful, feel free to up-vote by clicking the up-arrow :-). Let me know if you have anything else. Happy to help again. Thanks once again Tim! You are awesome! You save the day. I was so stumped on this. :D I want to upvote but to low on rep. xD No worries, mate. Glad I could help. Keep posting as things come up...
common-pile/stackexchange_filtered
libc include guards not respecting source type parameter changes Question If I include time.h, change a "source type parameter" and re-include that header, shouldn't it add in those new definitions? I understand that this is happening due to include guards. My question is: is this a bug in libc? Shouldn't it be able to handle this? #include <time.h> #define _XOPEN_SOURCE 600 #include <time.h> static struct timespec t; Error message: example.c:5:24: error: storage size of ‘t’ isn’t known 5 | static struct timespec t; | ^ Background I discovered this behavior building a Python extension while compiling with -std=c99. If I included standard libraries before I included Python.h I would get compilation errors due to missing definitions of POSIX functionality. If I moved the Python.h include before everything else, all was fine. Of course compiling with -std=gnu99 works as well. But I wanted to get to the bottom of why the error was occurring and distilled it down to the above code sample. Which begs another question. If the above behavior isn't a bug, is setting _XOPEN_SOURCE and similar source type parameters in a header considered bad practice? Should Python remove the setting of that parameter in their headers and instead require users to define it during compilation, or use std=gnu99? "If I include time.h, change a "source type parameter" and re-include that header, shouldn't it add in those new definitions?" No, quite the contrary, actually. The guards are there so that you don't declare something a second time. So the "old" definitions are the ones that stay, they don't get overwritten. What you're calling "source type parameters" are called feature test macros, and they are specifically required to be defined before inclusion of any standard header if they are defined at all. This is specified in XSH 2.2.1 POSIX.1 Symbols: A POSIX-conforming application shall ensure that the feature test macro _POSIX_C_SOURCE is defined before inclusion of any header. ... An XSI-conforming application shall ensure that the feature test macro _XOPEN_SOURCE is defined with the value 700 before inclusion of any header. The Linux man page for feature-test-macros also clearly states this requirement for the standard ones and its extensions: NOTE: In order to be effective, a feature test macro must be defined before including any header files You cannot redefine and reinclude headers to change things, and in fact defining or undefining/redefining them between headers (even different, seemingly unrelated headers) may completely break things. So this means that it is likely Python documentation lacking. They should state that Python depends upon POSIX standards and extension modules should be compiled with -std=gnu99 or -D_XOPEN_SOURCE. I don't think this is a matter of Python documentation. If you want to compile with -std=c99 but want POSIX or further functionality, you need to use FTMs to get it. This is documented in GCC I think. The preferred way is adding the proper -D wherever you added -std=c99 (in CFLAGS), not editing sources. Then you ensure it's defined before any header is included. It is a matter of documentation. I am not using POSIX, Python is, and it assumes it is there. Because there was no documentation stating otherwise, I thought using C99 and reordering includes was acceptable, it is not. I see. Then yes, Python should document that you need to compile module sources using the Python headers/interfaces with appropriate FTMs to make POSIX baseline (or XSI, or whatever) functionality available and mention that they need to be defined at top of files or via -D.
common-pile/stackexchange_filtered
Transcendental proofs vs. Irrational proofs Why are proofs of the transcendence of certain numbers usually harder than irrationality proofs of those same numbers (for example, Lindemann's proof of the transcendence of pi vs. Niven's proof of the irrationality of pi?) Maybe because transcendence is a more complex concept than irrationality? Proving a number irrational only involves showing that the assumption that the number is rational leads to a contradiction. In other words, the number cannot be the root of a linear equation with integer coefficients. To prove that a number is transcendental, you must show that the assumption that the number is a root of $any$ polynomial of $any$ degree with integer coefficients leads to a contradiction. This is far more difficult. This is why the Greeks were able to show that $\sqrt{2}$ is irrational (this can be done using only geometry, not algebra), while it took until 1844 for the existence of transcendental numbers to be proved by Liouville. Hermite proved $e$ was transcendental in 1873, Cantor proved that almost all numbers are transcendental (by showing that the algebraic numbers formed a countable set), Lindeman proved that $\pi$ was transcendental in 1882, and so on. Other names worthy of study are Weierstrass, Hilbert, Gelfond, Schneider, and Baker. Is the proof for transcendence far more difficult because, without a proof, there could potentially be a polynomial with integer coefficients that had as a root, the number in question (such as pi or e)? So it would be harder to prove that for ALL integer-coefficient polynomials, none of then had a root corresponding to the number in question?
common-pile/stackexchange_filtered
Fmdb Select query with variable table name I want to get results from different tables, tables are selected by the user. So, I am using table name as variable but it returns nil query. FMResultSet *query = [db1 executeQuery:@"SELECT Image, Explanation FROM %@ WHERE Image !='empty'" "UNION SELECT Image, Explanation FROM %@ WHERE Image !='empty'" "UNION SELECT Image, Explanation FROM %@ WHERE Image !='empty'" "UNION SELECT Image, Explanation FROM %@ WHERE Image !='empty'" "UNION SELECT Image, Explanation FROM %@ WHERE Image !='empty'" "UNION SELECT Image, Explanation FROM %@ WHERE Image !='empty'", [NSString stringWithFormat:@"%@1",tableName], [NSString stringWithFormat:@"%@2",tableName], [NSString stringWithFormat:@"%@3",tableName], [NSString stringWithFormat:@"%@4",tableName], [NSString stringWithFormat:@"%@5",tableName], [NSString stringWithFormat:@"%@6",tableName]]; If I hardcode the table name it returns the data. FMResultSet *query = [db1 executeQuery: @"SELECT Image, Explanation FROM Class1 WHERE Image !='empty'" "UNION SELECT Image, Explanation FROM Class2 WHERE Image !='empty'" "UNION SELECT Image, Explanation FROM Class3 WHERE Image !='empty'" "UNION SELECT Image, Explanation FROM Class4 WHERE Image !='empty'" "UNION SELECT Image, Explanation FROM Class5 WHERE Image !='empty'" "UNION SELECT Image, Explanation FROM Class6 WHERE Image !='empty'"]; I logged the tableName value and it is returning the correct value, which is "Class". Please help me solving this issue and also suggest the best query for this purpose. Use this Code : FMResultSet *query = [db1 executeQuery:[NSString stringWithFormat:@"SELECT Image, Explanation FROM %@ WHERE Image !='empty'" "UNION SELECT Image, Explanation FROM %@ WHERE Image !='empty'" "UNION SELECT Image, Explanation FROM %@ WHERE Image !='empty'" "UNION SELECT Image, Explanation FROM %@ WHERE Image !='empty'" "UNION SELECT Image, Explanation FROM %@ WHERE Image !='empty'" "UNION SELECT Image, Explanation FROM %@ WHERE Image !='empty'", [NSString stringWithFormat:@"%@1",tableName], [NSString stringWithFormat:@"%@2",tableName], [NSString stringWithFormat:@"%@3",tableName], [NSString stringWithFormat:@"%@4",tableName], [NSString stringWithFormat:@"%@5",tableName], [NSString stringWithFormat:@"%@6",tableName]]]; Thanks @Vin. Is this a correct/optimized query for this purpose?
common-pile/stackexchange_filtered
Android how to make ok button on dialog not all caps For an alert dialog in Android, how do you make the positive button not have all capital letters. The text is "OK" instead of "Ok". What kind of dialog are you using? Please show your code if you want a proper answer. @Pheonixblade9 Um... I said alert dialog if you read the question? Yes, that is why I'm confused. You set the text yourself. There are no default options. this is a working solution : http://stackoverflow.com/questions/27893840/lollipop-capitalizes-buttons-text-in-my-app/39143743#39143743 You can set it to be anything you want - Eg.: AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this); builder.setTitle("Title"); builder.setMessage("message"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { return; } }); AlertDialog dialog = builder.create(); dialog.show(); Reference: http://developer.android.com/reference/android/app/AlertDialog.Builder.html#setPositiveButton(int, android.content.DialogInterface.OnClickListener) No problem. When in doubt, double check the documentation - which can be done online or from your IDE! Also, posting the code you are trying to get work always helps us direct your/our efforts better! this thing is not gonna work on lolipop and version greater than it. As in, should be a Snack bar ? Starting with Android 5.0, Buttons automatically have their text capitalized. you can't set capitaliztion in builder directly. The accepted solution above won't work in Lollipop and above. Here's the working solution. After showing the dialog, I'm setting the button all caps false. Make sure you do it after dialog.show(). Else, you'll get Null Pointer Exception. AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this); builder.setTitle("Title"); builder.setMessage("message"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //Do Something } }); AlertDialog dialog = builder.create(); dialog.show(); dialog.getButton(AlertDialog.BUTTON_POSITIVE).setAllCaps(false); @Henry Zhu, See the above answer. getButton() not available in AlertDialog @KamrujjamanJoy Are you using androidx.appcompat.app.AlertDialog? If so, it should be. Use the DialogInterface.BUTTON_POSITIVE or DialogInterface.BUTTON_NEGATIVE to customize the action buttons. val builder = MaterialAlertDialogBuilder(requireContext()) builder.setTitle(getString(R.string.alert_title)) builder.setMessage(getString(R.string.alert_msg)) builder.setPositiveButton(getString(R.string.action_yes)) { _, _ -> // todo: your action } builder.setNegativeButton(getString(R.string.action_no), null) val dialog = builder.create() dialog.show() dialog.getButton(DialogInterface.BUTTON_POSITIVE).isAllCaps = false dialog.getButton(DialogInterface.BUTTON_NEGATIVE).isAllCaps = false Or even : builder.setPositiveButton("Ok", null); For the basic usage. using androidx.appcompat.app.AalertDialog fixed for me. its late, but it could help other who visits. To change the button text case, from all capitals to small case, usual method such as dialog.getButton(AlertDialog.BUTTON_POSITIVE).setAllCaps(false); this will not work with the alert builder anymore, upon exploring alert dialog code, I found Buttons used for it, and as default it will show capital text. To set, we need to add style while creating the alert dialog. Follow below steps for the same. In your theme.xml or style.xml add below style. <style name="custom_alert_button_text" parent="ThemeOverlay.MaterialComponents.Dialog.Alert"> <item name="android:textAllCaps">false</item> <item name="android:textSize">@dimen/_13ssp</item> <item name="android:textAppearance">?textAppearanceFiraSansBoldBlue34Text</item> </style> While building the alert dialog, add style to your alert dialog as follow. val alertBox = AlertDialog.Builder(context, R.style.custom_alert_button_text) alertBox.setCancelable(false) alertBox.setMessage("Your message for dialog") alertBox.setNegativeButton( "No" ) { dialog, _ -> dialog.dismiss() } alertBox.setPositiveButton( "Yes" ) { dialog, _ -> dialog.dismiss() //your action to perform on yes tap. } alertBox.show() This way, the positive and negative buttons text cases can be changed. I am using this method to change the text cases for alert dialog with builder. Hope it helps!
common-pile/stackexchange_filtered
Vector space isomorphism Let $V$ be the real vector space $\mathbb{R}[X]$ and $M \subset \mathbb{R}$ a set with $d$ elements. Let $$U_2 := \{ f \in \mathbb{R}[X] \mid \deg(f) \leq d − 1\}$$ be a vector space of $V$. Let $\Phi: V\rightarrow Ab(M,\mathbb{R})$ be a linear mapping that is defined by $\Phi (f)(m):=f(m)$. I want to show that $\Phi\mid_{U_2}:U_2\rightarrow \text{Ab}(M,\mathbb{R})$ is a vector space isomorphism. So, we have to show that $\Phi$ is an hoomomorphiism, injective and surjective. To show that the mapping is injective, we take to elements of $U_2$, say $f,g\in U_2$. For them it holds that $f(m)=g(m)=0$ for every $m\in M$. Suppose that $\Phi (f)=\Phi (g)$ then it follows that $f(m)=g(m)$. Is this correct? So, $\Phi$ is injective, right? How can we show that the mapping is surjective? Please carefully re-read your question statement and fix it rather than expecting us to do so for you. Particular problems: (1) $U_1$ appears to be irrelevant. (2) "It follows that $f = m$". (3) What is $Ab(M, \Bbb R)$? (4) The value $d$ appears to be unbound. At "f=m" there is a typo. I meant $f(m)=g(m)$, is this correct? There is no further information about $\text{Ab}(M,\mathbb{R})$, it is the range of the mapping. @JohnHughes Presumably, $Ab(M,\Bbb R)$ is the space of $\Bbb R$-valued functions over $M$. To show that $\Phi$ is injective, it suffices to show that $\Phi(f) = 0$ implies that $f = 0$ (which is to say that $\Phi$ has a trivial kernel). Now, suppose that $f \in U_2$ is given by $f(x) = a_0 + a_1x + \cdots + a_{d-1}x^{d-1}$. The statement $[\Phi(f)](m) = 0$ (for every $m \in M$) gives us $d$ equations. In particular, if $M = \{m_1,\dots,m_d\}$, then we have $$ a_0 + a_1 m_1 + \cdots + a_{d-1}m_1^{d-1} = 0\\ a_0 + a_1 m_2 + \cdots + a_{d-1}m_2^{d-1} = 0\\ \vdots\\ a_0 + a_1 m_d + \cdots + a_{d-1}m_d^{d-1} = 0 $$ Now, how can we deduce that $f(x) = 0$? With the appropriate matrix considerations, we could show that this function is also surjective. However, once you've shown either that the matrix is injective or surjective, it suffices to apply the rank-nullity theorem. In particular, $\Phi$ is a map between two vector spaces of dimension $d$. It follows that either $\Phi$ is both injective and surjective, or it is neither. $f$ has degree $d-1$ and it has $d$ roots. So, it must be the zero-polynomial, right? If that's a theorem you're allowed to use here, then that's great. Great!! For the surjectivity: We have that $\dim \ker \Phi|{U_2}+\dim im \Phi{U_2}=\dim U_2$. We have shown that the kernel is the trrivial and so $\dim \ker \Phi|{U_2}=0$. So $\dim im \Phi{U_2}=\dim U_2$. Is this correct? That's exactly what I meant. In order to use that, however, it's important to note that both spaces have dimension $d$ Ah ok!! So, we have that $\Phi$ is also surjective. So, it is left to show that $\Phi$ is an homomorphism, or not? Or is trivial this is a linear mapping? It's pretty easy to show that this is a linear map. In particular, we should note that $$(f+kg)(m)=f(m)+kg(m)$$ by definition It is given that $\Phi$ is linear. When we restrict it remains linear, right? Yes: if you restrict a linear map to a linear subspace, the result is again a linear map. I see!! Thank you!! :-) Let $$U_1 := { f \in \mathbb{R}[X] | \forall m \in M : f(m) = 0}$$ an other vector space. Why can we write every polynomial as a sum of an element of $U_1$ and one of $U_2$ ? If we take a polynomial with degree $\leq d-1$ we can write it as $h=0+g$, where $g\in U_2$. What for the other polynomials? There are no other polynomials over $M$; $\Phi$ is surjective $\Phi$ is surjective when we restruct it to $U_2$, or not? It is; that's what we just showed
common-pile/stackexchange_filtered
How to set dynamic custom header in i18next-http-backend plugin? i18next-http-backend - Docs I have the following configuration for i18next in react application. My problem is to set dynamic values in header, such as: "accept-lang". According to documentation customHeaders provided for this, but it has no any context arguments. For example, i can't get current language in this customHeaders function. How can i set dynamic header values in configuration? const initOptions: I18nInitOptions = { debug: true, fallbackLng: 'en', supportedLngs: ['en'], interpolation: { escapeValue: false, }, detection: { order: ['localStorage'], }, backend: { backends: backends, backendOptions: [ { loadPath: backendUrl, customHeaders: () => { return { 'accept-lang': 'LANG VALUE HERE?', }; }, }, ], }, initImmediate: false, saveMissing: true, }; I tried to set custom headers, get current language, but library doesn't provide, tried to log params of provided method, but its "undefined"
common-pile/stackexchange_filtered
Planetarium discussion area after the evening's Centaur presentation ends. Observer: Chiron switching between asteroid and comet classifications makes more sense now - that dual behavior from the same object. Analyst: The orbital instability explains why. Between Jupiter and Neptune, those gravitational tugs constantly reshape their paths over millions of years. Observer: But why would some develop comas while others stay rocky-looking? They're all coming from the same Kuiper Belt region originally
sci-datasets/scilogues
Funds deposited in my bank account. Account closed for suspicious activity. Is this a scam? Here's an interesting story. I lost my job and I needed extra income so when I was looking for a sugar daddy on Instagram, I met a guy. He claims that he is a Business Contractor and is working for UNICEF, currently building in Lagos, Nigeria. We talked for awhile and he didn't seem like a scammer. Some weeks later, he asked me for my name, date of birth and bank information (routing and account number). After I gave this to him, he made two mobile check deposits of $900 and $1,200 into my dormant bank account (I haven’t used it for awhile because I have no money, no job). I waited a couple of days for the checks to clear. I received a letter from my bank indicating that they had closed my account due to suspicious activity. FWIW, he also didn’t spell my name right on the check . Two weeks later I received another letter from the bank. It stated: “As a follow up to the letter we sent you about the closure of your account, this check includes any remaining account balances”. Along with the letter was a cashiers check for $883. I didn’t have any money in my account when he had access my bank info so I don’t know where this money came. I called my bank to determine if the cashiers check was real and the rep said that $883 was in my savings account and that I would be receiving another check for $12. With that verification, I cashed the check. The $883 is gone. It went toward my bills. I blocked him when my was account closed. Yesterday, I unblocked him and texted him that I had received the money. He wants to send me more and he wants me to withdraw the money as soon as it clears, keeping $300 and sending him the rest of it through Western Union. What do I do? Am I getting scammed? Here is some more information. He was born in California and claims to be a Business Contractor building for UNICEF right now in Lagos, Nigeria. He said that he would be there for 2-3 months and then he’s going back home. He has visited many countries for his job. He is getting this money from UNICEF who he told that I was his secretary so that they would send the money to me. As soon as I heard that I knew that it was a scam. He also said, “You know the FBI don’t take shit, they never play with their money”. I have blocked him on everything and I no longer have any contact with him! Also, he will not video chat me because he says that the government will not allow him to video chat in Nigeria. Check out https://money.stackexchange.com/q/71918/25694 to get an idea of how the scam was supposed to work. It sounds like your bank rightfully detected this scam and protected you, kudos to your bank! Should perhaps an auto-generated answer "This is a scam" be posted every time a question mentions Western Union? related: Sugar daddy wants my online banking login info to make deposits — is it a scam? How is it that the bank received checks for $900 and $1,200 and they are sending you a total of $895 ($883 + $12). What happened to the $1,200. I'm puzzled. I'm assuming from context that you're in the US, so how exactly is a guy in Nigeria supposed to become your sugar daddy? I mean, a certain amount of physical contact is an inherent part of the job, no? @jamesqf Not necessarily. Long-distance relationships exist, particularly in the days of webcams. There are bigger red flags here than that. "in Lagos, Nigeria" -- yes, it's a scam. Anything even slightly suspicious that comes out of Nigeria is a scam. In fact, if you have "Internet" and "Nigeria" in the same sentence, the chance that it's a scam is about 99%. It seems to me that you know this was a scam, and your question is: can you keep the money? Seems a fake story, maybe OP's trying to perfect the scheme. Who is scamming whom? @PeterA.Schneider Every day is, for someone in the world, the first day he/she learns about Nigerian scams. https://xkcd.com/1053 This is a new'ish scam that exploits the banking system, the person is 'washing' the money through you by having you deposit funds from stolen banking information, they'll get to keep everything that you sent them, and your bank will withdraw the misappropriated funds leaving you in debt to the bank: https://www.cbc.ca/news/canada/toronto/toronto-woman-warns-car-wrap-scam-montreal-victim-1.3801338 It sounds like a scam gone wrong. If the bank gives you a cashier's cheque, that cheque is good for value - it's not going to bounce unless the bank itself folds. But the bank might still come after you for reimbursement if they deem that it was paid out due to false impressions. Try writing to the bank, explaining the whole situation as you've done here, and getting them to reply to you in writing about whether the cheque for $883 and the expected $12 are still yours to keep. In the event that things turn uglier, you'd want the paper trail to show that you've been above board in your dealings. Don't fall for the Western Union line. If he needs to make a payment to someone else, he can do it himself without involving you - him wanting the excess to be routed back to himself just makes it worse. Yes, it's a scam. All the red flags are there. Most scammers don't seem like scammers because if they did, they wouldn't be able to scam people. The cashier's check you received from your bank sounds like it was genuine. Perhaps the money was in an associated account you had forgotten you had, perhaps he had deposited it and was intending to get it back later one way or another. "Most scammers don't seem like scammers because...." Actually, this is completely false (both the premise and the conclusion). Scammers can scam more people if they seem like scammers so that only gullible people respond in the first place. See https://www.microsoft.com/en-us/research/publication/why-do-nigerian-scammers-say-they-are-from-nigeria/?from=http%3A%2F%2Fresearch.microsoft.com%2Fpubs%2F167719%2Fwhyfromnigeria.pdf @Wildcard maybe it can be clarified. "Most scammers don't seem like scammers to the ones whom get scammed..." Laundering I reckon he's using an array of stolen funds (perhaps purchased on the dark web) to relay to your account. This way, you deal with the anti-fraud authorities, but of course, you're innocent. Sure, some of the money gets seized, but some clears successfully (ie. isn't detected as fraud deposit by bank) - and now the "sugar daddy" wants you to send him a cut, so he can receive some fruits. So essentially, you're not the one loosing money here. Nor is he trying to steal directly from you. Of course, if you give sensitive information he can withdraw from your account, but that seems to be besides the point of this particular scam. What does it mean to purchase stolen funds on the dark web? He's buying dirty cash at a discount and using it to launder it in this manner? If so, it would seem to me that there should be more efficient ways to launder money, particularly without using a bank and possibly involving the authorities. But what do I know? I use the money I print at local stores ;->) @BobBaerker you're thinking too small. You could launder a normal persons salary that way, you couldn't launder 100x as much. And the objective isn't to get stuff per se, it's to make the money looks not stolen so it can be used in ways other than as cash. @Dan Neely - I think you missed the point of my question and you got sidetracked by my quip about my printing counterfeit money (an objective to get "stuff"). How do you use money in other ways than as cash? Cash deposited to account. Cash withdrawn from account. Cash sent to Nigeria. @BobBaerker stolen funds need to be laundered in some way to avoid being swept up in bad activity checks by the banks like happened to the OP. You can't put millions in cash into your account without raising a huge number of red flags, so organized crime goes through massive contortions to hide the illicit origins of their money by trying to make it look like normal income. @BobBaerker If the stolen funds are at a bank, how do you launder them without using a bank? For example, often what you buy are other people's online banking credentials. See here for an example. This is what it sounds like to me. He's asking you to circulate and clean the money trail for him. The small amount he sent is likely to whet your greed, then he'll start sending you more - each time you can take a 'cut', but you become liable. Just to clear things up. Stolen funds == stolen credit / debit card information. Usually this is sold by hackers, so they don't have to deal with the consequences. Once bought, the criminal transfers amounts to a variety of accounts. So, as others have written, yes, it is a scam. The interesting part here is the bank's reaction. What was supposed to happen: your supposed sugar daddy who doesn't work for Unicef and wasn't born in California sends money to your account using some fraudulent means you receive the money you send some of the money to him via Western Union, which you can't ever get back the initial payment gets cancelled when the bank finds out it's fraudulent so you lost the money you sent What apparently happened is that the bank detected that the $1200 payment was fraudulent very quickly, blocked it, and closed your account. They did not (yet) detect that the $900 payment was fraudulent as well, thought that this was legitimate, and sent you that money (minus some fees or the like). Now, the problem is that the bank could at some point find out that those $900 were fraudulent as well, and decide that you need to reimburse them. It's not necessarily going to be easy for them, but be prepared for trouble. The other problem is that, as you have received, taken and used the money, you could be considered an accomplice in a fraudulent operation (it could be forged cheques, hacked bank accounts or payment cards, money laundering...). Of course, don't send anything via Western Union to anyone you don't really, physically know (and you are sure that the person asking you to send it is actually the person they say they are). Don't tell that person anything. Don't block them. Wait for instructions from the next point Go to the police and let them know what happened. Their chances of catching the scammer are slim, but: they could catch them if things go really bad, you're on the right side, and it should help prevent you being considered an accomplice it helps them detect and block further attempts But be prepared to have to pay back the $900. Be prepared to pay back to $900, but don't be too pro-active with it. In particular, make sure that it's paid back to the rightful owner. And that is likely not your bank. You want to avoid having to repay $900 twice, once to the bank and once to the victim, so demand that the bank confirms that its will take over the legal obligation to repay the victim (i.e. confirm you're off the hook). The request for you to cash a check, keep some, and pass some on is a classic scam. There is usually no legitimate reason to ask someone to do that, and it's an easy way to launder money. The scammer sends you money via a check or direct transfer. This money is dirty in a way that probably won't be noticed for a few days. You receive it. The banking system nowadays is good at catching up to fraud, and your bank will remove the money from your account on finding the money was stolen or fraudulently sent or whatever. If you have just left the money in your account, it will come and go and you won't have a problem. If you passed on some money to another person, then that will be considered a legitimate transfer, and you don't get to call it fraudulent and get it back. You're just out the money you sent on, as well as what you kept, and the dishonest person at the end has it. Sure, you can sue, if you can afford to start a lawsuit, but you'll undoubtedly find that the scammer is not in any jurisdiction that's going to pay any attention. tl;dr: Anyone who asks you to accept money from them and send some of it back, or to another destination, is a scammer. Do not cooperate, and do not continue dealing with the person. Why do you say: "If you have just left the money in your account"? She did leave the money in the account until the bank shut down the account and send a cheque for the remaining balance. She even called the bank to confirm that the cheque was legit. 100% SCAM. Read my story, similar to yours. This happened to me back in Australia. I was searching for a job desesperately and I eventually emailed a business which were looking for a marketing assistant or something like that. After contacting them, few hours later I received a call which they wanted to hire me, they were looking for my profile and if I could start ASAP. It all seemed too good to be true, I was going to earn arround 2000 AUD/month plus commissions, working half-time. I didn't know what I had to do, either when or where did I have to go but I signed a contract they sent me. I did read all of it and it seemed legit. I was 18, alone in Australia borrowing money from my mum, living in a 5 persons shared apartment in a 2 person shared room paying weekly 180$ and eating rice + tuna each meal, to survive with the less money I could in order to not get my mum broke. After a few days of signing the contract I did receive a call, it was arround 9pm. They wanted me to go to my closest bank and withdraw 2500$ they sent me and go to a western union and send it somewhere. They didn't specify where to send it until I had withdraw it and I was ready to send. I had to send it and I did send it and because it was the 1rst time sending I would keep all the comission which was 300$ dollars. I knew something wasn't going as it should, it seemed ilegal but at the moment I was not realizing what was happening. Anyway, I ended up with 300$ dollars and a happy face at the moment. Next morning my bank closed my account. I instantly went to the bank and asked what happened. After 2 hours in the bank, the money I withdrawed was stolen and washed through me. Someone used me and I just fell in the scam. I ended up talking with the police through the bank telephone, I gave all the info I had about these crew to the police. In the end it all went fine but such an experience. did you end up having to pay the 2500? No, I only had to pay the 300$ comission that I earned, which was completely fair. They gave me the money back (the one I had in the bank account before closing it). You are most likely an accomplice in money laundering. The scammer is using you as a third party to cycle money through. You are getting other peoples funds sent to you, as a test, then are asked to send to him through a valid bank account that you will not flag as being compromised. Your account got investigated because the money was sent to you from someone elses account who flagged it being compromised, therefore, funds being frozen.
common-pile/stackexchange_filtered
c++ if (DEBUG) ... expected primary-expression before '==' token #define DEBUG 1 void senddata() { ... if (DEBUG==1) { cout << row->Printable () << endl; }; .... } getrow.cc: In function 'void senddata()': getrow.cc:277: error: expected primary-expression before '==' token IMO that code was running some days ago... - Any idea what's wrong here? At a guess, something is undefining DEBUG. yep I renamed it and it's fine. I changed the build environment recently and the new system seems to define/undefine DEBUG . You Want to copy it in an answer , unapersson? I wouldn't do it like that at all. This seems more appropriate: #ifdef DEBUG cout << row->Printable() << endl; #endif This also generates better warnings and errors if you are doing something wrong (like forgot a semicolon somewhere).
common-pile/stackexchange_filtered
$6x + 13 = 7 \pmod{24}$ $6x + 13 = 7 \pmod{24}$ What method can I use to solve this problem? I tried with the method I used here but it won't work because I can't use Euclidean algorithm on this problem. There are $4$ values to check $x=0,1,2,3$ after that it repeats. This is same as $6x\equiv-6\pmod{24}$. It might help to recall some general theory of solving $ax\equiv b\pmod{m}$. Let $d=\gcd(a,m)$. Recall that $ax\equiv b\pmod{m}$ has a solution iff $d\mid b$. If $d\mid b$, there are $d$ distinct solutions mod $m$, and a unique solution mod $m/d$. First solve $\frac{a}{d}x\equiv \frac{b}{d}\pmod{\frac{m}{d}}$ for $x$ (you should at least be able to do this as $\gcd\left(\frac{a}{d}, \frac{m}{d}\right)=1$). Then if $x_0$ is a solution to this, the $d$ distinct solutions to the original congruence are ($x_0 + k\frac{m}{d}$) mod $m$, for $k=0,1,\ldots, d-1$. To write $6x + 13 \equiv 7 \pmod{24}$, type $6x + 13 \equiv 7 \pmod{24}$. Please [edit] your question to show what you have attempted and explain where you are stuck so that you receive responses that address the specific difficulties you are encountering. This tutorial explains how to typeset mathematics on this site. Hint: $6x+13\equiv7\pmod{24}\iff6x\equiv-6\pmod{6\times4}$. $$6x+13\equiv7\pmod{24}\iff 6x+6\equiv0\pmod{24}\iff 24|6x+6\iff 4|x+1$$
common-pile/stackexchange_filtered
Cascading Tree like Structure in ADF Dynamically? I am need of representing a Cascading Tree Structure on UI of an ADF Application, but there is a catch, The depth of the Tree is unknown, i.e A Root Node has one or multiple nodes which in turn may have mutliple Child nodes. My initial idea of dealing was, creating multiple Tables from which ADF BC Components are created with multiple VO's having Master - Detail kind of relation, but this works for 2 - 3 Tables or more may be, but I need to add Dynamic Support to it. Any suggestion either Declartive or Programmatic Approach will be appreciated. Thanking in Advance :) Currently ADF requires you to define rules for tree hierarchies, which limits the dynamic approach in that you i) need to have accessors defined on the ADF BC level between the views and ii) need to define rules based on these associations when configuring an ADF bound tree. To achieve you requirement, you would build your own tree model based on the Trinidad ChildPropertyTreeModel see: http://myfaces.apache.org/trinidad/trinidad-api/apidocs/org/apache/myfaces/trinidad/model/ChildPropertyTreeModel.html In this custom model you can then query ADF BC views (through the ADF binding layer or not) to build the dynamic tree structure you want
common-pile/stackexchange_filtered
Wiring my internet I have Verizon internet service and am currently using wifi. My router is in the basement and my desktop computer is 2 floors and on the other side of the house above it... Worst possible positioning but that's just how things worked out. My wireless currently is extremely unstable so I've decide to correct the problem by wiring my computer directly. The problem lies here: when redoing the room next to it (when the wall was open) we went ahead and wired some coaxial cable from our attic to our basement (with plenty of slack on both ends, don't ask me why we didn't go ahead and wire a CAT6 cable). The question is: Can I use the coaxial cable to bring me internet connection? Naturally the router (which needs to stay where it is) takes a coaxial cable input and has Ethernet outputs. So maybe I would have to take a ethernet cable, convert to coaxial-coaxial to my computer, convert back to ethernet. Is this even possible to convert from coaxial to ethernet? Or do I have to attempt to go ahead and fish a cat6 cable through my house. I cannot just split the signal because that would require two routers and two networks (which I don't believe would work with one cable-one ISP correct me if I'm wrong). Thanks Do people closer need the modem over there? If not, you could plug the Coax into the house into the one up to your room, and serve the house from up there. yeah we do need to leave the modem down there. Yes, you can run ethernet over coax, and while I don't have any direct experience of doing this, you should be able to get reasonable speeds. You are looking for an Ethernet Over Coax Converter. Wikipedia: http://en.wikipedia.org/wiki/Ethernet_over_coax A web search will find many vendors of coax to ethernet converters that support standard 75ohm coax, such as this one: http://www.comnet.net/comnet-products/valueline.html Another alternative would be to use the existing coax cable to "pull" a Cat6 cable through from the basement. Tape the cat6 to the end of the coax and pull it up. Make sure you tape it well so that It doesn't snag on anything when you pull it It doesn't come loose (this is obviously a risky proposal, but you might consider it worth it) @sawdust Current coax/ethernet converters support 75ohm. Yes, it is risky to pull a new cable, but the answer to this question is going to be either "no" or something hacky. Power line networking might be a good alternative for your situation. This is actually what I ended up doing! Thanks for the recommendation!
common-pile/stackexchange_filtered
Need a check on Latin translation to see whether correct in context with English version I need to ask for a check on the correctness of the Latin translations I have, to see whether they are correct in context with the English phrases I had translated. Animae celare bestias exiguae laxis vestibus illicitus est. This is translated from - It is forbidden to conceal beasts of little intellect within the folds of your garment. This is spoken by a saint to a man who wants to take up holy orders but is attempting to smuggle animals into the monastery. Nam eum hinc ferunt. Translated from - For they beareth him hence. This refers to a group of men carrying another man away from danger. Diabolo se agnosci non placet. Translated from - The Devil does not like to be recognised. Nam idem quod eos edit edunt. Translated from - For they eateth that which eateth them. Refers to people who eat things which are capable of eating them, such as worms and parasites. Ferens infantes exit. Translated from - It came out carrying infants. Refers to a sinister old woman emerging from a small cottage carrying infants under her arms. I have also been given - Ferens infantes emersit. 1. What you have: Animae celare bestias exiguae laxis vestibus illicitus est. What you are trying to say: It is forbidden to conceal beasts of little intellect within the folds of your garment. What I think it should be: Celare bestias animi exigui in sinibus vestis tuae illicitus est. Changes: I moved some words to be closer to the ones they modify. I tried to preserve the word choices you made, since nearly all of them were near in meaning to the sense you are getting at. I changed animae to animi because you want the word animus not anima. The former means "intellect" while the latter refers to the spirit. You could also use mens (mentis in this case) to mean "intellect" as well. I changed laxis to sinibus because laxus means "empty," where as sinus means "fold." Finally, I changed vestibus to vestis because you are saying "of the garment," which requires a genitive. I added tuae after vestis to convey the "your." 2. What you have: Nam eum hinc ferunt. What you are trying to say: For they beareth him hence What I think it should be: This one seems fine to me! 3. What you have: Diabolo se agnosci non placet What you are trying to say: The Devil does not like to be recognized. What I think it should be: Diabolo agnosci non placet. Changes: I only removed se because it is a reflexive pronoun in the accusative (i.e. the direct object), but passive verbs usually do not take objects. Literally, this one translates to "It is not pleasing for the devil to be recognized (himself)." You can see why the se (himself) does not seem to fit. 4. What you have: Nam idem quod eos edit edunt. What you are trying to say: For they eateth that which eateth them. What I think it should be: Looks fine to me. Just note that it literally translates from Latin as "For they eat the same thing which eats them" (idem means "same"). This slightly different but I think it works well with what you are trying to accomplish. 5. What you have: Ferens infantes exit. What you are trying to say: It came out carrying infants. What I think it should be: Ferens infantes emersit. Changes: Now, you've already received commentary on this one in a separate question, but that's okay, I guess. The reason I prefer emersit over exit is that of connotations. Exit means "to go out/away, to become visible," but it also can mean "to die" or "to sprout." It would probably be pretty clear from context which one you mean, but emersit lacks these other connotations. One can also look at the English derivatives of the two words. Exeo (exit) leads to the word "exit" which usually means "to go away" or "to go out of the current place" which implies a motion away (not always, though). Emergo (emersit), on the other hand, leads to "emerge" which means "to come into view." I think this more accurately captures the picture you are painting. you obviously cannot rely solely on English derivatives when making word choices, but it can be a useful tool sometimes. If you are dead set on using exit, you should put it in the perfect exivit because it is in the past tense. Thanks for this. One question regarding the phrase about concealing animals of little intellect within the folds of your garment. The translation I had for this was expressed to me thus - laxis vestibus for 'within the folds of your garments' is from Lucan, The Civil War. I am presuming this is correct from the 17th Century in England rather than classical Latin? Thanks. C Garvey @ChrisG I'm not sure what you mean by 17th century, as Lucan is a 1st century writer. That being said, the phrase laxis vestibus in the poem you mention is not used in the way you say. It is usually translated as "flowing robes" rather than "fold of clothes," according to two different translations I checked.
common-pile/stackexchange_filtered
Implementation of an interface which contains a struct I am bit confused about how the typesets in go work. Post Go 1.18, go supports embedding structs inside an interface. For instance, this is perfectly valid go code : type ABCInterface interface { ABC } type ABC struct { A, B, C int } My question is how do I instantiate an object which satisfies the ABCInterface? I tried creating instance of ABC but that is not of type ABCInterface. I also defined a new struct type ABCImpl struct { ABC } but this is not an implementation of ABCInterface as well. ABC is in the type set of ABCInterface, it can therefore be used as the type argument when instantiating a generic function or struct that have ABCInterface as their type parameter, see: https://go.dev/play/p/rryTq45cBSi. ABCImpl on the other hand is neither ABC nor does it implement ABCInterface. This seems like an XY Problem. Please show the code you expected to work but doesn't. "My question is how do I instantiate an object which satisfies the ABCInterface?" You cannot. This type of interface is only useful as a constraint in generics. In Go, an interface is a set of method signatures that define the behavior that a struct (or type) must adhere to. When a struct implements all the methods specified by an interface, it is said to satisfy or implement that interface. In your case, let's consider that you want an interface that implements a Sum method. To implement the interface, you'll add the listener as follows: package main import "log" // ABCInterface provides a blueprint for types that include the Sum method. type ABCInterface interface { Sum() int } // ABC is a type that represents values of A, B, and C. type ABC struct { A, B, C int } // ABCImpl is a type that inherits fields from ABC and implements ABCInterface. type ABCImpl struct { ABC } //You could eliminate the `ABC` struct and simply use type ABCImpl struct { A,B,C int } // Sum calculates the sum of A, B, and C and returns the result. func (a ABCImpl) Sum() int { return a.C + a.A + a.B } func main() { // Create an instance of ABCImpl. trialValue := ABCImpl{ ABC: ABC{ A: 1, B: 2, C: 3, }, } // Call the Sum method on the trialValue instance and print the result. log.Println(trialValue.Sum()) }
common-pile/stackexchange_filtered
C++ Game AI only works in main I have a problem getting the AI to work if I do it in a subclass. Here is my main loop in which I access the player and enemy classes for their move, logic, and show functions. //Logic myPlayer.player_move(); myEnemy.enemy_logic(); //Rendering myPlayer.player_show(); myEnemy.enemy_show(); So I access the Player class's function that moves the player then I access the logic(AI) function of the Enemy Class. void Enemy::enemy_move(){ eX -= 2; } void Enemy::enemy_logic(){ Player myPlayer; if(myPlayer.x > SCREEN_WIDTH / 2){ enemy_move(); } } So if the Players x value is greater than half the screen, I want the enemy to start moving left I can compile the program but when I move the player past the halfway point of the screen, the enemy does nothing. If I were to put this if statement in the main.cpp then it works fine. Any advice? This isn't AI in any real sense, so I'm removing that tag. @JohnDibling: A computer program making decisions (the decision to move the enemy) based on environmental conditions (the position of the player) is AI, even if it's not very sophisticated. @BenjaminLindley: By that definition you could say that all computer programs exhibit artificial intelligence. I don't buy it. It's because you're re-initializing your instance of the class Player. Instead, pass it as a parameter: void Enemy::enemy_logic(Player myPlayer){ if(myPlayer.x > SCREEN_WIDTH / 2){ enemy_move(); } } That way the function uses your instance, and not a new instance in a different scope. Also, I've noticed you're using SDL. I recommend making a fast switch to SFML. http://www.sfml-dev.org/ I'm just beginning with game development and I thought SDL would be relatively easy. I'm going to eventually switch to something else. That's why I started with SDL too, but I know both and I think SFML is much easier. More modern, more versatile, less C and more C++, and much better documentation. I know it'll be tough switching so soon if you're new to it, but just skim through a couple tutorials. I think you'll want to switch. Because you are initializing an instance of Player as myPlayer that is not connected to anything. You should define a private variable for myPlayer inside your Enemy Class or pass a pointer to the Player class instance as an argument, in this way you will be able to maintain the state. No, you'd better follow my second suggestion: void Enemy::enemy_logic(Player* myPlayer) or pass by value void Enemy::enemy_logic(Player myPlayer) If your enemies depend on a single player you can "bind" each enmy to a player like this: class Player { Position m_x, m_y, m_z; public: Position const & x (void) { return m_x; } }; class Enemy { public: Enemy (Player &p) : m_player(p) { } Player & m_player; void logic (void) { if (m_player.x() > SCREEN_WIDTH/2) { move_x(); } } void move_x (void) { /*...*/ } }; int main (void) { Player the_player; Enemy the_enemy(the_player); // move the player the_enemy.logic(); // the_enemy knows the_player and acts accordingly }
common-pile/stackexchange_filtered
Error handling in GameState Machine for menus using Singleton Style classes Let me preface by saying I am very new to programming and c++. I have been researching various methods for creating a menu system for a simple game that allows the player to go from one menu(representing a location) to the next and back to create a menu-driven world to explore with many locations each with their own menu chains to dive into. The problem I am having is, I intend to expand this to possibly hundreds of locations as I tell a story, so I want to avoid using endless if else and switch statement chains. I have been trying to find a solution that is simple, maintainable, and easily expandable. This is when I stumbled upon the existence of State Machines. I understand to some extent the push pop of a stack, but actually implementing this in code with my still budding understanding is far from trivial for me and after about 2 weeks of trial and error with each iteration ending up in a bundle of errors that I am ill equipped to troubleshoot, I must resign to asking the community for guidance. This is imperative to get this little game to work and I refuse to give up on it yet. In its current state, I am having the following seemingly simple errors, but with every solution I try to correct them, it only seems to add to the number. These specific errors are less of the issue and more a question of how can I turn what I have into the foundation for a working state machine, or should I scrap it and start again? several 'identifiers not found' several 'cannot instantiate abstract class' 'C2664 'void StateMachine::pushState(State *)': cannot convert argument 1 from 'TownState' to 'State *' several Messages stating nothing more than 'due to the following members' several missing user defined conversion operators. On their own, many of these issues I am confident I can resolve in a simpler codebase, but whenever I fix one, I end up with many more different errors seemingly unrelated. At one point I was up to 200 errors. I have reverted the code back to the least amount of errors I could just to ask this question, and to basically start over, and any push in the right direction here from an experienced developer would be much appreciated. Even if it is only resources to read to get a better understanding of how all this should come together or strategies one should use to approach this kind of design. I feel there is a really simple refactor and a few minor touch ups hidden in here somewhere and it will work fine. I'm just not seeing it with my still budding grasp on coding. I have tried too many major and minor changes over the last two weeks to the point of frustration, along with complete redos. I have been reading articles, browsing stack overflows questions and watching videos but am unable to find resources that tread close enough to this specific project's needs or that are simple enough for my noob self to fully understand and implement. Here is the entirety of my code below. If this is not appropriate or there is a better way to ask this question to make this more clear for Stack Overflow's expectations, let me know and I will amend it. Thank you all. (P.S. I have not yet split many of the files into .h and .cpp yet. In these cases, I have omitted the .cpp files. main.cpp #include "state_handling.h" #include "state_machine.h" #include "game.h" #include "main_menu.h" #include "options_state.h" #include "town_darda.h" #include "the_valley.h" #include "quit_state.h" // Note: to return to previous State, use "stateMachine.pop_state();" as the case option. class GamePlayState : public State { public: GamePlayState() {} void handleInput() {}; //handle input specific to Game Play. void update() {}; //update logic specific to Game Play. void renderMenu() {}; //render logic and menu specific to Game Play. }; int main() { Game game; game.run(); return 0; } state_machine.h #ifndef _STATE_MACHINE_H #define _STATE_MACHINE_H #include <vector> #include "state_handling.h" //Manages current Game State Stack. class StateMachine { private: std::vector<State*> states; public: void pushState(State* state) { states.push_back(state); } void popState() { states.pop_back(); } State* currentState() { return states.back(); } bool isEmpty() { return states.empty(); } }; #endif state_handling.cpp #include "state_handling.h" class GameState : public State { public: void handleInput() override { // Handle input specific to the GameState } void update() override { // Update game logic specific to the GameState } void renderMenu() override { }; }; state_handling.h #ifndef _STATE_HANDLING_H #define _STATE_HANDLING_H class State { public: virtual void handleInput() = 0; virtual void update() = 0; virtual void renderMenu() = 0; private: static State* m_instance; }; #endif game.h #ifndef _GAME_H #define _GAME_H #include "state_machine.h" #include "main_menu.h" //Responsible for creating and managing the state machine. All other classes that need to use it can access it through the 'Game' instance. class Game { private: StateMachine stateMachine; public: void run() { stateMachine.pushState(new MainMenuState()); while (!stateMachine.isEmpty()) { stateMachine.currentState()->handleInput(); stateMachine.currentState()->update(); stateMachine.currentState()->renderMenu(); } } }; #endif main_menu.h #ifndef _MAIN_MENU_H #define _MAIN_MENU_H #include "state_machine.h" #include "town_darda.h" #include <iostream> class MainMenuState : public State { public: MainMenuState() {} void handleInput() { //handle input specific to Main Menu. int choice; std::cout << "MAIN MENU:\n[1] Start Game\n[2] Options\n[3]Quit\n" << std::endl; std::cin >> choice; switch (choice) { case 1: //Introduction here before entering game first time. stateMachine.pushState(DardaState()); break; case 2: //stateMachine.pushState(OptionsState()); break; case 3: //stateMachine.pushState(QuitState()); break; default: std::cout << "Invalid Option..."; break; } } void update() {}; //update logic specific to Main Menu. void renderMenu() {}; //render logic and menu specific to Main Menu. }; #endif the_valley.h #ifndef _THE_VALLEY_H #define _THE_VALLEY_H #include <iostream> #include "state_handling.h" #include "gamestates.h" #include "state_machine.h" #include "game.h" class TheValleyState : public State { public: TheValleyState() {} void handleInput() { int choice{}; std::cout << "THE VALLEY MENU:\n[1] Explore\n[2] Hunt\n[3] Information\n[4]Leave Area\n[X]Options" << std::endl; std::cin >> choice; switch (choice) { case 1: //stateMachine.pushState(TheValleyExplore()); break; case 2: //stateMachine.pushState(TheValleyHunt()); break; case 3: //stateMachine.pushState(TheValleyInfo()); break; case 4: //Display The Valley's Adjacent Area Menus (Darda, Coral Cove, Bluster Bluffs, Thalen Pass) //Handle choice then go to new location state "stateMachine.pushState(XXXXXXState());" stateMachine.pushState(DardaState()); break; case 5: //change choice to char and allow for X to open Options Menu. default: std::cout << "Invalid Option..."; break; } } void update() {} void renderMenu() {} }; #endif town_darda.h #ifndef _TOWN_DARDA_H #define _TOWN_DARDA_H #include <iostream> #include "state_handling.h" #include "state_machine.h" #include "the_valley.h" class DardaState : public State { public: static DardaState* instance() { if (!m_instance) m_instance = new DardaState(); return m_instance; } void handleInput() { int choice{}; std::cout << "DARDA MENU:\n[1] Market\n[2] Inn\n[3]Leave Town\n" << std::endl; std::cin >> choice; switch (choice) { case 1: //stateMachine.pushState(DardaMarket()); break; case 2: //stateMachine.pushState(DardaInn()); break; case 3: stateMachine.pushState(TheValleyState()); break; default: std::cout << "Invalid Option..."; break; } } void update() {} void renderMenu() {} private: static DardaState* m_instance; }; #endif quit_state.h #ifndef _QUIT_STATE_H #define _QUIT_STATE_H #include "state_handling.h" class QuitState : public State { public: QuitState() {} void handleInput() {}; //handle input specific to Quit State. void update() {}; //update logic specific to Quit State. void renderMenu() {}; //render logic and menu specific to Quit State. }; #endif options_state.h #ifndef _OPTIONS_STATE_H #define _OPTIONS_STATE_H #include "state_handling.h" class OptionState : public State { public: OptionState() {} void handleInput() {}; //handle input specific to Option State. void update() {}; //update logic specific to Option State. void renderMenu() {}; //render logic and menu specific to Option State. }; #endif This function void pushState(State* state) accepts a pointer argument. In this statement stateMachine.pushState(DardaState()); you are trying to pass an instance of an object, not a pointer to one. I didn't look for any other issues, it's just too much code. I would suggest starting much smaller and focusing on a single issue. In the end though this approach will likely me unmaintainable. You should consider a more data driven design. Much appreciated! I will check out some data driven approaches. And apologies for the length of the code. I just wanted to provide as much as I could in hopes people could understand the mess I created. haha. Cheers! "At one point I was up to 200 errors" If you haven't, you should have started with a minimal amount of code which compiles and run without any warnings or error (an Hello World would be perfect), then add one piece of functionality at a time, test it, correct any warnings and errors and only then add another piece. Also, consider reading: https://gameprogrammingpatterns.com/contents.html Haha yeah it always starts small. But it inevitably must grow. But thank you for the link. I'll check it out.
common-pile/stackexchange_filtered
how to synchronize webservice calls in javascript I have a control application - using asp.net webservices. I have a timer which does an asynchronous webservice call every 5 seconds to update the screen.There are also user buttons to refresh parts of the screen, also doing async webservice calls. The issue is my screen get messy if a user webservice command is issued before the timer webservice response has arrived. Basically, I want the user command to wait, if there is a pending async timer call in process. How do I synchronize between these calls in Javascript? Thanks. Is it possible to ignore the timed postback when a user postback occurs? If so, set 2 flags (DontRequest and IgnoreNext) when the user does postback. When the user postback returns, unset DontRequest. Your automated process would not start requests while DontRequest is set. If a response is received and IgnoreNext is set, ignore the response and unset the flag.
common-pile/stackexchange_filtered
2D-arrays ND-arrays appear to index differently in numpy As part of a larger project, I need to be able to make an orthogonal "projection" of a scalar-field in each of its N-dimensions. (Effectively I want to take the mean of the data in every dimension except the "dimension of projection"). Below is a simplified (but complete and runnable) excerpt of the relevant code that works.... except when the projection dimension is the 0-th or 1-st axis. When this is the case, the code appears behave as if these two dimensions have been swapped. I need help to understand why this is happening, and what the best way is to reconcile this behavior so that the program works consistently no matter which dimension is indexed. from pylab import * import scipy.interpolate def projectAxis(d,projection_dim,nDim) : """calculate (and plot) the mean across all axes, except for the projection dimension """ all_axes_except_projection_dim = range(nDim) all_axes_except_projection_dim.remove(projection_dim) plot(mean(d,axis=tuple(all_axes_except_projection_dim))) ylim(0,1); yticks([0,1]); def test(nDim,varies_in_dim,col=1) : """Generate a gradient in nDim-dimensional space, and project it in each dimension. """ ## generate 1000 randomly distributed coordinates xs = np.random.rand(1000,nDim) ## generate a value to be associated with each coordinate. The ## value is assigned such that it correlates (exactly) with a ## particular dimension / axis of the data. The particular ## dimension is assigned by the parameter 'varies_in_dim'. z = xs[:,varies_in_dim] ## interpolate, to create a regular n-dimensional mesh lattice_width = 11 m_points = [linspace(0,1,lattice_width)]*nDim interpolation_points = tuple(np.meshgrid(*m_points)) zi = scipy.interpolate.griddata(xs, z, interpolation_points, method='nearest') def plotProjection(axis,nDim) : projectAxis(zi,axis,nDim) if col == 3 : ylabel('axis=%d' %(axis)) gca().yaxis.set_label_position("right") # if there are sufficient dimensions to display # variation in the specified dimension... if nDim > varies_in_dim : for d in xrange(4) : if nDim > d : subplot2grid((rows,cols),(d,col)) plotProjection(d,nDim) if d == 0 : title('%d-D space' %(nDim)) figure(figsize=(7,8)) rows,cols = 4,4 varies_in_dim = 1 suptitle('Data should only substantially vary along axis %d' %(varies_in_dim) ) test(2,varies_in_dim,col=0) test(3,varies_in_dim,col=1) test(4,varies_in_dim,col=2) test(5,varies_in_dim,col=3) show() When run with varies_in_dim = 2 (or for higher values), the output is what I would expect. For each test case (spaces of 3,4 or 5 dimensions), the only projection that shows variation is the 2nd dimension (where dimensions are indexed from 0). Here is the output for varies_in_dim = 2, which is correct: But when varies_in_dim = 1, the output shows variation in dimension 0...and vice versa: when varies_in_dim = 0, the output shows variation in dimension 1. The following image shows the output for varies_in_dim = 1, which wrongly shows the variation as occuring in dimension 0. What am I missing? How should my program be reorganized to work consistently? I wonder: am I using scipy.interpolate.griddata wrong? Not sure if this is the reason (tl;dr), but: meshgrid by default swaps the first two dimensions, to please Matlab users. meshgrid(..., indexing="ij") does not swap the first two dimensions. That fixes it. Thank you. My dislike of matlab has intensified! How can this inconsistent behavior be the default? Shocking! So does contourf and imshow do similar "behind-the-scenes" axis swapping? Can you point me to the documentation on this? Thanks. @pv. perhaps you can post your comment as the answer... Yeah, @pv. if you post this as the answer, I will accept and the questions can be closed. Thanks again.
common-pile/stackexchange_filtered
adding arguments to process not working? I got this program written in C# WinForms. im using system.diagnostic to create a CMD process. with that cmd i want some arguments but they are not present or working :S dont know why ?! NOTE: im not sure how to use more than 1 argument, correct me if im wrong :D im trying to replicate the "copy /b %filename% lpt1" command.... here is my code: public void OutputBtn_Process_Click(object sender, EventArgs e) { foreach (FileInfo fi in listBox1.Items) { Process process1 = new Process(); process1.StartInfo.UseShellExecute = false; process1.StartInfo.Arguments = "copy /b myfile.txt test.txt"; //process1.StartInfo.LoadUserProfile = true; process1.StartInfo.FileName = "cmd.exe"; process1.StartInfo.WorkingDirectory = Path.GetDirectoryName(fi.FullName); process1.Start(); } } NOTE: i just added the test.txt instead of LPT1 for testing purpose. That's correct, you just need the "/c" as the first parameter. Do you actually have FileInfo instances being retrieved from listbox1.Items? yeap. so far it works :) without path.GetdirectoryName it would'nt work sayin something like" path is invalid" but that also opens up for my next question. how do I add in my file names into to cmd line ?? Try this process1.StartInfo.Arguments = "/C \"copy /b myfile.txt LPT1:\""; The documentation on Windows 7 command-line tool cmd.exe thanks. it sure did something now. the CMD windows pops up quick and closes again saying that LPT1 is not recognize device. but thats probably cause I dont have LPT port in my laptop. string strCmdText; strCmdText= "/C copy /b myfile.txt test.txt"; System.Diagnostics.Process.Start("CMD.exe",strCmdText);
common-pile/stackexchange_filtered
react-native-firebase v6 -> TypeError: undefined is not a function near (...'this.firestore.native.collectionGet...') I've been trying to integrate Firebase into my react native app. I created my RN project using react-native init myProjectName and cd ios && pod install I've followed the installation guide from https://rnfirebase.io/. after finish setup Firebase by yarn add @react-native-firebase/app and all other steps, I tried to integrate Firebase Cloud Firestore and followed this doc https://rnfirebase.io/firestore/usage , but then i got TypeError: undefined is not a function near (...'this.firestore.native.collectionGet...') error. Here are the dependencies in package.json "dependencies": { "@react-native-firebase/app": "^7.2.0", "@react-native-firebase/firestore": "^7.2.0", "react": "16.11.0", "react-native": "0.62.2" }, Here are the codes in App.js import React, {useEffect} from 'react'; import {SafeAreaView, View, Text, StatusBar} from 'react-native'; import firebase from '@react-native-firebase/app'; import firestore from '@react-native-firebase/firestore'; const App = () => { const getData = async () => { const db = await firestore().collection('stories').get(); console.log({db}); }; useEffect(() => { getData(); }); return ( <> <StatusBar /> <SafeAreaView> <View> <Text>Hello There</Text> </View> </SafeAreaView> </> ); }; export default App; Here's are the screenshots of my projects: I would highly recommend checking a similar issue on github[1]. It seems what may have resolved the issue for the user was to guarantee that the native module was properly installed. [1]https://github.com/invertase/react-native-firebase/issues/3749
common-pile/stackexchange_filtered
Inject sleep() into a function of an external process I know how to inject a DLL into a running process and also how to utilize functions used internally by the process e.g. void__stdcall remoteMethod(unsigned short id) { typedef void (__stdcall *pFunctionAddress)(unsigned short); pFunctionAddress pMyFunction = (pFunctionAddress)(0xCAFEBABE); pMyFunction(id); } Now i want to add a sleep() into an existing method in the running process - this is the main loop of the program and doesnt stop for a sec and uses up all processing power. I know that with frameworks like detours i could make a trampoline function which calls my function and then the original one - however my problem is that the while(1) loop is somewhere within the function of the external process. So i know the offset where the loop starts - and after that i would like to first call sleep() and then continue with the normal route of the loop. The only alternative i saw so far is binary editing the program but this is not a good solution. Any suggestion? Thanks +1 for trying to sleep() with the 0xCAFEBABE. I think you are trying to be too cute here. Just call SuspendThread/ResumeThread alternately on a timer. I know it's ugly, but you aren't going to enter your solution in any beauty pageant I suspect. Agreed. Or much simpler: start the process with start.exe /low Thats a nice idea - how do i get the main thread from binary if i inject my dll into it? If you have the main window handle you can call GetWindowThreadProcessId. What if it does? You need to find the miscreants and go to work on them. Post the name of the spin-waiting program. Wait for SO-ers to send hate mail to the developer. Install the update the developer sends you as a bribe to stop the hate mail. In principle, as long as you've been executed once within the space of the other process, and you know that the loop isn't executing, then you could enabling writing to text pages and patch the actual loop code in situ. You'll need a few redundant bytes to write a call to your function over (extending the function will need a lot of rewriting as all relative offsets will break). This is not, however, terribly easy nor terribly robust. Consider why you want to to this, and if you can achieve the goal another way. as i said my goal is that the target process does not consume all cpu on one core because of some lousy programming which does a while(1) without sleep i might be able to indicate some unneeded function call in the loop like a printF which i could replace with a sleep so that the stack pointer etc is not influenced since the functions size isnt altered How have you determined that the program has a while(1) loop that does nothing? Can't you just nice the process down the scheduler priority, if you're worried about unresponsiveness?
common-pile/stackexchange_filtered
Parsing "Key" = "Value" pair I'm trying to parse the string in the folowing format using the regex: "Key" = "Value"; The following code is used to extract the "key" and "value": NSString* pattern = @"([\"\"'])(?:(?=(\\\\?))\\2.)*?\\1"; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:NULL]; NSRange matchRange = NSMakeRange(0, line.length); NSTextCheckingResult *match = [regex firstMatchInString:line options:0 range:matchRange]; NSRange rangeKeyMatch = [match rangeAtIndex:0]; matchRange.location = rangeKeyMatch.length; matchRange.length = line.length - rangeKeyMatch.length; NSTextCheckingResult *match2 = [regex firstMatchInString:line options:0 range:matchRange]; NSRange rangeValueMatch = [match2 rangeAtIndex:0]; It doesn't look efficient and is not considering the following example as invalid: "key" = "value" = "something else"; Is there any efficient way to perform parse of this kind of parsing? I'm not familiar with that dialect, but since you've tagged regex, here's one that should do it in principle: ^"([^"]*)" = "([^"]*)";$ You're not being exact about the format so you may need to add some conditional white-space here and there depending on your input format. Another thing that might come into play is the need to escape the parentheses. For example with sed, you'd have to write: echo '"Key" = "Value";' | sed -e 's#^"\([^"]*\)" = "\([^"]*\)";$#key is \1 and value is \2#' NSRegularExpression follows the ICU standard, in case people are interested. Ah, and just to make the pattern slightly more robust, I'd use \s+ in place of the single space. This code should match "key" = "value" and not "key" = "value" = "something else": NSString *line = @"\"key\" = \"value\""; NSError *error = NULL; NSString *pattern = @"\\\"(\\w+)\\\"\\s=\\s\\\"(\\w+)\\\"$"; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionAnchorsMatchLines error:&error]; NSRange matchRange = NSMakeRange(0, line.length); NSTextCheckingResult *match = [regex firstMatchInString:line options:0 range:matchRange]; /* It looks like you were not quite looking at the ranges properly. The rangeAtIndex 0 is actually the entire string. */ NSRange rangeKeyMatch = [match rangeAtIndex:1]; NSRange rangeValueMatch = [match rangeAtIndex:2]; NSLog(@"Key: %@, Value: %@", [line substringWithRange:rangeKeyMatch], [line substringWithRange:rangeValueMatch]);
common-pile/stackexchange_filtered
Image() onLoad not waiting for image to load I've figured out the centering and resizing issues, but I still can't get onLoad to work properly. Anyone have any ideas? I thought onLoad was supposed to wait for the image to be loaded completely before firing the code. As this is right now, it resizes the img for the next img, and fades it in before it's loaded, so the previous image fades in again. Once the show has run through once, it works perfectly, so obviously it's not waiting for the image to load completely before firing imageLoad(). <div id="slideShow"> <div id="slideShowImg" style="display:none; margin-right:auto; margin-left:auto;"> </div> <div id="slideShowThumbs"> </div> <script type="text/javascript"> loadXMLDoc('http://www.thehoppr.com/hopspots/82/82.xml', function() { var slideShow = document.getElementById('slideShow'); var items = []; var nl = xmlhttp.responseXML.getElementsByTagName('image'); var i = 0; var t; var slideShowImg = document.getElementById('slideShowImg'); var slideShow = document.getElementById('slideShow'); var maxHeight = 300; var maxWidth = 800; var imgNode = new Image(); function image() { var nli = nl.item(i); var src = nli.getAttribute('src').toString(); var width = parseInt(nli.getAttribute('width').toString()); var height = parseInt(nli.getAttribute('height').toString()); imgNode.onLoad = imageLoad(); imgNode.src = src; imgNode.height = height; imgNode.width = width; imgNode.setAttribute("style", "margin-right:auto; margin-left:auto; display:block;"); var ratio = maxHeight / maxWidth; if (imgNode.height / imgNode.width > ratio) { // height is the problem if (imgNode.height > maxHeight) { imgNode.width = Math.round(imgNode.width * (maxHeight / imgNode.height)); imgNode.height = maxHeight; } } else { // width is the problem if (imgNode.width > maxHeight) { imgNode.height = Math.round(imgNode.height * (maxWidth / imgNode.width)); imgNode.width = maxWidth; } } } function imageLoad() { slideShowImg.appendChild(imgNode); Effect.Appear('slideShowImg', { duration: 1 }); t = setTimeout(nextImage, 7000); } function nextImage() { slideShowImg.setAttribute("style", "display:none"); if (i < nl.length - 1) { i++; image(); } else { i = 0; image(); } } if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { //XML Loaded, create the slideshow alert(xmlhttp.responseText); image(); } }); </script> Interesting enough it appears to actually work in Chrome, but not IE or Firefox. Obviously the script is pulling from the cache before the onLoad even gets assigned? Preloading an image while the other is being shown is probably going to be my best bet here. If anyone can provide me with some sample code that might speed this up would be appreciated, I'm fairly new to Javascript. It's late though and I'm heading to bed. Here are some of my thoughts (it's all open discussion)... Preloading - Since you're limited to downloading 2 resources in parallel per hostname, it may not make sense to preload everything up front. Since it's a slideshow, how about modifying image() to download the i + 1 image through an Image object that doesn't get appended to the DOM? It doesn't seem beneficial to prefetch i + 2 and beyond in a slideshow setting. Centering the images - Regarding using the auto margin width for horizontal centering, I believe you'll have to explicitly set the image to display:block. Obviously that doesn't solve centering vertically. Are all the images the same size? Also, will the slideShowImg div have a defined height/width? If so, then some math can be applied to achieve the centering. Hope this helps! :) I was able to figure out the centering and resizing. I'm using the onLoad event now to trigger the animation effect that makes the div container appear, but that does not appear to work no matter what sort of configuration I try. i thought the onLoad event was supposed to wait for the image to be loaded and then it fires the code you want. Preloading one image ahead sounds like a good idea as well, could you include some sample code?See my updated code above! Ok so I fixed the issue with the onLoad, and I even added a little preloading to help the slideshow along as well. All I had to do was define the onload first, and then do everything else except define the src inside the onload's function. I then added a little nextImg preloading so there's little if no hiccup between images even if it's the first time the browser is loading them. Here's the final code for anyone who has similar onload issues and finds there way here: <div id="slideShow"> <div id="slideShowImg" style="display:none; margin-right:auto; margin-left:auto;"> </div> <div id="slideShowThumbs"> </div> <script type="text/javascript"> loadXMLDoc('/82.xml', function() { var slideShow = document.getElementById('slideShow'); var items = []; var nl = xmlhttp.responseXML.getElementsByTagName('image'); var i = 0; var t; var slideShowImg = document.getElementById('slideShowImg'); var slideShow = document.getElementById('slideShow'); var maxHeight = 300; var maxWidth = 800; var curImg = new Image(); var nextImg = new Image(); function image() { var cli = nl.item(i); var src = cli.getAttribute('src').toString(); var width = parseInt(cli.getAttribute('width').toString()); var height = parseInt(cli.getAttribute('height').toString()); curImg.onload = function() { curImg.height = height; curImg.width = width; curImg.setAttribute("style", "margin-right:auto; margin-left:auto; display:block;"); slideShowImg.appendChild(curImg); var ratio = maxHeight / maxWidth; if (curImg.height / curImg.width > ratio) { // height is the problem if (curImg.height > maxHeight) { curImg.width = Math.round(curImg.width * (maxHeight / curImg.height)); curImg.height = maxHeight; } } else { // width is the problem if (curImg.width > maxHeight) { curImg.height = Math.round(curImg.height * (maxWidth / curImg.width)); curImg.width = maxWidth; } } } curImg.src = src; if (i < nl.length - 1) { var nli = nl.item(i + 1); var nsrc = nli.getAttribute('src').toString(); nextImg.src = nsrc; } Effect.Appear('slideShowImg', { duration: 1 }); t = setTimeout(nextImage, 7000); } function imageLoad() {} function nextImage() { slideShowImg.removeChild(curImg); slideShowImg.setAttribute("style", "display:none"); if (i < nl.length - 1) { i++; image(); } else { i = 0; image(); } } if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { //XML Loaded, create the slideshow alert(xmlhttp.responseText); image(); } }); </script>
common-pile/stackexchange_filtered
Generating Weighted Choice of a String I am trying to write a code to generate random numbers of length l each consisting of a letter and its probability selection where the percentages sum to 100. For example : If I give Random(10,[("X",50),("Y",40),("Z",10)]) should give me "yxxzyyxzzx" i.e 10 random numbers in any fashion(it need not be of 50% of X and 40% of Y and 10% of Z,its just that the sum should be 100(50+40+10)). Similarly Random(5,[("X",50),("Y",40),("Z",10)]) should give me "XXYZZ" I tried the following code : from random import choice def Random(length,weightedchoice): string="" for count in range(length): string+=weightedchoice([("X",50),("Y", 40), ("Z", 10)]) return string Did you already look at the weighted random choice answers elsewhere here? A naïve way of doing it (I'm actually not sure how this would work statistically) is to simply fill up a list of 100 elements of X, Y, and Z objects and then pick out a number of elements at random. Is this what you want? You can obviously see that this is not very space-efficient at all, mostly wondering if I'm getting at the general idea of what you're looking for (I'd prefer this to be in a comment but I can't post comments yet).
common-pile/stackexchange_filtered
How do I pass and extract data in googlemaps api in my android app using java? I am new to android development but familiar with java. I want to send a request (containing coordinates of locations) to google maps api for distance matrix and later calculate the sum of distances for each point. The response from api is either in javascript or xml (i dont really know which one). How do i send the query in java and how do i extract the distances from the response? Try using seperate classes to send and recieve data through the Google maps API. try using JSON to send aaplication data. In order to use any thing like this (or that is owned by google etc.. ) You first need to setup a developer account at https://play.google.com/apps/publish/signup/ It does cost 25 dollars but in all honesty it's worth it as you get access to a lot of different things including the google maps api, if you're not interested in spending the $25 I would suggest looking into an alternative mapping api. If on the other hand you will spend the money they've got some great tutorials laid out in the documentation! A Google Maps Distance Matrix API request takes the following form: https://maps.googleapis.com/maps/api/distancematrix/output?parameters If you need more information, Refer to "Distance Matrix Requests". https://developers.google.com/maps/documentation/distance-matrix/intro#DistanceMatrixRequests You can also use the "getDistanceMatrix" that issues a distance matrix request. https://developers.google.com/maps/documentation/javascript/3.exp/reference#DistanceMatrixService
common-pile/stackexchange_filtered
append textbox value and checkbox value to a string I am having trouble figuring out how to append the values in the text field(exclude empty textboxes and corresponding checkboxes) and all the checked and unchecked values to a string in the order: name|T|F_name|F|F I have this code, I have been trying to figure out how to make it into a single string. On submit I will send this string to my controller. <input type="text" value="jim"> <input type="checkbox" checked="checked"> <input type="checkbox"> <input id="button_1" type="button" value="delete" ><br> <input type="text" > <input type="checkbox"> <input type="checkbox"> <input id="button_2" type="button" value="delete"><br> <input type="text" value="deb"> <input type="checkbox" checked="checked"> <input type="checkbox" checked="checked"> <input id="button_3" type="button" value="delete"><br> <input type="submit"> $(':input[type="text"]').each(function() { if($(this).val() != "") { nameString = $(this).val(); }); $(':checked').each(function() { }); UPDATE jsfiddle I used 2 for loops as I believe you want it results per line. check http://jsfiddle.net/s7JZF/7/ Note: I have added conditions to exclude row if the textbox is empty. var results = [], delimiter = '|'; $('table tr').each(function () { var line = []; $(this).find('input').each(function () { if (this.type == 'text') { //exclue blank textbox if (this.value == '') return false; line.push(this.value); } else if (this.type == 'checkbox') { line.push(this.checked?'T':'F'); } }); if (line.length) { results.push(line.join(delimiter)); } }); alert(results.join('_')); Thanks so much... this works like a charm !. What was the mistake in the jsfiddle code ? I'd suggest: var results = [], delimiter = '|', n, c; $('input[type="text"]').each(function(){ var that = $(this); n = this.value; if (n !== ''){ c = that.nextUntil('input[type="button"]').map(function(){ return this.checked == true; }).get().join(delimiter); results.push(n,c); } }); console.log(results.join(delimiter)); JS Fiddle demo. The above does rely, somewhat, on the structure of your HTML (specifically the radio elements coming before the button(s). If you need the true/false to be T/F, then instead use: var results = [], delimiter = '|', n, c; $('input[type="text"]').each(function(){ var that = $(this); n = this.value; if (n !== ''){ c = that.nextUntil('input[type="button"]').map(function(){ return (this.checked == true).toString().toUpperCase().slice(0,1); }).get().join(delimiter); results.push(n,c); } }); console.log(results.join(delimiter)); JS Fiddle demo. References: Array.join(). Array.push(). each(). get(). map(). nextUntil(). Object.toString(). String.toUpperCase() in the jsfiddle example your code works excellent, but your code in my code doesn't print the value of the checkbox. I am confused what is happening Then you need to work out the differences between your code and the linked demonstrations; are there any errors generated in the console? What're the differences in JavaScript, or the html? See the updated section. My actual html and your javascript function. The table is generated dynamically based on the resultset, so I am appending an integer at the end of the id to differentiate the item. For some reason the value of the checkbox is blank when I implement your code. Within the map() method add a console.log(this, this.value, this.checked); this should be the input element, this.value should be on or off, this.checked should be either true or false. I'm unsure as to why the input[type="text"] selector should work, while the checkbox-es don't. I see it empty.. I don't think its even getting into the map function I have updated your jsfiddle demo http://jsfiddle.net/s7JZF/4/ to table and not it doesn't work with the checkbox elements. Can you let me know why it happens You're almost there, but there are a few minor changes you'll have to make if I understand your code correctly... namestring = ""; $(':input[type="text"]').each(function() { if($(this).val() != "") { namestring += $(this).val(); $(this).find("input[type='checkbox']").each(function() { if($(this).is(":checked")) checked = T; else checked = F; namestring += checked; } namestring += "_"; } } //<Send namestring places> This code should do what you are looking for, but I have not tested it. EDIT: http://jsfiddle.net/PuQ4r/ Its not attaching the checkbox value. I would be needing the checkbox value to be either T or F based on if it checked or unchecked I would recommend using $(this).is(":checked") instead of checking the attribute value. @TJC its returning false everytime for me, though the textbox is checked and I am getting the checkbox value as false for 6 times. I have 2 rows and the value is nameFFFFFF_nameFFFFFF_ do you ever close your input elements? i dont see any tags in your code. this would throw off the code... also, i updated the if statement above. @TJC I see whats happening. In the example code, I have a total of 6 checkboxes, first row is empty and so are its corresponding checkboxes, the code returns the value of all the checkboxes. i think you need to namespace your HTML a little bit better, like put each row in its own div. This will make it a thousand times easier to iterate over it with jQuery. I have put it in a table with text field, checkboxes and delete button as column elements. http://jsfiddle.net/PuQ4r/ There's a js fiddle that does what youre looking for, minus the omission of any without a val. I wouldnt bother with a table, a div does what you need and is waaaaay cleaner. @TJC Can we skip the checkbox values for the rows that has empty text field. I am using your code and everytime I have to validate the string to remove the checkbox values from the string that starts with FF after underscore yeah definitely, its just an additional line. I updated the JSfiddle. http://jsfiddle.net/PuQ4r/ if this works for you, please mark it as answered. @TJC It's not working for me. See the case when the second text field is empty and the checkboxes are unchecked and the first text field has a value and one of the checkboxes is checked, this is the ans I get from your code jim|T|F_|F|F_deb|T|T_ I need to strip of the empty text box and checkbox values from the string and ans should be something like jim|T|F_deb|T|T_ if you set the same name for each of your inputs, values will be sent as a string array. so your server side controller (you didn't say which technology is) should pick em right away. checkbox without checked value wont be sent by default. you can 'preview' this doing a GET instead of POST form, so if you have : <input name="form1" value="yes" type="text" /> <input name="form1" type="checkbox" value="sure" checked /> <input name="form1" type="checkbox" value="noway" /> a GET form will give you : someAction?form1=yes&form1=sure which in turn will be a string array on your server. I know is not a direct answer, but a proper use of HTML input elements that may help in your situation.
common-pile/stackexchange_filtered
Call a function of PurchaseModel in to another model name SalesModel without loading PurchaseModel into SalesModel Hi Everyone I have a query regarding model of CodeIgniter. I have two model in my project model one is PurchaseModel and model second is SalesModel. In some operation i need a function from PurchaseModel. I can easily copy that function and use it in my SalesModel but i would like to know that "Can I call a function from PurchaseModel to use that function in SalesModel". It will be good if i can get answer in both ways like loading PurchaseModel into SalesModel(if possible) and without loading PurchaseModel to SalesModel. I am using CodeIgniter-3 version. The procedure differs depending on which version of CodeIgniter you're using. Unfortunately, you weren't clear about which version you're referring to. CI 3.x : Loading and using a codeigniter model from another model CI 4.x: Upgrade Models CI 4.x : $this->x = model('X'); I am currently using codeIgniter-3 version Does this answer your question? Loading and using a codeigniter model from another model @steven7mwesigwa The above question you mentioned gives me the answer of "with loading model into another model". That means we can't do without loading that model in another model. Yes, that's correct. Thank You Sir @steven7mwesigwa
common-pile/stackexchange_filtered
Cyborg death match: Make your move Found this one in my son's puzzle book. You are a cyborg in a death match with two other cyborgs. All three of you have identical blasters, and one single shot from these blasters will destroy any of you. You have a 33% (read as 1/3) chance of hitting your target per shot. The next cyborg has a 50% chance. The next cyborg will always hit his target. In this match the cyborgs take turns shooting, one shot per round. The weakest accuracy (you) goes first, on up to the strongest. If a cyborg is eliminated he won't get another turn. You are all logical and will try to win. What is your optimum first move? With this move what are your odds of being the final survivor? Dang. I searched but not good enough I guess. Different numbers tho. For a good explanation of the solution, see https://books.google.ca/books?id=fA3CAgAAQBAJ&pg=PA51&lpg=PA51&dq=martin%20gardner%20puzzle%20shoot%20first&source=bl&ots=QxCcl-suW0&sig=R1HgbRT8puvUu4hkHcAkzL_A7FY&hl=en&sa=X&ei=aYz7U6HfOIisyASZ_oDoDQ&ved=0CCYQ6AEwAQ#v=onepage&q&f=false
common-pile/stackexchange_filtered
Matlab num2str (A, format) function component-wise? I have a=[0.221354766 315.806415]; I want sth like (same fieldwidth) 0.2214 315.8064 I tried b=num2str(a) % b = % 0.2213548 315.8064 c=num2str(a,'%8.4f') % c = % 0.2214315.8064 d=num2str(a,'%8.7g') %d = %0.2213548 315.8064 Any suggestion? Tks you say you want the same field width but then show that you want the same number of decimal places, this is not the same thing, could you specify? Also do you want the output as strings or numbers? num2str seems to eat the leading whitespace. Try your examples with sprintf Tks. I tried sprintf('%8.4g',a), but it didnt work well. I want [__0.2214, 315.8064], and it seems the same number of decimal places and same field width (including the whitespace) can not be met at the same time @Steve I think you need an extra trailing whitespace to separate the numbers '%8.4f ' If I understand you correctly, you want the same number of decimal places? If this is the case, just leave off the first number in your format string: num2str([0.221354766 315.806415],'%.4f ') ans = '0.2214 315.8064' Tks.I want [__0.2214, 315.8064], and it seems the same number of decimal places and same field width (including the whitespace) can not be met at the same time. Your approch shows no 2 characters whitespace before 0.2214@MrAzzaman If you use sprintf instead, it should work, kind of. If you use sprintf('%8.4f',a), you'll get __0.2214315.8064, because your last number is 8 characters long. If you used 9.4 instead, you'd have a space between them, i.e. ___0.2214_315.8064. If you want to store these values as strings, then by all means use num2str(a, '%.4f'). It seems odd to take a numerical martrix and store all of the values as strings though, to just round the result use round m = round([0.221354766 315.806415], 4) >> m = [0.2214, 315.8064]
common-pile/stackexchange_filtered
Finishing a proof for commuting matrices $A,B$ implies $p(A)=B$ If $A$ has distinct eigenvalues $\lambda_1,\ldots,\lambda_n$ and there exists $B$ such that $AB=BA$, then there exists a polynomial $p(t)$ with degree at most $n-1$ such that $p(A)=B$. I have an argument, and I'm pretty sure it's almost complete, but it does not use the fact that $A$ and $B$ commute. Proof: Let $B$ have eigenvalues $\beta_1,\ldots,\beta_n$ (not necessarily distinct). Let $\vec{x_i}$ be the distinct eigenvector corresponding to eigenvalue $\lambda_i$. Since $\lambda_1,\ldots,\lambda_n$ are distinct, there exists a polynomial $p(t)=\sum_{i=0}^{n-1}a_it^i$ such that $p(\lambda_i)=\beta_i$ for all $i=1,2,\ldots,n$. Therefore, \begin{align*} p(A)\vec{x_i}&=a_0A^0\vec{x_i}+a_1A^1\vec{x_i}+\cdots+a_{n-1}A^{n-1}\vec{x_i} \\&=a_0\lambda_i^0\vec{x_i}+a_1\lambda_i^1\vec{x_i}+\cdots+a_{n-1}\lambda_i^{n-1}\vec{x_i} \\&=(a_0\lambda_i^0+a_1\lambda_i^1+\cdots+a_{n-1}\lambda_i^{n-1})\vec{x_i} \\&=p(\lambda_i)\vec{x_i} \\&=\beta_i\vec{x_i} \end{align*} Therefore, each $\beta_i$ is an eigenvalue of $p(A)$. So $B$ and $p(A)$ have the same eigenvalues. I have that $p(A)$ and $B$ are similar, but not that they are equal. How do I go about finish this proof? $A$ and $B$ have the same eigenvectors You implicitely use the fact that $A$ and $B$ commute, since you use the fact that they are diagonalizable in the same base $(x_1,\ldots,x_n)$. It is for this reason that you can write $p(A)(x_i)=p(\lambda_i)(x_i)=\beta_ix_i=B(x_i)$ since you know that $x_i$ is an eigenvector of $B$. The fact that the eigenvalues of $A$ are distinct implies that $B$ is diagonalizable in the same base than $A$. The problem is, that $A$ and $B$ not necessarily have the same eigenvectors (if they don't commute). But if they commute, you can choose a base, such that $A$ and $B$ both have JNF in that base (hence also have the same eigenvectors).
common-pile/stackexchange_filtered
Syllabify English words - kind of You're tasked with writing a program that syllabifies words in a string of text, by separating them with a hyphen. That would be a lot of work, so you want to skip some parts, mainly because you don't want to have a table of the pronunciations required for perfect algorithm. You also want to make it as short (and thus unreadable and unmaintainable) as possible as a revenge for being given this assignment. You have two choices: Write a program that takes the string from STDIN and outputs the result to STDOUT. Write a function that takes the string as a single parameter, and returns the result. Specification In this case, string means any string-like construct in your language of choice (byte arrays, character arrays, strings...). Vowels are a, e, i, o, u The string given has 1 <= n <= 10 words, where each has a length between 1 - 30 characters, inclusive.. Your output should be those words hyphenated. All letters are lowercase and words are always separated with spaces. Thus, the input consists of characters [a-z ] Apply rules in order of importance. When a word is divided, start again with the right half of the word. Rules for syllabification, in order of importance Two consecutive same vowels count as one (ie. feet has only one vowel, but beat and finding have two). Every syllable has exactly one vowel, thus there is one syllable for each vowel. If the whole word has only four letters, return it unchanged. (skip this for the rest of the word) If the word has only one vowel, return the word unchanged. If the word has two consecutive vowels, divide between them (ie. diaspora -> di-as-po-ra) When two or more consonants come between two vowels (same or different), divide after the first consonant (ie. sis-ter) unless the consonant part is ck, in which case divide the word after it. (ie. nickel -> nick-el) When a y comes between two vowels, divide the word after it (e.g. paying -> pay-ing). When one consonant comes between two vowels (same or different), divide before the consonant (ie. dra-gon) Return the word unchanged if no division could be done. I chose these rules, because they can be applied recursively without problems and require no pronunciation tables. Thus, they are not accurate, and for example rule #5 is often not correct. In general case though, it is. Example In: hello world Out: hel-lo world In: have a nice day Out: have a nice day In: pour some nickel and xenon there Out: pour some nick-el and xe-non the-re Are you sure about x-e-non? Reference for rule #4? @JanDvorak "When a word is divided, start again with the right half of the word.", followed by rule #6. I mean, shouldn't rule #4 only split between syllables? @JanDvorak Wait... Fixing! Edit: Fixed. The x rule was not general enough. The first rule has many exceptions: pogo, yoga, mama... Worth fixing or just stick with it as it is? What about 'y'? Sometimes effectively a vowel "happy", sometimes a consonant "yellow"? @DigitalTrauma I feel the more general case is to keep it as it is. @DigitalTrauma y is not a vowel as in letters. I want to keep pronounciation out of this. I don't think you fully fixed the problem Jan pointed out. At present, the word hemlocks would split hemlock-s. @PeterTaylor Ouch, you got a point there. Let's add a word to the specification. @PeterTaylor And thank you. In Finnish y is a vowel, so I forgot it for a moment. y is never two consonants, so I've taken the liberty of correcting that part of the spec. It's still dodgy for words like quicksilver, but it's not going to be perfect. There's one outstanding major problem, which is that when the same rule can be applied in more than one place you haven't given an importance tie-breaker. I think this question would have benefitted from some time in the sandbox. Rule #1 deals with four letters words. What about words with less than four letters? e.g. lua @DigitalTrauma They get prosessed normally, but rarely have two syllables. Back to the case of quicksilver, when we have more than just the ck between two vowels (cks) do we apply the ck rule? @Nexus We should, but I misworded it and after three answers, I don't feel comfortable changing it. How about some double (or more) consonant words like diphthong, knight, thrash, mathematics...? According to the 4th rule it'll be divided at the first consonant but I don't think dip-hthong, k-night, t-hrash, mat-he-ma-tics are reasonable solutions @LưuVĩnhPhúc Knight and trash don't change with these rules. The other cases are known as exceptions. I don't want to include any more special cases. An English teacher of mine from way back used the hand-under-chin technique. Place a hand half an inch under the chin as you speak, and each beat (touch of chin against hand) indicated a syllable. @WallyWest I believe that's hard to turn into code. Ruby, 144 bytes If we're going for unmantainable, how about a single giant regex? puts gets.split.map {|w| w.scan(/(^.{4}$|[^aeiou]*([aeiou])\2?((?=[^aeiouy]?[aeiou])|ck|[^aeiou]((?=.*[aeiou])|.*$)|$))/).map(&:first)*'-'}*' ' some output: echo "hello world" | ruby syllable.rb hel-lo world echo "have a nice day" | ruby syllable.rb have a nice day echo "pour some nickel and xenon in there" | ruby syllable.rb pour some nick-el and xe-non in the-re echo "diaspora dragon paying sister hemlock happy quicksilver" | ruby syllable.rb di-as-po-ra dra-gon pay-ing sis-ter hem-lock happy qu-ick-sil-ver Lua, 292 Lua might not have been the best language to do this in, but it works. It pretty much flows like the question asked. The rules are mainly in order with some optimizations: #2 is skipped (it isn't needed unless there is a one vowel word with "ck" at the beginning), and the ck and y rules are gone through before the rest of #4 and #6, which are combined. Since some vowels in the word need to be captured twice (after one hyphen and before another), that search is performed twice. i=io.read()v="([aeiou])"for s in i:gfind("%l+ ?")do if s:len()~=4 then s=s:gsub(v..v,function(x,y)if x==y then return x..y;end;return x.."-"..y;end)s=s:gsub("ck"..v,"ck-%1")s=s:gsub(v.."y"..v,"%1y-%2")for b=1,2 do s=s:gsub(v.."([^aeiou\-]?)([^aeiou\-]+)"..v,"%1%2-%3%4")end end io.write(s)end Ungolfed function checkEquals(x,y) if x==y then return x..y end return x.."-"..y end i=io.read() v="([aeiou])" for s in i:gfind("%l+ ?") do if s:len()~=4 then s=s:gsub(v..v,checkEquals) s=s:gsub("ck"..v,"ck-%1") s=s:gsub(v.."y"..v,"%1y-%2") for b=1,2 do s=s:gsub(v.."([^aeiou\-]?)([^aeiou\-]+)"..v,"%1%2-%3%4") end end io.write(s) end Test it here: http://ideone.com/g57TzA I don't have ruby, but it seems fine indeed. Bash+coreultils, 173 bytes I think I have all the latest rule changes: v=aeiou r="[$v])/\1-\2/g" s=s/\([$v] e="$s[^$v-])([^$v-]+$r " tr \ \\n|sed -r "/^([a-z]{4}|[^$v]*[$v][^$v]*)$/bx $s)($r ${s}ck)($r $e$e${s}y)($r $s)([^$v-]$r :x"|tr \\n \ Note the last character of the last line is a (space). I think this sufficiently satisfies "unreadable and unmaintainable" ;-) Takes input from STDIN. Mostly straight regex substitution. The first line of the sed expression matches for rules 1 and 2, then simply jumps to the :x label at the end of the expression. The trs at the start and end of the pipeline make the words newline-separated, so they are easier for sed to deal with. I was hoping to do and all sed answer, but this way is simpler and easier. Example: $ ./sylabify.sh <<< "diaspora nickel sister dragon hello world have a nice day pour some nickel and xenon there paying tricks quicksilver" di-as-po-ra nick-el sis-ter dra-gon hel-lo world have a nice day pour some nick-el and xe-non the-re pay-ing tricks qu-ic-ksil-ver $ Argh, I keep forgetting the rule #3 changed. It's fine.
common-pile/stackexchange_filtered
Are threading issues for C/C++ "system level programmers" significantly different from those faced by Java programmers? I'm looking for a development job and see that many listings specify that the developers must be versed in multithreading. This appears both for Java job listings, and for C++ listings that involve "system programming" on UNIX. In the past few years I have been working with Java and using its various synchronization mechanisms. In the late 90s I did a lot of C++ work, though very little threads. In college, however, we used threads on Solaris. My question is whether there are significant differences in the issues that developers in C/C++ face compared to developers in Java, and whether any of the techniques to address them are fundamentally different. Java obviously includes some nicer mechanisms and synchronized versions of collections, etc. If I want to refresh or relearn threading on UNIX, what's the best approach? Which library should I look at? etc. Is there some great current tutorial on threads in c++? The fundamental challenges of threading (e.g. synchronization, race conditions, inter-thread communication, resource cleanup), but Java makes thread much more manageable with garbage collection, exceptions, advanced synchronization objects, advanced debugging support with reflection. With C++, you are much more likely to have memory corruption and "impossible" race conditions. And you will need to write a lot more low-level thread primitives or rely on libraries (like boost) that are not part of the standardized language. The next C++ standard, due shortly, will address threading an synchronization quite close to boost library implementation. If you want to go for C++ threading, consider boost as a good start point. The terms "boost" and "C++ standard library" are becomming more and more merged. It is my understanding that boost was founded during a C++ standard meeting in order to encourage the development of libraries for C++. Look at pthreads and boost (the pthreads one was a random lijnk, but it looks ok as a starting point). At a high level the issues for Java/C/C++/ are the same. The specifics about how you solve the problem (functions to call, classes to create, etc...) vary language to language. Garbage collection makes programming threads that do not leak memory easier, and there are fancy things you can do to address the timing of the collections. Deterministic destructors make programming threads that do not spawn zombies easier, see ACM paper here This answer needs clarification. Okay, I added the adjective deterministic to destructors and linked to an ACM paper. It depends on what level you choose to work at. Intel TBB and OpenMP handle a lot of common cases from a pretty high level. Posix threads, Windows APIs, and portable libraries like Boost threads bring you closer to the same level as primitives in Java. C++0x threading (especially with acquire and release memory barriers) allow you to go to an even lower level for more control and complexity than Java offers (marking a variable volatile in Java gives it both an acquire and a release memory barrier, but in Java you can't ask for just the acquire or just the release barrier; where in C++0x you can). Please note that C++0x's threading model is intentionally low level with the hope that people will build things like TBB on top of it and the next time the standards committee meets they'll be able to figure out which of those higher level libraries and toolkits work well enough to learn from. Regardless of the programming language being uses, the idiosyncrasy of thread are common. For instance even across OS the POSIX threads & WIN32 threads have same set of logical idiosyncrasies, though the API calls & native implementation WRT underlying hardware/kernel might change, but to system programmers the logical thinking about threads & how to make them work as expected & in achieving this is the most hardest part. This is even true when coming to programming languages. If you really understand the concept of threading & thread synchronization you are good to go & use them in any programming languages you like. Since these programming languages provide syntactic sugars on top of the native thread/thread synchronization implementation.
common-pile/stackexchange_filtered
Unable to fetch from controller - React/asp.net core Web API When I try to fetch data from the UserController I get returned Html for some reason. It is the index.html file under the React > Public folder. It should be returning the Users from the UserController. I have a React frontend app which I have added ASP.NET Core Web API backend. https://learn.microsoft.com/en-us/visualstudio/javascript/tutorial-asp-net-core-with-react?view=vs-2022 The browser URL is https://localhost:3000/ The backend, ASP.NET Core Web API, App URL is (found under Properties > Debug) https://localhost:7015;http://localhost:5015 This is what is returned <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="/logo192.png" /> <!-- manifest.json provides metadata used when your web app is installed on a user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/ --> <link rel="manifest" href="/manifest.json" /> <!-- Notice the use of in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML. Unlike "/favicon.ico" or "favicon.ico", "/favicon.ico" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm run build`. --> <title>React App</title> <script defer src="/static/js/bundle.js"></script></head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <!-- This HTML file is a template. If you open it directly in the browser, you will see an empty page. You can add webfonts, meta tags, or analytics to this file. The build step will place the bundled scripts into the <body> tag. To begin the development, run `npm start` or `yarn start`. To create a production bundle, use `npm run build` or `yarn build`. --> </body> </html> My fetch code - I am returning .text() instead of .json() because obviously it results in an error because json is not returned but html. useEffect(() => { const fetchUsers = async () => { const result = await fetch('https://localhost:3000/api/user'); const usersText = await result.text(); console.log(usersText) } fetchUsers(); }, []) If I return .json() instead of .text() I get the following error, because obviously html is returned. Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 UserController.cs using Microsoft.AspNetCore.Mvc; namespace ASPNETCore_Backend.Controllers { [Route("api/[controller]")] [ApiController] public class UserController : ControllerBase { [HttpGet] public ActionResult<IEnumerable<User>> List() { // in real life - retrieve from database var users = new List<User>{ new User { Id = 1, Name = "Jon Hilton", Summary = "36 / Lead Software Developer" } }; return Ok(users); } } public class User { public int Id { get; set; } public string Name { get; set; } public string Summary { get; set; } } } Update - I have added AddCors() to Program.cs builder.Services.AddCors(options => { options.AddPolicy("CORSPolicy", builder => { builder .AllowAnyMethod() .AllowAnyHeader() .WithOrigins("https://localhost:3000"); }); }); code above... app.UseHttpsRedirection(); app.UseCors("CORSPolicy"); // Added app.UseStaticFiles(); code below... and updated the fetch code to const result = await fetch('https://localhost:7015/api/user'); but no luck, still get an error, though at least it doesn't return the Html file. GET https://localhost:7015/api/user 404 What is the error? Well, if I return .json() instead of .text() I get "Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0" because the Html file is returned instead. How do you run the project? It seems like your .NET backend is returning the react public HTML file The "error" is that I have no idea why it's returning this html file, when it should be returning the Users from the UserController. @evolutionbox how do I run the project? I just press ctrl+f5 in visual studio. I mean, I followed the Microsoft tutorial in how to set it up, how to connect React with ASP.NET Core Web API. Looking at other resources https://www.c-sharpcorner.com/article/fetching-data-using-web-api-in-react/ it seems the two things are different projects? One for the API, the other for react? Yes, two different projects, if I'm not mistaken. It's the joining of React Frontend with ASP.NET Core Web API backend. So does pressing Ctrl+F5 start two projects? Yes. The backend starts up before the frontend. https://learn.microsoft.com/en-us/visualstudio/javascript/tutorial-asp-net-core-with-react?view=vs-2022 Do they run on different ports? Maybe you meant localhost:3001/api/user? I think the ports are set up correctly, otherwise I get the error "GET https://localhost:3001/api/user net::ERR_CONNECTION_REFUSED" and "Uncaught (in promise) TypeError: Failed to fetch" I'm not convinced. https://learn.microsoft.com/en-us/visualstudio/javascript/tutorial-asp-net-core-with-react?view=vs-2022#set-the-project-properties defines in step 2 screenshot that APP URL has two values. The two ports displayed for me like in the screenshot is https://localhost:7015;http://localhost:5015 If I use 7015 in the fetch method. I also get the error "Access to fetch at 'https://localhost:7015/api/user' from origin 'https://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled." as well as the errors above but for :7015 My guess (that's what it is) is that react is on one, and the API is on the other. Try visting /api/user on both? I just get an additional CORS policy "error". could you add the CORS configuration in Startup.cs to your question? I added AddCors( .... .WithOrigins("https://localhost:3000"); ) and using fetch('https://localhost:7015/api/user'); Yet still get error. "Failed to load resource: the server responded with a status of 404 ()" I'll update my question to include what I changed. Firstly, you should make sure if the api url is correct, using tools like postman or using any browswer to call https://localhost:7015/api/user and make sure the api can be accessed directly. And I think you can try builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin(); for test instead because my react app has a default url http://localhost:3000 but not http. At last, check if your react code is right: componentDidMount() { fetch('https://localhost:44304/api/user') .then(response => response.json()) .then(data => { console.log(data); }); } it worked in my side ============================Update=================================== Follow the tutorial you provide, and do the first 3 steps : Then I get a solution within 2 projects(one react and one asp.net core 6 web api project) Adding a controller with your code then I can access the api with url https://localhost:7119/api/user in the browser. Modify the App.js file in the react project, adding the fetch method in the componentDidMount() function. Then start both the project. I called 'https://localhost:7015/api/user' in the browser and got "This localhost page can’t be found No webpage was found for the web address: https://localhost:7015/api/user HTTP ERROR 404" Browser console: "Failed to load resource: the server responded with a status of 404 ()" "crbug/1173575, non-JS module files deprecated." then how you create your api project? I test in my side with a newly created asp.net core web api project, and create a new controller with your code. And I can access the api with pressing f5 in the visual studio. The same way you did, I believe. I just followed the Microsoft tutorial https://learn.microsoft.com/en-us/visualstudio/javascript/tutorial-asp-net-core-with-react?view=vs-2022 I test the tutorial in my side, and I followed all the steps before this section, now I have 2 projects in one solution, then I create a new controller and copied your code. Then I start the application, and I can call the api successfully. just fix your action route, API controller doesn't support any REST [Route("~/api/user/getList")] public ActionResult<IEnumerable<User>> List() and make the same fetch route htt.../api/user/getList Happy new year sir, your reputations increased quickly. And about this case, I test in my side followed the tutorial provided by OP and it really worked for me, so if it's necessary here to change the Route for the method? Thanks for your reply in advance. @TinyWang. Happy New Year to you too. It depends on how many actions OP is going to have in the controller. If it is only the one as it is now , he can put attribute "~/api/user" instead of "~/api/user/getList " and be happy. But I don't think that it makes much sense to have just a list of user. I guess he is going to have CRUD at least, so it is better to start to give the meaninigfull names for the routes.
common-pile/stackexchange_filtered
Using CrossWalk for making a Call using WebRTC The call is working perfectly fine for the first time. But after that it freezes just before connecting to WebRTC, this is currently happening only on Samsung Galaxy S5 out of my 5 devices that I test upon. Other devices are: Motorola Moto G2 Nexus 5X Samsung Grand Samsung S2 (Genymotion emulator) Please point me to something that can help... Sorry, but I don't have the logs for this error I am from Crosswalk team. We are maintaining some basic tests for WebRTC on Crosswalk and haven't find similar issues. If you can share your test page, it could accelerate the problem fixing. Another way is to file bugs a bug JIRA where we use to track bugs, https://crosswalk-project.org/jira/secure/Dashboard.jspa Hi! Welcome to StackOverflow. We're a little different from other sites; this isn't a discussion forum but a Q&A site, where we reserve the answer space for answers. Please check out our short [tour]. This "answer" is more appropriate as a "comment" in the Question.
common-pile/stackexchange_filtered
Deserialize JSON Object C# with Newtonsoft I need to deserialize the following: {"result":{"success":true,"value":"8cb2237d0679ca88db6464eac60da96345513964"}} to a C# object using Newtonsoft.Json WebClient wc = new WebClient(); var json = wc.DownloadString(url); Worker w = JsonConvert.DeserializeObject<Worker>(json); Here is the class code: public class Worker { [JsonProperty("success")] public string success { get; set; } [JsonProperty("value")] public string value { get; set; } } The code does not error out, but the success and value are null. You're missing the outer object. public class Worker { [JsonProperty("result")] public Result Result { get; set; } } public class Result { [JsonProperty("success")] public string Success { get; set; } [JsonProperty("value")] public string Value { get; set; } } Thanks! Figured "result" needed to be serialized. Also you may want to consider capitalizing your property names, since that is the standard convention in C#. Since you're already controlling the JSON serialization with attributes, it won't affect that. I edited my answer to show what I mean. @luksan +1 What if I want the C# class to contain three fields: Result, Success and Value? When I set the JsonProperty attribute to "result.success" or "result.value" it returns null. Is it possible? @Anar I'm not sure I understand. Maybe try creating a new question on here with example code. My fault, sorry. I wanted to ask whether you could specify JsonProperty value two levels deep, hence, "result.success". It does not work that way, maybe you know a way. Yeah, I don't think you can do that. You would need to use two separate classes like in this example. I'm not familiar with that library, but success and result look to be both properties of the object "result" Have you tried [JsonProperty("result.success")]? Edit: Well, regardless it looks like a scoping issue. After viewing the documentation, this is my new suggestion: public class Result{ [JsonProperty("result")] public Worker result { get; set; } } then Json.Convert.Deserialize<Result>(json) instead. Good thought... still Null. You don't need any class and can make use of dynamic keyword string json = @"{""result"":{""success"":true,""value"":""8cb2237d0679ca88db6464eac60da96345513964""}}"; dynamic dynObj = JsonConvert.DeserializeObject(json); Console.WriteLine("{0} {1}", dynObj.result.success, dynObj.result.value);
common-pile/stackexchange_filtered
Can we configure users in Jenkins to only view build history for jobs submitted by them We have 3 users in Jenkins Admin User - Has the complete access of Jenkins Developer - Has complete access to create/edit/view/delete Jobs Tester - Has access to only view/run Jobs We want to build a capability where Developer & Tester should be able to only view build history of jobs submitted by him/her but Admin should be able to view build history of jobs submitted by all users. Please guide as I am new to Jenkins.
common-pile/stackexchange_filtered
Checking from a preemptive evaluation whether a main evaluation is ongoing How can I programmatically check from a preemptive evaluation whether a main evaluation is currently ongoing? I need a function mainEvaluationOngoingQ[] so that Button["Evaluating?", Print@mainEvaluationOngoingQ[], Method -> "Preemptive"] will print True only if a main evaluation is ongoing. If you control the launch of the main evaluation process, then a very simple way is to wrap your code in a dynamic environment (Block), which would set some flag: mainEvaluationOngoingQ[] := TrueQ@mainEvaluationQ Block[{mainEvaluationQ = True}, Do[i^2, {i, 1, 10^8}]] You can automate this by creating an environment: SetAttributes[withMainEvaluation, HoldAll]; withMainEvaluation[code_] := Block[{mainEvaluationQ = True}, code] You can further automate this with $Pre, if needed: $Pre = withMainEvaluation. +1 Very nice. I hope his main evaluations aren't triggered by buttons with Method->"Queued". Any way to cover those cases too? @Rojo If buttons are generated in the same session, then I'd write a preprocessor that would dynamically generate code where the body of the button is wrapped in withMainEvaluation. If not, one can probably write code which would pre-process a notebook and change that at the box level. Other than that, I don't know how to do this - this may need some lower-level stuff. I'm very late with this, but isn't that question superfluous: With Method->"Queued", the evaluation is queued to be evaluated using the main link, so there by definition isn't a (-nother) main evaluation running, and mainEvaluationOngoing always returns False, which is correct when interpreted as "is another main evaluation ongoing". Or am I missing something? @AlbertRetey Yes, but IIRC, the question was about how to determine whether or not the main evaluation is ongoing, from the preemptive evaluation, not from the queued one. The following works with Mathematica <IP_ADDRESS>: Button["Evaluating?",Print@(Drop[Stack[],-7]!={}),Method->"Preemptive"] However the -7 here is an empirical factor which removes all those entries generated from executing the button code itself; it changes depending on the exact form of the code the Stack[] is embedded in, and might even depend on the Mathematica version (I don't think the inner mechanics of Button is documented, let alone guaranteed never to change).
common-pile/stackexchange_filtered
Link with javascript:window.location Any idea how to click a link with the following criteria: <a href="javascript:window.location='/app/exe/add.do?Id=8&val=1&callerURL=details'; I tried several variations to the following examples, but can't seem to get it to work. #$ie.a(:href => "http://app.com/app/exe/add.do?Id=8&val=1&callerURL=details").click #$ie.link(:xpath,"//a[contains(@href='/app/exe/add.do?Id=8&val=1&callerURL=details')]/").click #$ie.link(:href => "javascript:window.location='/app/exe/add.do?Id=8&val=1&callerURL=details'").click #$ie.execute_script(:href => "javascript:window.location='/app/exe/add.do?Id=8&val=1&callerURL=details'").click $ie.link(:xpath,"//a[contains(@href='/app/exe/add.do?Id=8&val=1&callerURL=details')]/").fire_event('onclick') Why don't you put the url in the href attribute of that link? :) are you trying to trick the user? Not sure what you mean. For the first example, i tried $ie.link(:href =>....) etc.. with the href attribute. There isn't any other properties to use. If you try to match the href by a string, it has to be an exact match. The variations you tried are missing some characters at the end. Try: $ie.link(:href => "javascript:window.location='/app/exe/add.do?Id=8&val=1&callerURL=details';").click Note the '; were missing before. Though there must be something better to identify the link with. Perhaps its text or its parent elements. Going based on this href, which is probably dynamic given the Id=8 part, is likely to be brittle.
common-pile/stackexchange_filtered
Copy files if directory does not exist on target Can you copy files (using rsync ideally but any scriptable tool considered) from server A to server B skipping directories that already exist on the target, and any files they contain? Server A FEED --CUSTOMER1 ----feed_12414.xml --CUSTOMER2 ----feed_6583.xml --CUSTOMER3 ----feed_97334.xml Server B FEED --CUSTOMER1 ----feed_new.xml --CUSTOMER5 ----feed_new.xml Result should be: Server B FEED --CUSTOMER1 ----feed_new.xml --CUSTOMER2 ----feed_6583.xml --CUSTOMER3 ----feed_97334.xml --CUSTOMER5 ----feed_new.xml rsync --ignore-existing --recursive /source_dir /destination_dir is this what you mean ?
common-pile/stackexchange_filtered
Debug Assertion Failed CDialog I have an error in my c++ project. If I clicked "Cancel" or "OK" or "X" buttons program is crashing and display an error like the screenshot. What could be problem? Here is full code ; http://pastebin.com/54DfqrDb void CSettingDlg::OnBnClickedCancel() { CDialog::OnCancel(); } void CSettingDlg::OnBnClickedOk() { CDialog::OnOK(); } Publish the entire code of your dialog class. Your stack is probably corrupted somewhere else. Also generally you should not have custom OK and Cancel handlers as you have virtual functions OnOK() and OnCancel() that you should override in your dialog class. Where did you use your dialog? In InitInstance or somewhere else? This code is 476 row, how can publish it? Tell me a way for publish it please. @Mykola BOOL CSettingDlg::OnInitDialog(){CDialog::OnInitDialog();} As you did in qestion copy & paste And you should only post the method wich uses that dialog Here is published http://pastebin.com/54DfqrDb also post the method wich creates dialog and call DoModal() I suppose you did not use modal dialogs? yeap I used modal dialogs and this dialog is a modal. could you please post the code wich creates and shows your dialog (not dialog class) here -> http://pastebin.com/cu9G5vmU Not successfull architecture was selected. Its hard to delerminate were the error occures. Impressive internationalisation failure in this dialog. I fixed this problem. If I declare already don't working a class variable this problem is occurred. Solution : //CZipArchive m_ZipArchive; //this class variable is don't working for me
common-pile/stackexchange_filtered
Angular 6: HttpErrorResponse SyntaxError: Unexpected token s in JSON I am posting a request and I am suppose to receive a 'success' string back as response. I am getting an HttpResponseError with the following information posted in the image below. PurchaseOrderService postPurchaseOrderCustom(purchaseOrderCustom: PurchaseOrderSaveCustom) { const url = `${this.localUrl}purchaseOrderCustom`; return this.http.post<String>(url, purchaseOrderCustom, {headers: this.header}) .pipe( catchError(this.handleError('postPurchaseOrderCustom', 'I am an error')) ); } PurchaseOrderComponent this.purchaseOrderService.postPurchaseOrderCustom(purchaseOrderCustom).subscribe( response => { console.log("Testing", response); }, error => { console.error('errorMsg',error ); } The way I am doing it is the same way its done in the documentation. Do point out to me what I am doing wrong. This is angular error realted to you api respond ,http object by default try to parse you api respond it 's seen just plain text this why the throw this cand in error ,try this in you console JSON.parse('Hi') if you don't get my pont Either wrap your response in quotes at the backend, or change the responseType to 'text' in the front end @user184994 what do you mean by wrap in quotes in the backend, it is already in quotes and that makes it a string. That is if I am getting you write. And what happens if you are receiving an object back Yep, but you need extra quotes, something like `""success"". If you receiving a valid JSON object back, there won't be any issues, it depends on what you mean when you say "an object" @user184994 Im using springboot as my backend and usually when you send an object it gets parsed as Json and is transformed to the corressponding Object in Angular. Thats if Im correct. So why is it different from a string object. This related to your api respond type ,success is not valid json format,by default HttpClient is expected json response type and try to parse it later . You can solve this by set the respond type to text like this return this.http.post<String>( url, purchaseOrderCustom, { headers: this.header, responseType: 'text' } ) .pipe( catchError(this.handleError('postPurchaseOrderCustom', 'I am an error') )); I had to add as 'json'. before it worked so if you can edit your answer so I accept it. {headers: this.header , responseType:'text' as 'json'}) did you add this to make it work responseType:'json' this is what I did {headers: this.header , responseType:'text' as 'json'}) . just adding text didnt work for me. And from discussions from Github people added that to make it work did you use Http or HttpClient ? I use HttpClient, do you by the way know why this is as operater is related to typescript if you remove it will work ,try this in typescript playground http://www.typescriptlang.org/play/index.html ,let c = {headers: '' , responseType:'text' as 'json'} if you check the chrome network panel you will see that the responseType is text,you just change the default respond type from json to text as I said in my answer Albarmaw sorry didnt get what you meant , but when I remove the as json I get a squiggly line error and it doesnt compile till I add the as json. do you know the usage of as operator ? let b = '10' as number this mean '10' type is number but the b will be '10' this just related to typescript but the value still '10' but typescript will think b type is number thiss responseType:'text' as 'json' you just tell typescript the type of respondType is litiral value of 'json' but the value will be 'text' @user3701188 hope you got my point so {headers: this.header , responseType:'text'} will work and the respond type is text so will not parse your respond and you will not got the error that you use to have I do understand, but the problem here is your code gives me an error in the file, it give a red squiggly error and it doesnt compile when I do it the way you suggested and when I add the as json it works fine and I dont get an error in my console again This is what it says Argument of type '{ headers: HttpHeaders; responseType: "text"; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: Ht...'. Types of property 'responseType' are incompatible. Type '"text"' is not assignable to type '"json { headers: HttpHeaders; response Type: "text"; } you separate the property with ; semicolon and this is wrong just look to my answer it is , comma it is the error that shows that my codes are exactly as your answer and it gives the error. I have updated a picture in the main question take a look at it and also take a look at the discussions provided in Github. https://github.com/angular/angular/issues/18586 as the github issues show this consider a bug but it 's close and it 's since 12 month you may consider update your angular version if it 's old @user3701188 These are my angular dependencies so I think I am using the latest version "@angular/animations": "^6.0.2", "@angular/common": "^6.0.2", "@angular/compiler": "^6.0.2", "@angular/core": "^6.0.2", "@angular/forms": "^6.0.2", "@angular/http": "^6.0.2" so i had to remove the cast that is in order to make your way work, can you also take of the cast so I get to approve the answer Like it has already been said, this has everything to do with the response coming from your server. In my case, I had a Spring Boot application that returned this: return new ResponseEntity<>("Your SSN was generated successfully", HttpStatus.OK); and this was the response I was getting on the Angular end: {error: SyntaxError: Unexpected token Y in JSON at position 0 at JSON.parse (<anonymous>) at XMLHtt…, text: "Your SSN was registered successfully."} So what I did was create a custom CustomHttpResponse class in my Spring Boot application and then changed the code in my controller to this: ... CustomHttpResponse customHttpResponse = new CustomHttpResponse(); customHttpResponse.setMessage("Your SSN was registered successfully."); customHttpResponse.setStatus(HttpStatus.OK.value()); return new ResponseEntity<>(new Gson().toJson(customHttpResponse), HttpStatus.OK); } Now I'm getting this: {message: "Your SSN was registered successfully.", status: 200} message: "Your SSN was registered successfully." status: 200 Essentially, this error occurs when Angular is expecting JSON but gets something else instead I was also facing same issue while getting pdf data buffer in response and I handled it in following manner, it's working for me server side pdf.create(output, options).toBuffer((err: any, buffer: any) => { if (err) reject(err); response.type('pdf'); response.send(buffer); }); in Angular Service downloadPdf(dateRange, labs){ return this.httpClient.post(url, data,{responseType:'blob'}); } And in Component.ts file downPdf1(){ this.analyticService.downloadPdf(this.dateRange, this.labs).subscribe( res => this.extractPdf(res), (error:any) => throwError (error || 'Server error') ); } extractPdf(res){ let myBlob: Blob = new Blob([res], {type: 'application/pdf'}); var fileURL = URL.createObjectURL(myBlob); window.open(fileURL); }
common-pile/stackexchange_filtered
CLion and Qt Framework So I figured out how to get Qt Framework working with CLion, but I don't have Qt Designer in CLion. How can I make a GUI in CLion using Qt Framework? Every tutorial i've seen uses Qt Creator so I cannot get an answer. The only Qt development I've seen (I typically work on backend stuff) outside Qt Creator/Designer is either straight commandline with a make tool and a compilation tool (typically qmake and jom), or Visual Studio. Qt used to have plugins for Visual Studio 2013, but IIRC, their usage was deprecated, then completely dropped for Visual Studio 2015. I'd be very interested in a general solution to this answer, but knowing how it works with CLion would certainly help. Well it is quite simple. CLion depends on CMake so you have to link it by using CMake. Its a little hard to explain... Is using jom after CMake valid? I've never tried. Or is there a preferred set of tools to use? CLion doesn't have any GUI designer tool. I worked with QtCreator and then with Qt5 libraries on Clion. For a better understanding see my project at https://github.com/FraScandiffio/Timer_Laboratorio Search for MyTimerApp.ui .h .cpp files. 1)You need a .ui file: it was created for me by QtCreator: when i worked on Clion i just copied the file into my project folder and add in the SOURCES_FILES. You can download it from my project: it's the MyTimerApp.ui file but you have to change just 3 words to adapt it to your needs. Re-name the file with the name that you prefer. Now open the file with a text editor and replace all the "MyTimerApp" with the name that you have just chosen. 2)Add this in your Cmake.txt (the explanation of why you have to do it is here) cmake_minimum_required(VERSION 3.3) project({your_project_name}) set(CMAKE_AUTOMOC ON) set(CMAKE_INCLUDE_CURRENT_DIR ON) set(CMAKE_AUTOUIC ON) set(SOURCE_FILES main.cpp MyApp.ui #...) #... the rest of your cmake.txt ... Download also MyTimerApp.cpp and MyTimerApp.h files. (i suggest you to create a new .h file and paste into them the code instead of refactor my file) Open it and replace "MyTimerApp" whit the same name you have chosen before. obviously add them into the SOURCE_FILES list. In the main.cpp type #include "nameyouhavechoosen.h" #include "QApplication" #include "QWidget" int main(int argc, char *argv[]){ QApplication app(argc, argv); QWidget* MyWidget= new {nameyouhavechoosen}; MyWidget->setGeometry(500,200,617,416); app.setActiveWindow(MyWidget); MyWidget->show(); return app.exec(); } If you run it you should see a very simple window. In my github repository you can find how to create buttons/timer and more. Anyway Qt documentation is great for learning.
common-pile/stackexchange_filtered
How to add a character in a string by checking the delimiter? I have a string in my program where in which it need to be altered with another string value before a "/". Source String : qos-tree/output_rate Target String : qos-tree-2/output_rate #include <stdio.h> #include <string.h> void append(char* s, char c) { int len = strlen(s); s[len] = c; s[len+1] = '\0'; } int main(void) { char str[256] = "qos-tree/output_rate"; char c = "a"; append(str, c); printf("%s\n", str); return 0; } This is what i have done so far,I think the logic is wrong here.Can anyone guide me to correct it? Once the execution is completed the source string should have a "-2" before the "/" Nothing in your "logic" inserts "-2". Also, nothing in your logic looks for a slash. Consider trying fixing both first. If you want to do it in-place, find the /, memmove everything after 2 chars to the right and add your "-2". Protip: Start by finding the '/'. void insert_before_ch(char *s, const char *ins, char c){ char *p = strchr(s, c); if(p){ size_t len = strlen(ins); memmove(p + len, p, strlen(p)+1); memcpy(p, ins, len); } } int main(void){ char str[256] = "qos-tree/output_rate"; insert_before_ch(str, "-2", '/'); printf("%s\n", str); return 0; } In your attempt, you don't look for a slash and I do not see any "-2" anywhere. Try this instead: #include <stdio.h> #include <string.h> void append(char* s, char del, char* substring) { char origin[256]; strcpy(origin, s); int i = 0, j = 0, z = 0; for(; origin[i]; ++i) { if(origin[i] != del) { s[j++] = origin[i]; } else { for(; substring[z]; ++z) { s[j++] = substring[z]; } s[j++] = origin[i]; } } s[j] = '\0'; } int main(void) { char str[256] = "qos-tree/output_rate"; char del = '/'; char* substring = "-2"; append(str, del, substring); printf("%s\n", str); return 0; } The logic is that inside the function we use origin array to remember the actual contents of the array and then we copy from origin to s (which is the actual array of main()). If we find our delimiter del, then we copy the substring in that position and continuing with copying. Note that the length of the array should be enough to store the resulted string. In this case, it is. Note: this code will not work if the array is not long enough. Of course @iharob. Good point though for beginners, I should put it as an edit. Thanks, nice answer by the way, +1. first of all thist char c = "a" should be replace with this char c = 'a'; because c is a character not a string as for your problem I didn't realy see the relation between what your code is doing with what you said you wanted to do , but here a piece of code to achieve what , I think , you want to do : #include <string.h> #include <stdio.h> #include <stdlib.h> void append(char* str , char c) { char firststr[60]; char therest[30]; strcpy(firststr , strtok(str , "/")); strcpy(therest , strtok(NULL , "/")); strcat(firststr , &c); strcat(firststr , "/"); strcat(firststr , therest); strcpy(str , firststr); } int main(void) { char str[60] = "qos-tree/output_rate"; char c = '2'; append(str , c); printf("%s\n" , str); } there you go I think this is what you wanted to do you can modify the array sizes to fit your needs I think you should make your function work with dynamic allocation, because inserting characters into the string will make the resulting string larger, so this is my suggestion #include <stdlib.h> #include <stdio.h> #include <string.h> void insert(char **str, char chr, unsigned int position) { int length; char *ptr; if (str == NULL) return; length = strlen(*str); if (position >= length) return; ptr = realloc(*str, 2 + length); if (ptr == NULL) return; *str = ptr; memmove(ptr + position + 1, ptr + position, length - position + 1); ptr[position] = chr; } int main(void) { const char *source = "qos-tree/output_rate"; size_t length = strlen(source); char *str = malloc(1 + length); if (str == NULL) return -1; strcpy(str, source); insert(&str, '-', 8); insert(&str, '2', 9); printf("%s\n", str); free(str); return 0; }
common-pile/stackexchange_filtered
How to vertically align text Blocks on the left in flutter I am trying to align three Text() on the left side of the page. These texts are inside Padding() blocks and these inside a Column(). Here is how it looks: And here is the code: Column( mainAxisAlignment: MainAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: <Widget>[ Padding( padding: EdgeInsets.only(top: 78), child: Text( 'Matches', style: TextStyle( color: Colors.white, fontSize: 44, fontWeight: FontWeight.bold, ), ), ), Padding( padding: EdgeInsets.only(top: 20), child: Text( 'Today\'s Live Matches', style: TextStyle( color: Colors.white, fontSize: 20, fontWeight: FontWeight.bold), ), ), Column( mainAxisAlignment: MainAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: <Widget>[ Padding( padding: EdgeInsets.only(top: 20), child: Text( 'LIVE MATCH', style: TextStyle( color: Colors.white, fontSize: 12, fontWeight: FontWeight.bold), ), ) ], ) ], ) crossAxisAlignment To align Text Refering to: Text class The Text widget has a textAlign property. just add textAlign = TextAlign.left to your Text widget Refer here for more textAlign options To align column Refering to: Column class The column has a crossAxisAlignment property which is default to center add crossAxisAlignment = CrossAxisAlignment.start to your Column widget Refer here for more crossAxisAlignment options Try this crossAxisAlignment: CrossAxisAlignment.start
common-pile/stackexchange_filtered
In Delphi connecting to a database in runtime I'm busy with a project where the database must be embedded in such way that if it should be copied over to any computer you can run it without establishing the connection to the database again. I have tried this : path:=extractFilePath('MEDA_p.exe'); dmMEDA.conMeda.ConnectionString:='Provider=Microsoft.ACE.OLEDB.12.0; Data Source= '+path+'dbMEDA.accdb; Persist Security info=false'; dmMEDA.conMeda.Connected:=true; But keep getting 'Stack overflow' errors. Or if I Do this: dmMeda.conMEDA.open; path:=extractFilePath('MEDA_p.exe'); dmMEDA.conMeda.ConnectionString:='Provider=Microsoft.ACE.OLEDB.12.0; Data Source= '+path+'dbMEDA.accdb; Persist Security info=false'; dmMEDA.conMeda.Connected:=true; dmMEDA.conMeda.close; I get 'Operation is not allowed when the object is open'. Any help? Update: I have tried some of the suggestions, like adding double quotes and using connection and setting it false then afterward true, but when I try and make the tables (active) true I get another 'Stack overflow error' dmMEDA.tbllogs.Active:=true; What should I do? Have you opened the connection in the IDE? If so, set it to active = false in the IDE before you run the program. I don't know what that path variable is for, but if you're intending to use it as a path to writeable data, it's an accident waiting to happen. Don't assume you can write to the folder where the app is located. Your sequence of events is wrong in the second block. You need to close the connection, make the change, and then open the connection again. dmMeda.conMEDA.Connected := False; path:=extractFilePath(Application.ExeName); dmMEDA.conMeda.ConnectionString:='Provider=Microsoft.ACE.OLEDB.12.0; Data Source= '+path+'dbMEDA.accdb; Persist Security info=false'; dmMEDA.conMeda.Connected:=true; Note that if the path to the application can contain spaces, you may need to surround it with double quotes as well. dmMeda.conMEDA.Connected := False; path := extractFilePath(Application.ExeName); dmMEDA.conMeda.ConnectionString := 'Provider=Microsoft.ACE.OLEDB.12.0; Data Source= "' + path + 'dbMEDA.accdb"; Persist Security info=false'; dmMEDA.conMeda.Connected := True; The path does require double quotes, I've had such an issue in the past.
common-pile/stackexchange_filtered
Getting OSError: [WinError 6] The handle is invalid im running my function with multiprocessing implementation def assign_task(self, module, command): logging.debug("Assigning task for {0}".format(command._get_module_id())) if self.queue is None: self.queue = JoinableQueue() if self.processes is None: self.processes = [Process(target=self.do_execute) for i in range(self.max_process)] for process in self.processes: process.daemon = True process.start() logging.debug("Queuing message {0}".format(command._get_module_id())) self.queue.put((module, command)) def do_execute(self): # the code but getting this error Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\muhammad.aqshol\AppData\Local\Programs\Python\Python38\lib\multiprocessing\spawn.py", line 107, in spawn_main new_handle = reduction.duplicate(pipe_handle, File "C:\Users\muhammad.aqshol\AppData\Local\Programs\Python\Python38\lib\multiprocessing\reduction.py", line 79, in duplicate return _winapi.DuplicateHandle( OSError: [WinError 6] The handle is invalid Am i wrong on the implementation or something missing? Does this answer your question? Python running as Windows Service: OSError: [WinError 6] The handle is invalid i got the problem, it's because Inter-Process Communication doesn't work between class. Would you expand on that @AlifianAdexe ? I get the same error message, but I cannot reproduce it with your code. Could you make a minimal working example that gives the error message? With me, it turned out that the instance of the method I had as target could not be pickled. To find this out, I put the instantiation of Process within a try...except, and then use traceback.print_exception to print the exception. The exception does not show up when I re-raise it. Don't know where it goes. It should be around calling start on the Process.
common-pile/stackexchange_filtered
Floyd's Algorithm implemented in Python. two dimensional print array I am attempting to print my python program that implements floyds algorithm. n=5 for k in range(n): for j in range(n): for i in range(n): if A[i][k]+A[k][j]<A[i][j]: A[i][j]=A[i][k]+A[k][j] I am trying to print the solution in the same format as below: (not including the first column and row) 0 1 2 3 4 ----------- 0|0 1 4 500 3 1|1 0 2 500 4 2|4 2 0 1 5 3|500 500 1 0 3 4|3 4 5 3 0 500 indicates infinity Any ideas? I am hoping indices will do the trick. Also does anyone know the order of magnitude of this algorithm? The post is a little bit messy... Maybe you could edit it? Take into account that hitting the enter will exit the code sample {}. Hit enter while holding the caps. Once I see that maybe we'll be able to help you better. You could use this. >>> A = [[0, 1, 4, 500, 3], [1, 0, 2, 500, 4],[4,2,0,1,5],[500,500,1,0,3],[3,4,5,3,0]] >>> for elem in A: print "\t".join(['Inf' if val == 500 else str(val) for val in elem]) 0 1 4 Inf 3 1 0 2 Inf 4 4 2 0 1 5 Inf Inf 1 0 3 3 4 5 3 0 this is what i got when i ran the program. why? 0 1 3 4 3 1 0 2 3 4 3 2 0 1 4 4 3 1 0 3 3 4 4 3 0 I don't know about the algorithm. Are you implementing it right? i believe so. i used the program from above. Are there supposed to be two similar nested loops? for j in range(n) oh no but even when that is changed to i it does not produce the indicated @user2627901 : There must be something wrong with your implementation of the algorithm, then. The printing has nothing to do with it and is being handled seperately. any idea what that could be? Your code seems to agree with some webpages I have checked, why do you think it is not correct? Yes, your code gives the correct answer for the example in: http://nptel.iitm.ac.in/courses/105104098/TransportationII/mod13/16slide.htm . Check your initial numbers and your results! it has to print the following order ----------- 0|0 1 4 500 3 1|1 0 2 500 4 2|4 2 0 1 5 3|500 500 1 0 3 4|3 4 5 3 0 @user2627901 : It does print that, I just replaced 500 with Inf.
common-pile/stackexchange_filtered
Naming in Security Protocols: Alice, Bob and Eve Among computer scientists and programmers, there's the common habit of naming people in the context of security protocols e.g. Alice, Bob or Eve. Descriptions of more elaborate attack vector sometimes refer to Charlie (as does this XKCD strip), but is there a convention for additional participants? @MichaelT: Oops, how embarrassing. I thought of "security protocol names", "protocol participant", but not the most obvious... Thanks!
common-pile/stackexchange_filtered
Biotech company boardroom, late afternoon strategy session. **Pharmaceutical Executive**: The genome data keeps surprising us. When we sequenced those thousand fungal species, we found thirty-six thousand biosynthetic gene clusters, but most are completely silent. **Research Director**: That's the paradox we're facing. These clusters encode the machinery for producing secondary metabolites, yet they're transcriptionally inactive under standard laboratory conditions. We're essentially looking at a locked chemical library. **Pharmaceutical Executive**: So how do we unlock it? The traditional approach of screening fungal extracts only scratches the surface.
sci-datasets/scilogues
C# MVC Localization Issue with Image URLs I need to build a c# MVC portal that is localized. I have the following route defined: routes.MapRoute( name: "DefaultLocalized", url: "{lang}/{controller}/{action}/{id}", constraints: new { lang = @"(\w{2})|(\w{2}-\w{2})" }, // en or en-US defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); Also implemented a LocalizedControllerActivator. All works great. Defaults urls: http://test http://test/about ... When language changed to German it routes to http://test/de http://test/de/about ... that is great. The issue I have is with images. for the following line <img src="media/images/backgrounds/bg.jpg" alt="Smiley face" height="42" width="42"> it would resolve to http://test/de/media/images/backgrounds/aria_bg3.jpg I would like to simply use http://test/media/images/backgrounds/bg3.jpg and ignore the language string all together or I would like to have a different structure like http://test/media/de/images/backgrounds/bg3.jpg Any help would be appreciated. Thanks, Moz See ASP.NET MVC 5 culture in route and url. The reason why the URL is being generated this way is because your constraint always matches this route when generating the URL (same as the other answer). Try to prepend the src with a /. It will give you the base path. So for example if thats/a/test is resolved under url https://www.google.com/images, the resulting URL will be https://www.google.com/images/thats/a/test, but when you use /thats/a/test, the resulting URL will be https://www.google.com/thats/a/test. I think this would fix your problem. No problem, glad I could help you Use relative path to the root of your website. Try to start your attribut "src" by "/", like this : <img src="/media/images/backgrounds/bg.jpg" alt="Smiley face" height="42" width="42"> An other solution is to use html base tag in the head of your webpage, like this : <head> <base href="http://test/" target="_blank"> </head>
common-pile/stackexchange_filtered
How can I escape $.each loop with my data? I'm doing an Json call to retrieve an a list of locations with information details for each location. longitude and latitude are included in this info. I am using Google's distance matrix api to get the distance from coordinates provided as a query in the url. I thought the most logical way to do this would be to loop through the locations and compare searched and location coordinates per location. I am appending some of the info returned from the distance matrix calls onto my data array. This works fine except the data returned from the distance matrix is only usable within the return function for the distance matrix. I pass the wanted data from the distance matrix return function into a function outside the matrix return function but still inside the $.each loop. This seamed like a step towards solving my problem but I'm stuck. I need to use the original data but with the distance matrix data appended so that I can sort the items in the data by distance and output it. I don't think a sort function would work well inside of the $.each loop so I need to break out of the loop with the appended version of the data intact. at least I think. any help would be appreciated. var ltlg = []; var sLat = parseFloat(35.2219971); var sLng = parseFloat(-101.83129689999998); var sLatLng = {lat: sLat, lng: sLng}; var locLat; var locLng; var locLatLng = []; $.getJSON("file.json",function(data){ if(sLat && sLng) { $.each(data, function(x, y){ locLat = data[x].Address.Location.Latitude; locLng = data[x].Address.Location.Longitude; //locLatLng.push({lat: locLat, lng: locLng}); var service = new google.maps.DistanceMatrixService; service.getDistanceMatrix({ origins: [sLatLng], destinations: [{lat: locLat, lng: locLng}], travelMode: 'DRIVING', unitSystem: google.maps.UnitSystem.IMPERIAL, avoidHighways: false, avoidTolls: false }, function(response, status) { if (status !== 'OK') { console.log('status is ' + status); } else { var distance = response.rows[0].elements[0].distance.value; var miles = response.rows[0].elements[0].distance.text; var time = response.rows[0].elements[0].duration.text; addData(distance, miles, time); } }); function addData(distance, miles, time) { data[x]["distance"] = distance; data[x]["miles"] = miles; data[x]["time"] = time; } }); console.log(JSON.stringify(data)); } else { console.log('no query'); } }); I replaced the query variables with static lat lng for the snippet. Why dont you use Array.map/forEach/filter ? @Jonasw I don't know how to do that. Could you give me an example? Please do not vandalize your posts. By posting on the Stack Exchange network, you've granted a non-revocable right for SE to distribute that content (under the CC BY-SA 3.0 license). By SE policy, any vandalism will be reverted. If you would like to disassociate this post from your account, see What is the proper route for a disassociation request? @JSum unfortunately, Stack Exchange keeps a version history of all edits for all questions and answers. To my knowledge, there is no way to 100% redact sensitive information once it has been posted on the site, unless contacting the site owners and requesting manual removal of the history is possible, but that I am not sure of. You may want to implement a global callback, sth like: function loaddata(callback){ var counter=0; data.forEach(function(y,x){ //get data function addData(distance, miles, time) { data[x]["distance"] = distance; data[x]["miles"] = miles; data[x]["time"] = time; if(++counter==data.length){ callback(data); } } }); } So you can do: loaddata(function(data){ console.log(data); }); Data now contains distance,miles and time. I would really like to know why that worked. can you point me in the direction of documentation about this type of function? @JSum https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call The answer that @Jonasw has provided is unnecessarily complicated, and because a new addData() is declared for every single iteration, and a completely pointless counter is initialized, this consumes a lot of memory that can be conserved with a smarter approach. Since you have asynchronous callbacks for every data point, and you want to depend on all of them completing, the approach that makes the most sense would utilize Promise.all(): var sLat = 35.2219971; var sLng = -101.83129689999998; var sLatLng = { lat: sLat, lng: sLng }; var service = new google.maps.DistanceMatrixService; function serviceCallback(value, resolve, response, status) { if (status !== 'OK') { console.log('status is ' + status); reject(status); } else { value.distance = response.rows[0].elements[0].distance.value; value.miles = response.rows[0].elements[0].distance.text; value.time = response.rows[0].elements[0].duration.text; resolve(value); } } function promiseExecutor(value, resolve, reject) { service.getDistanceMatrix({ origins: [sLatLng], destinations: [{ lat: value.Address.Location.Latitude, lng: value.Address.Location.Longitude }], travelMode: 'DRIVING', unitSystem: google.maps.UnitSystem.IMPERIAL, avoidHighways: false, avoidTolls: false }, serviceCallback.bind(null, value, resolve)); } $.getJSON("file.json", function (data) { if (![sLat, sLng].some(isNaN)) { Promise.all(data.map(function (value) { return new Promise(promiseExecutor.bind(null, value)); })).then(function (data) { console.log(JSON.stringify(data, null, 2)); }); } else { console.log('no query'); } }); However, I see you are making a request for each individual data point when you are able to make one for every single data point at once, so to save even more resources, you can try something like this: var sLat = 35.2219971; var sLng = -101.83129689999998; var sLatLng = { lat: sLat, lng: sLng }; var service = new google.maps.DistanceMatrixService; $.getJSON("file.json", function (data) { if (![sLat, sLng].some(isNaN)) { service.getDistanceMatrix({ origins: [sLatLng], destinations: data.map(function (value) { return { lat: value.Address.Location.Latitude, lng: value.Address.Location.Longitude }; }), travelMode: 'DRIVING', unitSystem: google.maps.UnitSystem.IMPERIAL, avoidHighways: false, avoidTolls: false }, function (response, status) { if (status !== 'OK') { console.log('status is ' + status); } else { response.rows[0].elements.forEach(function (element, index) { if (element.status === 'OK') { data[index].distance = element.distance.value; data[index].miles = element.distance.text; data[index].time = element.duration.text; } }); console.log(JSON.stringify(data, null, 2)); } }); } else { console.log('no query'); } }); @Jonasw how about zero promises? :P
common-pile/stackexchange_filtered
Load chart from JSON - Change format of JSON array I am using an example of a chart that gets the data from a JSON string. I am calculating the final JSON that the chart is going to use (called data2). The issue is that I cannot use the array (data2) when I build the chart in the javascript section. It works fine as shown below in the snippet. What I need to do is to replace the static JSON after the 23d line of the JS script with the array data2. Here is the basic snippet I started working on : var json_data= {"headers":["Day","Hobby","Rate"],"rows":[["2017-10-16 00:00:00.0","beer",0.15824918844270675],["2017-10-16 00:00:00.0","push",0.10932372179344997],["2017-10-17 00:00:00.0","beer",0.16243707878321656],["2017-10-17 00:00:00.0","push",0.12342467710200489],["2017-10-18 00:00:00.0","beer",0.1701333117371019],["2017-10-18 00:00:00.0","push",0.13646302215695214],["2017-10-19 00:00:00.0","beer",0.1691911053818885],["2017-10-19 00:00:00.0","push",0.13529176147742863],["2017-10-20 00:00:00.0","push",0.12471145913670185],["2017-10-20 00:00:00.0","beer",0.16660114595720843],["2017-10-21 00:00:00.0","beer",0.1632134150509216],["2017-10-21 00:00:00.0","push",0.12104479125233003],["2017-10-22 00:00:00.0","push",0.11789599576807194],["2017-10-22 00:00:00.0","beer",0.15304531708971758],["2017-10-23 00:00:00.0","push",0.12068839662857922],["2017-10-23 00:00:00.0","beer",0.16865158102680616],["2017-10-24 00:00:00.0","beer",0.16968791058133556],["2017-10-24 00:00:00.0","push",0.12554102534428885],["2017-10-25 00:00:00.0","push",0.1277794674703459],["2017-10-25 00:00:00.0","beer",0.16345087602572633]]}; var platform_data = json_data.rows; var data2 = '['; var push_metric = 0; var beer_metric = 0; for (var i in platform_data) { var date = platform_data[i][0]; if(platform_data[i][1] == 'push'){push_metric = (platform_data[i][2]*1000).toFixed(0)}; if(platform_data[i][1] == 'beer'){beer_metric = (platform_data[i][2]*1000).toFixed(0)}; data2+='{ day: "'+ date+'", '+ 'pushups: '+ push_metric +', '+ 'beers: '+ beer_metric+'},'; } data2+= ']'; new Morris.Line({ // ID of the element in which to draw the chart. element: "pushups", // Chart data records -- each entry in this array corresponds to a point on // the chart. data: [{ day: "2017-10-16 00:00:00.0", pushups: 0, beers: 158},{ day: "2017-10-16 00:00:00.0", pushups: 109, beers: 158},{ day: "2017-10-17 00:00:00.0", pushups: 109, beers: 162},{ day: "2017-10-17 00:00:00.0", pushups: 123, beers: 162},{ day: "2017-10-18 00:00:00.0", pushups: 123, beers: 170},{ day: "2017-10-18 00:00:00.0", pushups: 136, beers: 170},{ day: "2017-10-19 00:00:00.0", pushups: 136, beers: 169},{ day: "2017-10-19 00:00:00.0", pushups: 135, beers: 169},{ day: "2017-10-20 00:00:00.0", pushups: 125, beers: 169},{ day: "2017-10-20 00:00:00.0", pushups: 125, beers: 167},{ day: "2017-10-21 00:00:00.0", pushups: 125, beers: 163},{ day: "2017-10-21 00:00:00.0", pushups: 121, beers: 163},{ day: "2017-10-22 00:00:00.0", pushups: 118, beers: 163},{ day: "2017-10-22 00:00:00.0", pushups: 118, beers: 153},{ day: "2017-10-23 00:00:00.0", pushups: 121, beers: 153},{ day: "2017-10-23 00:00:00.0", pushups: 121, beers: 169},{ day: "2017-10-24 00:00:00.0", pushups: 121, beers: 170},{ day: "2017-10-24 00:00:00.0", pushups: 126, beers: 170},{ day: "2017-10-25 00:00:00.0", pushups: 128, beers: 170},{ day: "2017-10-25 00:00:00.0", pushups: 128, beers: 163},], // The name of the data record attribute that contains x-values. xkey: "day", parseTime: false, // A list of names of data record attributes that contain y-values. ykeys: ["pushups", "beers"], // Labels for the ykeys -- will be displayed when you hover over the // chart. labels: ["Pushups", "Beers"], lineColors: ["#373651", "#E65A26"] }); body { background-color: #E0E2DD; font-family: helvetica, open-sans; } .graph-wrapper { width: 100%; max-width: 750px; margin: 0 auto; } .graph { height: 300px; width: 100%; max-width: 750px; padding: 25px; background-color: #FFF; border-radius: 5px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script> <script src="http://stevenlevithan.com/assets/misc/date.format.js"></script> <div class='graph-wrapper'> <div class='graph' id='pushups'></div> </div> And I am focusing on the issue which is the format of the JSON array. More specifically, in the snippet below, I have both arrays. I only need to change the syntax (remove the quotes from each object) I guess. Unless there is another easier solution: var json_data= {"headers":["Day","Hobby","Rate"],"rows":[["2017-10-16 00:00:00.0","beer",158],["2017-10-16 00:00:00.0","pushup",109],["2017-10-17 00:00:00.0","beer",162],["2017-10-17 00:00:00.0","pushup",123],["2017-10-18 00:00:00.0","beer",170],["2017-10-18 00:00:00.0","pushup",136],["2017-10-19 00:00:00.0","beer",169],["2017-10-19 00:00:00.0","pushup",135],]}; var platform_data = json_data.rows; var pushup_metric = 0; var beer_metric = 0; var data2 = []; for (var i in platform_data) { var date = platform_data[i][0]; if(platform_data[i][1] == 'push'){pushup_metric = platform_data[i][1]}; if(platform_data[i][1] == 'beer'){beer_metric = platform_data[i][2]}; object = '{ day: "'+ date+'", '+ '"pushups": '+ pushup_metric +', '+ '"beers": '+ beer_metric+'}'; data2.push(object); } var data = [{ day: "2017-10-16 00:00:00.0", pushups: 0, beers: 158},{ day: "2017-10-16 00:00:00.0", pushups: 109, beers: 158},{ day: "2017-10-17 00:00:00.0", pushups: 109, beers: 162},{ day: "2017-10-17 00:00:00.0", pushups: 123, beers: 162},{ day: "2017-10-18 00:00:00.0", pushups: 123, beers: 170},{ day: "2017-10-18 00:00:00.0", pushups: 136, beers: 170},{ day: "2017-10-19 00:00:00.0", pushups: 136, beers: 169},{ day: "2017-10-19 00:00:00.0", pushups: 135, beers: 169},]; console.log(data); console.log(data2); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.2/raphael-min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.0/morris.min.js"></script> <div id='data2'></div> <br><br> <div id='data1'></div> <br><br> could you please post the relevant code without any parts to be ignored? :) Why do you build a JSON String by concatenating strings... JS can natively work with JSON. Whyyyy do you do like data2 += "{...}" work with objects, use a real array like data2.push({day: 12, pushups: 69}); What I need to do is to replace the static JSON after the 25th line of the JS script with the variable data2. what do you mean? 25th line of code? 25th entry of rows? @DanFromGermany Question updated. I just need to manipulate the JSON for now. Unless there is another solution. I need to remove the double quotes from each object when I push the objects in the array. You don't have to use quotes at all when you build an object. Compare your code to this: object = { day: date, pushups: pushup_metric, ...}; no quotes, plain javascript. Oh yes. You can post it as an answer. I thought there was another issue here. Don't try to "build" Javascript objects using strings and string concatenation. Simply push objects to arrays and work with JSON: object = { day: date, pushups: pushup_metric, ...}; date2.push(object);
common-pile/stackexchange_filtered
Decorator or wrapper function to abstract special cases in Python I find myself writing a lot of explicit statements like the following: ...inside a larger loop over i: if i == 0: y = ... # some value specifically for i = 0 x[i] = func(y, z) elif i == iMax: y = ... # some value specifically for i = iMax x[i] = func(y, z) else: x[i] = func(y, z) #'z' some other input that does not depend on i to generalize the example There seems like there should be a more abstract or pythonic way to implement this construct, beyond the trivial answer of writing another function: def new_func(i, y, z): #--- get y based on i x = func(y, z) return x While this may be a style question, I keep seeing this paradigm with different 'func', so I am thinking there is decorator or wrapper solution to streamline this that accepts various functions 'func', but I just haven't worked my way through it and thought community feedback would be helpful - thoughts? Clarification / Expansion: Following solution only solve the simple case: if i == 0: y = 0 #...some value elif i == iMax: y = 1 #... some other value else: y = 0.5 #... some non-limiting value x = func(y, z) I am looking at the next level of abstraction. Here is simple example where you would be interpolating within a 1d array to get a value 'z', used to evaluate another function 'func2' to produce 'y' and then compute a new 'x' through original function 'func' if i == 0: y = func2(z[i]) elif i == iMax: y = func2(z[i-1]) else: y = func2(0.5*(z[i-1] + z[i]) x = func(y) Maybe another way to pose the question is "what is a preferred method for nesting functions so that the outer function returns an intermediate value 'y' based on loop index 'i' that is then evaluated by inner function 'func'"? Perhaps I misunderstand, but couldn't you have a dict that maps i to y e.g. y_dict = {i_1: y_1, i_2: y2, i_n: y_n}? So all of it would be reduced down to x[i] = func(y_dict.get(i, default_value), z) y=y0 if i==0 else ym if i ==imax else y Actually, yeah, the suggestion by @PM2Ring makes more sense than my suggestion if it's just an if/elif/else case without more possibilities. I don't think decorators are helpful here. Maybe use jump tables instead?
common-pile/stackexchange_filtered
What is the best way to utilize a beacon for mining I was wondering if anyone uses the beacon for standard branch mining? Its range is just 50 and I'm not sure if it can be used at all, since 50 blocks is too little to cover the whole mine. Do you dig your tunnels in a specific way? I'm no hardcore minecrafter myself, but I know someone who is: Etho. In episode 303 of his let's play he introduces a new way of gathering a ton of resources and levels. He digs all the way down to y=12 and sets up two beacons, one with Haste II the other one with Speed II. (Speed is not required, but does make it easier, provided you have a second beacon.) You'll want to use an Efficiency IV, Unbreaking III pickaxe for mining. Now, the thing with branch-mining is, that it requires a quite a bit of precision. While it might be true that the ratio of mined blocks vs. exposed ore is the highest when branch-mining, it's not the quickest. What you instead want to do is break every block in a two high area. The Haste II and Efficiency IV will make sure that stone gets mined instantly. If you quickly move your mouse from side to side, you will not be breaking ores, as they require more time to mine. As a bonus to the tons of ores you get, you will accumulate a whole lot of levels. You might want to watch the episode (starting at 7min) to see this in action. Wow, thanks a lot for this! I assume he then simply moves the beacon 100 blocks once he finishes clearing the area I'm not sure, but that would be the best thing to do.
common-pile/stackexchange_filtered
Two entry boxes on one zenity command Using zenity i can create an combo box like this zenity --entry --title "Window title" --text "Insert your choice." a b c d e How can i create two combo boxes in one dialog, i tried using the separator command like this zenity --entry --title "Select Flash Drives" --text "Insert your choice." --separator="," --add-entry="IP address" --add-entry="PORT" But it says --separator is not supported for this dialog Is it possible to create two combo boxes in one zenity dialog No, it's not possible. Zenity is designed "to create simple dialogs" and what you are asking for is that one tiny step further from simple. I think you need to look for a different tool. YAD is a fork of Zenity that adds some improvements and might help you achieve what you want. While two combo boxes are not possible, producing two entry boxes in one dialog is possible with the --forms option, which also allows incorporating lists (from each of which the user may select at most one item): zenity --forms --title "Select Flash Drives" --text "Select Flash Drives" \ --add-entry "Insert your choice" \ --add-entry="IP address" or even zenity --forms --title "Select Flash Drives" --text "Select Flash Drives" \ --add-list "Insert your choice" --list-values 'a|b|c' \ --add-entry="IP address" --add-entry="PORT" The main problem with --forms is that it does not allow for default values. (Unless the form starts with a list, in which case its first value seems to be selected by default.) The only work-around is to specify the default value in the question text (so that the user gets to see it) and then check if any value was supplied by the user in the script outside of zenity: RETURNVALUE=`zenity --forms --title "Select Flash Drives" --text "Select Flash Drives" \ --add-entry="IP address (leave empty to use <IP_ADDRESS>)" \ --add-list "Insert your choice (leave empty to use C)" --list-values 'a|b|c'` # extract the IP and DRIVE values IP=$(awk -F'|' '{print $1}' <<<$RETURNVALUE); DRIVE=$(awk -F'|' '{print $2}' <<<$RETURNVALUE); # [[ -z $var ]] is true iff the length of $var is zero # the second element in && is evaluated only if the first one is true [[ -z $IP ]] && IP="<IP_ADDRESS>"; [[ -z $DRIVE ]] && DRIVE="C";
common-pile/stackexchange_filtered