source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0003291521.txt" ]
Q: How are the Poco C++ events handled? Lets say i have a Poco::Thread: Thread Parent has an eventhandler method within it. The parent then spawns two children threads, who are given events that are the parent subscribes the eventhandler to. So two events both have the same event handler attached. If Child A triggers their event, and Parent starts to execute it, what would happen if Child B triggered their event before Parent was finished? Are these requests queued up automatically, or do i have to lock everything out myself? A: Event delegates are called within the thread of the caller (unless you're using notifyAsync()), so in the case of multiple threads triggering the same event you'll have to take care of synchronization in your event handlers yourself.
[ "stackoverflow", "0009417662.txt" ]
Q: Exiting an application when it goes to the background When the application goes to the background I need to exit the application. I have googled and found out that I have to set UIApplicationExitsOnSuspend to YES in the plist. But where in plist should I add this? Can someone help me out? A: Go to the "AppName-Info" plist in the supporting files folder, you have to add 'Application does not run in background' and change it to YES.
[ "stackoverflow", "0057235961.txt" ]
Q: Angular Material CDK Drop Event not fireing I'm trying to use Angular material to drag drop a free node. It's not part of a list but I would like to know when the item has been dropped. I'm not sure how I can bind to this event. I simply want to know when the node has been dropped. here is my code so far: <svg id="svgCanvas" > <g *ngFor="let link of linkPaths"> <path [attr.d]="link"></path> </g> <g *ngFor="let node of nodes" id="nodesGroup"> <circle class="node" [attr.cx]="node.x" [attr.cy]="node.y + 45" [attr.r]="settings.nodes.radius" (click)="nodeClick($event)" (dragEnd)="drop($event, node)" [attr.data-selected]="node.data.selected" cdkDrag cdkDragBoundary="#svgCanvas" ></circle> </g> </svg> I want the dragEnd event to fire and call my drop function in the component's code. private drop(event) { console.log('drag end') } The click event seems to work but the drop won't fire. I can see that Lists support the drop feature but I am not using my drag drop for a list. These are free moving nodes. A: Use the (cdkDragEnded) event (cdkDragEnded)="drop($event, node)". https://material.angular.io/cdk/drag-drop/api Stackblitz: https://stackblitz.com/edit/angular-fk9wpa <div class="example-box" (cdkDragEnded)="drop($event)" cdkDrag> Contents of dragable element </div> In your case: <g *ngFor="let node of nodes" id="nodesGroup"> <circle class="node" [attr.cx]="node.x" [attr.cy]="node.y + 45" [attr.r]="settings.nodes.radius" (click)="nodeClick($event)" (cdkDragEnded)="drop($event, node)" [attr.data-selected]="node.data.selected" cdkDrag cdkDragBoundary="#svgCanvas" ></circle> </g>
[ "stackoverflow", "0016996282.txt" ]
Q: Get the children of a given parent I have a set of numbers: 1,2,4,8,16,32,64,etc. Now given a number let say 44, I have to identify that it has children 32, 8 and 4. (32 + 8 + 4 = 44) What I have so far is the following code: public static long[] GetBTreeChildren(long? parentMask) { var branches = new List<long>(); if (parentMask == null) return branches.ToArray(); double currentValue = (double)parentMask; while (currentValue > 0D) { double power = Math.Floor(Math.Log(currentValue, 2.0D)); double exponentResult = Math.Pow(2, power); branches.Add((long)exponentResult); currentValue -= exponentResult; } return branches.ToArray(); } But the code above is not working when a given number is very large (e.g. 36028797018963967) I am using VS2012 (C#). A: The reason it does not work for very large numbers, is because you are using double data types, which are limited in precision (about 16 digits). Instead of using Math.Pow and Math.Log, everything you need can be done with simple, extremelly more efficient, bitwise operations. public static long[] GetBTreeChildren(long? parentMask) { var branches = new List<long>(); if (parentMask == null) return branches.ToArray(); for(int i = 0; i < 63; ++i) { if( (parentMask & (1L << i)) != 0) branches.Add(1L << i); } return branches.ToArray(); } Basically, each bit is already a power of 2, which is what you are looking for. By doing (long) 1 << i you are shifting the first bit to the i'th power of 2. You can adapt the code above to be more similar to yours, and slightly more efficient, by instead of iterating over i, simply shifting parentMask's bits to the right, but then you must be aware of what would happen to negative numbers, and how logical shifts differ from arithmetic shifts.
[ "stackoverflow", "0009099911.txt" ]
Q: EXTJS changing Grid cell back ground color on click Portion of my code xtype: 'grid', width: 500, store: store6, columns:[{ text:'Market', sortable: false, width:145, dataIndex: 'market }] I've tried using listeners(which I think i didn't do correctly) and I don't know if click will work here due to each cell not having an id tag. USE CASE 1. User clicks cell 2. Code turns cell green 3. User clicks the same cell 4. Code turns cell white The color to each cell depends solely from the user. This is all client side development which I haven't started any server side (PHP) development yet. I've searched on Stack for a bit and I haven't found a solution that works. Any help or comments would really help. A: This is exactly what I'm looking for. Thank InnerJL for directing me in the right direction. I needed it to work for click. Alternating between white and green. Solution is posted below function(value, metaData, record, rowIndex, colIndex, store) { var test = Ext.get(metaData.id).getStyle("background-color"); if(test == "green") { Ext.get(metaData.id).setStyle("background-color", "white"); } else { Ext.get(metaData.id).setStyle("background-color", "green"); } return value; }
[ "gis.meta.stackexchange", "0000004210.txt" ]
Q: Why was question about GDAL Python bindings closed as off topic? I posted Adding GDAL as dependency to Python package? on the usage of the pygdal Python package and it was closed as off topic. Why are the GDAL Python bindings off topic? Note that there are over 5,000 questions on python and some 2,000 on gdal. Is there any criteria to pre-assess what is off-topic in this domain? A: I was not one of the close voters. If I had been, I would be happy to explain why. To me it seems to meet the criteria to be open which come from the help/on-topic page qualified by Meta Q&As here. None of the close voters on your question has provided an answer here to explain their votes (and no one is required to explain their vote). Consequently, we may never know why your question was voted to be closed. In the meantime, it looks like it was re-opened by someone other than the close voters.
[ "stackoverflow", "0005549503.txt" ]
Q: ClearCase vs. Git version control We are using a multisite ClearCase repository, and often we require to merge and build our system. This merge and replication takes almost three days to be available across sites. Hence to be more efficient, we are planning to move to Git version control. Could you please advise of the potential drawback that we can encounter if we move to the Git from ClearCase? A: @zzz777: Your question was asked in such a ClearCase centric view that it failed to be comprehensible to people who never used ClearCase before. In fact, Git is light years ahead of ClearCase, and it is the commercial SCMs that need to catch up with OSS systems. I have experience with both ClearCase and Git, and I can tell you that the Find merges (mis)feature of ClearCase is a result of its (fundamentally broken) design based on versioning files, but in Git you don't need such a primitive tool to merge the shared branch to your private branch. ClearCase is file-oriented, and checkin-s are file based, and that's why you need the Find (files) to merge utility, but Git is commit based, and that is the right model, since when you fix an issue or implement a feature, the entire changeset or none of it are the only options that make sense. Git has a very powerful merge feature, and it does the right thing. There are two ways to do what you are asking (updating your private branch to be the shared branch + your changes). The most obvious is to do a merge, so while on your private branch you just do: git merge sharedbranch then, if there are conflicts (really a lot more rare than in ClearCase), you resolve them and git commit And that's it. As a bonus, because Git has all history locally, you don't have to waste countless hours, if you have lots of files, like you do in ClearCase, the merge is blazingly fast, by the time ClearCase in a dynamic view does a merge of 10 files, Git will probably finish merging 100, easily. Using git merge means that you preserve history and if your history looked like this before the merge: o---1---2---3 (sharedbranch) \ a---b---c (privatebranch) after the merge it will look like this: o---1---2---3 (sharedbranch) \ \ a---b---c---m (privatebranch) This preserves the history of your changes and can allow others to review your work. And remember, these are NOT file revision histories. These if the tree history, which is the only history that makes sense to store, even if branches differ only by one or two files. The state you want to preserve is the tree, not one file. The second option is to use rebase, which means that you make it like it seems al your changes have been made starting from the latest code on the shared branch. The command you use (again, while on the private branch): git rebase sharedbranch The history tree will change from: o---1---2---3 (sharedbranch) \ a---b---c (privatebranch) to o---1---2---3 (sharedbranch) \ a'--b'--c' (privatebranch) So if you give Git some time to understand it, and use it a little, you'll see how much better is the Git model and how broken the ClearCase model is. BTW, the evil twin problem in ClearCase simply does not exist in Git because Git does not track directories (trust me, you do not need that). Also, if you ever had a configuration specification, which is a little more complicated with several branches and you migrated files from one branch to the other, you probably know how important the order of the rules in the configuration specification is, and how frustrating is to see old versions of files because the configuration specification is "wrong". That happens in ClearCase due to its base design, and, needless to say, that kind of crap can't happen in Git. So, to conclude, Git does not have a primitive tool such as "find merge", because it does not need it. It has a superior model and superior merge model which actually works. It is lightning fast compared to ClearCase (CCRC static view or dynamic view, you name it). The only place ClearCase could have an edge is the instantaneous update of the dynamic view, but that is also mitigated by the fact that you can type faster git checkout branch than you can update the configuration specification. A: Problems that I have had in a professional mixed ability office: Mutable History. You can do some really silly (and powerful) things with Git. This can cause source loss. Auto Merging. This is the best feature of Git. But, we had to shut development down for a week to find the source code that went missing. MSVS has a happy issue with randomly changing line endings and if you don't pull from the repository regularly it gets confused, and changes get lost. Push/Pull order. ClearCase handles the date ordering and history for you, but Git ignores it. Staging. ClearCase (at least UCM) handles branch promotion and other things for you. Git does not. You will have to manage this carefully. $ID$ Does not exist for Git. Version tracking from actual releases and problem finding from knowing what the version of the source file is will have to be handled manually. (I am not sure what your release process is.) For you final code repository, I might suggest a release repository, either another source control system or a separate Git repository, that is managed and only accepts pulls. I am currently using Git for my solo project, and it is fine. But, in a mixed-ability house with a variety of editors I would be careful. You can really blow you foot off without knowing with Git. I have not used either, Mercurial or Bazaar. It might be worth looking at these as some of the problems go away, and they have features to mitigate some of the above problems. A: I've worked with both Git and ClearCase and once you learn how to use Git and then make the switch, you'll never look back. Make sure that you have the time to train your developers -- this should be your top priority. Git is an entirely different approach to SCM than ClearCase. Some things to consider (possible downsides): You will need a true repository master, not just someone to watch over the source, but someone who understands how the SCM actually works (not just what a GUI displays to them) and can handle your branching model (see #2) Adopt/develop a robust branch model. A great example, and one I've used is A successful Git branching model You're going to have to invest a great deal of time helping your developers relearn everything they thought they knew about using/interacting with an SCM. If you can overcome the three above, then there's very little downside (#3 being the toughest). As for @PAntoine, most of those issues are related to training -- #1 would have to require a truly poor decision to lose source code. git reflog will provide you access to every commit to the repository. The only way to destroy source would be through git reflog expire --expire=whatever refs/heads/master, git fsck --unreachable, git prune, and git gc, which should only be handled by the repository master -- and then there's the universal issue of a developer not committing their source (D'oh!)
[ "stackoverflow", "0063066683.txt" ]
Q: Reasons to implement lazy loading in a Vue Single Page Application? I understand lazy loading will improve initial load times in a SPA, but just how much realistic benefit would I get out of it with a Vue application if I used Vue-router, Vuex and many components. Do the performance benefits of lazy loading a Vue SPA come close to minifying and bundling code (in my case, with gulp)? I understand if I upload hundreds of MB of media content in nested pages that the initial load-time benefit would be there, but I am wondering as to the need for a general use case. All answers appreciated. A: The team I work for use it to load large external javascript packages only when they are needed. Imagine a project has five javascript visualization libraries all 1Mb each, but the home page is just a normal document, full of text. We don't want to make visitors who are just here to read text updates of our site to have to load three.js, plotly, etc if they aren't going to use it. Webpack also supports lazy loading, so you can still minify and bundle while lazy loading. It's just a bit of extra work to set up and debugging becomes a little harder. I couldn't say how much benefit you'd get in your app but it worked well for us in a nested site (reduced the initial bundle size by half for us). I would check what bundle portions in Mb of your site is needed on the page load vs later because you will get big savings there. Discliamer: I'm not an expert in this topic, just sharing my experience over the last year of working on a massive web app where performance is an issue
[ "stackoverflow", "0026112100.txt" ]
Q: Sign app in XCode with another developer account I have a client that doesn't want my apple developer account to interfere with his application. So, can I use his developer account(without the credentials) to sign and test an application? I searched and I found myself lost with some questions over a possibility that I'm not sure it works. The thing I found was him exporting the developer profile via XCode, sending me the developer profile file and me importing that into my XCode. What I did not understand, however, was: will this thing work? will I need his account id and password for importing this, afterwards? (because this would be a problem) is it required for him to generate this through XCode or is there any alternative? can we both use this after he exports the file and I import it? is he able to revoke me after this is finished? Edit: Is there any other way to acheive that? Maybe any third party application? A: It is very easy : Get the p12 of his certificate : he could export from his keychain then install this certificate and adhoc provisioning profile in you system. You can use this for taking build .
[ "stackoverflow", "0052618840.txt" ]
Q: Parse API output in ruby Apologies if it is very basic one , completely new to ruby. Below is the sample response I am getting while using the curl , need to get the values of body , created_at from the below output . When I tried to check type of the value , puts returns true for (string) and false for hash and array `#puts value.is_a?(Hash) #puts value.is_a?(Array) #puts value.is_a?(String)` Not sure how to get value from the below output , Please help on with the first step/idea need to do here , will try on and revert back on getting any issues further SAMPLE CALL curl https://api.statuspage.io/v1/pages/qfn30z5r6s5h/incidents.json \ -H "Authorization: OAuth 2a7b9d4aac30956d537ac76850f4d78de30994703680056cc103862d53cf8074" SAMPLE RESPONSE [ { "created_at": "2013-04-21T11:45:33-06:00", "id": "tks5n8x7w24h", "impact": "none", "impact_override": null, "incident_updates": [ { "body": "We will be performing a data layer migration from our existing Postgres system over to our new, multi-region, distributed Riak cluster. The application will be taken offline during the entirety of this migration. We apologize in advance for the inconvenience", "created_at": "2013-04-21T11:45:33-06:00", "display_at": "2013-04-21T11:45:33-06:00", "id": "kb4fpktpqm0l", "incident_id": "tks5n8x7w24h", "status": "scheduled", "twitter_updated_at": null, "updated_at": "2013-04-21T11:45:33-06:00", "wants_twitter_update": false, "affected_components": [ { "code": "ftgks51sfs2d", "name": "API", "old_status": "operational", "new_status": "operational" } ] } ], "metadata": [ "jira": { "issue_id": "value" } ], "monitoring_at": null, "name": "Data Layer Migration", "page_id": "jcm87b8scw0b", "postmortem_body": null, "postmortem_body_last_updated_at": null, "postmortem_ignored": true, "postmortem_notified_subscribers": false, "postmortem_notified_twitter": false, "postmortem_published_at": null, "resolved_at": null, "scheduled_auto_in_progress": false, "scheduled_auto_completed": false, "scheduled_for": "2013-05-04T01:00:00-06:00", "scheduled_remind_prior": false, "scheduled_reminded_at": null, "scheduled_until": "2013-05-04T03:00:00-06:00", "shortlink": "", "status": "scheduled", "updated_at": "2013-04-21T11:45:33-06:00" }, { "created_at": "2013-04-21T11:04:28-06:00", "id": "cz46ym8qbvwv", "impact": "critical", "impact_override": null, "incident_updates": [ { "body": "A postmortem analysis has been posted for this incident.", "created_at": "2013-04-21T11:42:31-06:00", "display_at": "2013-04-21T11:42:31-06:00", "id": "dn051mnj579k", "incident_id": "cz46ym8qbvwv", "status": "postmortem", "twitter_updated_at": null, "updated_at": "2013-04-21T11:42:31-06:00", "wants_twitter_update": false }, { "body": "The application has returned to it's normal performance profile. We will be following up with a postmortem about future plans to guard against additional master database failure.", "created_at": "2013-04-21T11:16:38-06:00", "display_at": "2013-04-21T14:07:00-06:00", "id": "ppdqv1grhm64", "incident_id": "cz46ym8qbvwv", "status": "resolved", "twitter_updated_at": null, "updated_at": "2013-04-21T11:36:15-06:00", "wants_twitter_update": false, "affected_components": [ { "code": "ftgks51sfs2d", "name": "API", "old_status": "degraded_performance", "new_status": "operational" } ] }, { "body": "The slave database has been successfully promoted, but is running slow due to a cold query cache. The application is open and available for requests, but should will be performing in a degraded state for the next few hours. We will continue to monitor the situation.", "created_at": "2013-04-21T11:14:46-06:00", "display_at": "2013-04-21T11:14:46-06:00", "id": "j7ql87ktwnys", "incident_id": "cz46ym8qbvwv", "status": "monitoring", "twitter_updated_at": null, "updated_at": "2013-04-21T11:14:46-06:00", "wants_twitter_update": false, "affected_components": [ { "code": "ftgks51sfs2d", "name": "API", "old_status": "major_outage", "new_status": "degraded_performance" } ] }, { "body": "The slave database is 60% through it's recovery process. We will provide another update once the application is back up.", "created_at": "2013-04-21T11:08:42-06:00", "display_at": "2013-04-21T11:08:42-06:00", "id": "xzgd3y9zdzt9", "incident_id": "cz46ym8qbvwv", "status": "identified", "twitter_updated_at": null, "updated_at": "2013-04-21T11:08:42-06:00", "wants_twitter_update": false, "affected_components": [ { "code": "ftgks51sfs2d", "name": "API", "old_status": "major_outage", "new_status": "major_outage" } ] }, { "body": "The master database server could not boot due to a corrupted EBS volume. We are in the process of failing over to the slave database. ETA for the application recovering is 5 minutes.", "created_at": "2013-04-21T11:06:27-06:00", "display_at": "2013-04-21T11:06:27-06:00", "id": "9307nsfg3dxd", "incident_id": "cz46ym8qbvwv", "status": "identified", "twitter_updated_at": null, "updated_at": "2013-04-21T11:06:27-06:00", "wants_twitter_update": false, "affected_components": [ { "code": "ftgks51sfs2d", "name": "API", "old_status": "major_outage", "new_status": "major_outage" } ] }, { "body": "We're investigating an outage with our master database server.", "created_at": "2013-04-21T11:04:28-06:00", "display_at": "2013-04-21T11:04:28-06:00", "id": "dz959yz2nd4l", "incident_id": "cz46ym8qbvwv", "status": "investigating", "twitter_updated_at": null, "updated_at": "2013-04-21T11:04:29-06:00", "wants_twitter_update": false, "affected_components": [ { "code": "ftgks51sfs2d", "name": "API", "old_status": "operational", "new_status": "major_outage" } ] } ], "metadata": [ "jira": { "issue_id": "value" } ], "monitoring_at": "2013-04-21T11:14:46-06:00", "name": "Master Database Failure", "page_id": "jcm87b8scw0b", "postmortem_body": "##### Issue\r\n\r\nAt approximately 17:02 UTC on 2013-04-21, our master database server unexpectedly went unresponsive to all network traffic. A reboot of the machine at 17:05 UTC resulted in a failed mount of a corrupted EBS volume, and we made the decision at that time to fail over the slave database.\r\n\r\n##### Resolution\r\n\r\nAt 17:12 UTC, the slave database had been successfully promoted to master and the application recovered enough to accept web traffic again. A new slave database node was created and placed into the rotation to guard against future master failures. The promoted slave database performed slowly for the next couple of hours as the query cache began to warm up, and eventually settled into a reasonable performance profile around 20:00 UTC.\r\n\r\n##### Future Mitigation Plans\r\n\r\nOver the past few months, we've been working on an overhaul to our data storage layer with a migration from a Postgres setup to a distributed, fault-tolerant, multi-region data layer using Riak. This initiative has been prioritized, and the migration will be performed in the coming weeks. We will notify our clients of the scheduled downtime via an incident on this status site, and via a blog post.", "postmortem_body_last_updated_at": "2013-04-21T17:41:00Z", "postmortem_ignored": false, "postmortem_notified_subscribers": false, "postmortem_notified_twitter": false, "postmortem_published_at": "2013-04-21T17:42:31Z", "resolved_at": "2013-04-21T14:07:00-06:00", "scheduled_auto_in_progress": false, "scheduled_auto_completed": false, "scheduled_for": null, "scheduled_remind_prior": false, "scheduled_reminded_at": null, "scheduled_until": null, "shortlink": "", "status": "postmortem", "updated_at": "2013-04-21T11:42:31-06:00" }, { "created_at": "2013-04-01T12:00:00-06:00", "id": "2ggpd60zvx3c", "impact": "none", "impact_override": null, "incident_updates": [ { "body": "At approximately 6:55 PM, our network provider at ServerCo experienced a brief network outage at their New Jersey data center. The network outage lasted approximately 14 minutes, and all web requests during that time were not received. No data was lost, and the system recovered once the network outage at ServerCo was repaired.", "created_at": "2013-04-21T11:02:00-06:00", "display_at": "2013-04-21T11:02:00-06:00", "id": "mkfzp9swbk4z", "incident_id": "2ggpd60zvx3c", "status": "investigating", "twitter_updated_at": null, "updated_at": "2013-04-21T11:02:00-06:00", "wants_twitter_update": false } ], "metadata": [ "jira": { "issue_id": "value" } ], "monitoring_at": null, "name": "Brief Network Outage", "page_id": "jcm87b8scw0b", "postmortem_body": null, "postmortem_body_last_updated_at": null, "postmortem_ignored": false, "postmortem_notified_subscribers": false, "postmortem_notified_twitter": false, "postmortem_published_at": null, "resolved_at": null, "scheduled_auto_in_progress": false, "scheduled_auto_completed": false, "scheduled_for": null, "scheduled_remind_prior": false, "scheduled_reminded_at": null, "scheduled_until": null, "shortlink": "", "status": "resolved", "updated_at": "2013-04-01T12:00:00-06:00" } ] A: It's JSON. Since you're using Rails, it will be sufficient to call JSON.parse(value) This will return an array of multiple hashes which you will be able to further map.
[ "stackoverflow", "0055585935.txt" ]
Q: Regarding git prune Is the below command dangerous in any way ? git remote prune origin --dry-run I had a look here here, but could not arrive at any conclusion A: No, it is not. A dry-run is by definition a simple output operation, modifying nothing whatsoever.
[ "cooking.stackexchange", "0000009480.txt" ]
Q: on proper thermometer poking? When you use a thermometer and poke a large hole in the meat, can you use the same hole to accurately gauge temperature later on? A: I use the same hole if what I am checking is large, like a loaf of bread, and I don't want to poke it full of holes...although with my instant read thermometer, the hole is not particularly large. If the hole is a large proportion to the item (big hole in the side of a cookie...I know, absurd, but you get the idea) where you think heat can run down that tunnel you've made, then be concerned, but I can't imagine any situations where it is likely that the thermometer hole is going to let enough heat in to alter the cooking. I CAN imagine a situation where a thermometer in place could help transmit heat to the center and make it, potentially, cook quicker. We used to put a large nail in the center of a potato that we were baking in the coals of a fire so that the steel would help transmit heat to the center of the potato to make sure it got done evenly, but I don't know how much of a difference even THAT made.
[ "unix.stackexchange", "0000404329.txt" ]
Q: How to restrict the X11 forwarding access on CentOS 6.5 for specific users? The setting: A remote Linux server with about 10 users running CentOS 6.5. The users use a username/password to connect to the server with PuTTY. Certain users need to have X11 forwarding available, but others do not need and must not be able to use X11 forwarding, but they can login remotely. For the users with X11 forwarding, if they run a GUI application for more than an hour, it is killed automatically. How can I apply these restrictions? P.S. I could enable the X11 forwarding by modifying the sshd config file. However, I cannot do the rest. A: You can enable X11 based on group or user. /etc/ssh/sshd_config : X11Forwarding no AllowTcpForwarding no # Allow group to use X11 Match Group group_name X11Forwarding yes AllowTcpForwarding yes # Allow user to use X11 Match User user_name X11Forwarding yes AllowTcpForwarding yes You can create a cron job to kill the process after 1 hour (3600 Seconds) Kill all processes that are running for more than 5 minutes by a given user in linux bash script kill -9 $(ps -eo comm,pid,etimes | awk '/^procname/ {if ($3 > 3600) { print $2}}')
[ "stackoverflow", "0039365394.txt" ]
Q: DateTime + 12 hours showing same DateTime. Why? When I am increasing DateTime value by any hours, the result is OKAY, but when I increase it by 12 hours, it is not increasing. Please see the following code for details: $creation_date = new DateTime('2016-09-07 06:00:00', new DateTimeZone('Asia/Kolkata')); $expiration_date = new DateTime('2016-09-07 06:00:00', new DateTimeZone('Asia/Kolkata')); When I increase the $expiration_date variable by 1 hour, 3 hour, 8 hour, 24 hours etc., the result is perfect. For example, Case 1: $expiration_date->add(new DateInterval('PT1H')); echo "Creation Date: ".$creation_date->format('Asia/Kolkata')."<br/>Expiration Date: ".$expiration_date->format('Asia/Kolkata'); Result 1: Creation Date: 2016-09-07 06:00:00 Expiration Date: 2016-09-07 07:00:00 Case 2: $expiration_date->add(new DateInterval('PT3H')); echo "Creation Date: ".$creation_date->format('Asia/Kolkata')."<br/>Expiration Date: ".$expiration_date->format('Asia/Kolkata'); Result 2: Creation Date: 2016-09-07 06:00:00 Expiration Date: 2016-09-07 09:00:00 Case 3: $expiration_date->add(new DateInterval('PT8H')); echo "Creation Date: ".$creation_date->format('Asia/Kolkata')."<br/>Expiration Date: ".$expiration_date->format('Asia/Kolkata'); Result 3: Creation Date: 2016-09-07 06:00:00 Expiration Date: 2016-09-07 02:00:00 Case 4: $expiration_date->add(new DateInterval('PT24H')); echo "Creation Date: ".$creation_date->format('Asia/Kolkata')."<br/>Expiration Date: ".$expiration_date->format('Asia/Kolkata'); Result 4: Creation Date: 2016-09-07 06:00:00 Expiration Date: 2016-09-08 06:00:00 But when I increase the $expiration_date variable by 12 hours, the date is not getting increased!They are showing the same datetime! Case 5: $expiration_date->add(new DateInterval('PT12H')); echo "Creation Date: ".$creation_date->format('Asia/Kolkata')."<br/>Expiration Date: ".$expiration_date->format('Asia/Kolkata'); Result 5: Creation Date: 2016-09-07 06:00:00 Expiration Date: 2016-09-07 06:00:00 What am I doing wrong? A: 8 hours gives you Creation Date: 2016-09-07 06:00:00 Expiration Date: 2016-09-07 02:00:00 Do you really think that that 6 + 8 is 2 ? No, it is 14 which is 2pm The same with 6 + 12 is 18 which is 6pm. Change format of displayed data to 24 hours ;)
[ "codereview.stackexchange", "0000062695.txt" ]
Q: Memory text based game Would anyone be so kind as to review my code for Memory? import java.util.*; public class Cards { public boolean gameInProgress = true; public void shuffleCards() { Scanner userInput = new Scanner(System.in); List cardList = new LinkedList(); List matchedCards = new LinkedList(); //this is the list of cards available to pick from String[] cards = {"a", "b", "c", "d", "e", "a", "b", "c", "d", "e"}; //this shuffles the cards each game Collections.shuffle(Arrays.asList(cards)); //this moves the cards array into a LinkedList Collections.addAll(cardList, cards); //main game loop. stops when all cards are matched while (gameInProgress) { //Stores the users card picks in variables card1 and card2 System.out.println("pick a card (0-9)\n"); int card1 = userInput.nextInt(); System.out.println("First card picked is the letter " + cardList.get(card1)); System.out.println("pick a second card.\n"); int card2 = userInput.nextInt(); while(card1 == card2){ System.out.println("You cannot pick the same card twice. Pick a different card."); card2 = userInput.nextInt(); } System.out.println("second card picked is the letter " + cardList.get(card2)); //checks if a card has been picked already while(matchedCards.contains(cardList.get(card1))) { System.out.println("First card already picked. Pick again: "); card1 = userInput.nextInt(); } while(matchedCards.contains(cardList.get(card2))){ System.out.println("Second card already picked. Pick again: "); card2 = userInput.nextInt(); } //copies the matched cards to a new linked list if (cardList.get(card1) == cardList.get(card2)) { System.out.println("You got a match!\n"); matchedCards.add(cardList.get(card1)); matchedCards.add(cardList.get(card2)); System.out.println("You have collected " + matchedCards.size() + "/10 cards"); System.out.println(matchedCards + " are in the matched pile\n"); //stops the game once all cards have been matched if (matchedCards.size() == 10) { System.out.println("You Win!!!"); gameInProgress = false; } } else { System.out.println("Not a match\n"); } } } } public class Game { public static void main(String[] args) { Cards card = new Cards(); card.shuffleCards(); } } A: Review: public void shuffleCards() Should only shuffle cards, because that's what it says it does. Create new methods void playGame() int getFirstPick(), int getSecondPick(), boolean isAlreadyMatched(int card1, int card2), boolean areAllCardsMatched() and possibly others. Assign these methods to the class that they should belong to. Game void playGame() int getFirstPick() int getSecondPick() boolean verifyFirstPick(int firstPick) boolean verifySecondPick(int firstPick, int secondPick) Cards void shuffleCards() boolean isAlreadyMatched(int card) boolean areAllCardsMatched() Why? Because right now you've got one long piece of code that does everything, and it's confusing you and causing bugs. By splitting it up, it'll be easier to identify what you need to do and whether the code is doing it. If you do it right, you'll end up with code like this: public void playGame(){ //printInstructions(); //an idea, perhaps? setupGame(); while(!isGameWon()){ doTurn(); } printGameWon(); } That's awfully abstract, Pim. Okay, lets dive a level deeper, in setupGame: public void setupGame(){ cards = new Cards(); cards.shuffle(); userInput = new Scanner(System.in); } That sets up the playing field and the input, it seems. What's the next method? isGameWon()... public boolean isGameWon(){ return (cards != null && cards.areAllCardsMatched()); } It's just a check for whether all the cards are matched. (There's a sneaky shortcut here; with cards != null I check whether the game has been initialized yet.) Okay, what about doTurn() then? That one is a bit bigger. public void doTurn(){ int firstPick = -1; do { firstPick = getFirstPick(); } while(!verifyFirstPick(firstPick)); printFirstPick(firstPick); int secondPick = -1; do { secondPick = getSecondPick(); } while(!verifySecondPick(firstPick, secondPick)); printSecondPick(secondPick); checkMatch(firstPick, secondPick); } It handles getting the first picked card and the second picked card, then passes them along to checking for a match. Let's go look at the checkMatch function. public void checkMatch(int firstPick, int secondPick){ if(cards.match(firstPick, secondPick)){ printMatch(); printRemainingMatches(); } else { printNoMatch(); } } We STILL haven't seen any real code doing anything. All I have shown you right now that actually does anything is the setupGame method. The rest just structures the game flow. Function lists right now: Game void setupGame(); void playGame(); void doTurn(); void checkMatch(int firstPick, int secondPick); int getFirstPick(); int getSecondPick(); boolean verifyFirstPick(int firstPick); boolean verifySecondPick(int firstPick, int secondPick); boolean isGameWon(); void printFirstPick(int firstPick); void printSecondPick(int secondPick); void printMatch(); void printNoMatch(); void printRemainingMatches(); void printGameWon(); Cards void shuffleCards(); boolean match(int card1, int card2); boolean isAlreadyMatched(int card); boolean areAllCardsMatched(); It'll be your task to implement the ones I haven't shown yet. You'll also have to move some of the variables so they're class members, not just declared in a function (hint: cards and userInput are two of these, I don't know if there are more). Given the name of the functions, it should be easy to guess what they do. shuffleCards shuffles the cards. match tests if two cards are a match. And so on... A: Bug: Match a pair (lets assume they're at 0 and 1). Pick 0 as your first card, pick 2 as your second card. Repick 2 as your first card. We've circumvented the double pick check. And then we have a match. I'd fix this by reordering the statements: System.out.println("pick a card (0-9)\n"); int card1 = userInput.nextInt(); //checks if a card has been picked already while(matchedCards.contains(cardList.get(card1))) { System.out.println("First card already picked. Pick again: "); card1 = userInput.nextInt(); } System.out.println("First card picked is the letter " + cardList.get(card1)); System.out.println("pick a second card.\n"); int card2 = userInput.nextInt(); while(matchedCards.contains(cardList.get(card2) || card1 == card2)){ System.out.println("Second card already picked. Pick again: "); card2 = userInput.nextInt(); } System.out.println("second card picked is the letter " + cardList.get(card2)); I merged the "second card already picked" and "can't pick same card" messages because technically you're picking a card that's already picked. A: Besides what Pimgd has pointed out, I have some more things to say: First of all, your code is a bit of a mess as the indentation is quite far off, and the spacing likewise. If you're using an IDE, which I hope that you are, use your IDE to automatically correct these things. Or look at Pimgd's code to see how it's done. In your setup, you are first creating a list, then an array, then a list from the array, then add your array to the first list. This can be done simpler. Additionally, your array is not maintainable as it is very easy to accidentally switch one of the letters to a completely different letter, so that there are no pairs anymore. Also, you're not using generics for your lists, and I would recommend using ArrayList instead of LinkedList, because it will be faster with regards to the remove method. A better setup would be: List<String> cards = Arrays.asList(new String[] { "a", "b", "c", "d", "e" }); List<String> cardList = new ArrayList<String>(); cardList.addAll(cards); cardList.addAll(cards); Collections.shuffle(cards); In these two lines: System.out.println("You have collected " + matchedCards.size() + "/10 cards"); if (matchedCards.size() == 10) { You are referring to the number 10? But why are you referring to the number 10? Really, why the number 10? Ah, because that's the number of cards you have? Then why don't you refer to the number of cards you have!? What if you would add some cards? System.out.println("You have collected " + matchedCards.size() + "/" + cards.size() + " cards"); if (matchedCards.size() == cards.size()) {
[ "stackoverflow", "0052933690.txt" ]
Q: Responsive UI - modify reading order in screen readers? I have a responsive layout that must be accessible for screen readers. The issue is around the order of buttons on desktop vs mobile. On desktop the button order is Cancel - Remind Me Later - Learn More ...and the screen reader reads left to right. However on mobile the button order is vertically stacked and is ordered as the reverse of the desktop: Learn more Remind me later Cancel The problem is the screen reader still reads as if user was in desktop mode - the visual order no longer matches. Is there a way for the screen reader to change the reading order depending on the viewport? A: Is there a way for the screen reader to change the reading order depending on the viewport? One solution is to have two sets of the same menu and use your media queries to use one or the other <div class="desktop">Cancel - Remind Me Later - Learn More</div> <div class="mobile"> Learn more Remind me later Cancel </div> CSS: .mobile {display:none} @media screen and (max-width: 600px) { .desktop {display:none} .mobile {display:block} } This way, you will be free to let the DOM order match the visual order.
[ "math.stackexchange", "0000019395.txt" ]
Q: Infinite series $n^7/(\exp(2\pi n)-1)$ I found an interesting topic on this site with regards to the series I am trying to evaluate: Summing $\frac{1}{e^{2\pi}-1} + \frac{2}{e^{4\pi}-1} + \frac{3}{e^{6\pi}-1} + \cdots \text{ad inf}$ I was wondering if there is a closed form for even m when we have: $$\sum_{n=1}^{\infty}\frac{n^{2m-1}}{e^{2\pi n}-1}$$ I have the series $$\sum_{n=1}^{\infty}\frac{n^{7}}{e^{2\pi n}-1},$$ I am trying to evaluate. The aforementioned thread mentions that if m > 1 and odd, then we can use $$\frac{B_{2m}}{4m}$$ to find the sum. But, if m is even, the formula omits and error term. Does anyone have info on this error term or how to evaluate my series or others that involve even m?. I noticed that when m=1, there is an error term of $$-\frac{1}{8\pi}$$ The error appears to get smaller the larger m, and thus the power of n, becomes. Thanks to all. A: The above answers do not mention that we can also find closed form expressions by using harmonic sum formulae. Introduce the sum $$S_m(x) = \sum_{n\ge 1} \frac{(nx)^{2m-1}}{e^{2\pi nx}-1}$$ so that we are looking to find $S_m(1).$ The sum term is harmonic and may be evaluated by inverting its Mellin transform. Recall the harmonic sum identity $$\mathfrak{M}\left(\sum_{k\ge 1} \lambda_k g(\mu_k x);s\right) = \left(\sum_{k\ge 1} \frac{\lambda_k}{\mu_k^s} \right) g^*(s)$$ where $g^*(s)$ is the Mellin transform of $g(x).$ In the present case we have $$\lambda_k = 1, \quad \mu_k = k \quad \text{and} \quad g(x) = \frac{x^{2m-1}}{e^{2\pi x}-1}.$$ We need the Mellin transform of $1/(e^{2\pi x}-1)$ which is $$\int_0^\infty \frac{1}{e^{2\pi x}-1} x^{s-1} dx = \int_0^\infty \frac{e^{-2\pi x}}{1-e^{-2\pi x}} x^{s-1} dx.$$ Expanding the inner sum we obtain $$\int_0^\infty \sum_{q\ge 1} e^{-2\pi qx} x^{s-1} dx = \sum_{q\ge 1} \int_0^\infty e^{-2\pi qx} x^{s-1} dx = \Gamma(s) \sum_{q\ge 1} \frac{1}{(2\pi q)^s} = \frac{1}{(2\pi)^s} \Gamma(s) \zeta(s).$$ It follows that the Mellin transform $g^*(s)$ of $g(x)$ is given by $$\frac{1}{(2\pi)^{s+2m-1}} \Gamma(s+2m-1) \zeta(s+2m-1).$$ Therefore the Mellin transform $Q_m(s)$ of $S_m(x)$ is given by $$\frac{1}{(2\pi)^{s+2m-1}} \Gamma(s+2m-1) \zeta(s)\zeta(s+2m-1).$$ The Mellin inversion integral here is $$\frac{1}{2\pi i} \int_{3/2-i\infty}^{3/2+i\infty} Q_m(s)/x^s ds$$ which we evaluate by shifting it to the left for an expansion about zero. We need to examine which poles of the gamma function term are canceled by the two zeta function terms. The poles of the gamma function term are at all integers less than or equal to $-(2m-1).$ The plain zeta term cancels all the even ones and it also cancels the one at $-(2m-1)+1$ from the compound zeta term when $m>1.$ The compound zeta term cancels all the odd ones starting at $-(2m-1)-2.$ This leaves only two poles at $s=1$ and at $s=-(2m-1).$ Therefore we have the following residues that contribute: $$\mathrm{Res}(Q_m(s)/x^s; s=1) = \frac{1}{(2\pi)^{2m}} \Gamma(2m) \zeta(2m) \frac{1}{x} \\= \frac{1}{(2\pi)^{2m}} (2m-1)! \frac{(-1)^{m+1} B_{2m} (2\pi)^{2m}}{2\times (2m)!} \frac{1}{x} = \frac{(-1)^{m+1} B_{2m}}{2\times 2m} = \frac{(-1)^{m+1} B_{2m}}{4m} \frac{1}{x}$$ and $$\mathrm{Res}(Q_m(s)/x^s; s=-(2m-1)) = \zeta(-(2m-1)) \zeta(0) x^{2m-1} \\= -\frac{1}{2} \times -\frac{B_{2m}}{2m} x^{2m-1}= \frac{B_{2m}}{4m} x^{2m-1}.$$ When $m=1$ there is a pole at $s=0$ which contributes $$ \mathrm{Res}(Q_m(s)/x^s; s=0) = -\frac{1}{4\pi}.$$ We now specialize in the case when $m$ is odd and at least three. Then we observe a fact which is of critical importance, namely that $Q(s)$ is odd on the line $\Re(s) = -(m-1),$ which we now prove. Recall the formula for $Q(s),$ which was $$\frac{1}{(2\pi)^{s+2m-1}} \Gamma(s+2m-1) \zeta(s)\zeta(s+2m-1).$$ Now put $s = -(m-1)+it$ to get $$\frac{1}{(2\pi)^{m+it}} \Gamma(m+it) \zeta(-m+it+1)\zeta(m+it).$$ Using the functional equation of the Riemann zeta function on the first zeta function term this becomes $$\frac{2}{(2\pi)^{2m}} \Gamma(m+it) \Gamma(m-it) \zeta(m+it) \zeta(m-it) \cos\left(\frac{1}{2}(m-it)\pi\right).$$ Now using the series representation of the zeta function in the half plane $\Re(s)>1$ it is easy to see that the two zeta function terms are conjugates of each other and hence their product is a real number. More importantly the value stays the same when $t$ changes sign. Similarly the limit definition of the gamma function shows that the product of the two gamma function terms is a real number, which also stays the same when $t$ changes sign. The factor in front no longer depends on $t.$ That leaves $$\cos\left(\frac{1}{2}(m-it)\pi\right) = \cos\left(\frac{\pi}{2}m - \frac{\pi}{2}it\right) = (-1)^{\frac{m-1}{2}} \sin\left(\frac{\pi}{2}it\right).$$ This term is indeed odd in $t$ which concludes the argument. Returning to the original computation we now know to shift the integral from $\Re(s) = 3/2$ to $\Re(s) = -(m-1),$ picking up only the residue at $s=1$ and profiting from the fact that the contribution from the left vertical segment is zero. (Set $x=1$ before the shift.) We have established that for $m$ odd and $m>1,$ $$\sum_{n\ge 1} \frac{n^{2m-1}}{e^{2\pi n}-1} = (-1)^{m+1} \frac{B_{2m}}{4m} = \frac{B_{2m}}{4m}.$$ There is a correction term of $1/\pi/8$ when $m=1$ originating as a half contribution from the pole at zero, which is on the left side of the contour. A: Take a look at equation $(6)$ in Ramanujan's Formula for the Logarithmic Derivative of the Gamma Function by David Bradley. Note that just before the formula it says, "Let $N$ be a positive integer," but the formula is valid for negative $N$ as well. EDIT: To answer Cody's question in the comments: When $N$ is a negative even integer, where $N=-2m,$ the sum on the RHS of $(6)$ is taken to be the empty sum, and so is equal to zero. This means that for $N=-4$ we have $$\sum_{k=1}^\infty \frac{k^7}{ e^{2\pi k} -1 } = \frac{\pi}{8} \sum_{k=1}^\infty \frac{k^8}{ \sinh^2(\pi k) } - \frac{1}{480}$$ and more generally $$\sum_{k=1}^\infty \frac{k^{4m-1}}{ e^{2\pi k} -1 } = \frac{\pi}{4m} \sum_{k=1}^\infty \frac{k^{4m}}{ \sinh^2(\pi k) } + \frac{B_{4m}}{8m}.$$
[ "stackoverflow", "0020438070.txt" ]
Q: Cocoa Setting Terminal Exit Code Variable I would like to be able to set a terminal variable; basically what I want to do is assign my own exit code through my app. My research finds that NSTask maybe the way to do this, but I can't say for sure how to go on about this since I know for one, I do not know if I can have a setLaunchPath:. Here is an example of what I would type in the terminal: bash-3.2$ $(exit 15); echo ${?}; 15 Sorry if the question doesn't sound very technical. Please ask if you need clarifications. Thx in advance. A: This isn't a good fit with a Cocoa application. Or are you considering a Foundation command-line tool? First, it's not typical to invoke a Cocoa application from a command-line shell. If you do, it's most common to do so using the /usr/bin/open command, which is not normally synchronous and so doesn't convey the app's exit status to the shell. Second, the process which exits does not directly set the shell variable. It exits with a status code and that's stored in the kernel. The shell then obtains that status code from the kernel and sets its own variable. It is not generally possible for one process to set an environment variable (or any other state) in another process (other than one it spawns itself) without that other process's cooperation. Third, a Cocoa application typically quits using -[NSApplication terminate:]. That doesn't provide a way to tell the framework what value to use as the exit status code. NSApplicationMain(), which is what's typically called by the app's main() function, is documented to never return and to call exit(). The documentation suggests that it may specify some meaningful status code – "If you want to determine why the application exited, you should look at the result code from the exit function instead." – but not what that might be nor any way to influence it. You might call exit() yourself from the -applicationWillTerminate: method of your application delegate. That way, you get to specify the status code. I'm not sure, though, if that might break any final cleanup that Cocoa might do. For example, if you have promised some data to the pasteboard, Cocoa requests that you provide it before your application terminates. I'm not sure if that occurs before or after -applicationWillTerminate: (probably before). That delegate call is in response to the application object posting the NSApplicationWillTerminateNotification notification and there may be other observers of that notification. The order in which observers get notified is not specified, so the app delegate is not necessarily the last thing that would get it.
[ "stackoverflow", "0057008432.txt" ]
Q: Function calculating 9 sums (of 'consecutive elements') of a vector with 10 elements let's say I have a vector test1 <- 1:10 I want to write a function that sums the values of 2 consecutive elements of this vector. The output will therefore necesseraly be of length 'test1 -1'. I looked up on the internet and found most of the times suggestions with loops. I am very new to R and still don't really get the syntax of loops and furthermore, I'd like to have a function because what I really want to do at the end is apply this function using the purrr package to a larger dataset. So I am really just looking for the code of this simple function so that I can use it afterwards for my big dataset. Also, I red something about "rolling window functions", which seems to be promising, but again, I am very new to R and I would like to keep it simple. The "cumsum" function is not what I am looking for as I am interested in the sum between 2 consecutive elements instead of the cumulative sum over all elements. The biggest problem I have right now is that I don't know how to tell R that really what I'm trying to sum over are consecutive positions rather than 2 values (not quite sure if you get what I mean). I tried stuff like sum_fun1 <- function(x) { [x] + [x+1] } but he doesn't get that x in that case refers to a position really, rather than the content of that position / element. Thanks a lot <3 A: You can use the rollapply function from the zoo package: library(zoo) test1 <- 1:10 x <- rollapply(test1, 2, sum) In this case the first argument is your data, the second is the width of the rolling window (number of observations) that you are considering; in your case, this is 2 since you are dealing with consecutive sums. The third argument is the function you want to apply to each rolling window, in this case, sum. You should be able to use it in your function.
[ "tex.stackexchange", "0000222263.txt" ]
Q: Overruling global node style in matrix I want to build a matrix of several nodes of different types. In my example there is a matrix containing two "modules" and one "label". For convenience I wanted to use matrix of nodes with nodes={module} since there are modules than labels. Now, if I want to set the style of the label, I would usually use |[label]| as in: \documentclass{article} \usepackage{tikz} \usetikzlibrary{matrix} \tikzset{ module/.style={draw, rectangle, fill=white, minimum width=4cm, minimum height=0.8cm}, label/.style={ } } \begin{document} \begin{tikzpicture} \matrix[fill=black!20, matrix of nodes, nodes={module}] { |[label]| Label \\ % this doesn't produce the desired output Module 1 \\ Module 2 \\ }; \end{tikzpicture} \end{document} This produces: Sure I could just specify every node explicitly, but this seems quite cumbersome. Is there a better solution? A: As label is predefined style in TikZ, for my answer I'll use mymodule and mylabel in place of module and label. What is happening here is that when you put nodes={mymodule} and then |[mylabel]|, the style of the cell became equivalent to |[mymodule,mylabel]|. So if mylabel/.style={} finaly the style of your cell is just like for all other cells |[mymodule]|. As @user43963 says in his comment, you have to overwrite the properties that you don't want anymore. Like this: \documentclass[varwidth,border=1cm]{standalone} \usepackage{tikz} \usetikzlibrary{matrix} \tikzset{ mymodule/.style={draw, rectangle, fill=white, minimum width=4cm, minimum height=0.8cm}, mylabel/.style={draw=none,fill=none} } \begin{document} \begin{tikzpicture} \matrix[fill=black!20, matrix of nodes, nodes={mymodule}] { |[mylabel]| Label \\ % this produce the different output Module 1 \\ Module 2 \\ }; \end{tikzpicture} \end{document}
[ "stackoverflow", "0007174127.txt" ]
Q: Ruby: taking unique subarrays with respect to a specific field Let's say there is an array of arrays of strings: array = [["John","Apples"],["Tim","Apples"],["Frank","Apples"], ["Tom","Pears"],["John","Pears"],["Frank","Oranges"],["Tim","Oranges"]] Now the game is to select any records that are unique on the second value of the Arrays in an easy way, e.g. the result could be: array2 = [["Frank","Apples"],["Tom","Pears"],["Tim","Oranges"]] Does anyone know if there's a one-liner that does this? A: Array#uniq can take a block argument: array.uniq { |e| e[1] } For example: >> array = [["John","Apples"], ["Tim","Apples"], ["Frank","Apples"], ["Tom","Pears"], ["John","Pears"], ["Frank","Oranges"], ["Tim","Oranges"]] >> array.uniq { |e| e[1] } => [["John", "Apples"], ["Tom", "Pears"], ["Frank", "Oranges"]] You'll probably get the first match (rather than the last as in your "could be" output) but I don't think there is any guarantee as to which one will be chosen. Note that this only works in 1.9, 1.8 doesn't like it so you'll have to work harder in 1.8 but not that much harder: array.inject({ }) { |h,e| h[e[1]] = e[0]; h }.map { |k,v| [ v, k ] } The inject/map version works the same in 1.8 and 1.9. Also, this one picks the last of the duplicated values. A: Another solution that should work in 1.8 and 1.9: array.group_by(&:last).map { |k,v| v.last } # => [["John", "Pears"], ["Frank", "Apples"], ["Tim", "Oranges"]] A: In Ruby 1.8: array.map{ |k,v| v }.uniq.map{ |uv| array.select{ |k,v| v == uv }.last } or Hash[*array.map{ |k,v| [v,k] }.flatten].map{ |k,v| [v,k] } [updated: "mu is too short" gave an excellent answer for Ruby 1.9, and the above answers I gave are good for Ruby 1.8]
[ "stackoverflow", "0029397540.txt" ]
Q: How to install numpy and scipy for Ironpython27? Old method doesn't work I think this is the most popular way to do it before: https://pytools.codeplex.com/wikipage?title=NumPy%20and%20SciPy%20for%20.Net But this link is no longer exist: https://store.enthought.com/repo/.iron/ I recently found a clone for the instruction, and also found a clone of ironpkg-1.0.0.py on github. But http://www.enthought.com/repo/.iron/eggs/index-depend.txt is no longer exists in the internet(I googled it, but failed to find it) Getting started with SciPy for .NET 1.) IronPython Download and install IronPython 2.7, this will require .NET v4.0. 2.) Modify PATH Add the install location on the path, this is usually: C:\Program File\IronPython 2.7 But on 64-bit Windows systems it is: C:\Program File (x86)\IronPython 2.7 As a check, open a Windows command prompt and go to a directory (which is not the above) and type: ipy -V PythonContext 2.7.0.40 on .NET 4.0.30319.225 3.) ironpkg Bootstrap ironpkg, which is a package install manager for binary (egg based) Python packages. Download ironpkg-1.0.0.py and type: ipy ironpkg-1.0.0.py --install Now the ironpkg command should be available: ironpkg -h (some useful help text is displayed here) 4.) scipy Installing scipy is now easy: ironpkg scipy numpy-2.0.0b2-1.egg Question I think I have done as much as I can do. Any body succeed to install numpy and scipy for Ironpython27? A: [COMMENT BY ENTHOUGHT SUPPORT: The link in this answer is not valid. See answer below by Jonathan March on August 17, 2018] For those struggling to get numpy/scipy install for ironpythopn, enthought have moved the download link to https://store.enthought.com/repo/.iron/ . The link would only allow you in if you are registered. Therefore first up you'd have to register yourself for free, then open the above link, then follow the steps below Download the IronPython-2.7.msi and install it. Download ironpkg-1.0.0.py from the above link. Using command line navigate to the directory where you placed ironpkg-1.0.0.py and run ipy ironpkg-1.0.0.py --install Check whether the install worked using ironpkg -h The last step is lightly different to the one suggested by enthoughts. Running ironpkg scipy won't work as it looks at the old web address for download. Instead download all the eggs and index-depend.txt from the above link. For installation to work, you would have to modify the download location in the config file to point to the local drive instead of website. The config file can be found at user directory eg.C:\Users\Nilster\.ironpkg . Open it in the textpad and change the location to directory where you downloaded the eggs Eg, mine looks like IndexedRepos = ['file://C:\Work\Python\Enthought_Eggs',] Then run the following to install numpy/scipy ironpkg scipy Check whether the install worked using ipy -X:Frames -c "import scipy" A: Enthought support here. The Iron Python numpy and scipy packages can be downloaded here: http://code.enthought.com/.iron/README.txt http://code.enthought.com/.iron/eggs/index.html FYI, Microsoft stopped work on the IronPython project in 2012 in favor of supporting standard CPython. Those archived versions of numpy and scipy were built in 2011 (so contain no newer features or fixes), and are 32-bit-only. We do not plan to update them in any way. FYI, we typically recommend that those who wish to use Python in a .net context consider using the actively developed pythonnet package to interface with the living CPython ecosystem.
[ "ru.stackoverflow", "0000864823.txt" ]
Q: Стилизация детей в CSS Здравтсвуйте. Нужна помощь в вертске flex-блоки таким образом, чтобы все элементы + 1 начиная со второго имели одинаковые стили. То есть у меня есть, например, 15 блоков, нужно чтобы первый блок был белый, второй и третий серый, четвертый и пятый белый, шестой и седьмой снова серый и так далее, что бы стили чередовались по 2 элемента. Не могу понять как этого добиться с помощью css. Чувтсвую, что нужно использовать nth-child, но какое правило не понимаю A: Сделать это можно к примеру так: *, *:after, *:before { -webkit-box-sizing: border-box; box-sizing: border-box; padding: 0; margin: 0; outline: 0; } /*стили выше добавлены только для этого примера, в реальном проекте используйте normilize.css\reset.css*/ .child { width: 50px; height: 50px; border: 2px solid #000; } .child:nth-child(4n+2), .child:nth-child(4n+3) { background: gray; } <div class="child">1</div> <div class="child">2</div> <div class="child">3</div> <div class="child">4</div> <div class="child">5</div> <div class="child">6</div> <div class="child">7</div> <div class="child">8</div> <div class="child">9</div> <div class="child">10</div> <div class="child">11</div> <div class="child">12</div> <div class="child">13</div> <div class="child">14</div> <div class="child">15</div>
[ "gaming.stackexchange", "0000177686.txt" ]
Q: What are the yellow and green glowing objects in minecraft? I made an end portal and defeated the ender dragon. What is the yellow and green stuff I collect? (I am on creative mode.) A: Those are experience orbs!: An Experience Orb is an entity similar to an item entity, an orb that fades between a green and yellow color. Experience orbs drop in the following situations: When a killed mob's corpse vanishes When a player is killed When animals breed When mining any ore that drops its mineral (that is, not iron, gold, or any use of Silk Touch). When you break a Bottle o' Enchanting. Mining (destroying) a spawner block Breeding animals. You also gain experience (but no experience orbs will drop) from: Smelting any of various items. Fishing. Trading with villagers. When you collect experience orbs your are rewarded with experience points. According to the "Experience Orb" page on the wiki, you collected 12,000 experience points from killing the Ender Dragon: The Ender Dragon drops 11 huge orbs totalling 12,000 experience points. When you collect enough experience points you will level up. You can use your levels for Enchanting, or to use an Anvil.
[ "stackoverflow", "0034034591.txt" ]
Q: Display multiple phone numbers with dashes I am struck into a problem in which situation is that I have a customer role in my website, for whom I have to save their phone numbers and alternative phone numbers but because customers belong to US, due to which there we need to poy dashes in their phone numbers. for example: 111-222-3333. I also have integrated a referral system in the site in which I am able to refer friends using their phone numbers.I can send referral to multiple phone numbers at once. For example: 111-222-3333, 111-333-444, 444-233-9330 But the condition is that the phone number which we are referring should not be in customer's profile (The user should not be already registered with that number). The problem arises when the customer's phone number is saved with dashes but because customer can refer multiple comma separated phone numbers, due to which I am unable to provide a pattern of dashes to fill phone number in. But now customer can send referral to phone number which is not dashed like (1112223333) which if anyone is already registered with the same phone number and having dashes like (111-222-3333). In such case it wont be matched with already registered phone number. And the Problem is about displaying the multiple phone numbers in dashes while referring. Can anyone please give solution for this. How to display multiple phone numbers with dashes. Sorry if you have any trouble in understanding the concept but I'll explain it again. Any help would be appreciated. Sorry I've edited the question. I didn't metion the actual problem A: It seems like you could fix the issue by stripping the phone numbers of all non-numeric characters before comparing them. You can strip all non-numeric characters from a string by using preg_replace as follows: $str = preg_replace('/[^0-9]+/', '', $str); Here's a short example of a comparaison: <?php $phoneNumber1 = "(418) 515-4184"; $phoneNumber2 = "4185154184"; if (preg_replace('/[^0-9]+/', '', $phoneNumber1) == preg_replace('/[^0-9]+/', '', $phoneNumber1)) { echo "Phone numbers are the same"; } else { // do stuff } ?> Hope that helps!
[ "stackoverflow", "0025634593.txt" ]
Q: Show new ViewController after tapping UIButton in a custom cell Heyhey! I'd like to show a ViewController with an Action (tappedInside of a UIButton in a custom cell). In this case I can't just control-drag from the UIButton in the custom cell to the NavigationController (ViewController is embedded). How can I realize that a "tappedInside" on a Button (in a custom cell) in a row of a tableview will show up a new ViewController? Thank you! A: You can trigger when you click a cell with the delegate: func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) { // some code } To open a new viewcontroller, if you use a storyboard you can try this: let storyboard = UIStoryboard(name: "Main", bundle: nil) let newVC = storyboard.instantiateViewControllerWithIdentifier("myIdentifier") as youClassController self.presentViewController(newVC, animated: false, completion: nil) Hope that help
[ "stackoverflow", "0004478121.txt" ]
Q: What's wrong with this SQL query? SELECT [travel], [fro_m], [t_o], [dep], [arr], [fare], [discount], [faresleeper], [rating], [seats], [s_no], [booking_closed] = CASE WHEN s1from <= @date AND s1to >= @date THEN s1Rate ELSE fare END WHEN s2from <= @date AND s2to >= @date THEN s2Rate ELSE fare END WHEN s3rate <= @date AND s3to >= @date THEN s3Rate ELSE fare END FROM a1_volvo WHERE (fro_m = @fro_m) AND (t_o = @t_o) A: The case statement is incorrect: CASE WHEN s1from <= @date AND s1to >= @date THEN s1Rate WHEN s2from <= @date AND s2to >= @date THEN s2Rate WHEN s3rate <= @date AND s3to >= @date THEN s3Rate else fare END You have and else statement after each line in the case statement. It should only be at the end. MSDN Case Statement
[ "stackoverflow", "0026482487.txt" ]
Q: Incorrect Linux free space I want to get Linux free space and memory using Java. public final class EnvironmentCheck { public EnvironmentCheck() { // If the HDD Free Space is less than 200 Megabytes write message HDD // is too low if (200 > checkHDDFreeSpace()) { System.out.println("*** WARNING Hard Drive free space " + checkHDDFreeSpace() + " Megabytes " + "is too low! ***"); } // If the RAM Free Space is less than 200 Megabytes write message HDD // is too low if (200 > checkRAMFreeSpace()) { System.out.println("*** WARNING RAM free space " + checkRAMFreeSpace() + " Megabytes " + "is too low! ***"); } } public long checkHDDFreeSpace() { long availableSpace = 0; FileSystem fs = FileSystems.getDefault(); for (FileStore store : fs.getFileStores()) { try { availableSpace = store.getUsableSpace() / (1024*1024); } catch (IOException e) { } } return availableSpace; } public long checkRAMFreeSpace() { Runtime rt = Runtime.getRuntime(); long freeMem = rt.maxMemory() - (rt.totalMemory() - rt.freeMemory()); return freeMem / (1024 * 1024); } } I get always this message: * WARNING Hard Drive free space 0 Megabytes is too low! * Can you help me to fix my code? On Windows I don't see this warning message. A: I guess you want to sum the total space availableSpace += store.getUsableSpace() / (1024*1024);
[ "stackoverflow", "0001762568.txt" ]
Q: How to change category page layout in Magento? My problem is I want to change my category page layout similar as homepage I tried a lot but didn't get the answer. A: However, the best way to do this is to not edit catalog.xml, but page.xml under , edit the first block you see there: <block type="page/html" name="root" output="toHtml" template="page/3columns.phtml"> change this to: <block type="page/html" name="root" output="toHtml" template="page/2columns-right.phtml"> for further detail follow this link http://www.magentocommerce.com/boards/viewthread/16838/ A: Login to admin side Catelog -> manage Categories -> Choose your category Then on the tab section select Custom Design. Change the Page Layout as what ever you want. A: I am not sure if I understand your question. Anyways... You can edit the category view at template/catalog/category/view.phtml. If you require to use the 3 column layout like the home page, you need to assign the 3 column template in the catalog.xml file.
[ "unix.stackexchange", "0000240858.txt" ]
Q: error in script for counting number of occurences #!/bin/sh count=1 while read line do found=$( grep M $line ) if [ "$found" ]; then echo $count")" $line >> filesave.txt fi count=$((count+1)) done < log1.txt but I am getting error like ./count.sh ./count.sh: syntax error at line 10: `found=$' unexpected A: The problem is unquoted variable reference $line in either found=$( grep M $line ) and/or echo $count")" $line >> filesave.txt` in both cases $line should be double-quoted: found=$( grep M "$line" ) echo $count")" "$line" >> filesave.txt` The example uses the lines from log1.txt as filenames, which may not be what you want. If you want to search each line read from log.txt for the string M, then you could use this: found="$( echo "$line" | grep M )" After this, $found would equal $line only if $line contained the letter M.
[ "stackoverflow", "0022422092.txt" ]
Q: How to improve string parser method for 2 columns (reading 2 string on a line) public class testing_string { public static void read_doc_word(String line){ String doc_id = "" ; String word_id = "" ; boolean doc_id_ends = false ; for(int i = 0 ; i < line.length() ; i++){ if(line.charAt(i) == 9) doc_id_ends = true ; // 9 is TAB in asci else if(doc_id_ends == false) doc_id += line.charAt(i) ; else if( doc_id_ends == true) word_id += line.charAt(i) ; } System.out.println("doc id " + doc_id ) ; System.out.println("word id " + word_id ) ; } public static void main(String[] args) { String x = "1 29" ; read_doc_word(x) ; } } Input: every line has 2 numbers. What is better way to do it? I want to avoid the ugly "doc_id += line.charAt(i) " , concatenating every char to string. How do I just do this: read the whole string before tab skip tab read the whole stringafter tab or only way is to check every char? (like I did) I d like to avoid checking every char! A: You should be using String.split(). Please refer this documentation. So your code can be modified as follows: public static void read_doc_word(String line){ String doc_id = "" ; String word_id = "" ; String[] split ; split = line.split("\\t"); if(split.length==2){ doc_id = split[0]; word_id = split[1]; } System.out.println("doc id " + doc_id ) ; \\ 1 System.out.println("word id " + word_id ) ; \\29 } Please note that in order to split by tab, you need to use the regular expression "\\t" and not just "\t".
[ "stackoverflow", "0008899212.txt" ]
Q: php filtering an array by key I have a csv file in a format resembling the following. There are no column heads in the actual file - They are shown here for clarity. id|user|date|description 0123456789|115|2011-10-12:14:29|bar rafael 0123456789|110|2012-01-10:01:34|bar rafael 0123456902|120|2011-01-10:14:55|foo fighter 0123456902|152|2012-01-05:07:17|foo fighter 0123456902|131|2011-11-21:19:48|foo fighter For each ID, I need to keep the most recent record only, and write the results back to the file. The result should be: 0123456789|110|2012-01-10:01:34|bar rafael 0123456902|152|2012-01-05:07:17|foo fighter I have looked at the array functions and don't see anything that will do this without some kind of nested loop. Is there a better way? A: const F_ID = 0; const F_USER = 1; const F_DATE = 2; const F_DESCRIPTION = 3; $array = array(); if (($handle = fopen('test.csv', 'r')) !== FALSE) { while (($data = fgetcsv($handle, 1000, '|')) !== FALSE) { if (count($data) != 4) continue; //skip lines that have a different number of cells if (!array_key_exists($data[F_ID], $array) || strtotime($data[F_DATE]) > strtotime($array[$data[F_ID]][F_DATE])) $array[$data[F_ID]] = $data; } } You'll have, in $array, what you want. You can write it using fputcsv. NOTE. I didn't test this code, it's meant to provide a basic idea of how this would work. The idea is to store the rows you want into $array, using the first value (ID) as the key. This way, on each line you read, you can check if you already have a record with that ID, and only replace it if the date is more recent.
[ "biology.stackexchange", "0000017235.txt" ]
Q: How does Oedipus complex fit in the evolutionary theory? This is somthing that really makes me curious. How is posible that trough a evolution process the best posible candidate is the one that falls in love whith his progenitor? A: It doesn't. The Oedipus complex is one of Freud's theories to explain human behavior, not something that is endorsed by the fields of psychology or psychiatry. Freud had a lot of interesting theories, some of which remain core concepts in psychology, and some of which have been marginalized or rejected. There are some professionals who feel it has merits for consideration, to one degree or another, but if you look at publications by the APA (American Psychological Association) and Psych.org (American Psychiatric Association), you won't see in their practice guidelines. APA: http://psycnet.apa.org/journals/pst/32/4/535/ Wikipedia: http://en.wikipedia.org/wiki/Oedipus_complex#Criticism If you're asking how might it fit with evolution if it were to be true, that's more of a philosophical question - which perhaps is the better angle from which to approach the question. In "survival of the fittest" - "fittest" is better described as "those who most successfully reproduce and produce offspring that are also highly successful in reproducing." Reproducing with one's immediate family results frequently in severe birth defects, the opposite of "fit." Those who want to reproduce with their mother but don't, and reject all other mates, will not reproduce. Not "fit." The only possibility similar to the oedipal complex is that males choose mates that are like their mothers. What is true is that we often marry someone similar to our parent - but it is not a result of an actual oedipal complex. Freud wrote the oedipal complex in part to try to explain this phenomenon. But there are better explanations - we are attracted to that with which we are most familiar, to that which makes us feel comfortable, to that which makes us feel warm and fuzzy. Our definition of beauty is largely shaped by family faces - because that is what you are surrounded with as your mind develops. Etc etc.
[ "sharepoint.stackexchange", "0000032977.txt" ]
Q: What is the proper way to change your site collection's URL to a friendly name? I have an internal portal in a SharePoint 2007 application containing one site collection with six subsites. The Subsites are functional areas within the portal which users may navigate to. Pages within the sites host Silverlight applications which access an external, custom database. My users have been navigating in it with no trouble, but the URL was an obscure server name. I decided I would "fix" this by adding a DNS entry for the portal name and resolving it with Host Headers on the server. User may still navigate around with the old URL (the server name). My fix is mentioned on Server Fault here How to use Host Headers... If they use the new portal name, they get to landing page, but all navigation afterwards is odd. They may get to the right page, but get an authentication challenge. The Silverlight applications are not working properly. I don't expect anyone here to help me with Silverlight. What have I done, and how do I really fix it this time? Did I change the URL the proper way? Will any fix allow users to use the old url (server name) to get there? A: Use alternate access mapping, configurable through Central administration, application management. Since sharepoint does lots of background stuff, it is generally inadvisable to set up alternate names with anything other than aam. If you want to go more into your silverlight issues, myself and I'm sure other on this site are capable of helping you. And it is on topic to talk about silverlight as it pertains to a SharePoint webpart application.
[ "android.stackexchange", "0000012894.txt" ]
Q: After update to GRJ90 I can no longer use WiFi hot-spot My phone updated to GRJ90 about two weeks ago and now I can no longer use WiFi hot-spot or USB tethering. When I try, my 3G connection is dropped. After disconnecting and waiting a few minutes, it comes back up. I used to be able to tether before the update. How can I bypass this, or stop the 3G from disconnecting when tethering. Sprint tells me that I need to pay for a hot-spot plan for $30, but there has to be a way around this besides rooting my phone and putting Cyanogen on it. Phone: Nexus S 4G from Google Carrier: Sprint A: Sprint tells me that I need to pay for a hot-spot plan for $30, but there has to be a way around this besides rooting my phone and putting Cyanogen on it. Sprint clamped down and disabled the previously free built-in tethering with the latest update. If you want USB tethering you can try PDANet, but wifi tethering will almost certainly require you to root, as it does on other devices. Even with root, you don't necessarily need to use CyanogenMod if you don't want to, though; you could just as easily install a free tethering app (one example). This has been covered here a lot, in fact, so you might want to take a look at any wifi tethering apps noted in other questions. See also: Is there a way to enable WiFi-tethering without root access?
[ "stackoverflow", "0028447908.txt" ]
Q: Package msm: segmentation-fault when introducing covariates While using the package msm, I am currently getting the error: * caught segfault * address 0x7f875be5ff48, cause 'memory not mapped' when I introduce a covariate to my model. Previously, I had resolved a similar error by converting my response variable from a factor to a numeric variable. This however does not resolve my current issue. The data <- https://www.dropbox.com/s/wx6s4liofaxur0v/data_msm.txt?dl=0 library(msm) #number of transitions between states #1: healthy; 2: ill; 3: dead; 4: censor statetable.msm(state_2, id, data=dat.long) #setting initial values q <- rbind(c(0, 0.25, 0.25), c(0.25, 0, 0.25), c(0, 0, 0)) crudeinits <- crudeinits.msm(state_2 ~ time, subject=id, data=dat.long, qmatrix=q, censor = 4, censor.states = c(1,2)) #running model without covariates (fm1.msm <- msm(state_2 ~ time, subject = id, qmatrix = crudeinits, data = dat.long, death = 3, censor = 4, censor.states = c(1,2))) #running model with covariates (fm2.msm <- msm(state_2 ~ time, subject = id, qmatrix = crudeinits, data = dat.long, covariates = ~ gender, death = 3, censor = 4, censor.states = c(1,2))) Alternatively, I can run the models with covariates if I set the state values dead and censor (3 & 4) to missing. #set death and censor to missing dat.long$state_2[dat.long$state_2 %in% c(3,4)] <- NA statetable.msm(state_2, id, data=dat.long) #setting initial values q <- rbind(c(0, 0.5), c(0.5, 0)) crudeinits <- crudeinits.msm(state_2 ~ time, subject=id, data=dat.long, qmatrix=q) #running models with covariates (fm3.msm <- msm(state_2 ~ time, subject = id, qmatrix = crudeinits, data = dat.long, covariates = ~ gender)) (fm4.msm <- msm(state_2 ~ time, subject = id, qmatrix = crudeinits, data = dat.long, covariates = ~ covar)) Thanks for your help A: In version 1.5 of msm, there's an error in the R code that detects and drops NAs in the data. This is triggered when there are covariates, and the state or time variable contains NAs. Those NAs can then be passed through to the C code that computes the likelihood, causing a crash. I'll fix this for the next version. In the meantime you can work around it by dropping NAs from the data before calling msm.
[ "stackoverflow", "0034698845.txt" ]
Q: 'ManyToManyField' object has no attribute 'm2m_reverse_field_name' I'm trying to run a migration for my Django project, but I'm getting the error: AttributeError: 'ManyToManyField' object has no attribute 'm2m_reverse_field_name' I when I ran make migrations on all my apps, I didn't get any errors. It's only when I try to actually migrate. I can't tell from the traceback information which model is creating the problem, or even which app. I've looked at my models, and I don't see anything that pops out at me. Here is the stack trace: Operations to perform: Apply all migrations: admin, sessions, case_manager, file_manager, auth, contenttypes, tasks, people_and_property Running migrations: Rendering model states... DONE Applying file_manager.0006_auto_20160109_1536...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 342, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor) File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/db/migrations/migration.py", line 123, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 201, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 467, in alter_field return self._alter_many_to_many(model, old_field, new_field, strict) File "/home/mint/Python_Projects/venv/lib/python3.4/site-packages/django/db/backends/sqlite3/schema.py", line 274, in _alter_many_to_many old_field.remote_field.through._meta.get_field(old_field.m2m_reverse_field_name()), AttributeError: 'ManyToManyField' object has no attribute 'm2m_reverse_field_name' How do I figure out which model is the problem? What should I look for? A: You have to make sure that the model you are creating the 'ManyToManyField' is already created in the database. You can do that by adding as a dependency the migration where the model is created to your migration in which you alter the field: Scenario 1: You alter the field to 'ManyToManyField' with a model from other app class Migration(migrations.Migration): dependencies = [ .......... ('[app]', '__first__'), ] operations = [ ......... ] Scenario 2: You create a 'ManyToManyField' and the model you are referring to is in the same file: class Migration(migrations.Migration): dependencies = [ .......... ] operations = [ ......... # Make sure the model you are making the reference with is before the ManyToManyField migrations.CreateModel(...) , migrations.AlterField/CreateField(...) ] A: I ran into the same problem, but I don’t know if for the same reasons. Luckily I don’t have any important data in the system, so I just changed the migration as follows – but note that this deletes all data in these columns! Before: operations = [ migrations.AlterField( model_name='resource', name='authors', field=models.ManyToManyField(related_name='resources_authored', to='api.Person'), ), migrations.AlterField( model_name='resource', name='editors', field=models.ManyToManyField(blank=True, related_name='resources_edited', to='api.Person'), ), ] After: operations = [ migrations.RemoveField( model_name='resource', name='authors', ), migrations.RemoveField( model_name='resource', name='editors', ), migrations.AddField( model_name='resource', name='authors', field=models.ManyToManyField(related_name='resources_authored', to='api.Person'), ), migrations.AddField( model_name='resource', name='editors', field=models.ManyToManyField(blank=True, related_name='resources_edited', to='api.Person'), ), ] While the altering failed for mysterious reasons, removing and recreating the fields worked.
[ "pt.stackoverflow", "0000337645.txt" ]
Q: 'str' object has no attribute 'encrypt' Fiz um programa que gera uma chave publica e outra chave privada, faz a serialização delas e salva elas em um arquivo .key. Dai tentei criar outro programa encriptar e desencriptar uma mensagem com essas duas chaves geradas em no outro programa, como posso fazer isso? from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.asymmetric import padding #o que ira ser criptografado. message = b"UMA CHAVE MUITO SECRETA" #chave privada gerada em outro programa e salva em um arquivo .key private_key ="""-----BEGIN ENCRYPTED PRIVATE KEY----- MIIFLTBXBgkqhkiG9w0BBQ0wSjApBgkqhkiG9w0BBQwwHAQIxLaJgjeSQbcCAggA MAwGCCqGSIb3DQIJBQAwHQYJYIZIAWUDBAEqBBDskixa53SXACIzrP/txssvBIIE 0HkKNOthGTkec0AtC28AX0H/8kCfuboCTnIejxJ7b1KUJc3g4tn51OLPwavEQw2q 2Lk8DgPHPVoWzYp7wU8a0wdWKkeZW/il6c+v7CjwxdO2SFVxsPj4UuCwcfx0+WcE 8EA9ueaPQTwF+DsSbDSsee24ajeOOTYJQbuliImedcrG8mt3pjawJ+KiN0xY9p15 6nnGZj8A5GFQJrSYae4hl46qycZ+B5CYSvnmprHDmqUopEESXCnl6TT8e8NoFASM xNJOQsd7B0Lgj1HliQz22MXq9T/H8bWEB1lw2vtWmWS8EBDlUuanC779CTYjbVUW s+DyJ4hl/6t5/rzQBKiLcbQqtzDTeTEp9GfH845Ui4fAoQ2vuPq5CoxlD6raSBTv 9X2GsRaBYtfiXSvWcXeo3bl4cvLIAr/ogIuKo+wVoWF579Jgxb4NhBCjRUwBfJY3 GjGIY4lLVoQ4O570uVEYotlzKnP0JmHiBh+ltPfV9GH5u5ZEIaiWXUQMlR/PRbaw y57O+O7pUfBt7SmBvijL0+BaIG3NKt+a8lThRn8pIl4Q4bLm8sm6RAPFOCGD8XDa Q3+7LbqGwDjHQ1+lYG9ZHvK3KuCKTq0uTAWSmJwh9cnNyO34QmoZI/PX4BiXXlj7 gbsCapn0BEOpW+WIekda50yxUSagfLTdUzvMS4ZcxUW6vEdNuFygRSXkPStmKpsC QR8QppDfLT/0nlUPifxt5clKUekImy5nTTFloP/udEfxoAdscSWHOrXYmLnFvdk2 Cyw/PwEKjo/MMpDi1dkR0v6aNeVIU87QRgCVp8xq93fqGNzLod7hSqQ2mu3sSKms DjPObtQ6WPgKN4iyNBRjRjkQsrB6tF1rThhgvXZuY0ubSVtMd688SK7I1vbe51Es UsVS/Ivf8th7jHSFsZI40h58D37HC6Djj+s4D0Ip9DwsX4MjUFcp4XKKqlQO/106 Jmgyui72LEopWpP8ysErqlnrn67ByIqrQZr92wZEyczK+uZDCrBJHPU5tAB1zN8O jTpGRIh/SZxkH3r/i34p+jGZWbPEzUbz57d8Y9f2/sIqGqOS0hXqEInljSM0Hpe3 Y71l4dDHPrHVL6KeBHW7Z3kUHGv2AfCYUQrvP0jp7VzgGHmLLcNx4Mtra4QQe798 Oqn3MJMiOGWyKx7md46NAfHwguRrQbQWBCEh5rL+GU/bVXthKEAgvU6hNCd9f0z0 sGsCR5/jeFyNHQ0L1JhsjpqBiYKrh9PZhO4eeKBh9Jnm+pstotG/7SyxBo83sDQb sT8SniRqRkdnHi6Rv4RNNpfh5Obd6hGV7Mi4TdPmvCTc4WF32gUU0QGoXw0CvWtR DnljEYWj199jwSdUrHeMjnjKtCJDt3+FoNVxM+TCC9zmMWq1Oj0FSu9CAZM5dlYZ knO+sLo3K36ptfFbFofG9WmaElPIlRPdx0YMf32U8gRgKpZBZoztlEtjeqrf9rvP 0PrpUweJzVBfvt9q+TvG35TMa4IPUeVi0Od1dtk6pdPmMHlG7z1+LBaRMlm1wzj5 Qxc30xZPFOWCmsLUJah+oxovEFcyWeQ6rH7qufqzEYHLm876uxKGSKJSTwYk5Boi 4XsrVl9UUGjvh9XsnMnIGc/xSrTuNAW4qhLvrdcuPXf8 -----END ENCRYPTED PRIVATE KEY----- """ #chave publica gerada em outro programa e salva em um arquivo key. public_key = """-----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxu6aLyNkusNci2aiIVoK 5Bc8JcwsBx5Rfq/S7u0OWRnQz+KXnJ+QEOTozP/ywzaubsuVSEr73dtkbrSvx/7K mGg9qiqgR6f3pUOKt4d7FGV/HBwYcHaEI8albex9vTInjsT5YiLG0fppjckLvYrZ xtjUcOsbOCYr7hUc1YgbyM5whbXbuCmC48KzAvEwIZnq1K0qqM5rea7y88a0Izr6 ADt6aGe/O8p13TSWbBeH+tufISSDBo2GN+KCWgYJ6heLcu7sS+9SvdxDwp+KaO0z lWOocA+Tcpc3Zu5KDS/lIq1LZDAmjVIl6I4+8UvGDmhnIvAKHFroW1Ulg7TptBKz pwIDAQAB -----END PUBLIC KEY----- """ #criptografando ciphertext = public_key.encrypt( message, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None ) ) print(ciphertext) #descriptografando normaltext = private_key.decrypt( ciphertext, padding.OAEP( mgf=padding.MGF1(algorithm=hashes.SHA1()), algorithm=hashes.SHA1(), label=None ) ) print(normaltext) A: Tá faltando código aí - Você tenta chamar public_key.decrypt() mas public_key é uma str - um tipo padrão que já vem definido no python - e nenhuma str tem os métodos decrypt nem encrypt, então falta uma peça no seu quebra-cabeça. Acredito que esses métodos que você quer chamar devem estar definidos em outro objeto da biblioteca de criptografia que está usando, e não em objetos do tipo str. Veja este exemplo que tirei da documentação da biblioteca: # ... >>> from cryptography.fernet import Fernet >>> key = Fernet.generate_key() >>> f = Fernet(key) >>> token = f.encrypt(b"my deep dark secret") # ... Como pode ver, ele chama o método .encrypt() em f que é uma instância da classe Fernet() e não em uma str. Ele passa a chave criptográfica para essa classe Fernet() o que retorna um objeto f que, esse sim, tem o método encrypt().
[ "stackoverflow", "0001141998.txt" ]
Q: Most useful Rails plugins, Ruby libraries and Ruby gems? I have seen many sites which provide the whole list of Rails plugins, Ruby libraries and Ruby gems, but we hardly use few of them and some may not suit our requirement and we spend a whole lot of time searching for useful Plugins which suits our requirement. I have created this poll, people can post useful libraries, gems and plugins which they have come across. It would be great help for newbies like me and to the entire Ruby on Rails community. Note: to keep this poll as useful as possible, please remember: Post only one library, gem, or plugin per answer Mention the name of the library, gem, or plugin which you find it useful. URL of the location of the resource We don't want duplicate answers, so before posting check if the library has been mentioned already. Edit: Any new plugins/Gems for Rails 3 ? Thanks! A: Will Paginate - essential for pagination. A: HAML and SASS A: devise - a more comprehensive authentication gem
[ "stackoverflow", "0008355536.txt" ]
Q: Data-Theme set to page not applied to header and footer with jquerymobile Maybe there is something obvious I cannot see but I think that setting data-theme in the div with data-role=page was supposed to set it for everything: <!DOCTYPE html> <html> <head> <title>Page Title</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.css" /> <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script> <script type="text/javascript" src="http://code.jquery.com/mobile/1.0/jquery.mobile-1.0.min.js"></script> </head> <body> <div data-role="page" data-theme="b"> <div data-role="header"> <h1>Page Title</h1> </div><!-- /header --> <div data-role="content"> <p>Page content goes here.</p> </div><!-- /content --> <div data-role="footer"> <h4>Page Footer</h4> </div><!-- /footer --> </div><!-- /page --> </body> </html> But I still get the default theme A What am I doing wrong? Or is this a bug? It was working in 1 alpha 4 but not in 1 final. A: Check the docs, http://jquerymobile.com/demos/1.0/docs/pages/pages-themes.html it specifically says: "However, headers and footers will default to theme "a". If you want to have a page with, for example, only theme "b" for all its elements, including its header and footer, you will need to specify data-theme="b" to the page div as well as the header and footer divs. " So this is not a bug.
[ "stackoverflow", "0044391903.txt" ]
Q: SQL calculation based on another column I am extracting data out of SQL database and need to calculate the opening balance of a stock item per project. I am getting the opening balance for the stock inclusive of all the projects. item code | Project | Qty In | Qty Out ----------+---------+--------+--------- 1234 1 0 90 1234 1 90 0 1234 2 431 0 1234 2 0 22 1234 3 925 0 1234 3 0 925 1234 3 925 0 1234 3 0 20 1234 3 0 40 1234 3 0 30 1234 3 0 40 1234 3 0 60 1234 3 0 50 1234 3 0 24 1234 3 0 40 1234 3 0 30 1234 3 0 17 1234 3 0 80 1234 3 0 30 1234 4 16 0 1234 4 0 16 1234 5 22 0 1234 5 0 23 Query: select OpeningBalanceQty = Qty_On_Hand + (select case when ServiceItem = 0 then IsNull(sum (QtyOut), 0) else 0 end from table1 where AccountLink=StockLink and txdate>='2016-06-01' and project ='2' ) - (select case when ServiceItem = 0 then IsNull(sum (QtyIn), 0) else 0 end from table1 where AccountLink=StockLink and txdate>='2016-06-01' and project ='2') from tablel join table2 on table1.AccountLink = table2.StockLink I have used project 2 as an example, it has two transactions(qty in:431)& (qty out:22) My opening balance should be 409 but it is giving the total for the product item My full code: select Table1.TxDate,Table2.Pack,Table1.Reference, OpeningBalanceQty= (select case when ServiceItem = 0 then IsNull(sum (QtyOut), 0) else 0 end from Table1 where AccountLink=StockLink and ProjectCode in('2') ) - (select case when ServiceItem = 0 then IsNull(sum (QtyIn), 0) else 0 end from Table1 where AccountLink=StockLink and ProjectCode in('2')) ,ProjectCode,ProjectDescription, Code, Description_1, Sum(ActualQuantity)*-1 as [Qty Processed],Sum(Debit)-Sum(Credit) as [Value],Trcode from Table1 join Table2 on Table1 .AccountLink = Table2.StockLink where ServiceItem = 0 and txdate>='2017-06-01 00:00:00' and txdate<='2017- 06-30 00:00:00' and Code='1234' Group by Description_1, Code,ProjectCode, ProjectDescription, stocklink, serviceitem,Qty_On_Hand,Table1.Reference,Table2.Pack,Table1.TxDate,trcode A: Do you think this could be helpful for you? SELECT PROJECT, SUM( QTYIN-QTYOUT) AS OPEN_BAL_QTY FROM yourtable WHERE txdate>='2016-06-01' GROUP BY PROJECT Output: PROJECT OPEN_BAL_QTY 1 0 2 409 3 464 4 0 5 -1 1° update: after your new information (pls, next time, try to give all the information in your initial post, and well formatted: see tour of stackoverflow to learn how to do). If you are using MSSQL 2005 or later, you can try this: SELECT TABLE1.TXDATE ,TABLE2.PACK ,TABLE1.REFERENCE , SUM(QTYIN-QTYOUT) OVER (PARTITION BY TABLE1.PROJECTCODE) AS OPEN_BAL_QTY ,PROJECTCODE ,PROJECTDESCRIPTION ,CODE ,DESCRIPTION_1 ,-SUM(ACTUALQUANTITY) AS QTY PROCESSED , SUM(DEBIT) - SUM(CREDIT) AS VALUE ,TRCODE FROM TABLE1 JOIN TABLE2 ON TABLE1.ACCOUNTLINK = TABLE2.STOCKLINK WHERE SERVICEITEM = 0 AND TXDATE >= '2017-06-01 00:00:00' AND TXDATE <= '2017-06-30 00:00:00' AND CODE = '1234' GROUP BY DESCRIPTION_1 ,CODE ,PROJECTCODE ,PROJECTDESCRIPTION ,STOCKLINK ,SERVICEITEM ,QTY_ON_HAND ,TABLE1.REFERENCE ,TABLE2.PACK ,TABLE1.TXDATE ,TRCODE 2° update If it doesn't work for you, you should try: SELECT A.* ,B.OPEN_BAL_QTY FROM SELECT TABLE1.TXDATE ,TABLE2.PACK ,TABLE1.REFERENCE ,PROJECTCODE ,PROJECTDESCRIPTION ,CODE ,DESCRIPTION_1 ,-SUM(ACTUALQUANTITY) AS QTY PROCESSED , SUM(DEBIT) - SUM(CREDIT) AS VALUE ,TRCODE FROM TABLE1 JOIN TABLE2 ON TABLE1.ACCOUNTLINK = TABLE2.STOCKLINK WHERE SERVICEITEM = 0 AND TXDATE >= '2017-06-01 00:00:00' AND TXDATE <= '2017-06-30 00:00:00' AND CODE = '1234' GROUP BY DESCRIPTION_1 ,CODE ,PROJECTCODE ,PROJECTDESCRIPTION ,STOCKLINK ,SERVICEITEM ,QTY_ON_HAND ,TABLE1.REFERENCE ,TABLE2.PACK ,TABLE1.TXDATE ,TRCODE ) A LEFT JOIN (SELECT PROJECTCODE, SUM( QTYIN-QTYOUT) AS OPEN_BAL_QTY FROM TABLE1 WHERE TXDATE>='2017-06-01' AND TXDATE <= '2017-06-30 00:00:00' GROUP BY PROJECT) B ON A.PROJECT_CODE = B.PROJECT_CODE
[ "stackoverflow", "0012184816.txt" ]
Q: Rails ActiveRecord Query for Not Equal Rails 3.2.1 Is there a way (without squeel) to use the hash syntax of ActiveRecord to construct a != operator? Something like Product.where(id: !params[:id]) Generates SELECT products.* FROM products WHERE id != 5 Looking for the opposite of Product.where(id: params[:id]) UPDATE In rails 4 there is a not operator. Product.where.not(id: params[:id]) A: You can use the following Product.where('id != ?', params[:id]) Which will generate what you are looking for, while parameterizing the query. With Rails 4, the following syntax has been added to support not clauses Product.where.not(id: params[:id]) Add multiple clauses with chaining... Product.where.not(id: params[:id]).where.not(category_id: params[:cat_id]) A: There isn't any built-in way to do this (as of Rails 3.2.13). However, you can easily build a method to help you out: ActiveRecord::Base.class_eval do def self.where_not(opts) params = [] sql = opts.map{|k, v| params << v; "#{quoted_table_name}.#{quote_column_name k} != ?"}.join(' AND ') where(sql, *params) end end And then you can do: Product.where_not(id: params[:id]) UPDATE As @DanMclain answered - this is already done for you in Rails 4 (using where.not(...)). A: Rails 4 has this figured out. So maybe you could just update your rails app Model.where.not(:id => params[:id])
[ "stackoverflow", "0057379036.txt" ]
Q: Can you update a collection in MongoDB and remove the first/last char on one field? My question might be simple be here's some more context to it. I have a MySQL DB, I've used an ETL tool to populate a MongoDBwith, however I couldn't manage to create proper ObjectId reference to it (I can only get a string of the ObjectId. So far I've had an idea (maybe crazy but still.. could work) I got this field populated like this in one document : "field1" : "ObjectId('5d48845c456145ee9d1ccffde')", What I would want to achieve through mongoDB is removing the first and last char to get (stripping the double quotes): "field1" : ObjectId('5d48845c456145ee9d1ccffde'), (note that MongoDB seems to automatically convert simple to Double quote after the change, so my reference become corret). Problem is, I don't find anything close to a sort of Update script for MongoDB to achieve this. Is there any way to do this ? Using NodeJS could work, however, querying the document at this state doesn't return the field1 (probably cause it find it incorect)... A: If its one time update, you can use the following query: db.COLLECTION.aggregate([ { $addFields:{ "field1":{ $toObjectId:{ $substrBytes:[ "$field1", 10, 24 ] } } } }, { $out:"COLLECTION" } ]) In aggregation, the 'field1' is cast to ObjectId. Later on, the old data in the collection is replaced with the aggregated one.
[ "stackoverflow", "0016799777.txt" ]
Q: Can't get Rails Server to work with MySQL I'm trying to get my Rails application to work with MySQL and not default SQLite. I've created a new project that forces the use MySQL which seemed to work correctly. It added gem entry in the Gem file as so: source 'https://rubygems.org' gem 'rails', '3.2.13' # Bundle edge Rails instead: # gem 'rails', :git => 'git://github.com/rails/rails.git' gem 'mysql2' And when I run the bundle command it shows that its using mysql gem: Using mysql2 <0.3.11> I've also configure the database.yml file as so: development: adapter: mysql2 encoding: utf8 reconnect: false database: dbname pool: 5 username: uname password: pass host: hostname test: development: adapter: mysql2 encoding: utf8 reconnect: false database: dbname pool: 5 username: uname password: pass host: hostname production: development: adapter: mysql2 encoding: utf8 reconnect: false database: dbname pool: 5 username: uname password: pass host: hostname But when I try to run the rails server I get this: C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/mysql2-0.3.11-x86-mingw32/l ib/mysql2/mysql2.rb:2:in require': 126: The specified module could not be found . - C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/mysql2-0.3.11-x86-min gw32/lib/mysql2/1.9/mysql2.so (LoadError) from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/mysql2-0.3.11- x86-mingw32/lib/mysql2/mysql2.rb:2:in' from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/mysql2-0.3.11- x86-mingw32/lib/mysql2.rb:9:in require' from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/mysql2-0.3.11- x86-mingw32/lib/mysql2.rb:9:in' from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.4/ lib/bundler/runtime.rb:72:in require' from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.4/ lib/bundler/runtime.rb:72:inblock (2 levels) in require' from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.4/ lib/bundler/runtime.rb:70:in each' from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.4/ lib/bundler/runtime.rb:70:inblock in require' from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.4/ lib/bundler/runtime.rb:59:in each' from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.4/ lib/bundler/runtime.rb:59:inrequire' from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/bundler-1.3.4/ lib/bundler.rb:132:in require' from C:/Users/n00151956/Desktop/RubyProjects/Demo/config/application.rb: 7:in' from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-3.2.1 3/lib/rails/commands.rb:53:in require' from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-3.2.1 3/lib/rails/commands.rb:53:inblock in ' from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-3.2.1 3/lib/rails/commands.rb:50:in tap' from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-3.2.1 3/lib/rails/commands.rb:50:in' from script/rails:6:in require' from script/rails:6:in' I was able to get the rails server running with default SQLite but for the life of me I can't get it working with MySQL. If anyone can help me out with this that would be great help! Thanks A: Download libmysql.dll file from - mysql-connector and put it in C:\RailsInstaller\Ruby1.9.3\bin should be here Image open command prompt as administrator and start the mysql server the following way: C:\Program Files\MySQL\MySQL Server 5.0\bin\mysql Update development: adapter: mysql2 database: proj_development username: root password: pass host: 127.0.0.1 socket: /tmp/mysql.sock test: adapter: mysql2 database: proj_test username: root password: pass host: 127.0.0.1 socket: /tmp/mysql.sock production: adapter: mysql2 database: proj_production username: root password: pass host: 127.0.0.1 socket: /tmp/mysql.sock
[ "stackoverflow", "0054373918.txt" ]
Q: Grouping parameters Say I have functions which accept the same parameters and I want to test if their outputs are equivalent for the same input. f :: a -> b -> c g :: a -> b -> c f a b == g a b How can I package the parameters a and b in x so I can write the following instead. f x == g x What are the best ways to accomplish this without needing to wrap the functions themselves? A: The only way to do exactly what you’re asking is to use uncurry: let x = (a, b) in uncurry f x == uncurry g x (Or uncurryN for N arguments.) However, instead of packaging the arguments in a tuple, you could use the (->) x instance of Applicative (i.e., functions taking x as input) to implicitly “spread” the arguments to the parameters of both functions, so at least you only have to mention them once. This instance is commonly used in point-free code. For example, using liftA2 specialised to this instance: -- General type: liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c -- Specialised to ‘(->) x’ (using TypeApplications syntax): liftA2 @((->) _) :: (a -> b -> c) -> (x -> a) -> (x -> b) -> (x -> c) You get this pattern: liftA2 h f g x -- = (h <$> f <*> g) x -- = h (f x) (g x) To lift more arguments, you add another liftA2 or … <$> … <*> …: liftA2 (liftA2 h) f g x y -- = (liftA2 h <$> f <*> g) x y -- = h (f x y) (g x y) So in a case like yours: f, g :: Int -> Char -> Bool f i c = chr i == c g i c = i == ord c (liftA2 . liftA2) (==) f g :: Int -> Char -> Bool -- = liftA2 (liftA2 (==)) f g -- = (\ x y -> f x y == g x y) The N in liftAN corresponds to the number of functions; the number of liftAN calls corresponds to the number of arguments.
[ "unix.stackexchange", "0000490922.txt" ]
Q: byobu configuration menu escape / exit always closes the tab I've been using byobu for ~4 years at this point and I do not remember this behavior before. If I press F1 (this always happens by accident actually, with the exception of initial setup I never want to see this menu again) which brings up the byobu configuration menu the normal way to exit is to press the escape key. This used to bring me right back to the byobu tab I was on. But now, it closes the current tab, making me lose that tab. I can't tell if the session / programs are still running (haven't tested anything really). How do I fix this behavior so it doesn't close? Is it a new bug / change in behavior? Or is there some potential odd thing in my setup that could be causing this? I'm using a mac. A: Add the following lines to the ~/.byobu/keybindings.tmux file: unbind-key -n F1 unbind-key -n F9 bind-key F1 new-window -n config byobu-config bind-key F9 new-window -n config byobu-config This removes a -k argument of the new-window command which kills the existing window and replaces it. I don't know if this issue affects other operating systems; I suspect this is a macOS X issue.
[ "stackoverflow", "0047478770.txt" ]
Q: test.bas() error 23: File not found I'm trying to run a simple FreeBASIC program: Print "Hello World" However when I try to run it, it gives me these errors: yamboy1@laptop:~$ fbc test.bas test.bas() error 23: File not found, crt1.o test.bas() error 23: File not found, crti.o test.bas() error 23: File not found, crtn.o ld: cannot find -lncurses ld: cannot find -lm ld: cannot find -ldl ld: cannot find -lpthread ld: skipping incompatible /usr/lib/gcc/x86_64-linux-gnu/5/libgcc.a when searching for -lgcc ld: cannot find -lgcc ld: skipping incompatible /usr/lib/gcc/x86_64-linux-gnu/5/libgcc_eh.a when searching for -lgcc_eh ld: cannot find -lgcc_eh ld: cannot find -lc This is not the same as this post A: This seems like a 32-bit / 64-bit mismatch, as if ld is looking for a 32-bit gcc toolchain. Did you by chance install the 32-bit FreeBasic? It seems you are on a 64-bit machine, so if you did, try grabbing and installing the 64-bit version from: https://sourceforge.net/projects/fbc/files/Binaries%20-%20Linux/FreeBASIC-1.05.0-linux-x86_64.tar.gz/download
[ "stackoverflow", "0051756258.txt" ]
Q: Table empty when populating cells from json I am trying to populate a table with json content. Everything seems to work fine except that the table is not showing any data. Actually, the code shown below should display the "title" information of each json data array into one cell. See line cell.textLabel?.text = myNewsItems[indexPath.row].title However, from what I can see in the console output, I can verify that the news array is parsed like expected (see Checkpoint: print(myNewsS)). Any idea what I am missing? Swift4 import UIKit // structure from json file struct News: Codable{ let type: String let timestamp: String let title: String let message: String } class HomeVC: UIViewController, UITableViewDelegate, UITableViewDataSource{ var myTableView = UITableView() var myNewsItems: [News] = [] override func viewDidLoad() { super.viewDidLoad() let barHeight: CGFloat = UIApplication.shared.statusBarFrame.size.height let displayWidth: CGFloat = self.view.frame.width let displayHeight: CGFloat = self.view.frame.height myTableView = UITableView(frame: CGRect(x: 0, y: 150, width: displayWidth, height: displayHeight - barHeight)) myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") myTableView.dataSource = self myTableView.delegate = self self.view.addSubview(myTableView) // JSON let url=URL(string:"https://api.myjson.com/bins/ywv0k") let session = URLSession.shared let task = session.dataTask(with: url!) { (data, response, error) in // check status 200 OK etc. guard let data = data else { return } do { let myNewsS = try JSONDecoder().decode([News].self, from: data) print(myNewsS) DispatchQueue.main.async { self.myTableView.reloadData() } } catch let jsonErr { print("Error json:", jsonErr) } } task.resume() } func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return myNewsItems.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = myNewsItems[indexPath.row].title return cell } } A: Assign the array myNewsItems = myNewsS DispatchQueue.main.async { self.myTableView.reloadData() }
[ "stackoverflow", "0014823008.txt" ]
Q: How to parse XML in a Windows Phone 7 application Could someone tell me how to parse a XML-String that i receive from a wcf-rest service? my webserive XML-String looks like <WS> <Info> <Name>Beta</Name> <Description>Prototyps</Description> </Info> <Pages> <Page> <Name>Custom</Name> <Description>toDo</Description> </Page> ...many other pages... </Pages> </WS> an my phone sourcecode: public void DownloadCompleted(Object sender, DownloadStringCompletedEventArgs e) { if (!e.Cancelled && e.Error == null) { var answer = XElement.Parse(e.Result).Descendants("WS"); // null ... } } if i try to parse it through XDocument.Load(e.Result) then i get the exception: File not Found. i just want the "unique" information of the Info-Node and a list of all Page-Nodes with their values Update Even if i try to load the Root-Element via var item = xdoc.Root.Descendants(); item will be assigned to the whole xml-file. Update 2 it seems the problem occurs with the namespaces in the root-element. with namespaces xdocument will parse the webservice output not correctly. if i delete the namespaces it works fine. could someone explain me this issue? and is there a handy solution for deleting all namespaces? update 3 A Handy way for removing namespaces1 A: With really simple XML if you know the format wont change, you might be interested in using XPath: var xdoc = XDocument.Parse(e.Result); var name = xdoc.XPathSelectElement("/WS/Info/Name"); but for the multiple pages, maybe some linq to xml var xdoc = XDocument.Parse(xml); var pages = xdoc.Descendants("Pages").Single(); var PagesList = pages.Elements().Select(x => new Page((string)x.Element("Name"), (string)x.Element("Description"))).ToList(); Where Page is a simple class: public class Page { public string Name { get; set; } public string Descrip { get; set; } public Page(string name, string descrip) { Name = name; Descrip = descrip; } } Let me know if you need more explanation. Also to select the Info without XPath: var info = xdoc.Descendants("Info").Single(); var InfoName = info.Element("Name").Value; var InfoDescrip = info.Element("Description").Value;
[ "stackoverflow", "0046689164.txt" ]
Q: VBA if conditions I wrote if condition which is shown below, it looks for value "Current Status:" in row A and copy B value from that row to other sheet, if not not found "0" is placed in a cell, it works fine. Sometimes value "Current Status:" might be in a different cell than A18, it might show up in the range from A16 to A20, how can I modify that code to find it within the range and copy corresponding value? If ws.Range("A18") = "Current Status:" Then .Range("V" & NewRow) = ws.Range("B18") Else .Range("V" & NewRow) = "0" End If A: Just put your code in a For loop... or use VLookup like Scotty suggested. It's basically the same thing. A For loop is more flexible but less optimized (VLookup is faster). They both run on the order of fractions of a μs/cell. For Each c In Range("A16:A20") If c.Value2 = "Current Status:" Then .Range("V" & NewRow) = c.Offset(0, 1) Exit For Else .Range("V" & NewRow) = "0" End If Next If using a For loop, this is a little bit more code than what's above but a better structure... 'Define a value holder variable where it's scope makes sense Dim NewValue As String '... other code here ... 'Default: NewValue = "" NewValue = "" For Each c In Range("A16:A20") If c.Value2 = "Current Status:" Then NewValue = c.Offset(0, 1) 'Exit For is optional in this case. It matters if 'there are multiple matches... do you want first or last result? Exit For End If Next 'Assign NewValue to cell .Range("V" & NewRow) = NewValue
[ "math.stackexchange", "0003334331.txt" ]
Q: Classic Quantitative Trading interview probability question, what's wrong with my reasoning? I roll a die up to three times. You can decide to stop and choose the number on the die (where the number is your payoff) during each roll. What's your strategy? I am confused about the strategy for the first roll. My reasoning is this: the chance of getting a 5 or 6 from rolls 2 and 3 is: $$1 - 4/6*4/6=1-4/9=5/9$$ So, you have a greater than $50\%$ chance to get a 5 or a 6 on either the 2nd or 3rd dice. Thus, you'd want to select the first dice only when it rolls a 6. However, this answer is incorrect. The solution says the Expected value during the first roll is \$4.25, which I can understand how they computed, and thus the strategy would be to settle with either a 5 or 6 on the first roll, but I can't figure out my logical fallacy. A: Work backwards from the end. The EV for the last roll is $3.5$. Thus on the second to last roll you should reroll if you get a $1,2,3$ and keep the die if you have a $4,5,6$. Thus we have an EV for the last two rolls of $\frac{1}{2}5 + \frac{1}{2}3.5 = 4.25$. Hence for the first roll, you should keep the die if you get a $5$ or $6$, and reroll otherwise. As for your fallacy, it's hard to say what your fallacy is because your reasoning is unclear. The goal is to maximize the EV, so it doesn't make sense to be talking about whether or not you have a greater than $50\%$ chance of rolling a $5$ or $6$ on the second and third rolls. That seems to be entirely unrelated to the question you're being asked. The question is how can you maximize your EV, which can be done by at each step comparing the EV of continuing to roll the die vs the value of keeping your current die.
[ "stackoverflow", "0043991282.txt" ]
Q: openssl md5 in command line and php md5 produce different results Here is the string I am submitting as text file (csr.txt) with command line https://pastebin.com/qBLJcKQB openssl command I am passing is: openssl req -noout -modulus -in csr.txt | openssl md5 e199562f2e9f6a29826745d09faec3a6 Here is the php script version for getting the md5 hash <?php $csr = '-----BEGIN CERTIFICATE REQUEST----- MIIBxzCCATACAQAwgYYxCzAJBgNVBAYTAlVLMQ8wDQYDVQQIDAZMb25kb24xDTAL BgNVBAcMBEJsYWgxDjAMBgNVBAoMBUJsYWgxMQ4wDAYDVQQLDAVCbGFoMjETMBEG A1UEAwwKSm9lIEJsb2dnczEiMCAGCSqGSIb3DQEJARYTb3BlbnNzbEBleGFtcGxl LmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAsfzWjyj7zlVFlXCaGMH6 Gj3jsWV2tC6rLnRKK4x7hUaI0JriqXUQTNYKTgVhDslR1K0zrJYcaqpmwb4PrUJ/ 2RY5si7QvHnndwJ3NOdHFOK8ggn1QqRvFFo4ssPpYWGY63Abj0Df9O6igEHQRQtn 5/9WkkM8evLLmS2ZYf9v6W8CAwEAAaAAMA0GCSqGSIb3DQEBBQUAA4GBADLYvFDq IfxN81ZkcAIuRJY/aKZRcxSsGWwnuu9yvlAisFSp7xN3IhipnPwU2nfCf71iTe/l SZifofNpqrnamKP90X/t/mjAgXbg4822Nda1HhbPOMx3zsO1hBieOmTQ9u03OkIZ hkuQmljK8609PGUGcX5KeGBupZPVWJRf9ly7 -----END CERTIFICATE REQUEST-----'; $csrDetails = openssl_pkey_get_details(openssl_csr_get_public_key($csr)); echo md5($csrDetails['rsa']['n']); ?> php script produces: 718926bb97aabc0fd1116fa25c295612 I have seen other threads which talk about excluding new line but in my case I am not using echo but rather using openssl. Why PHP's md5 is different from OpenSSL's md5? Appreciate some assistance. NOTE: If I drop from the command line "| openssl md5" & in the php script remove md5() then the results are identical php script produces: echo strtoupper(bin2hex($csrDetails['rsa']['n'])); B1FCD68F28FBCE554595709A18C1FA1A3DE3B16576B42EAB2E744A2B8C7B854688D09AE2A975104CD60A4E05610EC951D4AD33AC961C6AAA66C1BE0FAD427FD91639B22ED0BC79E777027734E74714E2BC8209F542A46F145A38B2C3E9616198EB701B8F40DFF4EEA28041D0450B67E7FF5692433C7AF2CB992D9961FF6FE96F A: In the php version you are hashing the binary representation of the modulus, i.e. the binary data 0xB1FCD68F28.... With the command line version you are hashing a printable text string representation of the modulus, i.e. the string "Modulus=B1FCD68F28...". Assuming you are on a machine using an ASCII based character set, this translates to the binary data 0x4D6F64756C... Therefore you are hashing different data in each case and so you are going to get a different result. Also it looks like openssl is adding a "\n" to the end of the output from the "openssl req ..." command. From php try running md5("Modulus=B1FCD68F28...\n"), i.e. note using " instead of ' and the \n on the end. I tried that and got "e199562f2e9f6a29826745d09faec3a6" - the same as the OpenSSL command line
[ "stackoverflow", "0009019773.txt" ]
Q: Encoding differences between using WebClient and WebRequest? In getting some random spanish newspaper's index I don't get the diacriticals properly using WebRequest, they yield this weird character: �, while downloading the response from the same uri using a WebClient I get the appropriate response. Why is this differentiation? var client = new WebClient(); string html = client.DownloadString(endpoint); vs WebRequest request = WebRequest.Create(endpoint); using (WebResponse response = request.GetResponse()) { Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); string html = reader.ReadToEnd(); } A: You're just assuming that the entity is in UTF-8 when creating your stream-reader without explicitly setting the encoding. You should examine the CharacterSet of the HttpWebResponse (not exposed by the WebResponse base class), and open the StreamReader with the appropriate encoding. Otherwise, if it reads something that's not UTF-8 as if it was UTF-8, it'll come across octet-sequences that aren't valid in UTF-8 and have to substitute in U+FFFD replacement character (�) as the best it can do. WebClient does pretty much this: DownloadString is a higher level method, that where WebRequest and its derived classes let you get in lower, it has a single call for "send a GET request to the URI, examine the headers to see what content-encoding is in use, in case you need to un-gzip or de-compress it, see what character-encoding is in place, set up a text-reader with that encoding and the stream, and then call ReadAll()". The normal high-level-big-chunk-instructions vs low-level-small-chunk-instructions pros and cons apply.
[ "stackoverflow", "0012645849.txt" ]
Q: Web Automation - Dealing with .aspx I'm trying to accomplish a little bit of automation which includes submitting a form on a webpage. The values for the form are already coded per item in the list. I've tried many different modules with Python and nothing seems to give me an answer. I don't have access to Visual Basic and I've personally never dealt with .aspx pages before. This is the Form name And I thought I was set and ready to go when I found the parameters for the form: function ShowEditForm(id, param1, param2, param3, param4) #actual parameter names removed for security And this is the part that's the major headache: <INPUT id=__EVENTTARGET type=hidden name=__EVENTTARGET> <INPUT id=__EVENTARGUMENT type=hidden name=__EVENTARGUMENT> <INPUT id=__VIEWSTATE type=hidden value=/wEPDw... #This continues for 800+ characters I believe this is the cause of my failure of code, am I on a witchhunt trying to post to an .aspx form in python? Thanks A: you would need to parse/parameterize your post headers and contents. this can be non-trivial. check out mechanize for access at the HTTP level, with some form handling convenience. check out selenium, for driving a real browser in Python.
[ "stackoverflow", "0053370243.txt" ]
Q: Understanding stack-allocated objects deallocation I'm trying to understand how deallocation of stack-allocated objects behaves. To be precise, I'm trying to find an explanation in the standard (N1570). Consider the following simple function: void foo(){ char test[4096]; test[10] = 0; } Here the test array will be deallocated when foo exits. It is easy to see in objdump that test is allocated on the stack. The standard (emphasis mine) states: An object whose identifier is declared with no linkage and without the storage-class specifier static has automatic storage duration, as do some compound literals. So test has automatic storage duration. We can easily rewrite the function as follows: void test(){ char *test= malloc(4096 * sizeof(char)); test[10] = 0; free(test); } But we have to deallocate it by ourselves, and yet test still has automatic storage duration. QUESTION: How the standard specifies that char test[4096] will be deallocated on function exit? The standard does not state that test is allocated on the stack, it is implementation defined. A: The standard describes the various storage durations at §6.2.4 1 An object has a storage duration that determines its lifetime. There are four storage durations: static, thread, automatic, and allocated. Allocated storage is described in 7.22.3. 2 The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it. An object exists, has a constant address, and retains its last-stored value throughout its lifetime. If an object is referred to outside of its lifetime, the behavior is undefined. The value of a pointer becomes indeterminate when the object it points to (or just past) reaches the end of its lifetime. 6 For such an object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way. (Entering an enclosed block or calling a function suspends, but does not end, execution of the current block.) If the block is entered recursively, a new instance of the object is created each time. The initial value of the object is indeterminate. If an initialization is specified for the object, it is performed each time the declaration or compound literal is reached in the execution of the block; otherwise, the value becomes indeterminate each time the declaration is reached. So you are pretty much correct. It doesn't at all describe when and how storage is deallocated per se. It only specifies when that storage is accessible with well-defined semantics. An implementation need not deallocate the storage of a variable with automatic storage duration right away, you just can't touch it if you want your program to be standard compliant. For allocated storage the same goes, with the added caveat that you have to explicitly tell the implementation you are done with the storage. But even if you do "free" it, an implementation may hold on to it still for a while longer. It's possible on paper for a very poor implementation to exist, one which never deallocates memory. But in practice, those are culled naturally because poor implementations of C just become disused by the masses, and abandoned.
[ "stackoverflow", "0027886055.txt" ]
Q: Form field validation - who renders the error? I have a model which contains 2 fields of type PositiveSmallIntegerField. And I have a ModelForm for this model and these fields. My validation works fine. But if I type in negative number or alphanumeric string, I get the validation error as some sort of pop-up(see images below). My question: is the validation error rendered by the browser? Shouldn't the error be rendered by Django as HTML code? And can I translate this error with django translations? Also, in my clean method of the form I have a custom validation and I do this: if cleaned_data['capacity_min'] > cleaned_data['capacity_max']: raise ValidationError(_("Some message")) I can translate this one and it is rendered as I was expected, simple HTML code in the page Thank you This is what happens with firefox This is what happens with Google Chrome A: These hint errors are showed by browser. Browser rejects to submit the invalid form to the server so your django validation didn't even run. To solve this problem change the widget for you field from NumberInput to TextInput: class MyForm(forms.ModelForm): class Meta: ... widgets = { 'capacity_min': forms.TextInput(), 'capacity_max': forms.TextInput(), }
[ "stackoverflow", "0007578786.txt" ]
Q: How to check alignment of text using selenium RC verify alignment of text or any other element in web page using selenium rc. i use python, is there any budy who can help with this. A: you can utilize getAttribute command for example String align = selenium.getAttribute("ele_locator@align");
[ "ru.stackoverflow", "0000289328.txt" ]
Q: Считать пробел в консоле С++. Я считываю символ который ввел пользователь.Выглядит это так: char temp=' '; cout <<"Введите любойсимвол"<<endl; cin>>temp; Проблема в том, что это работает со всеми символами, кроме пробела. Когда ввожу пробел ничего не происходит. Подскажите, пожалуйста, как считать пробел в консоли? A: Попробуйте cin.get().
[ "stackoverflow", "0015125853.txt" ]
Q: rAppid.js for mobile app - is server-side rendering practical? I'm evaluating the rAppid.js framework as a candidate for a new project. The project will be a web app aimed primarily at mobile devices (I will be using web views to wrap it as an app that can be submitted to the Apple and Android App Stores). I realize that's not the primary use case that rAppid.js was built for but I think it could potentially work well, at least in my case, thanks to rAppid.js's XML-based UI language. Could I, in theory, use the new rAppid.js server to render templates there and send the rendered HTML to the client? Given that I want the pages to load as quickly as possible, and the app doesn't need to work offline, I'd prefer to render the templates on the server side and send them to the client as plain HTML. Obviously the framework could only provide me with one-way data-binding in this case (unless I reworked the rAppid.js code to support a server-rendering model similarly to the Derby framework) but I think the performance improvement for the app could be worth it. Maybe I'm being overly pessimistic about rAppidJS's client-side rendering speed on mobile devices but in any case I'd be curious to hear opinions on this. A: Could I, in theory, use the new rAppid.js server to render templates there and send the rendered HTML to the client? Yes, with the node rendering feature. But please keep in mind, that node-rendering was developed for SEO reasons. Because of this background the only state of the application is the url. This could fit into you application concept (e.g. /user/{userid}/news) to render the news of the user, but the rendered site will be completely static. So if you relay on user inputs, client side validation, you should use rAppid:js the way it was designed, and render the complete application on the client. Given that I want the pages to load as quickly as possible, and the app doesn't need to work offline, I'd prefer to render the templates on the server side and send them to the client as plain HTML. Obviously the framework could only provide me with one-way data-binding in this case (unless I reworked the rAppid.js code to support a server-rendering model similarly to the Derby framework) but I think the performance improvement for the app could be worth it. My experience from RIA is that the have an initial loading phase (Flex applications showing a loader, iOS native applications shows a image until the app is ready) and the the app works quickly without additional load times. If you separate the application into modules (rAppid.js supports this very well) and just load the module during start that is needed the app should load really fast. If you wrap the app within a web view, the JS performance is slightly better than running it within the mobile browser. You can also try a combination of server and client side rendering, but without mixim them up. So render the page on the server and show the static html during the loading phase of the application. As long as the application is completely loaded switch the views. Maybe I'm being overly pessimistic about rAppidJS's client-side rendering speed on mobile devices but in any case I'd be curious to hear opinions on this. In our latest project we also added a preloader and separated the project into modules. In comparison to the flash version we also have it is 10 times smaller and loads faster in desktop systems. On mobile it doesn't load because of the flash plugin, so I cannot compare it. If you want a great performance on the mobile devices, split the application into several modules and load them only if the are needed. rAppid:js supports module loading based on routes, so it is also possible to start the application with a preselected module.
[ "math.stackexchange", "0002612488.txt" ]
Q: About constant product If we had two number variables A and B with their product to be a constant C; A x B = C. Doesn't that mean that if I increased A by an amount "n" and decreased B with the same amount "n" , then their product should not change and stays equal to C. But its not true, since for example : 5x3=15 ; (5-1)x(3+1)=16 and not equal to 15 I know that I have proved it wrong, but intuitively I'm still not convinced.. A: That's what I meant. If $ab=c$ then for $n \ne 0$ $$ \left(na\right)\left(\frac{b}{n}\right)=ab\frac{n}{n}=c $$ With an example $8\times10=80$ and $$ \left(2\times 8\right)\left(\frac{10}{2}\right)=16\times 5=80 $$
[ "softwareengineering.stackexchange", "0000206197.txt" ]
Q: Is it appropriate to have positive comments in code reviews, or is it exclusively for constructive criticism? I have been doing a lot of code review lately, and I am unsure of the positive and negative effects and professionalism of putting positive and/or funny comments in code reviews. We use Github as our code review platform on my team, so the comments are viewable by anyone. I generally try to use this platform so the entire process from start to finish is visible and historical. A: It's important to highlight positives as well as negatives. I know if I were reviewing the refactor of a particular hellish subsystem into something neat and clean, I'd probably buy the programmer a pizza for his efforts. If you're using reviews as training, it's doubly important - highlighting a good piece of code will be helpful for the junior programmers also reviewing that code. They will have a chance to ask questions about why a particular approach or technique is better than another. A: Funny: Save it for the water cooler, except in minimal doses - having a prune face is not a requirement for reviewing code. Positive: Certainly. Review includes both positive and negative/constructive, by definition. Positive Feedback helps everyone: For the one receiving the thumbs up, you reinforce their confidence and inspire them to do more of the same through your positive feedback. For the rest, as others have mentioned, they will learn what to do, as well as what not to do. They will also be encouraged to excel, so they too can one day be in the spotlight. I once worked for a boss who was liberal in his positive feedback - the team was very successful and productive as a result. He moved on, and others took over that lacked his ability to praise a job well done. Productivity and morale took a nosedive, and many of the better team members left the firm. A: I'd say keep the comments clean and to the point, exactly because of culture. You cannot avoid that some people will take things the wrong way. In order to mitigate that, a personal one to one talk will smooth things along, if face to face is not possible, chat or email or skype.
[ "stackoverflow", "0033455196.txt" ]
Q: Unable set background color to List item in Custom CursorAdapter I am trying to give alternate background color to my list view. I am using cursor adapter. Here is my CustomCursorAdapter class CustomCursorAdapter.java public class CustomCursorAdapter extends CursorAdapter { public CustomCursorAdapter(Context context, Cursor c) { super(context, c); } @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View retView = inflater.inflate(R.layout.single_row_item, parent, false); return retView; } @Override public void bindView(View view, Context context, Cursor cursor) { TextView textViewPersonName = (TextView) view.findViewById(R.id.tv_person_name); textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1)))); } @Override public View getView(int position, View convertView, ViewGroup parent) { final View row = super.getView(position, convertView, parent); if (position % 2 == 0) row.setBackgroundColor(Color.parseColor("#191919")); else row.setBackgroundColor(Color.parseColor("#323232")); return row; } } In getView(); I have setBackgroundColor to view. but they are not get assigned properly only texview background color are got affected. and here is my single_row_item.xml single_row_item.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp"> <ImageView android:layout_width="wrap_content" android:layout_height="match_parent" android:id="@+id/imageView2" android:src="@drawable/icon" /> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:textAppearance="?android:attr/textAppearanceMedium" android:text="Medium Text" android:id="@+id/tv_person_name" android:layout_marginLeft="10dp" /> </LinearLayout> and this is my output. please tell me how to do this. A: I have found the Answer. It was just small silly mistake. In My Activity's XML in which I have list view. That list view should have width = "fill_parent" or "match_parent".
[ "stackoverflow", "0045180346.txt" ]
Q: Properly Using Firebase Cloud Functions and Stripe I am trying to use Firebase Cloud functions and Stripe, and iOS (Swift). I want to use Firebase Cloud functions to perform the card charge as is required by Stripe. I am trying to use this example: Firebase Stripe Example I uploaded the example they gave, but I need to modify the charge function slightly. I tried setting it to the file path I have in my real time data base, but I am not sure how to modify the entire thing so that It will work off of my realtime database structure. Such as grabbing the parameters it needs. Here is what my structure looks like: after the Payments node is the userID. I know that the function basically looks for database updates to the specific node, but I am not sure how to make sure it grabs the correct values from the child nodes. I hope I have described this in an understandable way. If I haven't let me know and I will do my best to reword. Thank you! A: Alright guys I figured it out myself and I will write a mini tutorial here. Because this question specifically deals with stripe I will only cover this specific use case. First it is important to read the Stripe documentation. It specifies the parameters it is expecting you to give to it's api. Here is the link for what is expected when you charge a card with Stripe: Stripe Charges Documentation Second you need to model your Firebase Realtime database after those expected parameters, at least in regards to the purchases a user will make in your app. Most of the time you can use a dictionary with Key:value pairs. Make sure you multiply your amount parameter by 100 as Stripe only takes integers. This means if you you are charging 22.48 for example then you multiply it by 100 to get 2248. When you check your dashboard in stripe it will show up as 22.48. Third Stripe needs to talk to a back end so that you can charge the card. Firebase Cloud functions are perfect for this. Remember your real time database? Well you can trigger a Cloud function when a write occurs on a node that you specify. Luckily Firebase has provided a sample on GitHub: Firebase Stripe Example You can modify the line of code where it listens for a write to the data base. You can change it to your structure specifically as long as you return at least the token and the amount to be charged. If you are going to make the user enter their information every time, then you need to delete the customer parameter (in the index.js file) as it will expect a different token with a different prefix. (This is noted in the documentation) The rest of the example is well documented and can be followed. The outcome of the charge will be written back into your database. The following video shows you how Functions triggered on write work and some of the nomenclature used. : Youtube Video for Cloud Functions triggered on write. I hope this helps a few of you as I know questions about stripe and firebase are fairly common.
[ "stats.stackexchange", "0000040402.txt" ]
Q: How to find effects of several mostly categorial variables on a numeric value? I have the following problem: I want to analyze the following data: Sales of products per year with respect to product type product group (similar products types are grouped together) country where it was sold kind of application product was sold for So except the year all of those variables are categorial. What statistical methods could be used to create a prognose for the future and to analyze the existing data and the effects and interactions of the above mentioned factors on the sales figures? If it would be numerical factors, I'd think a regression could help - what can be done in this case? (My knowledge in statistics is quite limited up to now.) A: Regression can handle categorical predictors with no problem. Most statistical packages (e.g. R, SAS) will dummy code the categorical variables for you and allow various types of parameterization (effect coding, reference coding, etc)
[ "stackoverflow", "0034802084.txt" ]
Q: How to pass backend data to display as multiselect dropdown items (Jsfiddle attached) This is with reference to fiddle link -->> https://jsfiddle.net/etfLssg4/ As you can see in the fiddle, user can select multiple dropdown items. The dropdown values have been selected during initialization. Lisa and Danny are the default items selected. it gets displayed at the dropdown bar as shown in fiddle. The default values is set by this line of code. $scope.example13model = [items[2], items[4]]; Now the scenario is as follows. The backend data is passed to front end via string. it is as follows David,Danny It means David and Danny should be displayed at dropdown. Currently it is "Lisa,Danny" Heres the explaination of how this should happen. Once we get David,Danny from server side, it will compare with the list of items. From that list, it will come to know that David is number 0 and Danny is 4th of the list. The list is as follows. (as shown in fiddle) var items = [{ id: 1, label: "David" }, { id: 2, label: "Jhon" }, { id: 3, label: "Lisa" }, { id: 4, label: "Nicole" }, { id: 5, label: "Danny" }]; Once it knows the number, the code will then display the list of items selected by this line of code. $scope.example13model = [items[0], items[4]]; Can someone let me know how to achieve this dynamically. for eg. if string from backend contains only 'lisa', it should display Lisa at the dropdown. If there are 3 names passed as string from backend, it should be able to show those 3 names at dropdown. A: var items = [{ id: 1, label: "David" }, { id: 2, label: "Jhon" }, { id: 3, label: "Lisa" }, { id: 4, label: "Nicole" }, { id: 5, label: "Danny" }]; var backendSelection = "David,Lisa"; var selectedLabels = backendSelection.split(","); $scope.example13model = items. filter(function(item) { // if the the label property of the current item // is found in selectedLabels, return true (i.e. allow the current item // to pass through the filter) otherwise false. return selectedLabels.some(function(label) { // whenever the following expression evaluates to true, // the current item will be selected. return label === item.label; }); });
[ "stackoverflow", "0046696879.txt" ]
Q: Angular2 Material : Custom Validation for Angular Material Input In my Angular 2 and material application, I want to check whether username has already taken or not. If it is already taken then it should show the error. I am following below guide. https://material.angular.io/components/input/overview#error-messages Typescript file import {Component} from '@angular/core'; import {FormControl, Validators} from '@angular/forms'; const existingUserNames = ['rohit', 'mohit', 'ronit']; @Component({ selector: 'input-errors-example', templateUrl: 'input-errors-example.html', styleUrls: ['input-errors-example.css'], }) export class InputErrorsExample { emailFormControl = new FormControl('', [ Validators.required ] // I want to call below isUserNameTaken function but dont know // how to use it with Validators so that error message will be visible. isUserNameTaken() : boolean { this.attributeClasses = attributeClasseses; this.attributeClasses.find( object => { if(object.attributeClass === this.attributeClass) { console.log("found " + JSON.stringify(object)); return true; } }); return false; } } HTML <form class="example-form"> <md-form-field class="example-full-width"> <input mdInput placeholder="Email [formControl]="emailFormControl"> <md-error *ngIf="emailFormControl.hasError('required')"> Email is <strong>required</strong> </md-error> <!-- I want to make something like that - custom validation --> <md-error *ngIf="emailFormControl.hasError('username-already-taken')"> Username is already taken. Please try another. </md-error> <!-- custom validation end --> </md-form-field> A: You just have to change your function to receive a component as parameter and return null if everything is ok and an error object if it's not. Then, put it on the component validator's array. // Control declaration emailFormControl = new FormControl('', [ Validators.required, isUserNameTaken ] // Correct validator funcion isUserNameTaken(component: Component): ValidationErrors { this.attributeClasses = attributeClasseses; this.attributeClasses.find( object => { if(object.attributeClass === this.attributeClass) { console.log("found " + JSON.stringify(object)); // found the username return { username-already-taken: { username: component.value } }; } }); // Everything is ok return null; } It's explained in more depth in the link that Will Howell put on the comments. It also explains how to do the same for non reactive forms. Tutorial
[ "meta.stackoverflow", "0000387723.txt" ]
Q: Answer a question... inside the question In order to improve my question I always stated some approaches I've already tried to do right after the question description itself. Besides, I want to maintain my question - edit and add information. It applies to the list of "possible" solutions as well. I.e. while reading answers/thinking about/discussing the problem in comments, new solutions appear and I tend to append it all into the list with corresponding information, drawbacks, etc. And if the question has not a single trivial answer, but rather multiple ways to try with its pros and cons, this list becomes large. Q: Should I do this? Here I see several problems: By the time for some new reader of my question it may look like I have already answered my own question at the end of it. So the reader will just think - "all main possibilities already counted. I don't do plagiarism as well as don't want to waste my time devising some tricky-non-mentioned solution here". And will stop reading/participating. At first I'm not accepting answers (only if my question is so simple). Because I see that the problem is not fully solved or there are some flaws in solution or simply want to involve more people into discussion. But when my list of solutions is large - I even barely can accept any. Because proposed answers contain different approaches (which might be quite good), but none of them is full. The full answer resides in the end of my question that I've collected... But at the same time I'm even not sure that it's complete or in opposite - see that some small details still are not solved. But about these details nobody wants to think because of 1. And even if someone do and solve it - he would likely post an another clause 2. answer, i.e. without any other side cases. The minority of the ones who answer tends to change (even just fix small typos; I'm not talking about edits that would make major improvements in their own answer). Because of: they don't track new details that appear in the question, or they don't track other answers/conversation in comments, or "there can be the only one correct answer - theirs", or they have already received my upvote (if the answer brings any useful information - this is the most likely case) and what for would they improve answer, or ... So am I - because, again, I've collected bunch of solutions - it would definitely be unfair to give all these answers some person only. I can not even answer my own question in this state - because of "it would be definitely unfair ..." and even if I post it - it more likely would be copy-paste or the part of my question where I collected all this answers. Even worse - I definitely cannot stop to do it (also I am asking right now - should I do so or not?). Because no one (very-very likely) besides me will collect all the information together (because 4 and because I'm a maintainer and asker - I'm most interested). Besides for newcomers it's much more convenient when all information about the question is collected in one place, not teared up in comments. A: As a person who mainly answers questions and also works in the review queues... When I run into something like this I'm often not "happy". A list of what has already been tried, prior to asking, is important. Adding the information from answers, or "solutions" after-the-fact makes it hard to follow what the actual, original question is. And no marked answer is definitely a problem for me if the person asking the question indicates the problem is solved. If an answer is incomplete, add a comment to give its author an opportunity to improve. That will also signal future readers as to the contribution's short-comings. But be sure what you're asking was originally part of the question. If you're running into additional problems that you're only seeing once you have the information in the answer then, correctly, you should be asking a new question. As mentioned in a comment, if a combination of a number of contributed answers results in the final solution, you can post your own answer. Which contribution to mark as "the" answer, especially when you post your own version, I'd say depends on weighing the amount of effort involved, as well as the quality of the individual contributions. For example: If your answer mostly contains the code from one other person, with small modifications to make it work for your situation, then that other person's contribution should probably be marked as "the" answer. A more general approach might be more useful for future users than a very specific one. If another answer, on which your answer mainly bases, includes good explanatory text about solving the question and how the answer works, consider marking that as the Answer. If you decide to mark your own contribution as "the" answer, it would help to explain the reasoning: What you've taken from which other answers and why the combination is more useful in solving the problem. Just some thoughts... :-)
[ "stackoverflow", "0057913906.txt" ]
Q: Python multithreading unusal output in progress bar on terminal I am trying to implement a progress bar in my code. But it looks like for some reason the last element of previous progress status is not getting overridden. can someone explain why this is happening? Thanks. threadLock = threading.Lock() count = 0 def mail(email_no): # Some code with threadLock: global count count+=1 print('{} {}% completed. total sent={}'.format( chr(9608)*int((count/email_no)*100) ,((count/email_no)*100), count ), end ='\r' ) # server.quit() email_no = 1008 for i in range(1, email_no+1): t = Thread(target=mail, args=[email_no]) t.start() It is giving me the following output: ████████████████████████████████████████████████████████████████████████████████ 100.0% completed. total sent=1008l sent=1007 why this total sent=1008l sent=1007 is coming instead of total sent = 1008 only? A: The following assumes Python 3. The issue is that that the final line is shorter than the line before it. This is caused that len("{}".format((1007/1008)*100)) is 17 and len("{}".format((1008/1008.)*100)) is 5. The difference is 10 which is also the length of the unwanted suffix l sent=1007. One way to fix this is to keep track of the length of the last line printed and then pad the line to that length with spaces. Another option is just to pad every line printed like line.ljust(os.get_terminal_size().columns). import threading from threading import Thread threadLock = threading.Lock() count = 0 last_line_length = 0 def mail(email_no): # Some code with threadLock: global count, last_line_length count+=1 line = '{} {}% completed. total sent={}'.format( chr(9608)*int((count/email_no)*100) ,((count/email_no)*100), count ).ljust(last_line_length) print(line, end ='\r' ) last_line_length = len(line) # server.quit() email_no = 1008 for i in range(1, email_no+1): t = Thread(target=mail, args=[email_no]) t.start()
[ "stackoverflow", "0013488813.txt" ]
Q: Highcharts pie dataLabels inside and outside i want a pie-chart with datalabels inside and outside a pie. i know, with a negative distance it shows the label inside the pie. but i want it inside and outside. outside i want display the percentage and inside the total sum of the point. A: there is a easy work arround for it that is you overlay 2 pie with diferent datalabels http://jsfiddle.net/4RKF4/29/ $(function () { // Create the chart $('#container').highcharts({ chart: { type: 'pie', backgroundColor: 'rgba(0,0,0,0)', y:100 }, title: { text: 'sfs ' }, yAxis: { title: { text: ' ' } }, plotOptions: { pie: { // y:1, shadow: false, // center: ['50%', '50%'], borderWidth: 0, showInLegend: false, size: '80%', innerSize: '60%' , data: [ ['allo', 18], ['asdad', 14], ['asdad', 11], ['asdasd', 10], ['adad', 8], ['asdada', 7], ['adada ada', 7], ['adad', 5], ['asdas',7], ['ada', 3] ] } }, tooltip: { valueSuffix: '%' }, series: [ { type: 'pie', name: 'Browser share', dataLabels: { color:'white', distance: -20, formatter: function () { if(this.percentage!=0) return Math.round(this.percentage) + '%'; } } }, { type: 'pie', name: 'Browser share', dataLabels: { connectorColor: 'grey', color:'black', // y:-10, softConnector: false, connectorWidth:1, verticalAlign:'top', distance: 20, formatter: function () { if(this.percentage!=0) return this.point.name; } } } ] }); }); A: You have no possibility to set double datalabels, but you can use workaround, which is not perfect but maybe will be helpful. So you can set useHTML, then in formater return two divs, first appropriate datalabel (outside) and second with inside. Then set id with counter which define each div's id as unique, then only what you need is set appropriate CSS. Example of position one datalabel is available here: http://jsfiddle.net/4RKF4/ $(function () { var chart, counter = 0; $(document).ready(function() { chart = new Highcharts.Chart({ chart: { renderTo: 'container', plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false }, title: { text: 'Browser market shares at a specific website, 2010' }, tooltip: { pointFormat: '{series.name}: <b>{point.percentage}%</b>', percentageDecimals: 1 }, plotOptions: { pie: { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, color: '#000000', connectorColor: '#000000', useHTML:true, formatter: function() { counter++; return '<div class="datalabel"><b>'+ this.point.name +'</b>: '+ this.percentage +' %</div><div class="datalabelInside" id="datalabelInside'+counter+'"><b>'+ this.point.name +'</b>: '+ this.percentage +' %</div>'; } } } }, series: [{ type: 'pie', name: 'Browser share', data: [ ['Firefox', 45.0], ['IE', 26.8], { name: 'Chrome', y: 12.8, sliced: true, selected: true }, ['Safari', 8.5], ['Opera', 6.2], ['Others', 0.7] ] }] }); }); }); CSS styles: .datalabelInside { position:absolute; } #datalabelInside1 { color:#fff; left:-150px; }
[ "stackoverflow", "0052272657.txt" ]
Q: render object sorted after filtering I am facing issue while trying to display sorted suggestions with react-bootstrap-typeahead. JSON { "Code": "ABC", "Name": "Random City, Town Office (ABC), Random Country", "CityName": "Random City", "CityCode": "ABC", "CountryName": "Random Country", "CountryCode": "XY", "Field": "Town Office" }, { "Code": "CBA", "Name": "Random City, Town Office (CBA), Random Country", "CityName": "City", "CityCode": "CBA", "CountryName": "Country", "CountryCode": "CC", "Field": "Town Office" } The desired output should be searched by city alphabetically if it matches, if not should search for country name and then the output rendered should be sorted alphabetically. I tried pushing callback data from typeahead's filterBy to an array and sorting it, but, since JSON from service is not sorted and callback data is random, unable to achieve the same. Is there any other way to achieve the same? <Typeahead {...this.state.typeProps} labelKey="Name" placeholder="Enter Origin..." bsSize="large" onChange={(selected) => { this.setState({ selected }); }} filterBy={(option, props) => { if (this.filterAndPush(option, props)) { return true; } return false; }} }} options={this.state.originData} selected={this.state.selected} /> filterData = (option, props) => { const { text } = props; const { CityName, CityCode } = option; if (text) { if (CityName.toLowerCase().includes(text.toLowerCase())) { return true; } else if (CityCode.toLowerCase().includes(text.toLowerCase())) { return true; } return false; } return false; } filterAndPush = (option, props) => { //debugger; if (this.filterData(option, props)) { debugger; this.filterResultSet.push(option); this.filterResultSet.sort((a, b) => { if (a.CityName < b.CityName) return -1; if (a.CityName > b.CityName) return 1; return 0; }); return true; } return false; } A: There are two ways you can sort your data: 1) Pre-sort the options before passing them into the options prop. Given your scenario, this is probably the easiest approach. In your render method, simply do the following: const options = this.state.originData.sort(sortCallback); return ( <Typeahead ... options={options} /> ); 2) Sort the filtered results using renderMenu. Check out the custom menu example to see this in action. Basically, you can pass a callback that receives the filtered results and render them however you want: _renderMenu(results, menuProps) { const items = results.sort(sortCallback); return ( <Menu {...menuProps}> {items.map((item, index) => { <MenuItem key={index} option={item} position={index}> {...} </MenuItem> })} </Menu> ); } render() { return ( <Typeahead ... renderMenu={this._renderMenu} /> ); }
[ "stackoverflow", "0040555120.txt" ]
Q: Pass image from collectionview to VC I've tried a lot of methods i couldn't get it to work ViewController 1 have : Collectionview > Cell > image inside the cell ViewController 2 want to display the image which in VC 1 When you click on cell it has segue to push you to VC 2 override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "popup" { let viewController: friendpopup = segue.destination as! friendpopup let indexPath = sender as! NSIndexPath let nicknamex = self.nicknameArray[indexPath.row] let usernamex = self.userArray[indexPath.row] let photox = self.friendsphotos[indexPath.row] // the photos PFFiles i think viewController.snick = nicknamex viewController.suser = usernamex viewController.sphoto = // ???? } nickname and user works fine only the image i couldn't display it. I tried when you click on cell it will send the image to var but isn't working var photovar:UIImage! didSelectItemAt( self.photovar = cell.profilepic.image) then in prepareSegue( viewcontroller.sphoto = self.photovar) isn't woking, Anyone could help me to fix that to display the image? Thanks A: Tightening up your code a bit.... First VC override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "popup" { if let vc = segue.destination as? friendpopup { let indexPath = sender as! NSIndexPath vc.snick = self.nicknameArray[indexPath.row] vc.suser = self.userArray[indexPath.row] vc.sphoto = self.friendsphotos[indexPath.row] } } } Second VC: // making assumptions on variable types var snick:String! var suser:String! var sphoto:UIImage! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // do work here if sphoto != nil { imageView.image = sPhoto } else { // set a default image here } } Most of this is similar to your code, but one last note - if the first 2 properties are coming across correctly, check in the first VC that you are pulling the image out properly.
[ "stackoverflow", "0031772329.txt" ]
Q: Why is 1 byte being displayed as if it were 4 in this code? I am trying to write my C socket code in Assembly (just kinda bored and thought it'd be an interesting exercise) and in the process of trying to make the sockaddr_in struct I wrote this little program: #include <stdio.h> #include <string.h> #include <netinet/in.h> void showbytes(char *c, size_t len) { size_t i; for (i = 0; i < len; i++) printf("byte #%lu -> %x\n", i, c[i]); } int main(int argc, char* argv[]) { struct sockaddr_in q; bzero(&q, sizeof(q)); q.sin_family = 0x02; q.sin_port = htons(0x1f90); q.sin_addr.s_addr = htonl(INADDR_ANY); union { struct sockaddr_in sai; char c[sizeof(struct sockaddr_in)]; } un; un.sai = q; showbytes(un.c, sizeof(struct sockaddr_in)); return 0; } What I don't understand at all is that the output looks like this: byte #0 -> 2 byte #1 -> 0 byte #2 -> 1f byte #3 -> ffffff90 byte #4 -> 0 byte #5 -> 0 byte #6 -> 0 byte #7 -> 0 byte #8 -> 0 byte #9 -> 0 byte #10 -> 0 byte #11 -> 0 byte #12 -> 0 byte #13 -> 0 byte #14 -> 0 byte #15 -> 0 Why is byte #3 showing as 4 bytes? I checked sizeof(in_port_t) and it is definitely 2 bytes, but that isn't even the issue. A char should only ever be 1 byte.. I assume I am missing something pretty big here. A: You are missing that char is signed on your implementation and a negative value, interpreted as an unsigned int (for %x), is a large value. You may also be missing that you can't pass a one byte value to a variadic function like printf--integral values are always promoted to at least int or unsigned int. If you compile with gcc or clang, use -funsigned-char to make the char type unsigned. Then this problem does not occur.
[ "stackoverflow", "0051141289.txt" ]
Q: AngularFire2 RealTime DataBase sort by date value My Service get ActivityList():any { return this.activityList.snapshotChanges().map(changes => { return changes.map(c => ({ key: c.payload.key, ...c.payload.val(); })); }); } My Component getActivity() { this.activityService.ActivityList.subscribe(activity => { this.activity = activity; }); } HTML <div *ngFor="let item of activity"> {{item.created|date:'medium'}} </div> Question This is how I am currently getting my activity from Firebase RealTime Database. where and how is the best way to modify this to sort by the created value. A: change service to get ActivityList():any { return this.activityList.snapshotChanges().map(changes => { return changes.map(c => ({ key: c.payload.key, ...c.payload.val() })).sort((a, b) => b.created - a.created ); }); }
[ "math.stackexchange", "0002022766.txt" ]
Q: Periodic solutions of non autonomous differential equation $\dot{x}(t)=x(t)(1+\cos(t))-x(t)^3$ Find all $2\pi$ periodic solutions (either constant or non-constant) of the nonautonomous equation $\dot{x}=x(1+\cos(t))-x^3$. I know that the only equilibria is $x=0$ which is a source. A: You can solve this as Bernoulli equation, set $u=r^{-2}$ then $$ u'=-2r^{-3}r'=-2(1+\cos t)u+2 $$ which now can be nicely solved as a first order linear ODE. $A(t)=e^{2(t+\sin t)}$, then $(A(t)u(t))'=2A(t)$, $$ A(2\pi)u(2\pi)=u(0)+\int_0^{2\pi}A(s)ds $$ So for $u(2\pi)=u(0)$ you need $$ u(0)=\frac{\int_0^{2\pi}e^{2(s+\sin s)}ds}{e^{4\pi}-1}=\frac12e^{2\sin(\theta·2\pi)},\quad\theta\in(0,1) $$ which gives exactly one positive radius.
[ "stackoverflow", "0054191938.txt" ]
Q: Spring Data Rest JPA rest service with hibernate: control lazy loading I'm wondering if there is a way in which we can control lazy vs eager loading using rest service method calls. Let me elaborate. I have an entity like below. I don't need the lazily loaded jobDocuments some times, but I need it some other times. Can I write 2 rest methods, one will return Job object with jobDocuments and the other one doesn't ? @Table(name = "JOB") public class Job implements Serializable { @Id @Column(name = "JOB_ID", unique = true, nullable = false) private Long id; @OneToMany(fetch = FetchType.LAZY, mappedBy = "job") @Column(name = "PRINT_JOB_ID", length = 30) private JobDocument jobDocuments; } A: I suggest you to not mix data model and representation (entity and http response in your case). You can keep your Job entity with lazy loading by default, but don't use it as a rest service response. Create separate class which will represent http response and wrap data from your entity. For example: @Table(name = "JOB") public class Job implements Serializable { @Id @Column(name = "JOB_ID", unique = true, nullable = false) private Long id; @OneToMany(fetch = FetchType.LAZY, mappedBy = "job") @Column(name = "PRINT_JOB_ID", length = 30) private JobDocument jobDocuments; . . . } // your response class, which wrap Job data public class JobResponse { @JsonProperty("id") private Long id; @JsonProperty("jobDocuments") private JobDocument jobDocuments . . . // use this when you need to have jobDocuments public static JobResponse fromJobWithDocuments(Job job) { this.id = job.getId(); this.jobDocuments = job.getJobDocuments(); // you fetch lazy field, so it would be pre-populated } // use this when you don't need to have jobDocuments public static JobResponse fromJob(Job job) { this.id = job.getId(); } } And suppose you have controller like that: public class Controller { . . . public ResponseEntity<JobResponse> getJob(boolean withDocuments, long jobId) { JobResponse response; Job job = jobService.getJob(jobId); // assuming you are getting job somehow if (withDocuments) { response = JobResponse.fromJobWithDocuments(job) } else { response = JobResponse.fromJob(job) } return new ResponseEntity<JobResponse>(response); } . . . }
[ "stackoverflow", "0034846554.txt" ]
Q: rest routes deciding update vs add I'm writing a web app with node/express and I'm trying to set up some restful routes. Basically I have some generic items and I have a page that has a list of these items. so I've set up the following route: router.get('/items')... I'm currently setting up add/update items as well, but I'm not sure if I should set up a PUT for add and POST for update, or use POST for both? I've read that POST is acceptable for both add/update, but if I use post for add and update, then I have to use the same route, is this correct? Which would mean I have to pass back some sort of 'action' parameter to tell the route what action to take. is this a situation where I should use PUT and POST separately? A: You can use post to do both the insert and update with a url pattern like this POST -> items/ -- add an item POST -> items/{itemId} -- updates the given item with the id itemId Refer this for a more detailed description https://stackoverflow.com/a/630475/381407
[ "stackoverflow", "0031829211.txt" ]
Q: openfl - audio doesn't work on cpp target I've added <assets path="assets/audio" rename="audio" /> to the application.xml file. And I load the "mp3" files in the audio folder by calling Assets.getSound("2_3_1.mp3");, and then use the .play(); method on that (sound) object to play the file. The sounds play in flash target. But don't play on cpp targets. I'm mainly targeting Android (cpp) and iOS (c#) targets for my app. When debugging for windows (cpp) target, it shows these errors in console: Sound.hx:99: Error: Could not load "audio/2_3_1.mp3" Error opening sound file, unsupported type. Error opening sound data Done(0) A: I believe mp3 isn't supported on Windows and most other targets due a decision related to licensing costs for the format. The Flash target is an exception since Adobe has an agreement that allows developers to use the format without paying royalties. This is discussed more here: http://www.openfl.org/blog/2013/09/18/to-mp3-or-not-to-mp3/ A workaround is to use the .ogg format for non-Flash platforms for audio, and include the audio files for each platform by specifying the asset paths in your Project.xml e.g: <assets path="assets/music" type="music" if="flash"> <!-- mp3s --> </assets> <assets path="assets/music" type="music" unless="flash"> <!-- oggs --> </assets>
[ "stackoverflow", "0063289928.txt" ]
Q: SQL Statement to Update Rows using ids from another table and thanks in advance. I have a table called users which contains an id. I would like to collect the ids only from that table and run and insert using those ids as one of the arguments. I am new to SQL and having some trouble finding help or a solution. Here is the statement to get the ids SELECT id FROM public.usersWith the ids that are returned I would like to run an insert or update resembling insert into public.history (user_id, password, change_time) values (<ids from prev SELECT>, 'password', now()); Can I generate a loop? Could someone point me in the right direction using purely sql, I know this can be achieved in php but I'd like to include this in an db init with SQL only. A: You can do it with INSERT INTO ... SELECT: INSERT INTO public.history (user_id, password, change_time) SELECT id, 'password', now() FROM public.users
[ "math.stackexchange", "0003471745.txt" ]
Q: Convergence of Improper Integral $\int_{-\infty}^{\infty}p(x)q(x)e^{-x^2}dx$? Problem: Let $P_3$ be the set of all polynomials of degree less than or equal to $3$, show that $$<p(x),q(x)> =\int_{-\infty}^{\infty}p(x)q(x)e^{-x^2}dx$$ It is an internal product in $P_3$. I have solved this problem, but I am very curious that the term $ e ^ {- x ^ 2} $ appears in the integrand, I know that its role in the definition is to allow the improper integral to converge, because if you omit this, and we define $$<p(x),q(x)> =\int_{-\infty}^{\infty}p(x)q(x)dx$$ taking $ p (x) = x = q (x) $, clearly the integral does not exist. My question is, how can I prove that $$ <p (x), q (x)> = \int _ {-\infty} ^ {\infty} p (x) q (x) e^{- x ^ 2 } dx $$ converges for every pair $ (p (x), q (x))\in P_3 $? A: Split the integral into the sum of the 2 integrals $$\int_{-\infty}^0 p(x)q(x)e^{-x^2}\mathrm{d}x+\int_{0}^{\infty} p(x)q(x)e^{-x^2}\mathrm{d}x $$ $p(x)q(x)$ is a polynomial of degree $6$ or less, so for sufficiently large values of $x$, you have $|p(x)q(x)|<e^{2x-1}$, and by the comparison test, it remains to show that the integral $$\int_{0}^{\infty}e^{2x-1}e^{-x^2}\mathrm{d}x=\int_{0}^{\infty}e^{-(x-1)^2}\mathrm{d}x $$ is convergent, which is true since this is just the Gaussian integral. For the convergence of the first integral (from $-\infty$ to $0$), take $e^{-2x-1}$ instead.
[ "stackoverflow", "0062416192.txt" ]
Q: Multipeer Video This question has been asked a few times before but I have been unable to make any solution work. I am creating a multi-peer video chat. However, whenever a peer tries to connect, I get this error: DOMException: Failed to execute 'setRemoteDescription' on 'RTCPeerConnection': Failed to set remote answer sdp: Called in wrong state: kStable The odd thing is, if the user reloads the page, I don't get that error and the video displays. Both clients need to do the reload. I guess the browser has cached something and re-uses it on the 2nd attempt. // When a remote user joins, an object of this class is created. // Its job is to create am RTCPeerConnection between the local user // and the remote user. class VideoChat { constructor(name, remoteView) { this.remoteName = name; // ID of remote peer used by signal server this.remoteView = remoteView; // html video object to display remote video var configuration = {"iceServers": [ {urls: "stun:stun.l.google.com:19302"} {urls: "turn:numb.viagenie.ca", username: "xxx", credential: "xxx"} ]}; this.pc = new RTCPeerConnection(configuration); // 'onicecandidate' notifies us whenever an ICE agent needs to deliver a // message to the other peer through the signaling server this.pc.onicecandidate = event => { if (event.candidate) { ChatRoom.relay("signal", this.remoteName, event.candidate); console.log(`onicecadidate (${this.remoteName}): ${event.candidate}`); } }; // let the 'negotiationneeded' event create the offer this.pc.onnegotiationneeded = async () => { try { await this.pc.setLocalDescription(); ChatRoom.relay("signal", this.remoteName, {desc: this.pc.localDescription}) } catch (err) { console.error(err); } } // When a remote stream arrives display it in the #remoteView element this.pc.ontrack = (track, streams) => { log("adding remote TRACK to video element"); // don't set srcObject again if it is already set. if (this.remoteView.srcObject) return; this.remoteView.srcObject = event.streams[0]; }; } // This is called by main program when a remote user has signed on // This initiates everything.... // localVideo is html video element connected to local camera // stream is the main (local) user's mediaStream async start(localVideo, stream) { try { for (const track of stream.getTracks()) { this.pc.addTrack(track, stream); } localVideo.srcObject = stream; } catch (err) { console.error(err); } } // A message from the signal server async onmessage(message) { try { if (message.desc) { await this.pc.setRemoteDescription(message.desc); if (message.desc.type == "offer") { await this.pc.setLocalDescription(); ChatRoom.relay("signal", this.remoteName, {desc: this.pc.localDescription}); } } else if (message.candidate) { await this.pc.addIceCandidate(message); } } catch (err) { console.error(err); } } } Note the function: ChatRoom.relay("signal", this.remoteName, something) sends a message to signal server that gets relayed only to the remote peer with id this.remoteName. Also, I am using my own signal server I created in Java. A: If you set the remote description of different peers on the same peerconnection that isn't going to work. As the name "peerconnection" implied, it is specific to a peer. Calling this.pc.setLocalDescription() without creating an offer may be supported in some browsers but tread carefully. Also you're never creating an answer and only signaling the local description. Nor are you doing anything with answers. https://webrtc.github.io/samples/src/content/peerconnection/multiple/ is a canonical example of how to do things right.
[ "gis.stackexchange", "0000039168.txt" ]
Q: Using Elseif Conditional Statement in QGIS Field Calculator? I am trying to write an ELSEIF conditional statement in QGIS Field Calculator (version 1.8.0). I have used an example I found online: CASE WHEN val < 0 THEN 'negative' WHEN val = 0 THEN "neutral' ELSE 'positive' END I modified the statement as follows: CASE WHEN "GRID_ID" = 1 THEN 'complete' ELSEIF "GRID_ID" = 2 THEN "in progress' ELSE 'not started' END This statement would not run, the Output preview stated Expression is invalid. The more info stated: Parser Error: syntax error, unexpected COLUMN_REF, expecting WHEN or ELSE or END If anyone has had this error, what did you do to fix it? A: You have a few problems in your modified statement. Inconsistent use of quotes around "in progress' You don't need quotes around column names. You're using an "ELSEIF" when it should be a "WHEN". The following should resolve all three issues and works for me in 1.8.0: CASE WHEN GRID_ID = 1 THEN 'complete' WHEN GRID_ID = 2 THEN 'in progress' ELSE 'not started' END
[ "stackoverflow", "0043871358.txt" ]
Q: regular expression for DEA drug schedule variation Normally I'm pretty happy with my regex skills, but I'm having trouble with this one. I need a pattern to verify a variation of the DEA drug schedule. It looks like this: 22N 33N 4 5 1 2 3 22N-R 6 Basically there can be up to 6 'groups' separated by a space. Each group can have 1 or 2 of it's number, followed by an optional N, followed by an optional -R. There seem to be a few other restrictions (there is no 11 group) but that's not what is hanging me up. I had this: ^(1(-R)?)?\s?(2(-R)?)?(2N(-R)?)?\s?(3|3-R)?(3N|3N-R)?\s?(4(-R)?)?\s?(5(-R)?)?\s?(6(-R)?)?$ But the issue is the \s? are optional. So then this incorrectly passes: 22N33N45 If I make them required, then I can end up with leading or trailing spaces. So, I think I need some kind of lookaround, only have a space if it's surround by a 'group'? And here is the catch, I am required to do this with 1 regex. I can't split on spaces and then regex the parts, that would be too easy! Any input would be helpful! Thanks! A: @sebastian-proske put me on the right track, very clever sir! Making the existing regex either end the line, or have a space did the trick: ^((1(-R)?)(\s|$))?((2|22)N?(-R)?(\s|$))?((3|33)N?(-R)?(\s|$))?((4(-R)?)(\s|$))?((5(-R)?)?(\s|$))?(6(-R)?)?$ Thanks to all for the quick help.
[ "stackoverflow", "0029686788.txt" ]
Q: Generating a Pseudo-random sequence of plus/minus 1 integers Can anybody help me create a simple pseudo-random sequence of +-1 integers with length 1000 using Matlab? I.e. a sequence such as -1 -1 1 1 -1 -1 1 -1 -1 -1 1 1 1 1 -1 -1 -1 -1 1 I tried using this code below but this is the RANGE -1 to 1, which includes 0 values. I only want -1 and 1. Thanks x = randi([-1 1],1000,1); A: You can try generating a random sequence of floating point numbers from [0,1] and any values less than 0.5 set to -1, and anything larger set to 1: x = rand(1000,1); ind = x >= 0.5; x(ind) = 1; x(~ind) = -1; Another suggestion I have is to use the sign function combined with randn so that we can generate both positive and negative numbers. sign generates values that are either -1, 0, 1 depending on the sign of the input. If the input is negative, the output is -1, +1 when positive and 0 when 0. You could do an additional check where any values that are output to 0, set them to -1 or 1: x = sign(randn(1000,1)); x(x == 0) = 1; One more (inspired by Luis Mendo) would be to have a vector of [-1,1] and use randi to generate a sequence of either 1 or 2, then use this and sample into this vector: vec = [-1 1]; x = vec(randi(numel(vec), 1000, 1)); This code can be extended where vec can be anything you want, and we can sample from any element in vec to produce a random sequence of values (observation made by Luis Mendo. Thanks!). A: Some alternatives: x = 2*randi(2, 1000, 1)-3; %// generate 1 and 2 values, and transform to -1 and 1 x = 2*(rand(1, 1000, 1)<=.5)-1; %// similar to Rayryeng's answer but in one step x = randsample([-1 1], 1000, true); %// sample with replacement from the set [-1 1]
[ "stackoverflow", "0041029092.txt" ]
Q: Does it make sense to specialize std::decay? I have class that represents an array reference (class array_ref) and another that is (i.e. holds/own/contains) the array (class array). array_ref behaves like a reference. Does it make sense to specialize std::decay for class array_ref to be array? namespace std{ template<> class decay<arra_ref>{typedef array type;}; } What other alternatives do I have to tell generic programs that array is the "value type" of array_ref? Is std::decay used in any STL algorithm? A: It doesn't matter whether standard library algorithms use it or not. What matters is what the standard says in [meta.type.synop]/1: The behavior of a program that adds specializations for any of the templates defined in this subclause is undefined unless otherwise specified. Included in "this subclause" are all of the type-traits classes, including decay. So don't specialize it. Ever.
[ "serverfault", "0000770002.txt" ]
Q: Postfix sender_dependent_relayhost_maps: do not relay a specific address Let's say I don't set up relayhost because I want by default to send all the emails by the server itself. Then for some domains in the "FROM", I want to relay to a specific relay. For that I would use a sender_dependent_relayhost_maps = hash:/etc/postfix/relay_by_sender and inside it, I would put something like: @mydomain.com ses.amazon.com That is all very straight forward. Now, what do I put in "relay_by_sender" file to say that I want all my emails relayed for my domain, but one in particular. How would I do that? E.g @mydomain.com ses.amazon.com [email protected] null? Thanks A: In Postfix 2.6 or later, I guess you can return the keyword DUNNO, which is documented in sender_dependent_relayhost_maps topic. [email protected] DUNNO @mydomain.com ses.amazon.com If it doesn't work and you use Postfix 2.7 or newer, I suggest you to replace sender_dependent_relayhost_maps with sender_dependent_default_transport_maps. The latter provides more flexibility: # /etc/postfix/main.cf sender_dependent_default_transport_maps = hash:/etc/postfix/relay_by_sender # /etc/postfix/relay_by_sender [email protected] smtp @mydomain.com smtp:[ses.amazon.com]
[ "stackoverflow", "0024578185.txt" ]
Q: Disposal of AsyncLazy, what is the right (easy to use and non-leaky) way? I'm using a specialization of Stephen Cleary's AsyncLazy implementation, from his blog. /// <summary> /// Provides support for asynchronous lazy initialization. /// This type is fully thread-safe. /// </summary> /// <typeparam name="T"> /// The type of object that is being asynchronously initialized. /// </typeparam> public sealed class AsyncLazy<T> { /// <summary> /// The underlying lazy task. /// </summary> private readonly Lazy<Task<T>> instance; /// <summary> /// Initializes a new instance of the /// <see cref="AsyncLazy&lt;T&gt;"/> class. /// </summary> /// <param name="factory"> /// The delegate that is invoked on a background thread to produce /// the value when it is needed. /// </param> /// <param name="start"> /// If <c>true</c> commence initialization immediately. /// </param> public AsyncLazy(Func<T> factory, bool start = false) { this.instance = new Lazy<Task<T>>(() => Task.Run(factory)); if (start) { this.Start(); } } /// <summary> /// Initializes a new instance of the /// <see cref="AsyncLazy&lt;T&gt;"/> class. /// </summary> /// <param name="factory"> /// The asynchronous delegate that is invoked on a background /// thread to produce the value when it is needed. /// </param> /// <param name="start"> /// If <c>true</c> commence initialization immediately. /// </param> public AsyncLazy(Func<Task<T>> factory, bool start = false) { this.instance = new Lazy<Task<T>>(() => Task.Run(factory)); if (start) { this.Start(); } } /// <summary> /// Asynchronous infrastructure support. /// This method permits instances of /// <see cref="AsyncLazy&lt;T&gt;"/> to be await'ed. /// </summary> public TaskAwaiter<T> GetAwaiter() { return this.instance.Value.GetAwaiter(); } /// <summary> /// Starts the asynchronous initialization, /// if it has not already started. /// </summary> public void Start() { var unused = this.instance.Value; } } This is great code and I really appreciate how easy it is to use. i.e. class SomeClass { private readonly AsyncLazy<Thing> theThing = new AsyncLazy<Thing>( () => new Thing()); void SomeMethod() { var thing = await theThing; // ... } } Now my question, Suppose that SomeClass inherits from a class that implements IDisposable and that Thing implements IDisposable. We'd have skeleton implementation like this, class SomeClass : SomeDisposableBase { private readonly AsyncLazy<Thing> theThing = new AsyncLazy<Thing>( () => new Thing()); protected override void Dispose(bool disposing) { if (disposing) { // What do I do with theThing? } base.Dispose(disposing); } } So, what do I do with theThing in the Dispose override? Should I extend AsyncLazy<T> to have a new property? // ... public bool IsStarted { get { return this.instance.IsValueCreated; } } // ... Should I change AsyncLazy<T> to implement IDisposable? Have I misunderstood and I don't need to worry? Should I do something else? A: Stephen Toub's version of this class inherits from Lazy<Task<T>>, so you get the IsValueCreated property automatically. Alternatively, you could expose the IsValueCreated property from the private field: public sealed class AsyncLazy<T> { private readonly Lazy<Task<T>> instance; ... public bool IsValueCreated { get { return instance.IsValueCreated; } } } For consistency with the built-in Lazy<T> type, I'd avoid renaming the property to IsStarted.
[ "stackoverflow", "0056929164.txt" ]
Q: Format json array in required format this is the json format [ { baseurl: 'http://localhost:5051/springbootdemo/getServerData', server: '1' }, { baseurl: 'http://localhost:5052/springbootdemo/getServerData', server: '1' }, { baseurl: 'http://localhost:5053/springbootdemo/getServerData', server: '2' }, { baseurl: 'http://localhost:5054/springbootdemo/getServerData', server: '2' } ] i want to re arrange it in this form [ {server:1 , urls: [ "http://localhost:5051/springbootdemo/getServerData", "http://localhost:5052/springbootdemo/getServerData" ]}, {server:2 , urls: [ "http://localhost:5053/springbootdemo/getServerData", "http://localhost:5054/springbootdemo/getServerData" ]}`enter code here` ] I want the re arrangement in above format. A: Firstly, that's not JSON - it's an ordinary array. Secondly, you can use reduce like so: const arr = [{baseurl:'http://localhost:5051/springbootdemo/getServerData',server:'1'},{baseurl:'http://localhost:5052/springbootdemo/getServerData',server:'1'},{baseurl:'http://localhost:5053/springbootdemo/getServerData',server:'2'},{baseurl:'http://localhost:5054/springbootdemo/getServerData',server:'2'}]; const res = Object.values(arr.reduce((a, { baseurl, server }) => { (a[server] = a[server] || { server: +server, urls: [] }).urls.push(baseurl); return a; }, {})); console.log(res); .as-console-wrapper { max-height: 100% !important; top: auto; }
[ "stackoverflow", "0009371242.txt" ]
Q: How can I extract specific parts of a string matching a specific regex in bash? I'm working in bash, chosen mainly so I could get some practice with it, and I have a string that I know matches the regex [:blank:]+([0-9]+)[:blank:]+([0-9]+)[:blank:]+$SOMETHING, assuming I got that right. (Whitespace, digits, whitespace, digits, whitespace, some string I've previously defined.) By "matches," I mean it includes this format as a substring. Is there a way to set the two strings of digits to specific variables with just one regex matching? A: $BASH_REMATCH contains the groups from the latest regex comparison done by [[. $ [[ ' 123 456 ' =~ [[:blank:]]+([0-9]+)[[:blank:]]+([0-9]+)[[:blank:]]+ ]] && echo "*${BASH_REMATCH[1]}*${BASH_REMATCH[2]}*" *123*456*
[ "salesforce.stackexchange", "0000092684.txt" ]
Q: Convert Opportunity object data to Order object data We've inadvertently adopted opportunity objects as what we internally understand as orders, how would I go about converting my opportunities into orders? A: You may need to work with Salesforce Customer Support to enable importing creation dates. I remember having to do this when we went live with Salesforce. If you have not been using the Orders object, I would probably start by recreating any custom fields in your Orders object that you have in your Opportunity Object. From there, you can use the Salesforce Data Loader tool to export your Opportunities (as well as any child objects). Then, import the exported Opportunities back in as Orders. Finally, update the child objects to link to the new Order ID for each corresponding record. Once you have verified that the data imported and updated correctly, you can go ahead and delete your old "Opportunities".
[ "stackoverflow", "0013335700.txt" ]
Q: How to limit this using rownum in oracle Possible Duplicate: Oracle SQL - How to Retrieve highest 5 values of a column Hey so I have a query to do this: Write a query which retrieves only the ten companies with the highest number of pickups over the six-month period The 6 months I have been given and I tried many queries this is what I have but I know its wrong as I have no idea SELECT * FROM (SELECT customers.name,COUNT(MANIFEST.MANIFEST_BARCODE) AS Pickups FROM customers JOIN manifest ON (Reference = pickup_reference) ORDER BY Pickups desc;) WHERE ROWNUM < 11 A: Without seeing your table structures etc. I've no idea where the six-month restriction fits in, but for the rest you have an aggregate function (count) without a group by clause, and a random semi-colon in your inner query. Something like this ought to work and is close to what you already have: SELECT * FROM ( SELECT customers.name, COUNT(manifest.manifest_barcode) AS Pickups FROM customers JOIN manifest ON (Reference = pickup_reference) GROUP BY customers.name ORDER BY pickups DESC ) WHERE ROWNUM < 11; There are a lot of examples on this site, like this one for example.
[ "stackoverflow", "0024993978.txt" ]
Q: JavaScript - uncheck check box on mouseup I'm trying to implement a simple 'show password' toggle check box so that whilst the mouse is held down, the plain text password is shown, and once it's let go it reverts back to a password field. I've got the toggle of the input field working, however I'm using a check box to show the toggle state as well, and I can check the box on mousedown however my attempt at then unchecking the box is not quite working. Here's what I've got so far; DEMO var pwi = $('#new_pass'); $('.pw_show').on('mousedown', function () { $('.pw_show input').prop('checked', true); pwi.prop('type', 'text'); }); $('.pw_show').on('mouseup', function () { pwi.prop('type', 'password'); setTimeOut(function() { $('.pw_show input').prop('checked', false); }, 50); }); This almost works, however if the user double clicks quickly then they can break it leaving the checkbox checked. Is there a better way to do this? A: The problem with my code was the spelling of the setTimeout function. After fixing this, the small delay I added, allowed the check box to be checked and unchecked on click hold and release. $('.pw_show').on('mouseup', function () { pwi.prop('type', 'password'); setTimeout(function() { $('.pw_show input').prop('checked', false); }, 50); }); Fixed Fiddle
[ "stackoverflow", "0040624965.txt" ]
Q: React js: how to draw svg into a canvas that doesn't exist yet? I have a render() function that's rendering my React component, and I want to include a <canvas> that has some SVG rendered onto it, as in this fiddle. However, I can't include that js in the return of the render function, so I'm attempting to return the canvas element from a function I made that's supposed to create it, then attach the svg. This is what I have: getEditionCircle: function(result) { var canvas = <canvas id="can" width="37" height="37"/> // all the code in the fiddle to render the svg return canvas; } render: function() { return ( <div className={bemBlocks.item().mix(bemBlocks.container("item"))}> <span className='counterBadge'>{result._source.length}</span> <div>{this.getEditionCircle(result)}</div> <img className='gridImg' style={{height: 311}} src={imgUrl}/> </div> ) } Right now when I run it, it says canvas.getContext is not a function which makes sense to me, since the canvas isn't rendered yet. edit: Two things that are relevant; I have to pass data to this svg generator (hence the results parameter), and this is part of a component that will be repeated multiple times on one page, so there will be multiple canvas elements that have to be rendered to. A: If you want to access a DOM element after React has created it, use ref or onRef, explained here. Since you want to use the element as soon as it is created, use onRef: drawOnCanvas: function(canvas) { if (!canvas) { return; // Should not happen, but do check anyway } var ctx = canvas.getContext("2d"); // the rest of the code in the fiddle to render the svg } render: function() { return ( <div className={bemBlocks.item().mix(bemBlocks.container("item"))}> <span className='counterBadge'>{result._source.length}</span> <canvas onRef={this.drawOnCanvas} width="37" height="37" /> <img className='gridImg' style={{height: 311}} src={imgUrl} /> </div> ); }
[ "stackoverflow", "0016067658.txt" ]
Q: Creating Mobile app with MVC4 i need to know that weather i can create a mobile app using ASP.NET MVC4 framework. My concern is not about mobile sites rather apps that can be installed on iphone/android and also can be uploaded to apple store. If yes then please suggest some reference links to achieve the same. Thanks rohit A: Yes, sort of. You can use frameworks like PhoneGap to create an iPhone/Android app with HTML, CSS and JavaScript. PhoneGap will make requests to your server, so that can be implemented in whatever you want. If you want to use ASP.NET MVC, I suggest you return JSON data structures to your mobile app. You're probably better off writing a Web API than an MVC website for this, actually.
[ "stackoverflow", "0009789486.txt" ]
Q: Low-Memory Traversal of Database Table I have a database with a large number of records that are Date/Time stamped. I need to traverse through these records (in chronological order) and perform some analysis on them. The database is too large to pull in every record at once, so I thought of pulling in a few weeks/days/hours/etc at a time. The problem I'm having is that no matter what I've tried, the database (SQL Server) just uses all the memory on my machine. Even after the application is closed, sqlservr.exe is still using all of my memory. It typically uses about 1.8 GB of memory, no matter if my "batches" only contain 10 records or 1,000,000. The question is: How can I query the database to get "batches" of records at a time, without the database consuming every bit of memory? I am using the System.Data.SqlClient libraries. Here is a bit of pseudo-code: String file = "C:\\db.mdf"; String connString = @"Data Source=.\SQLExpress;AttachDbFilename="C:\db.mdf";Integrated Security=True;User Instance=True"; SqlConnection conn = new SqlConnection(connString); conn.Open(); DateTime start = DateTime.MinValue; DateTime end = DateTime.MaxValue; while() { // This should query for 1 hour at a time (but I should be able to change the time interval) // I would like for the memory usage to be proportional to the time interval String query = "SELECT * From MyTable WHERE Date BETWEEN '" + start.ToString() + "' AND '" + end.ToString() + "'"; SqlCommand cmd = new SqlCommand(query, conn); SqlDataReader reader = command.ExecuteReader(); while(reader.Read()) ProcessRecord(ref reader); start = end; end = end.AddHours(1); } conn.Close(); C# .NET 3.5 SQL Server 2008 Thanks. A: This is normal, SQL Server will use all available memory unless configured differently. Sql Server Express will release the memory when your other applications request more, but it will try to use all the memory it can to cache query plans and data. Quote from the linked article: The following example sets the max server memory option to 4 GB: exec sp_configure 'show advanced options', 1; GO RECONFIGURE; GO exec sp_configure 'max server memory', 4096; GO RECONFIGURE; GO exec sp_configure 'show advanced options', 0; RECONFIGURE; GO Do note that SqlConnection, SqlCommand and SqlDataReader implement IDisposable, so you usually would want to wrap them in a using clause.
[ "stackoverflow", "0008176349.txt" ]
Q: Google map api v3 add polylines from array I'm trying to add a set of poly lines to a google map from an array. Here is my code: <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no" /> <style type="text/css"> html { height: 90% } body { height: 90%; margin: 0; padding: 0 } #map_canvas { height: 100% } </style> <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"> </script> <script type="text/javascript"> var poly; var map; function initialize() { var latlng = new google.maps.LatLng(38.698044, -77.210411); var myOptions = { zoom: 8, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions); //var myLatLng = new google.maps.LatLng(0, -180); } var polyOptions = { strokeColor: '#000000', strokeOpacity: 1.0, strokeWeight: 3 } poly = new google.maps.Polyline(polyOptions); poly.setMap(map); var path = new MVCArray; $.getJSON('json.php', function(data) { //var items = []; $.each(data, function(key, val) { path.push(new google.maps.LatLng(val.lat, val.longi)); }); }); var myOptions = { zoom: 12, //center: myLatLng, mapTypeId: google.maps.MapTypeId.TERRAIN }; </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script> </head> <body onload="initialize()"> <div id="map_canvas" style="width:90%; height:100%"></div> </body> </html> <html> <head> </head> <body> </body> </html> Any thoughts on why the line path.push(new google.maps.LatLng(val.lat, val.longi)); isn't adding the data in? Or is there a better way for me to loop the data in? A: So you loop over the contents of data, adding things into the array, path.... and then, what? Nothing as far as I can see. Presumably you then want to use that path array to set the path for your polyline. var polyOptions = { strokeColor: '#000000', strokeOpacity: 1.0, strokeWeight: 3 } poly = new google.maps.Polyline(polyOptions); poly.setMap(map); var path = new MVCArray; $.getJSON('json.php', function(data) { //var items = []; $.each(data, function(key, val) { path.push(new google.maps.LatLng(val.lat, val.longi)); }); // now update your polyline to use this path poly.setPath(path); }); PS: Your HTML structure is all wrong: <body onload="initialize()"> <div id="map_canvas" style="width:90%; height:100%"></div> </body> </html> <html> <head> </head> <body> </body> </html> shouldn't that just be <body onload="initialize()"> <div id="map_canvas" style="width:90%; height:100%"></div> </body> </html>
[ "stackoverflow", "0042085252.txt" ]
Q: Hide a button in Spring Boot/Thymeleaf application if not logged in I'm trying to hide a button in the header of my Spring Boot application in the following way with my markup: <!-- Is not logged in, so don't show "Log In" --> <li sec:authorize="!isAuthenticated()"> <a href="/login" th:href="@{/login}" class="btn-login">Log In</a> </li>\ Is this not correct? I'm using the Thymeleaf templating engine. A: Add Spring Security Dialect in spring boot app for sec attribute to work, @Configuration public class ThymeleafConfig { @Bean public SpringSecurityDialect springSecurityDialect(){ return new SpringSecurityDialect(); } } If you have a Spring Security Dialect, then you can try, <!-- Show login link only for anonymous users --> <div sec:authorize="isAnonymous()"> <a href="/login" th:href="@{/login}" class="btn-login">Log In</a> </div>
[ "stackoverflow", "0007218600.txt" ]
Q: Xml online extract in textbox I have a xml file that is online with the tag <version>1.0</verion> and more, how can I extract the tag version and insert it into a textbox? the xml file is "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" A: You did not provide the xml file. However the answer is simple. Just use Linq to Xml and parse the file to get the value in version and whatever elements you need. string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><SampleFile><version>1</version><SomeData>Hello World</SomeData></SampleFile>"; XDocument document = XDocument.Parse(xml); string versionValue = document .Descendants("version") .Select(i => i.Value.ToString()) .FirstOrDefault(); Console.WriteLine("The version is {0}", versionValue); There was a comment which I think meant reading the xml document from a url. You should be able to use the XDocument.Load method. This will work and pull an xml doc I found from a Google search at this location. //var document = XDocument.Parse(xml); var document = XDocument.Load("http://producthelp.sdl.com/SDL%20Trados%20Studio/client_en/sample.xml"); var versionValue = document .Descendants("version") .Select(i => i.Value.ToString()) .FirstOrDefault(); Console.WriteLine("The version is {0}", versionValue);
[ "mathoverflow", "0000247548.txt" ]
Q: Percolation on the hyperbolic plane and convergence to SLE(6) on hyperbolic plane In "Percolation in the hyperbolic plane" the authors study the properties of percolation in the hyperbolic plane. Smirnov and others proved convergence of isotropic percolation to SLE(6). Do these results follow for the hyperbolic case too? Findings: 1)L. Arosio, F. Bracci, "Infinitesimal generators and the Loewner equation on complete hyperbolic manifolds," So there is a natural candidate. thanks A: Smirnov's theorem assert the convergence to SLE in the scaling limit: one discretizes the domain with the triangular lattice of mesh size $\delta$, and lets $\delta$ go to zero. It is only proven for the triangular lattice; it's a major open problem to prove universality of this result (in fact, even to extend it to the square lattice). Now, in the hyperbolic plane, you cannot discretize a domain by scaled copies of the same lattice, since there is no natiral scaling. So, it seems that even to formulate the problem sensibly, one has to deal with a large class of graphs. I don't see why proving it should be any easier than establishing universality in the Euclidean case.
[ "stackoverflow", "0015666917.txt" ]
Q: JavaScript: max of an array not working I have this javascript code: http://jsfiddle.net/MvWV7/5/ What I'm trying to achieve is that user should fill the inputs starting with 1. After the user types 1 the next value must be 2 (not nanother number) and so on. I'm trying to fill the inputs values in an array by doing this (as shown in the fiddle): var ary = []; $(".activity_order").not(self).each(function(t) {ary.push(this.value);}) but when I do ary.max() I get Uncaught TypeError: Object ,,,,,,,, has no method 'max' In console when I do ary.max() i get 0 if there's no numbers UPDATE My fault, I was using google console in jsfiddle and I started to look up for array methods inside. When I did ary.max() it gives 0 A: You're presumably typing [].max into the console on the jsfiddle domain. Note the output: function () { return Math.max.apply(null, this); // 'this' is your array } The reason here is that code on the jsfiddle domain has modified the prototype of Array to include the max method. It's mapped to the Math.max method and doesn't natively reside on the Array object itself, or its prototype.
[ "stackoverflow", "0040314406.txt" ]
Q: Remove commas from database column Basically in a table I want to remove all commas in metadata_value column entries someone put in where meta_key column is equal to 15, 16, or 17 So: SELECT REPLACE(metadata_value, ',', '') FROM project_content_to_metadata WHERE metadata_key = '15' AND metadata_key = '16' AND metadata_key = '17' But it did not work A: Your REPLACE is correct, but use OR instead of AND. One row can't have 3 different values. You could use IN to specify multiple OR conditions on one column: SELECT REPLACE(metadata_value, ',', '') FROM project_content_to_metadata WHERE metadata_key IN ('15','16','17') Also, if your metadata_key is of type Integer do not use quotes around values, so this could be: metadata_key IN (15,16,17) A: If you actually want to remove the commas in the table, then use update: update project_content_to_metadata set metadata_value = REPLACE(metadata_value, ',', '') where metadata_key in (15, 16, 17); Otherwise Kamil's answer is correct.