source
sequence
text
stringlengths
99
98.5k
[ "stackoverflow", "0005285940.txt" ]
Q: Correct way to delete cookies server-side For my authentication process I create a unique token when a user logs in and put that into a cookie which is used for authentication. So I would send something like this from the server: Set-Cookie: token=$2a$12$T94df7ArHkpkX7RGYndcq.fKU.oRlkVLOkCBNrMilaSWnTcWtCfJC; path=/; Which works on all browsers. Then to delete a cookie I send a similar cookie with the expires field set for January 1st 1970 Set-Cookie: token=$2a$12$T94df7ArHkpkX7RGYndcq.fKU.oRlkVLOkCBNrMilaSWnTcWtCfJC; path=/; expires=Thu, Jan 01 1970 00:00:00 UTC; And that works fine on Firefox but doesn't delete the cookie on IE or Safari. So what is the best way to delete a cookie (without JavaScript preferably)? The set-the-expires-in-the-past method seems bulky. And also why does this work in FF but not in IE or Safari? A: Sending the same cookie value with ; expires appended will not destroy the cookie. Invalidate the cookie by setting an empty value and include an expires field as well: Set-Cookie: token=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT Note that you cannot force all browsers to delete a cookie. The client can configure the browser in such a way that the cookie persists, even if it's expired. Setting the value as described above would solve this problem. A: At the time of my writing this answer, the accepted answer to this question appears to state that browsers are not required to delete a cookie when receiving a replacement cookie whose Expires value is in the past. That claim is false. Setting Expires to be in the past is the standard, spec-compliant way of deleting a cookie, and user agents are required by spec to respect it. Using an Expires attribute in the past to delete a cookie is correct and is the way to remove cookies dictated by the spec. The examples section of RFC 6255 states: Finally, to remove a cookie, the server returns a Set-Cookie header with an expiration date in the past. The server will be successful in removing the cookie only if the Path and the Domain attribute in the Set-Cookie header match the values used when the cookie was created. The User Agent Requirements section includes the following requirements, which together have the effect that a cookie must be immediately expunged if the user agent receives a new cookie with the same name whose expiry date is in the past If [when receiving a new cookie] the cookie store contains a cookie with the same name, domain, and path as the newly created cookie: ... ... Update the creation-time of the newly created cookie to match the creation-time of the old-cookie. Remove the old-cookie from the cookie store. Insert the newly created cookie into the cookie store. A cookie is "expired" if the cookie has an expiry date in the past. The user agent MUST evict all expired cookies from the cookie store if, at any time, an expired cookie exists in the cookie store. Points 11-3, 11-4, and 12 above together mean that when a new cookie is received with the same name, domain, and path, the old cookie must be expunged and replaced with the new cookie. Finally, the point below about expired cookies further dictates that after that is done, the new cookie must also be immediately evicted. The spec offers no wiggle room to browsers on this point; if a browser were to offer the user the option to disable cookie expiration, as the accepted answer suggests some browsers do, then it would be in violation of the spec. (Such a feature would also have little use, and as far as I know it does not exist in any browser.) Why, then, did the OP of this question observe this approach failing? Though I have not dusted off a copy of Internet Explorer to check its behaviour, I suspect it was because the OP's Expires value was malformed! They used this value: expires=Thu, Jan 01 1970 00:00:00 UTC; However, this is syntactically invalid in two ways. The syntax section of the spec dictates that the value of the Expires attribute must be a rfc1123-date, defined in [RFC2616], Section 3.3.1 Following the second link above, we find this given as an example of the format: Sun, 06 Nov 1994 08:49:37 GMT and find that the syntax definition... requires that dates be written in day month year format, not month day year format as used by the question asker. Specifically, it defines rfc1123-date as follows: rfc1123-date = wkday "," SP date1 SP time SP "GMT" and defines date1 like this: date1 = 2DIGIT SP month SP 4DIGIT ; day month year (e.g., 02 Jun 1982) and doesn't permit UTC as a timezone. The spec contains the following statement about what timezone offsets are acceptable in this format: All HTTP date/time stamps MUST be represented in Greenwich Mean Time (GMT), without exception. What's more if we dig deeper into the original spec of this datetime format, we find that in its initial spec in https://tools.ietf.org/html/rfc822, the Syntax section lists "UT" (meaning "universal time") as a possible value, but does not list not UTC (Coordinated Universal Time) as valid. As far as I know, using "UTC" in this date format has never been valid; it wasn't a valid value when the format was first specified in 1982, and the HTTP spec has adopted a strictly more restrictive version of the format by banning the use of all "zone" values other than "GMT". If the question asker here had instead used an Expires attribute like this, then: expires=Thu, 01 Jan 1970 00:00:00 GMT; then it would presumably have worked. A: Setting "expires" to a past date is the standard way to delete a cookie. Your problem is probably because the date format is not conventional. IE probably expects GMT only.
[ "stackoverflow", "0033200939.txt" ]
Q: Saving JSON in scala from SparkSQL I am using Spark SQL for extracting some information from a JSON file. The question is I want to save the result from the SQL analysis into another JSON for plotting it with Plateau or with d3.js. The thing is I don´t know exactly how to do it. Any suggestion? val inputTable = sqlContext.jsonFile(inputDirectory).cache() inputTable.registerTempTable("inputTable") val languages = sqlContext.sql(""" SELECT user.lang, COUNT(*) as cnt FROM tweetTable GROUP BY user.lang ORDER BY cnt DESC LIMIT 15""") languages.rdd.saveAsTextFile(outputDirectory + "/lang") languages.collect.foreach(println) I don´t mind if I save my data into a .csv file but I don´t know exactly how to do it. Thanks! A: It is just val languagesDF: DataFrame = sqlContext.sql("<YOUR_QUERY>") languagesDF.write.json("your.json") You do not need to go back to a RDD. Still, take care, that your JSON will be split into multiple parts. If that is not your intention, read Save a large Spark Dataframe as a single json file in S3 and Write single CSV file using spark-csv (here for CSV but can easily be adapted to JSON) on how to circumvent this (if really required). The main point is in using repartition or coalesce.
[ "stackoverflow", "0053351926.txt" ]
Q: Delayed printing within a whole program I want every message in my program to be printed with a small delay between each character. I can use import time string = "hello world" for char in string: print(char, end='') time.sleep(.25) to do that for a single string. I can extrapolate that to a class using a __print__ method, but that still requires me to use a class each time I want to use my edited print method. How can I add delay to every character printed for the entire program so that I can use print("foo") anywhere and expect it to work as intended? A: Well what you can do is create a function for this, i.e: def print_delayed(string): for char in string: builtins.print(char, end='', flush=True) # flush gets the actual delay, otherwise # the text is printed after all the sleeps time.sleep(.25) Then, you can set print equal to this function, i.e: print = print_delayed However, I wouldn't recommend doing this; just call the new function you have made, instead of overriding built-in ones. Here is a working example.
[ "stackoverflow", "0001085113.txt" ]
Q: jQuery Syntax Help Sorry for asking such a newbie question, I know it makes a few of you here angry. But I think learning the syntax is the hardest part so don't flame me too badly. Right, I'm using the Tabs widget from the jQuery UI. I'm stuck with setting the options for this. This is how it stands... <script type="text/javascript"> $(function() { $("#forumswitch").tabs({ event: 'mouseover', }); }); </script> I'm using Ajax with this however I want it to be cached instead of requesting new data each time a tab is changed. (http://docs.jquery.com/UI/Tabs#option-cache) How would I add this to the settings? I know it's done with arrays but I seem to mess it up every time I try. A: The argument being sent to tabs is a hash/associative array of options. Just add cache: true to this hash. <script type="text/javascript"> $(function() { $("#forumswitch").tabs({ event: 'mouseover', cache: true }); }); </script>
[ "mathoverflow", "0000094785.txt" ]
Q: How to generalize equilizers in a category to hom-sets? Assume $C$ is a locally small category with equalizers in the sense that given any two arrows $f$ and $g$ with a common source $a$ and target $b$, then there is an object $e$ and an arrow $i\colon e\to a$ such that $fi = gi$ that satisfies the usual universal property. Seems that this generalizes fairly easily (by induction) to any finite subset of the hom-set $C(a,b)$. That is, given a finite $A\subset C(a,b)$, there is an arrow $i\colon e\to a$ such that for any $f,g\in A$, we have $fi=gi$ and if $k\colon c\to a$ is such that for any $f,g\in A$ we have $fk=gk$, then there is a unique $h\colon c\to e$ such that $k=ih$. My question is whether this can be generalized to all of $C(a,b)$ when the hom-set is not necessarily finite. A: Consider the set of natural numbers as a monoid with the operation of "maximum" (so 0 is the identity element), and view it as a category with one object $*$. (That is, the morphisms from $*$ to $*$ are the natural numbers, and the composition of two of these is the larger of the two.) Then the equalizer of any two of morphisms $a,b$ exists; it is (the object $*$ with) the morphism $\max\{a,b\}$. (There is no significance to the fact that this is also the composite of $a$ and $b$.) But no morphism equalizes all the natural numbers --- specifically, any $a$ fails to equalize $a$ and $a+1$. A: Look for "equalizer of a family of arrows" in an arbitrary book on category theory. It is a special case of a limit. A typical example for a category which has finite limits, but not arbitrary limits (and therefore not all infinite equalizers), is the category of schemes.
[ "stackoverflow", "0019423107.txt" ]
Q: Merge slid-in box function and another function hope someone can guide me in the right direction. I have been asked to create a small slide in feature that when the user scrolls down the page, the box appears with the content: 'Find out more: field with email address box/ SUBMIT->' There will also be a small icon which the users can close this box if they dont want it there. Now i have all the functionality working for the box to show on scrolling: /************************** * * email function * **************************/ jQuery(window).scroll(function() { if (jQuery(this).scrollTop() > 200) { jQuery('#enquiry_submit form').stop().animate({ left: '0' }); } else { jQuery('#enquiry_submit form').stop().animate({ left: '-25%' }); } }); }); !!EDIT!! To make it not show on another page when the user clicks onto another page i was advised below to use cookies. I found a great working solution tested: http://jsfiddle.net/FcFW2/1/ Now i am stuck to merge these two functions together as when trying the css styling and two functions together just make the box hide all the time. I am a novice user with jQuery so i understand the basics and how to implement basic functions but in this case hit a wall. Any guidance would be appriciated. A: If you want it to stay closed on subsequent pages - the only way I can see this working is by setting a cookie when you close the div. Then, in your expand method, check for the presence of that cookie, and if it's there, just don't open the div.
[ "dba.stackexchange", "0000051235.txt" ]
Q: Designing a scenario where a primary key could be of two types I have a table: all_info, where it holds the users identification. The id of this table can be of two types (just one or another, never both), suppose: int and varchar, but one table can't have two primary keys, and a composite one wouldn't solve my problem. So, I can't do this: +--------------------+ | all_info | +--------------------+ | PK id1 varchar(50) | | PK id2 int | | ... | +--------------------+ Then, I created two others tables: unique_info1 and unique_info2 with the primary keys of the types that I needed, add some informations for the specific types of users, and made relations with the table: all_info, that holds the rest of the users informations (that both types share). With this scheme, I could relate unique_info1 and unique_info2 with every other table, but I would need to create two columns in every one of them to establish that relationship. To solve this, I had created an artificial primary key in all_info to make all posterior relationships. Now, it looks like this: Obs: FK uniq1_id varchar(50) and FK uniq2_id int(10) are unique and nullable. +--------------------+ +--------------------+ +-------------------------+ +-------------------------+ | unique_info1 | | unique_info2 | | all_info | | other_table | +--------------------+ +--------------------+ +-------------------------+ +-------------------------+ | PK id varchar(50) | | PK id int(10) | | PK id int(10) | | ... | | ... | | ... | | ... | | ... | | ... | | ... | | FK uniq1_id varchar(50) | | ... | | ... | | ... | | FK uniq2_id int(10) | | FK all_id int(10) | +--------------------+ +--------------------+ +-------------------------+ +-------------------------+ The thing is: that's the best approach, or should I change the plan? For examples: Choose other information to be the id of the users, where all will have the same type, and add all specific info of the users to that hole table? This would result in a lot of null columns for each user. Create two completely different tables for the two types of users? This would result in redundant info. A: Also search for super type/subtype here and on the SO.
[ "academia.stackexchange", "0000008768.txt" ]
Q: 3 years into my phd program, want to shift to theoretical physics I joined a phd in electrical engg 2 years back. But requiring physics, I did log of physics courses and I have now developed a deep interest in mathematical physics and condensed matter. But that has lead me to undergoing coursework in maths dept as i had already finished lot of basic/masters level courses in physics and which gave me a feeling that doing math courses thoroughly first is the right way to do any physics. But my supervisor now is terribly disappointed with me. Also I am confused about shifting university as I am already 2years + into a graduate program. Also there is a feeling that once am through the coursework , I might find some problem interesting to electrical engineers that I might solve with the new skills. But a few professors and my current supervisor are discouraging me saying it is a vague plan. So what should I do, any suggestions? A: You can find many areas in microelectronics which are closely related to the condensed matter physics (i.e: Electronic band structure, semiconductor, Conductors, Superconductor, Ferroelectric, etc). My recommendation is to find a specific field in condensed matter that is also interesting for your supervisors, and pursue your PhD. In your case, moving to another department is just burning two years.
[ "scifi.stackexchange", "0000111262.txt" ]
Q: Does Han Solo have twins? The real fans of Star Wars are talking about Han Solo having twins, a boy and a girl. Is there a canon answer to that? A: You're probably hearing mention of Jacen and Jaina Solo, introduced in Timothy Zahn's Thrawn trilogy (Leia was pregnant through the first two books, and the twins were born in the last). The Solo twins were regular character in the Star Wars Expanded Universe novels, and are quite popular among many fans of the EU, but are no longer canon; they were relegated to the non-canon Legends continuity with the rest of the EU following Disney's takeover of Lucasfilm. In the current canon, Han and Leia only have one known child, revealed in The Force Awakens: Kylo Ren, whose birth name is Ben Whether Disney will borrow any elements from Jacen and Jaina's adventures remains to be seen; there's already at least one similarity: In the Legacy of the Force novels, published between 2006 and 2008, Jacen Solo fell to the Dark Side and became Darth Caedus. One of his more unsettling acts was killing his younger brother, Anakin Solo. The similarities to The Force Awakens should be obvious.
[ "meta.stackexchange", "0000236775.txt" ]
Q: How do we deal with unclear questions having a deleted OP account? I came across this question: https://softwareengineering.stackexchange.com/questions/240513/mock-objects-real-issues-test-driven-design-with-java. The question does not have enough clarification from the OP, and now the OP account has been deleted. Flagging may not help because the OP is no longer around to respond to the flag. How do we deal with this situation? Should I flag for mod attention or flag as "Not Clear"? I do not have VTC permissions yet. NOTE: The one answer to this question would prevent it from being auto-deleted by the system. However, that answer has been deemed "incorrect" by the OP as is evident from their comment. A: When you flag posts, they're not handled by the original poster. Depending on the flag, they're either handled by community members with enough rep to review flagged posts, or they're handled by moderators. If you believe that the question is unclear, then flag it as unclear: Flagging a question like this will put it into the Close Review Queue for community review. Then users with enough reputation to vote to close will close the question, if they agree with your flag. Do not flag using "Other" to close questions. Only moderators review Other flags, but it's not necessary in the case of closing a question, because the community is already capable of reviewing those flags. You don't want to increase the workload of moderators unnecessarily. A: If the post is dealing with a general question that doesn't have an answer yet, one approach is to be bold and edit it to make it a good question. Yea, the OP isn't around and so it will never have an accepted answer, but if a good question can be made of it (even if you already know the answer), its 'better' than a closed question. The be bold approach is often something for people who have 2k rep to do so that they don't hit the suggested edit queue (the 'radical change' rejection may apply to some of the suggestions) and are familiar enough with the site to be able to rewrite it. If you happen to have less than 2k rep, it may be helpful to mention the OP is gone and you are trying to salvage the question. As the question linked is one on P.SE, there is some guidance on such a radical rewrite at What is needed to really fix a question (an Atwood transform) - note that is still a work in progress and not even faq-proposed. If people do have suggestions for improvements on that, I would be very interested in hearing them. On the other hand, if the question is about a specific problem or issue, such that someone reading it may not be able to properly clarify it, the thing to do is close it (which will likely ultimately lead to the roomba cleanup scripts deleting it some day - the 9 day script would likely be the one (closed, has a score of 0 or less, has no answers with score > 0, has no accepted answer)). Flagging a question puts it into one one of several queues to be handled. The 'unclear' one in particular sends it to the close vote review queue (other flags can send it to a low quality review queue or a queue handled by the diamond moderators of the site).
[ "stackoverflow", "0001968065.txt" ]
Q: How do I send a class throught UDP socket connection? I have a UDP server that I have being trying to send structures using send() method.. No luck so far... This is what I am using: H,G are structures... sender side: IFormatter formatter = new BinaryFormatter(); MemoryStream stream = new MemoryStream(); formatter.Serialize(stream, H); Byte[] buffer = stream.ToArray(); stream.Close(); and on the receiver side: IFormatter formatter = new BinaryFormatter(); Stream s = new MemoryStream(buffer.Data); ClientAnswerStruct G = (ClientAnswerStruct)formatter.Deserialize(s); s.Close(); MessageBox.Show(G.name); But I get this error: Unable to find assembly 'UdpClientSample, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. 'UdpClientSample' happens to be the title of the client program that is sending the data to the server... So I'm wondering if it takes more than serialization to be able so send a structure through UDP connection? Is there a breakthrough out there that explains what Iamamac says? A: I didn't see the whole code, but I guess the server and client is two different executable files, and the ClientAnswerStruct class is defined twice in both sides. When the receiver deserialize the data, it tries to reconstruct a ClientAnswerStruct object but can not find its definition (Notice that it is defined on the sender's side. Although on the receiver's side there is a class named ClientAnswerStruct, but they are not the same). The right way to do this is define the ClientAnswerStruct class in a standalone class library, and let the server and client code include it ('add reference' in C# terminology).
[ "stackoverflow", "0002655340.txt" ]
Q: HttpPostedFile.SaveAs() throws UnauthorizedAccessException even though the file is saved? I have an aspx page with multiple FileUpload controls and one Upload button. In the click handler I save the files like this: string path = "..."; for (int i = 0; i < Request.Files.Count - 1; i++) { HttpPostedFile file = Request.Files[i]; string fileName = Path.GetFileName(file.FileName); string saveAsPath = Path.Combine(path, fileName); file.SaveAs(saveAsPath); } When file.SaveAs() is called, it throws: System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.UnauthorizedAccessException: Access to the path '...' is denied. at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy) at System.IO.FileStream..ctor(String path, FileMode mode) at System.Web.HttpPostedFile.SaveAs(String filename) at Belden.Web.Intranet.Iso.Complaints.AttachmentUploader.btnUpload_Click(Object sender, EventArgs e) at System.Web.UI.WebControls.Button.OnClick(EventArgs e) at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) --- End of inner exception stack trace --- at System.Web.UI.Page.HandleError(Exception e) at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.departments_iso_complaints_uploadfiles_aspx.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) Now here's the fun part. The file is saved correctly! So why is it throwing this exception? Update I fixed it by checking for a non zero ContentLength: string path = "..."; for (int i = 0; i < Request.Files.Count - 1; i++) { HttpPostedFile file = Request.Files[i]; if (file.ContentLength == 0) { continue; } string fileName = Path.GetFileName(file.FileName); string saveAsPath = Path.Combine(path, fileName); file.SaveAs(saveAsPath); } A: I fixed it by checking for a non zero ContentLength: string path = "..."; for (int i = 0; i < Request.Files.Count - 1; i++) { HttpPostedFile file = Request.Files[i]; if (file.ContentLength == 0) { continue; } string fileName = Path.GetFileName(file.FileName); string saveAsPath = Path.Combine(path, fileName); file.SaveAs(saveAsPath); } Sometimes its the simple things that I overlook ...
[ "stackoverflow", "0039842798.txt" ]
Q: How do I skip to a certain part of my code if I encounter an error in Julia I have a 'wrapper function' that takes inputs and just runs a lot of functions in turn and spits out a result at the end. A simple example function wrapper(a,b) c = first_function(a,b) d = second_function(c) if typeof(d) == Int64 e = third_function(d) f = fourth_function(e) g = fifth_function(f) try h = sixth_function(g) catch i = "this has failed" end i = seventh_function(h) else i = "this has failed" end return i end There are about 5 different places throughout the list of functions that I want to set up 'if - else' statements or 'try - catch' statements. The 'else' part and the 'catch' part are always evaluating the same things. In this example you can see what I mean by seeing that both the else and the catch statements execute i = "this has failed". Is there a way that I can just define i = "this has failed" at the bottom of the function's code and just tell julia to skip to this line for the 'else' or 'catch' parts ? For example I'd like my above to be something like: function wrapper(a,b) c = first_function(a,b) d = second_function(c) if typeof(d) == Int64 e = third_function(d) f = fourth_function(e) g = fifth_function(f) try h = sixth_function(g) catch <skip to line 10> end i = seventh_function(h) else <skip to line 10> end <line 10> i = "this has failed" return i end A: You can use the @def macro from this SO post. For example: @def i_fail_code begin i = "this has failed" end and then you'd do: function wrapper(a,b) c = first_function(a,b) d = second_function(c) if typeof(d) == Int64 e = third_function(d) f = fourth_function(e) g = fifth_function(f) try h = sixth_function(g) catch @i_fail_code end i = seventh_function(h) else @i_fail_code end return i end This macro is pretty cool because even though it's essentially just copy/pasting what's in its definition it will even get the line numbers for errors correct (i.e. it will send you to the correct line in the @def definition). A: You got some great literal answers answering your literal question, but the real question is why do you need to do it like this in the first place? It sounds like a really bad design decision. Essentially you're reinventing the wheel, badly! You're trying to implement a "subroutine" approach as opposed to a "functional" approach; subroutines have all but disappeared decades ago, for good reason. The fact that your question essentially boils down to "GOTO for Julia" should be a really big red flag. Why not just define another function that handles your "fail code" and just call it? You can even define the fail function inside your wrapper function; nested functions are perfectly acceptable in julia. e.g. julia> function outer() function inner() print("Hello from inner\n"); end print("Hello from outer\n"); inner(); end outer (generic function with 1 method) julia> outer() Hello from outer Hello from inner So in your case you could simply define a nested handle_failure() function inside your wrapper function and call it whenever you feel like it and that's all there is to it. PS: Preempting the typical "there are some legit uses for GOTO in modern code" comment: yes; this isn't one of them.
[ "stackoverflow", "0009751307.txt" ]
Q: iPhone iOS how to make UIRotationGestureRecognizer and UIPinchGestureRecognizer to work together to scale and rotate a UIView with subviews? I'm implementing a drag/drop/resize/rotate labels within my app. So far everything is working except for the UIRotationGestureRecognizer gesture. More specifically, it does not work with the UIPinchGestureRecognizer gesture. Normally the two gestures compete for two finger touches, so I'm running them in parallel. Below are my 2 methods that the gesture recognizers invoke. When doing the rotation gesture, the view spins wildly around it's center, with it's height and width changing as follows: height becomes width, width slowly turns into height. Eventually, the view disappears. Within the view, I have another auto-resizing view. Normally, the pinch gesture automatically resizes the subviews as well, but in this case the subviews with autoresizing masks disappear. The subviews have height and width springs and left/top strut. What am I doing wrong? How can I both resize and scale a UIView with gestures? All the delegate methods and connections are setup properly. I need to understand how to handle the order in which the recognizers would be applying the scaling and rotation. //makes 2 gesture recognizers behave together - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{ return YES; } - (IBAction)handleRotationFrom:(id)sender { NSLog(@"Gesture rotation %.1f", rotationGestureRecognizer.rotation); //attempt to continuously rotate the label, starting with a remembered rotation float rotation = atan2(activeCompanionLabelView.transform.b, activeCompanionLabelView.transform.a); NSLog(@"existing rotation %.1f", rotation); // rotation = rotation<0?(2*M_PI)-fabs(rotation):rotation; rotation +=rotationGestureRecognizer.rotation; NSLog(@"*** gesture rotation %.1f sum: %.1f, saved: %.1f",rotationGestureRecognizer.rotation, rotation, activeCompanionLabelView.savedRotation); activeCompanionLabelView.transform = CGAffineTransformMakeRotation((rotation)); activeCompanionLabelView.savedRotation = rotation; } - (IBAction)handlePinch:(id)sender { NSLog(@"pinch %.2f", pinchGestureRecognizer.scale); //resize, keeping the origin where it was before activeCompanionLabelView.frame = CGRectMake(activeLabelContainerFrame.origin.x, activeLabelContainerFrame.origin.y, activeLabelContainerFrame.size.width*pinchGestureRecognizer.scale, activeLabelContainerFrame.size.height*pinchGestureRecognizer.scale); } A: If you want two gestureRecognisers to run in parallel (simultaneously) your view should implement <UIGestureRecognizerDelegate>. Also, you should make it a delegate of both gestureRecognizers. rotationGestureRecognizer.delegate=self; pinchGestureRecognizer.delegate=self; And you also should implement shouldRecognizeSimultaneouslyWithGestureRecognizer: method: - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer { return YES; } NOTE: if you have more then this two gestureRecognisers in your view you're gonna have to add some identity checking in this method. EDIT: Just found Ole Begemann's article on this topic: Gesture Recognition on iOS with Attention to Detail
[ "stackoverflow", "0040036976.txt" ]
Q: Sitecore Experience Accelerator License Error – Sitecore.SXA Not Found Is Sitecore Experience Accelerator(SXA) a licensed module ? I Followed below official Site and install the SXA. Sitecore Experience Accelerator 1.0 Initial Release In above SXA official site not mentioned about licence. We are using Sitecore Experience Platform 8.2. Before install SXA, I installed package "Sitecore PowerShell Extensions-4.1 for Sitecore 8" ,after that I installed package "Sitecore Experience Accelerator for 8.2", successfully installed. I able to create "tenant folder" and "tenant " in that tenant I able to create site, but while seeing the experience (or) preview mode of any item in that site getting error "A required license is missing". also tried to clear my browser history and cache, then also getting same error. Please confirm "SXA" is licence or free? If it is licence how to purchase it. Thanks in advance A: SXA is licensed and not free. You should contact your local sales office.
[ "stackoverflow", "0029017586.txt" ]
Q: The 'any()' or 'all()' function in python Is there a way to check two conditions? For example, a=np.array([1,2,3,4,5,6,7,8]) if any(a != 0 and a!=1)==True: do something EDIT: Answer provided. No need for any more input. Cheers A: You need to use a generator object or iterable containing Booleans. The generator expression below contains only true and false, depending if the item is a number other than one and zero. if any(i != 0 and i != 1 for i in a): print "I'll do something here" Problem is, you were trying to test if the array was not equal to zero and one, thus passing a single Boolean rather than an iterable or generator. You want to test the individual values not the array itself.
[ "stackoverflow", "0039910393.txt" ]
Q: Galleria: Won't render without a window intervention? New to Galleria - and trying to evaluate it for an angular system, ripping its image data from a google spreadsheet.. http://codepen.io/kylane/pen/amqWPw function readytogo() { window.alert('This is just a prototype'); Galleria.configure({ transition: 'fade', imageCrop: true, fullscreenDoubleTap: true, responsive: true, trueFullscreen: true, autoplay: 10000, lightbox: true, swipe: 'auto', showCounter: false, showInfo: true }); Galleria.run('#galleria'); $('#galleria').fadeIn('slow'); } window.onload = readytogo; Without the window.alert, the gallery won't render - and I'm not sure why. Any advice would be greatly appreciated! A: Turned out, I wasnt waiting for the google sheet JSON to load before rendering... ... my bad.
[ "stackoverflow", "0036314426.txt" ]
Q: Do you define global variables in a C library? Currently I have subroutines and global variables defined above my main(). I'm trying to create a library in C. Can I declare the global variables in the header file? A: Can I declare the global variables in the header file? Yes, you can declare your global variables in the header file. However, these must be declarations, not definitions of your global variables. In other words, the header should say // This goes into the header extern int my_global_int; and the C file should say int my_global_int; Note: The fact that you can do it does not mean that you should do it. Exposing "raw" global variables from a library is a bad practice, because users of your library can do unexpected things to them. A better approach would be hiding your globals by making them static, and exposing functions to manipulate them instead: // This goes into the header int get_global(); void set_global(int n); // This goes into the C file static int my_former_global; int get_global() { return my_former_global; } void set_global(int n) { if (<n-is-valid>) { my_former_global = n; } }
[ "stackoverflow", "0020429994.txt" ]
Q: mysql insert a query into a table column I'm creating a system log functionality. What I basically need to do is add the relevant insert,update query to a separate table with date time and user. My question is when i'm trying to insert an insert query as a row data I get an error. I understand this is because of the " ' " in the query.But I still need to re run those queries again.So removing the " ' " is not an option for me. Following is the query I'm trying to insert: insert into querylog (query,systemTime,user) values ('INSERT INTO invoice(invoiceno,invoicenote,invoicetotal,nettotal,invoicedate,customer,receivedby,vehicleno) VALUES ('I 501','3223',15000,15000,'2013-12-06','C 116','','-')', '12/6/2013 10:35:56 PM', 'Lakmal') A: Try doubling up on the apostrophes (two single apostrophes, not a double-quote) inside that inner "insert" statement: insert into querylog (query,systemTime,user) values ('INSERT INTO invoice(invoiceno,invoicenote,invoicetotal,nettotal,invoicedate,customer,receivedby,vehicleno) VALUES (''I 501'',''3223'',15000,15000,''2013-12-06'',''C 116'','''',''-'')', '12/6/2013 10:35:56 PM', 'Lakmal')
[ "stackoverflow", "0010627989.txt" ]
Q: How do I insert a tab character in Iterm? Simply put, I know you can do ctrl+v+tab to insert a physically real tab character in a bash statement. But how do I do the same for iTerm? A: The answer was to hit control+v, then tab afterwards, not all together! Hope this helps someone.
[ "stackoverflow", "0058403391.txt" ]
Q: How to monitor usage of CPU when function is called in Python psutil? Hey I'm learning psutil package and I want to know how to display current CPU usage when function is in progress? I suppose I need some threading or something like this, but how to do it? Thank u for any answers. import psutil import random def iHateThis(): tab = [] for i in range(100000): tab.append(random.randint(1, 10000)) tab.sort() return tab; while(True): currentProcess = psutil.Process() print(currentProcess.cpu_percent(interval=1)) A: You can use threading to run iHateThis or to run function with cpu_percent(). I choose second version. I will run cpu_percent() in thread. Because it uses while True so thread would run forever and there wouldn't be nice method to stop thread so I use global variaable running with while running to have method to stop this loop. import threading import psutil def display_cpu(): global running running = True currentProcess = psutil.Process() # start loop while running: print(currentProcess.cpu_percent(interval=1)) def start(): global t # create thread and start it t = threading.Thread(target=display_cpu) t.start() def stop(): global running global t # use `running` to stop loop in thread so thread will end running = False # wait for thread's end t.join() and now I can use it to start and stop thread which will display CPU. Because I may have to stop process using Ctrl+C so it will raise error so I use try/finally to stop thread even if there will be error. def i_hate_this(): tab = [] for i in range(1000000): tab.append(random.randint(1, 10000)) tab.sort() return tab # --- start() try: result = i_hate_this() finally: # stop thread even if I press Ctrl+C stop() Full code: import random import threading import psutil def display_cpu(): global running running = True currentProcess = psutil.Process() # start loop while running: print(currentProcess.cpu_percent(interval=1)) def start(): global t # create thread and start it t = threading.Thread(target=display_cpu) t.start() def stop(): global running global t # use `running` to stop loop in thread so thread will end running = False # wait for thread's end t.join() # --- def i_hate_this(): tab = [] for i in range(1000000): tab.append(random.randint(1, 10000)) tab.sort() return tab # --- start() try: result = i_hate_this() finally: # stop thread even if I press Ctrl+C stop() BTW: this can be converted to class which inherits from class Thread and then it can hide variable running in class. import psutil import random import threading class DisplayCPU(threading.Thread): def run(self): self.running = True currentProcess = psutil.Process() while self.running: print(currentProcess.cpu_percent(interval=1)) def stop(self): self.running = False # ---- def i_hate_this(): tab = [] for i in range(1000000): tab.append(random.randint(1, 10000)) tab.sort() return tab # --- display_cpu = DisplayCPU() display_cpu.start() try: result = i_hate_this() finally: # stop thread even when I press Ctrl+C display_cpu.stop() It could be also converted to context manager to run it as with display_cpu(): i_hate_this() but I skip this part.
[ "physics.stackexchange", "0000106808.txt" ]
Q: Why is jumping into water from high altitude fatal? If I jump from an airplane straight positioned upright into the ocean, why is it the same as jumping straight on the ground? Water is a liquid as opposed to the ground, so I would expect that by plunging straight in the water, I would enter it aerodynamically and then be slowed in the water. A: When you would enter the water, you need to "get the water out of the way". Say you need to get 50 liters of water out of the way. In a very short time you need to move this water by a few centimeters. That means the water needs to be accelerated in this short time first, and accelerating 50 kg of matter with your own body in this very short time will deform your body, no matter whether the matter is solid, liquid, or gas. The interesting part is, it does not matter how you enter the water—it is not really relevant (regarding being fatal) in which position you enter the water at a high velocity. And you will be slowing your speed in the water, but too quickly for your body to keep up with the forces from different parts of your body being decelerated at different times. Basically I'm making a very rough estimate whether it would kill, only taking into account one factor, that the water needs to be moved away. And conclude it will still kill, so I do not even try to find all the other ways it would kill. Update - revised: One of the effects left out for the estimate is the surface tension. It seems to not cause a relevant part of the forces - the contribution exists, but is negligibly small. That is depending on the size of the object that is entering the water - for a small object, it would be different. (see answers of How much of the forces when entering water is related to surface tension?) A: Let's look at this another way: you're just moving from one fluid to another. Sounds harmless, right? By specification of the problem, we're at terminal velocity when we hit the water. The force of drag (in both mediums) is roughly: $$ F_D\, =\, \tfrac12\, \rho\, v^2\, C_D\, A = \rho \left( \frac{1}{2} v^2 C_D A \right) $$ You can imagine that everything except for the density term is the same as you initially transition from the air medium to water. This isn't perfectly accurate, because these are very different Reynolds numbers, but it's good enough for here. That means that the force (and correspondingly, acceleration) will simply change by the same factor that the density changes by. Also, we know the original acceleration due to drag was 1g, in order to perfectly counteract gravity, which is the definition of terminal velocity. That leads to a simple estimation of the acceleration upon hitting the water. I'll assume we're at sea level. $$ \frac{a_2}{a_1} = \frac{ a_2 }{1 g}= \frac{ \rho_{H20} } { \rho_{Air} } = \frac{1000}{1.3} \\ a_2 \approx 770 g $$ The maximum acceleration a person can tolerate depends on the duration of the acceleration, but there is an upper limit that you will not tolerate (without death) for any amount of time. You can see from literature on this subject, NASA's graphs don't even bother going above 100g. Note that a graceful diver's entry will not help you - that's because an aerodynamic position also increases the velocity at which you hit. A: Consider jumping into a swimming pool. Do a barrel-roll (sorry I mean cannon ball, that just kind of slipped out). It's fun, you enter the water nicely and make a huge splash, probably soaking your sister in the process (that'll learn her). Now do a belly flop. Not as fun. You displace exactly the same amount of water in the same time, but this time there is a lot more pain and you come away with red skin and maybe some bruising. The difference? You cover more area in a belly-flop than a cannon ball. At extreme velocities, accelerating your body's mass of water will kill you anyway. However, what actually kills you is hitting the surface. Dip your hand in water... easy. Now slap the surface.... it's like hitting the table (almost). Pressures caused by breaking the surface make water act more solid on shorter timescales, which is why they say hitting water at high speeds is like hitting concrete; on those short times, it is actually like concrete!
[ "stackoverflow", "0060158577.txt" ]
Q: If statement in python/django I am trying to do a simple if statement in python. I have got two fields in my model that corresponds to price (price and discount_price). I would like to filter the results by price but I am not sure how to write the if statement. It should go like this: If 'discount_price exists' then filter by using 'discount_price' if not use field 'price' instead. my views.py def HomeView(request): item_list = Item.objects.all() category_list = Category.objects.all() query = request.GET.get('q') if query: item_list = Item.objects.filter(title__icontains=query) cat = request.GET.get('cat') if cat: item_list = item_list.filter(category__pk=cat) price_from = request.GET.get('price_from') price_to = request.GET.get('price_to') if price_from: item_list = item_list.filter(price__gte=price_from) if price_to: item_list = item_list.filter(price__lte=price_to) paginator = Paginator(item_list, 10) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) context = { 'items': items, 'category': category_list } return render(request, "home.html", context) A: Use Coalesce to get first value that is set from django.db.models.functions import Coalesce .annotate(current_price=Coalesce('discount_price','price')).filter(current_price...) Comment usage example item_list = item_list.annotate(current_price=Coalesce('discount_price','price')) if price_from: item_list = item_list.filter(current_price__gte=price_from)
[ "stackoverflow", "0058635526.txt" ]
Q: 'securestorage' does not contain a definition for setasync Following this tutorial, https://docs.microsoft.com/en-us/xamarin/essentials/secure-storage?tabs=android I have installed Xamarin.Essentials and added using Xamarin.Essentials; as instructed but it is not in used. I got this error: 'securestorage' does not contain a definition for setasync Here is my code: using System; using Xamarin.Essentials; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace Xamarin_SQLite.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class SecureStorage : ContentPage { public SecureStorage() { InitializeComponent(); try { SecureStorage.SetAsync("oauth_token", "secret-oauth-token-value"); } catch (Exception ex) { // Possible that device doesn't support secure storage on device. } } } } A: 'securestorage' does not contain a definition for setasync 1) Your class name for the page is SecureStorage and that is where the error is coming from. Change the class name and|or fully qualify the call to: `Xamarin.Essentials.SecureStorage.SetAsync` or create a using alias for Xamarin.Essentials and qualify the static method with that alias) 2) You need to await that call: `await Xamarin.Essentials.SecureStorage.SetAsync...`
[ "math.stackexchange", "0000164441.txt" ]
Q: Coin Arrangement Puzzle Disclaimer: I'm not sure how math related this puzzle is (it could potentially be), but I thought it was an interesting puzzle, and I also don't know how to solve it so I wanted to see if anyone had any ideas. You have a board divided in quarters and a coin is in each spot. You do not know whether each is facing heads or tails upwards. In each turn, you can choose flip any number of coins. Specify a sequence of turns that guarantees that at some point all coins will be facing the same direction. Follow up: Between each of your turns, the board is rotated an arbitrary amount amount (90, 180, 270 degrees). Specify a sequence of moves that guarantees that at some point all coins will be facing the same direction. A: For the follow-up you have to assume that success will be announced after each try if you manage. We assume that a malevolent adversary controls the rotation, but you can flip a single coin, an opposite pair, or an adjacent pair at your option. You just can't keep track of anything except relative position between flips. You start knowing they are not all heads or all tails. Flip two opposite coins. If that doesn't work, you either have an odd number of heads or two adjacent heads. Flip two neighboring coins. If that doesn't work, you either have two opposite heads or an odd number of heads. Flip two opposite coins. If that doesn't work, you have an odd number of heads. Note that so far, we have always flipped an even number, so the parity hasn't changed. Flip one coin. If that doesn't work, you have two heads and two tails. Flip two opposite coins. If that doesn't work, you have two neighboring heads. Flip two adjacent. If that doesn't work, you have two opposite heads. Flip two opposite. Guaranteed to work. If success is all heads instead of all the same, put flip all four at the start and after every step of the above.
[ "stackoverflow", "0007177830.txt" ]
Q: How can I get in Glassfish 3 a log of what is injected and how? Question title sums it up. However, to be a little more clear. I have EJBs scattered in my application, and I sometimes get exceptions like the following : [#|2011-08-24T16:40:38.937+0200|SEVERE|glassfish3.1|javax.enterprise.system.tools.deployment.org.glassfish.deployment.common|_ThreadID=73;_ThreadName=Thread-1;|Exception while invoking class org.glassfish.ejb.startup.EjbDeployer load method java.lang.RuntimeException: EJB Container initialization error at org.glassfish.ejb.startup.EjbApplication.loadContainers(EjbApplication.java:246) at org.glassfish.ejb.startup.EjbDeployer.load(EjbDeployer.java:290) at org.glassfish.ejb.startup.EjbDeployer.load(EjbDeployer.java:101) at org.glassfish.internal.data.ModuleInfo.load(ModuleInfo.java:186) at org.glassfish.internal.data.ApplicationInfo.load(ApplicationInfo.java:249) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:460) at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240) at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:370) at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:355) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:370) at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1067) at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:96) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1247) at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1235) at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:465) at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:222) at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:168) at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117) at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:234) at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:822) at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:719) at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1013) at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225) at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104) at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90) at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79) at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54) at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59) at com.sun.grizzly.ContextTask.run(ContextTask.java:71) at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532) at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513) (notice it is only an example, and not the error I precisely want to fix). In this error stack and message, I have absolutely no clue on the failing EJB and why it is failing. So, is it possible to obtain such details ? A: Log in to the admin console, go to configurations, your instance, logger settings and set the EJB Container to finest. From there you should be able to get enough info to see what ejb was loading.
[ "german.stackexchange", "0000055457.txt" ]
Q: Why is this negated with nicht and not kein? A text I am studying has the following sentence, Eine freie Presse gab es nicht. This contradicts everything I thought I understood about creating negative sentences in German. Surely the correct way to put this sentence is Es gab keine freie Presse. A: A nicht at the end of a clause means the verb in second position is negated. So, in Eine freie Presse gab es nicht. the predicate is nicht geben. That's slightly different from Es gab keine freie Presse. where eine freie Presse is negated. In your example, there is little semantic difference. The reason why the first form was used is the special position in front of the clause. It's the topic. The alternative Keine freie Presse gab es. which has the negated freie Presse as the topic sounds off. There's even a pun using that for effect: In a former GDR Kaufhaus: Haben Sie denn keine Schuhe? — Hier gibt's keine Hosen. Keine Schuhe gibt's dahinten. A: Both sentences are right. It's a matter of emphasis. If you hear a sentence starting with Eine freie Presse ... your expectation is: Ah, we are talking about freedom of speech now. What about free press? Well ... gab es nicht. Oh. That's bad. If the sentence starts with Es gab keine ... then it's more about was es gab and was es nicht gab. I guess you already know that word order in German is pretty free. Different word order is almost always about emphasis. A: Put simply, it's this: nicht means the verb doesn't. kein means the noun isn't. So both those sample sentences are correct -- either the free press does not exist, or there isn't a free press.
[ "stackoverflow", "0059163431.txt" ]
Q: Regex for IP capture or hostname I am trying to create a regex for IP capture or hostname, and ignore anything after # DATA 192.168.0.41 #obs SRVNET #obs 192.168.0.4 #obs REGEX ^(([1]?[0-9]{1,2}|2([0-4][0-9]|5[0-5])).){3}([1]?[0-9]{1,2}|2([0-4][0-9]|5[0-5]|[a-z]))$ A: In the first part of the pattern from the comments you are matching [^#]+ which is a negated character class and will also match a space. As you don't want to match spaces, you could add \s to it to not match whitespace characters. The whole match is wrapped in group 1, but as that is the only match you might make it non capturing (?: Note that you have to escape the dot to match it literally and that [1] is the same as just 1. ^(?:[^#\s]+)|^((1?[0-9]{1,2}|2([0-4][0-9]|5[0-5]))\.){3}(1?[0-9]{1,2}|2([0-4][0-9]|5[0-5]))$ ^^ ^^ ^^ Regex demo
[ "stackoverflow", "0049525407.txt" ]
Q: Trouble shooting ora-29471 Certain sessions cause ORA-29471 because dbms_sql inoperable for those sessions. We are facing this error in our application for few records. How this can be troubleshooted? How we can identify a particular session has no access on DBMS_SQL? Do we have any attribute/flag at session level? Below link provides a way to reproduce this problem locally. Reproduce A: The error is at runtime. It's possible you cannot guess it's going to happen before it happens. Maybe your solution is to have a single block checking with the cursor id you want to open dbms_sql.is_open(c_id). But if this is what you are looking for, here is how to find the list of opened cursors: select a.value, s.username, s.sid, s.serial# from v$sesstat a, v$statname b, v$session s where a.statistic# = b.statistic# and s.sid=a.sid and b.name = 'opened cursors current' ; You can also access v$open_cursor to count them: SELECT * FROM v$open_cursor oc, v$session s WHERE oc.sid = s.sid order by 3,2; Hope this helps you tweaking something to check if the expected cursor is used. A: Officially, once the ORA-29471 has been raised, your session can't use DBMS_SQL again. https://docs.oracle.com/cd/B28359_01/appdev.111/b28419/d_sql.htm#i1026408 ORA-29471 DBMS_SQL access denied: This is raised if an invalid cursor ID number is detected. Once a session has encountered and reported this error, every subsequent DBMS_SQL call in the same session will raise this error, meaning that DBMS_SQL is non-operational for this session. In practice, you can get away with a dbms_session.modify_package_state that will clear session state across all packages, closing all open cursors etc. Depending on your situation that may be more manageable than dropping/opening database connections. declare c_1 number := 5; l_res boolean; begin l_res := dbms_sql.is_open(c_1); end; / declare c_2 number; begin c_2 := dbms_sql.open_cursor(); end; / begin dbms_session.modify_package_state(dbms_session.reinitialize); end; / declare c_2 number; begin c_2 := dbms_sql.open_cursor(); end; /
[ "stackoverflow", "0002137415.txt" ]
Q: What's the right memory management pattern for buffer->CGImageRef->UIImage? I have a function that takes some bitmap data and returns a UIImage * from it. It looks something like so: UIImage * makeAnImage() { unsigned char * pixels = malloc(...); // ... CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, pixels, pixelBufferSize, NULL); CGImageRef imageRef = CGImageCreate(..., provider, ...); UIImage * image = [[UIImage alloc] initWithCGImage:imageRef]; return [image autorelease]; } Can anyone explain exactly who owns what memory here? I want to clean up properly, but I'm not sure how to do it safely. Docs are fuzzy on these. If I free pixels at the end of this function after creating the UIImage, and then use the UIImage, I crash. If I Release the provider or the imageRef after creating the UIImage, I don't see a crash, but they're apparently passing the pixels all the way through, so I'm skittish about releasing these intermediate states. (I know per CF docs that I should need to call release on both of the latter because they come from Create functions, but can I do that before the UIImage is used?) Presumably I can use the provider's dealloc callback to cleanup the pixels buffer, but what else? Thanks! A: The thumb rule here is "-release* it if you don't need it". Because you no longer need provider and imageRef afterwards, you should -release all of them, i.e. UIImage * image = [[UIImage alloc] initWithCGImage:imageRef]; CGDataProviderRelease(provider); CGImageRelease(imageRef); return [image autorelease]; pixel is not managed by ref-counting, so you need to tell the CG API to free them for you when necessary. Do this: void releasePixels(void *info, const void *data, size_t size) { free((void*)data); } .... CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, pixels, pixelBufferSize, releasePixels); By the way, you can use +imageWithCGImage: instead of [[[* alloc] initWithCGImage:] autorelease]. Even better, there is +imageWithData: so you don't need to mess with the CG and malloc stuff. (*: Except when the retainCount is already supposedly zero from the beginning.) A: unsigned char * pixels = malloc(...); You own the pixels buffer because you mallocked it. CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, pixels, pixelBufferSize, NULL); Core Graphics follows the Core Foundation rules. You own the data provider because you Created it. You didn't provide a release callback, so you still own the pixels buffer. If you had provided a release callback, the CGDataProvider object would take ownership of the buffer here. (Generally a good idea.) CGImageRef imageRef = CGImageCreate(..., provider, ...); You own the CGImage object because you Created it. UIImage * image = [[UIImage alloc] initWithCGImage:imageRef]; You own the UIImage object because you allocked it. You also still own the CGImage object. If the UIImage object wants to own the CGImage object, it will either retain it or make its own copy. return [image autorelease]; You give up your ownership of the image. So your code leaks the pixels (you didn't transfer ownership to the data provider and you didn't release them yourself), the data provider (you didn't release it), and the CGImage (you didn't release it). A fixed version would transfer ownership of the pixels to the data provider, and would release both the data provider and the CGImage by the time the UIImage is ready. Or, just use imageWithData:, as KennyTM suggested.
[ "stackoverflow", "0048089290.txt" ]
Q: Cannot set form_tag method as get I try to send a form_tag with get method like this = form_tag search_offers_path, method: :get, class: 'sort-form form inputs-underline' do .sort-inputs .input-group.inputs-underline.min-width-150px.sort-input = label_tag :sort_by, 'Sort by' = select_tag :sort_by, options_for_select([["Sort by", ""], ["User level", "user_level"], ["Success rating", "user_average_overall_rating"]]), class: "form-control" .input-group.inputs-underline.min-width-150px.sort-input = label_tag :sort_direction, 'Sort direction' = select_tag :sort_direction, options_for_select([["Sort direction", ""], ["Ascending", "asc"], ["Descending", "desc"]]), class: "form-control" But I don't understand why it becomes a POST as form_tag default Started POST "/offers/search" for 127.0.0.1 at 2018-01-04 12:35:18 +0700 ActionController::RoutingError (No route matches [POST] "/offers/search"): Anyone has a hint? UPDATE: I checked the HTML generated based on the feedback and see that data-remote = true (although I have never set it and I don't want an ajax request, too). A: <%= form_tag({}, {:method => :get, class: 'sort-form form inputs-underline'}) do %> Try this one. You can definitely get your solution.
[ "windowsphone.stackexchange", "0000005877.txt" ]
Q: Touch and Network+ app crashing in lumia 620 My touch and network+ app is crashing in Lumia 620 after updating to WP 8.1. Any suggestions how can it be fixed? A: If the apps are all up to date your only option is to do a hard reset as you can't uninstall / reinstall those apps manually. A hard reset usually fixes all issues caused by the WP8.1 update.
[ "stackoverflow", "0056238334.txt" ]
Q: mystery first value appearing out of nowhere Running simple code to read through many files at the same time and extracting data and collecting the means. The first value extracted is wrong (0), I've checked the data manually and the first data point to be extracted would be 7.21 (the 2nd value), i cant seem to figure out where the first is being generated from. Ive tried going over it manually but seems to be something wrong with my code. pollutantmean <- function(directory, pollutant, id = 1:332){ results <- vector('numeric', 1) for (i in id){ if(i < 10){ path <- paste(directory, '/00', i, '.csv', sep = '') data <- read.csv(path) mn <- na.omit(data[[pollutant]]) results<- c(results, mn) } When i plug in the first 2 arguments and 1:10 (meaning the first 10 files) I get 11 results. [1] 0.0000 7.2100 5.9900 4.6800 3.4700 2.4200 1.4300 2.7600 3.4100 1.3000 3.1500 The first value is unexpected and I dont know where its coming from. Its throwing my mean off. Can someone please help? Thank you A: In your function you first initialize the vector results: results <- vector('numeric', 1) This creates a vector of length 1 with 0 as entry: results # [1] 0 Now, inside your for-loop after reading in the data and everything you apend your result nm to the results vector. To visualize this I set the result to be the id for each step. for (i in 1:10){ mn <- i results <- c(results, mn) } So in each step of your loop we add an entry to the vector results, which initially has already length 1. results # [1] 0 1 2 3 4 5 6 7 8 9 10
[ "stackoverflow", "0014167305.txt" ]
Q: Simple UnityContainerExtension I'm working on an application that is using the bbv EventBrokerExtension library. What I'm trying to accomplish is that I want to have unity register the instance that are instantiated through the container with the EventBroker. I'm planning on doing this through a UnityContainerExtension and implementing the IBuilderStrategy. The problem is that the methods for the interface seem to be called for each parameter in the constructor. The problem is when Singleton instances get resolved when building an object they will be registered multiple times. For instance suppose you had class Foo(ISingletonInterface singleton){} class Foo2(ISingletonInterface singleton){} and you resolve them via unity using var container = new UnityContainer(); container.AddNewExtension<EventBrokerWireupStrategy>(); container.RegisterInstance<IEventBroker>(new EventBroker()); container.RegisterInstance(new Singleton()); var foo = container.Resolve<Foo>(); var foo2 = container.Resolve<Foo2>(); Then the UnityContainerExtension will call postbuildup on the same singleton object. Here is my naive implementation of UnityContainerExtension. using Microsoft.Practices.ObjectBuilder2; using Microsoft.Practices.Unity; using Microsoft.Practices.Unity.ObjectBuilder; using bbv.Common.EventBroker; using System.Collections.Generic; namespace PFC.EventingModel.EventBrokerExtension { public class EventBrokerWireupExtension : UnityContainerExtension, IBuilderStrategy { private IEventBroker _eventBroker; private List<object> _wiredObjects = new List<object>(); public EventBrokerWireupExtension(IEventBroker eventBroker) { _eventBroker = eventBroker; } protected override void Initialize() { Context.Strategies.Add(this, UnityBuildStage.PostInitialization); } public void PreBuildUp(IBuilderContext context) { } public void PostBuildUp(IBuilderContext context) { if (!_wiredObjects.Contains(context.Existing)) { _eventBroker.Register(context.Existing); _wiredObjects.Add(context.Existing); } } public void PreTearDown(IBuilderContext context) { } public void PostTearDown(IBuilderContext context) { } } } A: After further investigation it appears that the problem has to do with the EventBrokerExtension. If I subscribe them in a certain order then some of them don't get registered with the event broker. UPDATE: Wanted to update this question really quick with the answer in case anyone else witnesses similar behavior when using the bbv EventBroker library. The behavior I was seeing was that a subscriber would get events for a while but then would stop receiving events. By design the EventBroker only maintains weak references to the publishers and subscribers that have been registered. Since the eventbroker was the only class referencing the objects they were getting garbage collected at an indeterminate time and wouldn't receive events anymore. The solution was simply to create a hard reference somewhere in the application besides the EventBroker.
[ "electronics.stackexchange", "0000265636.txt" ]
Q: Why do datasheets include Tape and Reel information? Specifically: - Does a PCB designer need to be concerned with tape and reel information? - Is the information intended for PCB assemblers, pick and place machines, etc? - Will a pick and place machine mess up if you create your part with an orientation different from the way the part is oriented on the reel? A: You might be concerned with the quantity per reel (for costing), and with other details to make sure that your assembly shop(s) can actually handle the parts. For example, some OSRAM LEDs are double density on the tape and older machines cannot handle them. If you know more about the part orientation in the tape and the center point definition it should be possible to make library footprints that require less labour to set up pick&place, but I don't think most designers do that. Edit: Re orientation- PCB assemblers do a lot of 'touching' of the P&P file and such problems will be ironed out manually provided they get unambiguous direction on the proper orientation on the PCB. If you did the pick and place in-house you might have reason to make it better, but when you're getting charged for setup so I don't think it matters that much. It's not like bare PCBs where the Gerber files are generally plotted with basically no alteration. Read a bit more about the real situation here For example, one assembler I use for small-quantity high-end work creates a separate sheet for each component in the design. A: I don't think board designers need the tape and reel information, but assembly shops do, for loading and programming their pick-and-place machines.
[ "stackapps", "0000001043.txt" ]
Q: stackauth throwing 503 (in html format) after just a few /users/{id}/associated requests After 5-8 successful requests 503 error, in html format, are being thrown. The requests are unique and consecutive, no api abuse is occurring. A related, but critical, concern is that any error raised as the result of a JSONP API call needs to be JSON with a 200 status, not HTML. We covered this in this issue: API Suggestion: suppress http error code when jsonp is specified see all api endpoints except api.stackoverflow.com are failing paged requests with HTML 503 for related bug. Update 1: Tests show that the introduction of a delay of 300ms between requests bypasses the throttle guard on /users/{id}/associated. I suspect that this will be the case for all api endpoints except api.stackoverflow.com are failing paged requests with HTML 503 as well. While this could be considered a workaround, it adds unnecessary complexity and exception handling, especially in asynchronous scenarios and affects responsiveness of applications. Update 2: I am being told by the stack overflow team that they feel throttling is working as expected. I can't argue with them about the interval they choose to use as a throttle threshold, although the fact that api.stackoverflow seems to treat api requests 'properly', e.g. servicing consecutive unique requests without complaint, while all other sites do not would indicate that perhaps someone, somewhere at some time understood that an api is consumed programmatically. Or it could just be coincidence. What I can complain about is that I am not sure that they realized that the behavior of sending HTML 503 breaks JSONP clients. If they were to send a JSON formatted error with a status of 200 when JSONP is specified, we could capably handle the error, compensate and adjust the request rate. As it is, things just fall apart. I can also complain that there is no published threshold interval. How can we comply with a throttle threshold if we don't know what it is? Take a guess, fire some requests being ever vigilant for 503 (unless you are using JSONP, then you are SOL) and then take another quess? Does anybody realize the amount of complexity that introduces The bottom line, really, in my opinion, is that API requests are controlled via rate limits and as long as they are not representing polling abuse, e.g. identical requests within a minute of each other, which is easily handled with a caching buffer built into the library, they should be serviced without complaint, as they are by api.stackoverflow.com and as stated in Conscientious use of the API ....... GET /0.9/users/01b106cc-dc85-4f3c-a9af-3abfd2fc86a3/associated?key=[my key]&jsonp=Soapi._internal._callback144 HTTP/1.1 Accept: */* Referer: http://localhost:23616/src/UserSearchAutocompleteJQueryUI.htm Accept-Language: en-US User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Tablet PC 2.0; .NET4.0C; .NET4.0E) Accept-Encoding: gzip, deflate Host: stackauth.com Connection: Keep-Alive HTTP/1.1 503 Service Temporarily Unavailable Server: nginx Date: Wed, 07 Jul 2010 22:52:22 GMT Content-Type: text/html Content-Length: 650 Connection: keep-alive ------------------------------------------------------------------ GET /0.9/users/5627464e-02dd-4078-8594-00fff4c8a317/associated?key=[my key]&jsonp=Soapi._internal._callback145 HTTP/1.1 Accept: */* Referer: http://localhost:23616/src/UserSearchAutocompleteJQueryUI.htm Accept-Language: en-US User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; Tablet PC 2.0; .NET4.0C; .NET4.0E) Accept-Encoding: gzip, deflate Host: stackauth.com Connection: Keep-Alive HTTP/1.1 503 Service Temporarily Unavailable Server: nginx Date: Wed, 07 Jul 2010 22:52:22 GMT Content-Type: text/html Content-Length: 650 Connection: keep-alive ....... A: Request Throttling Limits
[ "stackoverflow", "0036247885.txt" ]
Q: How to get parameter value of enum in IF condition? How do write this switch parameter { case .CaseA(let valueA): print(valueA) } as an If condition statement? This doesn't work: if parameter == .CaseA(let valueA) { print(valueA) } A: You can use if case as follows enum Foo { case A(Int) case B(String) } let parameter = Foo.A(42) /* if case ... */ if case .A(let valueA) = parameter { print(valueA) // 42 } The if case pattern matching is equivalent to a switch pattern matching with an empty (non-used) default case, e.g. /* switch ... */ switch parameter { case .A(let valueA): print(valueA) // 42 case _: () } For details, see the Language Reference - Patterns.
[ "stackoverflow", "0046066636.txt" ]
Q: Swift - What Type is '()'? I tested some code to understand completion handlers, and I found that there are types such as ()->() and (). I know ()->() means "no parameters and no return value"; but what type is ()? If I define a function like this: func sayHello(){ print("hello") } and then check the type: type(of: sayHello) // ()->() type(of: sayHello()) // () Is "function execution" (()), a type? A: What you are really asking is why does type(of: sayHello()) result in (). Start by thinking about what sayHello() does. It actually calls the function. So type(of:) is telling you the type of the result of that call. Since the return type of sayHello is Void, the type is (). It's basically the second () of () -> () seen in the first call to type(of:). If you change sayHello to have a return type of Int instead of Void, then the 2nd type(of:) returns Int instead of (). And the 1st type(of:) would change from () -> () to () -> Int. tl;dr - () represents Void. The return type of calling sayHello().
[ "stackoverflow", "0020836409.txt" ]
Q: Web API Authentication using Message Handler and HttpClient I am new to web development using Web API and I'm having some issues dealing with authentication using a custom message handler - specifically calling the Web API methods from a C# WPF application using HttpClient. I've implemented authentication using a custom DelegatingHandler as in the TokenInspector class example given here (minus the HTTPS stuff). From the post I understand this moves authentication higher up in the request pipeline than having Action Filters as in this popular post. I can successfully call my secured methods using an ajax call like the following (where _key is the security token): $.ajax({ url: _api + '/Item', beforeSend: function(request) { request.setRequestHeader("X-Token", _key); }, type: 'GET', dataType: 'json', success: fnSuccessResult, error: function (xhr, status, error) { alert(xhr.status + ' ' + status + ' ' + error); } }); I am in the process of writing a test harness for my Web API in C# - how do I handle this type of authentication in C# using HttpClient? A: Try this: var client = new HttpClient(); var request = new HttpRequestMessage(); request.Headers.Add("X-Token", "token"); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); request.Method = HttpMethod.Get; client.SendAsync(request);
[ "stackoverflow", "0048503348.txt" ]
Q: Configuring a single page Create-React-App on Heroku With Firebase Hosting, when you deploy an app you are asked whether to rewrite all urls to /index.html. This means react-router routes would be properly fired whether they are accessed directly or navigated to from the homepage. We use Create-react-app and Create-react-app-buildpack to deploy to Heroku. How can we rewrite all the URLs to /index.html in the same manner? Following this issue, explaining about the routes directive, I configured a static.json in the root to no avail: { "routes": { "/images/*": "/images/", "/legal/*": "/images/", "/media/*": "/media/", "/fav/*": "/fav/", "/styles/*": "/styles/", "/**": "index.html" } } A: Create a static.json file in the project root with the following content: { "root": "build/", "routes": { "/**": "index.html" } } More here.
[ "stackoverflow", "0058558572.txt" ]
Q: php symfony 4 twig slash escaping double quotes is removed and JSON gets broken in my project I am using Symfony 4.3 with Twig and javascript with jquery. I need to pass a json encoded object from php to javascript, but it gets broken with double quotes. For example, on php side I do the following: $new_obj = new \stdClass; $new_obj->value = 'Some data with "double " quotes'; print_r(json_encode($new_obj));exit; return $this->render('mytemplate.html.twig', [ 'new_obj' => $new_obj ]); So here print_r(json_encode($new_obj)) gives the following: {"value":"Some data with \"double \" quotes"} and this looks loke valid json because double qoutes get escaped with slashes. But when I get it in my twig template, I receive the following: {&quot;value&quot;:&quot;Some data with "double " quotes&quot;} So double quotes are replaced with &quot; and escaping slash gets removed at all. I can restore encoded quotes back with the following code: function htmlDecode(input){ var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; } but how can I make my json valid again? JSON.parse() says Uncaught SyntaxError: Unexpected token d in JSON at position 26 at JSON.parse (<anonymous>) [![pic][1]][1] and I have alreadt tried twig internal {{ data|json_encode() }} function on my raw object, or json_encode($new_obj, JSON_HEX_QUOT) but it did not help. Any ideas how to fix it would be welcome. Thank you. A: You could either turn your variable into a json before passing it to twig : $new_obj = new \stdClass; $new_obj->value = 'Some data with "double " quotes'; return $this->render('mytemplate.html.twig', [ 'new_obj' => json_encode($new_obj) ]); And dumping new_obj would show you : {"value":"Some data with \"double \" quotes"} Or you could json_encode it using twig directly inside the page : {{ new_obj|json_encode|raw }}
[ "tex.stackexchange", "0000371034.txt" ]
Q: Begin only the first chapter with roman numbering (IV) I want to include the package acronym in my LaTeX document. This chapter should be numbered in a roman style. But it should not look like "I list of abbreviations", it should look like "IV list of abbreviations". It has to begin with the "IV" and only this chapter. The next chapter should be normaly begin with "1 Chapter One" \documentclass{book} \usepackage[printonlyused]{acronym} \begin{document} \tableofcontents \chapter{list of abbreviations} \begin{acronym} \acro{i.e.}{in example} \end{acronym} \chapter{Chapter One} Something, \ac{i.e.} nothing. \chapter{Chapter Two} \end{document} A: You can simply: change the formatting of the chapter numbering with \renewcommand{\thechapter}{...}. You can use \Roman{chapter} or \arabic{chapter} to get the capter number in (upper-case) roman or arabic literals, respectively (and similar for other representations of numbers). Of course you can also add other stuff like a trailing dot to it: \renewcommand{\thechapter}{\Roman{chapter}.} set the chapter counter to specific values with \setcounter{chapter}{...} Do this two times, first before the list of abbreviations and second before the first chapter. \documentclass{book} \usepackage[printonlyused]{acronym} \begin{document} \tableofcontents \setcounter{chapter}{3} \renewcommand{\thechapter}{\Roman{chapter}} \chapter{list of abbreviations} \begin{acronym} \acro{i.e.}{in example} \end{acronym} \setcounter{chapter}{0} \renewcommand{\thechapter}{\arabic{chapter}} \chapter{Chapter One} Something, \ac{i.e.} nothing. \chapter{Chapter Two} \end{document} Update Now I understand better what you want to achieve. You have an empty page layout for the front matter, so no page numbers are printed. However, you add toclines for table of contents, figures and tables manually, and they are printed with the page numbers in Roman literals, resulting in I, II and III. You want to print IV as the page number for the list of acronyms, although it is not actually on page four, however, it still has an empty page layout. Then, with the start of the first chapter, you change to a page style that displays page numbers, and reset the page number to one. In contrast to what I suggested above, I would proceed now this way: Set the page number at the start of the list of acronyms to 4: \setcounter{page}{4} Use \chapter* for the headline of the list of acronyms, and include the "IV." by hand. This line will not be included in the list of contents. \chapter*{IV. \acronymtitle} Add the list of acronyms manually to the list of contents, without a leading "IV.": \addcontentsline{toc}{chapter}{\acronymtitle} Here's an example for the full code: \documentclass[openany]{book} \usepackage[ngerman]{babel} \usepackage[utf8]{inputenc} \usepackage[printonlyused]{acronym} \begin{document} \pagenumbering{Roman} \addcontentsline{toc}{chapter}{\contentsname} \tableofcontents \thispagestyle{empty} \clearpage \addcontentsline{toc}{chapter}{\listfigurename} \listoffigures \thispagestyle{empty} \clearpage \addcontentsline{toc}{chapter}{\listtablename} \listoftables \thispagestyle{empty} \clearpage \setcounter{page}{4} \newcommand{\acronymtitle}{Abkürzungsverzeichnis} \addcontentsline{toc}{chapter}{\acronymtitle} \chapter*{IV. \acronymtitle} \thispagestyle{empty} \begin{acronym} \acro{d.h.}{das heißt} \end{acronym} \clearpage \pagenumbering{arabic} \setcounter{page}{1} \chapter{Erstes Kapitel} Etwas, \ac{d.h.} nichts. \chapter{Zweites Kapitel} \end{document}
[ "stackoverflow", "0023564945.txt" ]
Q: Should VBO be unbound before calling glDeleteBuffers? Is it required that we should unbind a buffer object before deleting it? If I had bound it in a VAO and deleted it without unbinding (binding to 0), what will happen? Will the reference still exist? public void dispose() { glBindVertexArray(0); glDeleteVertexArrays(vaoID); glBindBuffer(GL_ARRAY_BUFFER, 0); glDeleteBuffers(vboVertID); glDeleteBuffers(vboColID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glDeleteBuffers(eboID); } Is it a good or a bad practice to unbind before deletion? A: Is it necessary?   No. Is it a good idea?   Possibly, but not in your current pseudo-code. The only time you would want to manually unbind a resource in GL prior to deletion is if you have it bound in a separate context. That is because one the criteria for actually freeing the memory associated with a GL resource is that it have a reference count of 0. glDelete* (...) only unbinds an object from the current context prior to putting it on a queue of objects to free. If you delete it while a VAO that is not currently bound holds a pointer to this buffer, or if it is bound in a completely different OpenGL context from the one you call glDelete* (...) in, then the reference count does not reach 0 before glDelete* (...) finishes. As a result, the memory will not be freed until you actually unbind it from or destroy all VAO / render contexts that are holding references. You will effectively leak memory until you take care of all the dangling references. In short, glDelete* (...) will always unbind resources from the current context and reclaim any names for immediate reuse, but it will only free the associated memory if after unbinding it the reference count is 0. In this case, unbinding is completely unnecessary because you are doing so in the same context you call glDeleteBuffers (...) from. This call implicitly unbinds the object you are deleting, so you are doing something redundant. What is more, you already deleted your VAO prior to calling glDeleteBuffers (...) -- when that VAO was deleted, it relinquished all of its pointers and thus decremented the reference count to your buffer. A: Official documentation (https://www.opengl.org/sdk/docs/man/html/glDeleteBuffers.xhtml) says: glDeleteBuffers deletes n buffer objects named by the elements of the array buffers. After a buffer object is deleted, it has no contents, and its name is free for reuse (for example by glGenBuffers). If a buffer object that is currently bound is deleted, the binding reverts to 0 (the absence of any buffer object). As for VAO - https://www.opengl.org/registry/specs/ARB/vertex_array_object.txt (2) What happens when a buffer object that is attached to a non-current VAO is deleted? RESOLUTION: Nothing (though a reference count may be decremented). A buffer object that is deleted while attached to a non-current VAO is treated just like a buffer object bound to another context (or to a current VAO in another context).
[ "stackoverflow", "0033553467.txt" ]
Q: Adding test IDs to unit tests for reporting I'm using mocha and trying to build a testing system which reports tests individually. The goal is to have traceability between tests defined in the requirements for the project and unit tests. So, for example, the test 'Must be able to create new widgets' is in the requirements database with id of '43', I want the unit test which tests that criteria to report something like Test 43, Must be able to create new widgets, pass, and then update the corresponding db entry (another service could be responsible for this). Can this be done in mocha? The only thing I've found so far is to replace text in the it() function with the test id, and use the json reporter to process the results afterwards (but then I don't get the text for what is being tested, unless I combine them and do some kind of parsing). Note: not all tests would have an id. Here's an example of the kind of functionality I'm hoping for describe("Widget" function() { it("should allow creation of widgets", function() { this.id = 43; result = widget.create(); expect.result.to.exist; }); }); And then either a hook, like afterEach(function(test) { if (test.hasOwnProperty('id')) { report(test.result); } }); Or a custom reporter, or an adapter of some sort. runner.on('test end', function(test) { console.log(test.id); //doesn't exist, but i want it to report(test); }); A: What I wanted and what exists were so close! I was able to solve this using the ctx property of the test in the reporter, e.g. test.ctx.id test.js describe("Widget" function() { it("should allow creation of widgets", function() { this.id = 43; result = widget.create(); expect.result.to.exist; }); }); reporter.js runner.on('test end', function(test) { console.log(test.ctx.id); report(test); });
[ "stackoverflow", "0049257427.txt" ]
Q: Python: Flask cache unable to work in specific time range the Flask app I create only able to work if it outside the time range but return error if it is within the time range (the if path) from flask.ext.sqlalchemy import SQLAlchemy from flask.ext.cache import Cache from datetime import datetime, time app.config['CACHE_TYPE'] = 'simple' app.cache = Cache(app) @app.route('/thtop', methods=['GET']) @app.cache.cached(timeout=60) def thtop(): now = datetime.now() now_time = now.time() if now_time >= time(3,30) and now_time <= time(16,30): rv = app.cache.get('last_response') else: rv = 'abcc' app.cache.set('last_response', rv, timeout=3600) return rv If the time in the if path, it unable to show the string abcc but shown Internal Server Error. In WSGI error log, it also shown Exception on /thtop [GET]#012Traceback (most recent call last):#012 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1687, in wsgi_app#012 response = self.full_dispatch_request()#012 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1361, in full_dispatch_request#012 response = self.make_response(rv)#012 File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1439, in make_response#012 raise ValueError('View function did not return a response')#012ValueError: View function did not return a response What is wrong when I am caching? UPDATE Use flask_caching module but still same failures from flask.ext.sqlalchemy import SQLAlchemy from flask_caching import Cache from datetime import datetime, time cache = Cache(app, config={'CACHE_TYPE': 'simple'}) @app.route('/thtop', methods=['GET']) @cache.cached(timeout=60) def thtop(): now = datetime.now() now_time = now.time() if now_time >= time(3,30) and now_time <= time(14,30): rv = cache.get('last_response') else: rv = 'abcc' cache.set('last_response', rv, timeout=3600) return rv The difference I observed in both different module when I run in console, starting from def thtop(), app.cache.get('last_response') return nothing. However, cache.get('last_response') return abcc. The problem is when run in web app, it will cause error as shown above. A: You're getting the error whenever now_time >= time(3,30) and now_time <= time(14,30) is True and rv = cache.get('last_response') is None. When that happens, you're trying to return None from the view which causes the ValueError. You need to add some additional logic to check that the cache actually returns data: from flask import Flask from flask_caching import Cache from datetime import datetime, time app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' app.config['DEBUG'] = True cache = Cache(app, config={'CACHE_TYPE': 'simple'}) @app.route('/thtop', methods=['GET']) @cache.cached(timeout=60) def thtop(): now = datetime.now() now_time = now.time() rv = None if now_time >= time(3, 30) and now_time <= time(14, 30): rv = cache.get('last_response') if not rv: rv = 'abcc' cache.set('last_response', rv, timeout=3600) return rv if __name__ == '__main__': app.run() with this logic your route will always return something so you won't get the ValueError.
[ "superuser", "0000325620.txt" ]
Q: Do I need a NIC to be installed in my computer in order to use a GPRS modem? Modern motherboards come with a built-in LAN controller. What happens when I am using a GPRS modem - does it involves the usage of that LAN controller in any way? A: Depends on the GPRS Modem in question! If it is a GPRS card modem for a laptop (Express Card/similar) or desktop(PCI Express), the answer will be no. If it is a GPRS Modem that has only a network card port, the answer will obviously be yes.
[ "ell.stackexchange", "0000216581.txt" ]
Q: Can you say “I savaged myself” or “She savaged herself” for something or someone? Can you say “I savaged myself” or “He/She savaged himself/herself” for something or someone? For instance, someone was trying to prepare themselves for a contest or a competition, fiercely changing their appearance, behavior etc. and now they are not too happy about it. So is it O’K if this person would use a word “Savage” as a verb for a more dramatic effect (in an interview for example) and say that they savaged themselves for a chance to be on the show? Thank you! A: This is how Merriam-Webster defines the verb savage: : to attack or treat brutally If I mutilate myself with a knife, then it would make sense to say I savaged myself. In fact, I'd argue it would be a natural phrase in that context. It's at least one that I've heard applied in such a context before. The reflexive use is also fine in that context. But simply changing your appearance doesn't have the same sense of permanent harm or attack that savaged would imply. Hearing the verb applied to makeup or clothing would be out of place. Even if they are trying to use a verb in a dramatically figurative fashion, I think savaged would be taking it a little too far. You likely wouldn't say I brutalized myself or I abused myself in this context either. It's possible you could use attack, if you qualified it: I attacked myself with new clothing and makeup. If said in the right way, it would convey a mix of imagery and humour. Otherwise, something more simple like I transfigured myself would be dramatic enough, without also having an implication of harm. In response to a comment: changing the appearance in this context implies plastic surgery In that specific context, the use of savaged might be appropriate—although normally only if the results were undesirable and harmful. Also, unless you performed the surgery on yourself, the specific phrasing would be I was savaged or I got myself savaged.
[ "stackoverflow", "0001495225.txt" ]
Q: Why does hibernate-entitymanager-3.3.2.GA depend on hibernate-3.2.6.ga? In my Maven pom.xml I have the following dependencies: <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>3.3.2.GA</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>3.0.0.ga</version> </dependency> If I look at the Maven dependencies I find that hibernate-entitymanager depends on hibernate-3.2.6.ga. Is this correct? Why would it not depend on a 3.3.x version of Hibernate? Does this mean I am using a hybrid 3.2/3.3 version of Hibernate? Also, I am pulling my dependencies from repo1.maven.org -- should I instead be using repository.jboss.org? For example, repository.jboss.org has a newer version of hibernate-validator. A: The versions of the hibernate components are to a large degree independent of one another. v3.x of component A doesn't necessarily go with v3.x of component B. This link shows the dependencies between the various components. This confirms that Entity Manager 3.3.2 has a dependency of 3.2.x of Hibernate Core. If you want to use Hibernate Core 3.3.x, you need to use Entity Manager 3.4.0.
[ "stackoverflow", "0055086264.txt" ]
Q: Racket complex reduce function I am trying to use the reduce function in a more complex way then what it is usually intended for. I’m not even sure if this is possible, but here’s what I’m trying to do: Given a list (1 2 3) and two constants, let’s have them be 9 and 13, I’m trying to use reduce to end up with: (+ 1 (* 9 (+ 2 (* 9 (+ 3 (* 9 13)))))) I tried a method where I added 13 to the back of then list, so I had (1 2 3 13) then tried doing some mapping with Lambda and reduce, but I can’t get the correct answer. I would post my code that I’ve tried but my internet went out and I’m typing this on my phone, so sorry I can’t show what I tried to do, but the goal is the form of the expression above using reduce A: The proposed operations can indeed be implemented as a reduce (a.k.a. foldr): (+ 1 (* 9 (+ 2 (* 9 (+ 3 (* 9 13)))))) => 9739 (reduce (lambda (e acc) (+ e (* 9 acc))) 13 '(1 2 3)) => 9739 Regarding the constants, 13 is used only once in the innermost expression, so it's a good fit to be used as an initial value. 9 is used to multiply the accumulated value. The input list is used from right to left when the recursion starts to unwind, and at that point we add the current element to the accumulated result.
[ "stackoverflow", "0046495120.txt" ]
Q: Need Help in fixing the infinite loop in Javascript I have the following logic which when I run it in a standalone jsbin it works fine and returns the result. The code just deserialize the string to tree objects My requirement is to get the node information in a string format like "1,2,3,4" and then output the node in binary tree structure: 1 for root, 2 for root.left, 3 for root.right, 4 for root.left.left, etc... But when I call this using node.js using a require command, the while loop is going forever and its not returning the values.. I am new to node.js. please help standalone jsbin script link for below code which runs in jsbin http://jsbin.com/tukigaq/edit?js,console,output (function(exports) { 'use strict'; console.clear(); var createTree = function(treeString) { var createTreeNode = function(value) { var TreeNode = function(value) { this.left = null; this.right = null; this.val = value; }; return new TreeNode(value); }; var treeStringSplit = treeString.split(','); var root = createTreeNode(treeStringSplit[0]); var q = []; q.push(root); var i = 1; while (q.length > 0) { var node = q.shift(); if (node == null) continue; if (treeStringSplit[i] !== '#') { node.left = createTreeNode(treeStringSplit[i]); q.push(node.left); } else { node.left = null; q.push(null); } i++; if (treeStringSplit[i] !== '#') { node.right = createTreeNode(treeStringSplit[i]); q.push(node.right); } else { node.right = null; q.push(null); } i++; } return root; } console.log(createTree("1,#,2,3,4")); })(typeof window === 'undefined' ? module.exports : window) How I am calling this in the test method var expect = require('chai').expect; var helper = require('../index'); describe('createTree', function() { test createTree function it('should create a tree for the structure', function() { var result = helper.createTree("1,2,3"); expect(result.val).to.equal(1); expect(result.left.val).to.equal(2); expect(result.right.val).to.equal(2); }); it('should create a tree for the structure', function() { var result = helper.createTree("1,#"); expect(result.val).to.equal(1); expect(result.left.val).to.equal(null); expect(result.right.val).to.equal(null); }); }); A: Yes, you're shifting the array in the beginning, but then you're pushing multiple times to the array on each pass through the loop. You shift off the first element on each pass, but both of these if statements will add new elements to the array: if (treeStringSplit[i] !== '#') { node.left = createTreeNode(treeStringSplit[i]); q.push(node.left); } else { node.left = null; q.push(null); } i++; if (treeStringSplit[i] !== '#') { node.right = createTreeNode(treeStringSplit[i]); q.push(node.right); } else { node.right = null; q.push(null); } i++; So you'll always have more elements than you're shifting off. I'm not exactly sure what you're trying to accomplish, but you will need some additional control logic in there to either remove more elements from the array or prevent multiple elements from being added on each pass. Working Example Here's a plunker with a working example of the behavior I think you're trying to achieve: https://jsfiddle.net/abfoxef/25ny62h8/ The binary tree code is not mine, it's adapted from an excellent resource on computer science in javascript Adapted Original Code Here's a snippet (that won't run forever) where you can see what's happening in the array structure: var createTree = function(treeString) { var createTreeNode = function(value) { var TreeNode = function(value) { this.left = null; this.right = null; this.val = value; }; return new TreeNode(value); }; var treeStringSplit = treeString.split(','); var root = createTreeNode(treeStringSplit[0]); var q = []; q.push(root); var i = 0; console.log('What is q in the beginning?', q); while (i < 25) { var node = q.shift(); console.log('What is q after shift?', q); if (node == null) continue; if (treeStringSplit[i] !== '#') { node.left = createTreeNode(treeStringSplit[i]); q.push(node.left); } else { node.left = null; q.push(null); } i++; if (treeStringSplit[i] !== '#') { node.right = createTreeNode(treeStringSplit[i]); q.push(node.right); } else { node.right = null; q.push(null); } i++; console.log('What is q at the end of the loop', q); } return root; } console.log(createTree("1,#,2,3,4"));
[ "stackoverflow", "0038793834.txt" ]
Q: Adding a row from a List to a row in a 2nd List Powershell In Powershell: I have 2 lists-FontIDList and FontDefinitionList. I want to take the first row of FontID and add the first row of FontDefinition. Repeat thru all the elements, then write to a text file. I've tried: $newContent = $FontIDList2 | foreach {$_ + $FontDefList2} Add-Content "C:\Desktop\MasterFontList-TimeStamps\TestLatestDate.txt" -value $newContent As well as $newContent = $FontIDList2 + FontDefList2-and I'm pretty sure i need to use some kind of foreach, but am not sure of the syntax. A: You could iterate by index instead using a for loop and then concatenate your strings: $newContent = for ($i = 0 ; $i -lt $FontIDList.Count ; $i++) { $FontIDList[$i] + $FontDefList2[$i] } Add-Content "C:\Users\dtxxxxx\Desktop\MasterFontList-TimeStamps\TestLatestDate.txt" -value $newContent Note that Add-Content adds to a file, not sure if that's what you actually wanted.
[ "academia.stackexchange", "0000108944.txt" ]
Q: Can I conduct independent research and publish a paper on a H4 visa? I am in the USA on H-4 visa (family member of a H-1B visa holder which is an employee visa), waiting for my Employment Authorization Document (EAD). Can I conduct independent research and publish a paper? A: If by independent research, you mean that you are not being paid by anyone and are doing it on your time, then in principle it should be allowed regardless of your visa type. Whatever "hobby" you do in your personal free time is your own prerogative.
[ "stackoverflow", "0036209320.txt" ]
Q: Is there a clean way to convert a C# 'params object[]' constructor argument into a C++ constructor? I'm attempting to port some old code over from C# to C++, and I need to know if there's an efficient/clean method to translate a C# constructor that takes an argument of a params object[] over to C++. In my example, I have the following simple constructor: public ParameterDescriptor(bool required, ParameterType parameterType, params object[] values) { this.optional = optional; this.parameterType = parameterType; this.defaultValues.AddRange(values); } Where the values being inputted into the third argument can range from being absolutely blank to any number of command strings, i.e. "ON", "OFF", "RESET". These command strings then get added to a List containing each object value, through the following: List<object> defaultValues = new List<object>(); public List<object> DefaultValues { get { return this.defaultValues; } set { this.defaultValues = value; } } Is there any method in C++ that would achieve the same result here? That is to say, accept any number of string arguments from None to a large amount in the constructor and store them in a list/vector? I feel as though multiple constructors for varying lengths of command strings would work, but that doesn't solve the possibility of an unknown X amount of strings being inputted. I feel as though va_args might be up the right alley, but they seem like a really messy solution. What would work best here? A: std::vector is precisely what you are looking for. Since C++11, it can be initialised much more easily anyway: std::vector<int> v = { 1, 2, 3 }; However, the more difficult issue is how to best translate a C# object. C++ does not have any kind of root class. There is no such thing as object. Sometimes, a good C++ alternative is to use a template instead. Here is an example, in which I've also used a correct C++ initialisation list, rather than assignments, and const correctness: template <class T> class ParameterDescriptor { bool required; ParameterType parameterType; std::vector<T> defaultValues; // ... ParameterDescriptor(bool required, ParameterType const& parameterType, std::vector<T> const& values) : required(required), parameterType(paremeterType), defaultValues(values) { } void setDefaultValues(std::vector<T> const& values) { defaultValues = values; } std::vector<T> getDefaultValues() const { return defaultValues; } }; But it really depends on why you use object in C# in the first place. The point is, std::vector is the right choice here anyway, regardless of whether or not you use a template. Chances are you are looking for something like boost::any. You could then use a std::vector<boost::any>. I feel as though va_args might be up the right alley, but they seem like a really messy solution. va_args would be a horrible solution. Don't even think about using it. Also stay away from raw arrays. Their syntactical similarity, being declared with the [] notation, might fool you into believing that they match the C# code more closely, but they don't.
[ "unix.stackexchange", "0000551575.txt" ]
Q: custom systemd service order When you create two or more custom systemd services, how do you know which order they will be run? And will that order be sure thing? I am doing Type = idle which is supposed to mean Behavior of idle is very similar to simple; however, actual execution of the service program is delayed until all active jobs are dispatched. This may be used to avoid interleaving of output of shell services with the status output on the console. Note that this type is useful only to improve console output, it is not useful as a general unit ordering tool, and the effect of this service type is subject to a 5s timeout, after which the service program is invoked anyway Below is my /etc/systemd/system/myservice1.service #!/bin/bash [Unit] Description=my service After=default.target [Service] Type=idle ExecStart=/root/my_service1.sh TimeoutStartSec=0 [Install] WantedBy=default.target I then do { create /root/my_service.sh } chmod 700 /root/my_service1.sh systemctl daemon-reload systemctl enable my_service1 If I create many services of type idle, how do I know which order these services will be run in? I do want them to only happen after the system has fully booted and everything boot related has finished. I then plan on having a few custom do_this.service and do_that.service. I have not yet decided how I am naming everything. A: The attributes Before and After, to be included in the [Unit] section of your service, should allow you to also impose an order between different systemd services, and not only a service and the "default" target (see e.g. here for more information). So, if you want myservice1.service to be started before myservice2.service, it should be sufficient to add Before=myservice2.service to your service definition file, and reasonably also After=myservice1.service to that of myservice2.service.
[ "stackoverflow", "0006586004.txt" ]
Q: How to fill business object from dal I'm returning DataTable in DAL. And I have a businessObject called Customer. Where should I fill this object? Should it be done in DAL? Or in my front-end app? or where? A little cofused. A: It should be done in BL or Business Logic layer.
[ "math.stackexchange", "0002172009.txt" ]
Q: Difference between Sophie Germain primes are divisible by 3? It seems that the difference between two Sophie Germain primes greater than 3 is divisible by 3. If this is true, how to prove it? A Sophie Germain prime is a prime $p$ such that $2p+1$ also is a prime. A: For $2p+1$ to be prime you need it to be not divisible by $3$. Thus $p$ must not be $1$ modulo $3$ and thus is $2$ modulo $3$ (except for $p=3$ which you excluded). Thus every such $p$ is $2$ modulo $3$ and the difference of two such primes is divisible by $3$. A: A prime $>3$ is congruent to one of $\pm1\pmod6$. If $p\equiv1\pmod6$ then $2p+1\equiv3\pmod6$ is divisible by three and therefore $2p+1$ is not a prime. So if $p$ is the smaller member of a Sophie Germain pair, we must have $p\equiv-1\pmod6$. Then $2p+1\equiv-1\pmod6$ as well, and the difference $p+1$ is divisible by six.
[ "stackoverflow", "0036714384.txt" ]
Q: Docker - What is proper way to rebuild and push updated image to docker cloud? What I'm currently doing: Dockerfile: FROM python:3.5.1 ENV PYTHONUNBUFFERED 1 RUN mkdir /www WORKDIR /www ADD deps.txt /www/ RUN pip3 install -r deps.txt ADD . /www/ RUN chmod 0755 /www/docker-init.sh Build command: docker build -t my-djnago-app:latest . Tagging: docker tag my-djnago-app:latest lolorama/my-djnago-app-img:latest Pushing: docker push lolorama/my-djnago-app-img:latest After following these steps, the repository image still hasn't updated. I keep getting this message - "Layer already exists". The push refers to a repository [docker.io/lolorama/my-django-app-img] fd5aa641b308: Layer already exists d9c60c6f98e8: Layer already exists d9d14867f6d7: Layer already exists 64ce166099ca: Layer already exists 73b670e35c69: Layer already exists 5f70bf18a086: Layer already exists 9ea142d097a5: Layer already exists 52f5845b1de0: Layer already exists e7fadb3ab9d4: Layer already exists cef72744de05: Layer already exists 591569fa6c34: Layer already exists 998608e2fcd4: Layer already exists c12ecfd4861d: Layer already exists What am I doing wrong? A: I found the problem, thanks to @lorenzvth7! I've had two images with same tag (which i was pushing to cloud). Solution is: Inspect your images and find two or more with the same tag: docker images Delete them: docker rmi --force 'image id' Thats it! Follow steps from my question above. A: Another solution, albeit bruteforce, is to rebuild with the --no-cache flag before pushing again. docker rmi --force my-djnago-app:latest docker build -t my-djnago-app:latest . --no-cache docker push my-djnago-app:latest
[ "puzzling.stackexchange", "0000090814.txt" ]
Q: 2 fake coins from a pile of 30 coins You need to find two fake coins from a pile of 30 coins. You know that a fake coin has a different weight to a real coin, but you don't know whether it is lighter or heavier. You also know that all real coins weigh the same and all fake coins weigh the same. What is the least number of weightings you need to make to find the two fake coins using a two-sided scale? You can place any number of coins on each pan and each weighting has three outcomes: tip to left, stay equal, tip to right. This puzzle was inspired by these great puzzles: 30 fake coins out of 99 coins Twelve balls on a scale, where one ball is lighter and another is heavier A: These steps detail a full algorithm to figuring out which two coins are fake. Worst case, this takes $10$ comparisons. Edit: The algorithm was fixed to account for the error noted in the comments. This didn't affect the worst case scenario. Step 1: Split the $30$ coins into $3$ piles of $10$, which we will call $A$, $B$, and $C$. Compare $A$ and $B$. If they weigh the same, move to step $2$, else move to step $14$. Step 2: We know that either $A$, $B$ both have a fake coin and $C$ has no fake coins, or that $C$ has two fake coins and $A$, $B$ have neither. So, split $A$ into two piles of $5$ and compare. If the piles weigh the same, move to step $3$, else move to step $17$. Step 3: We know that both fake coins are in a pile of $10$ coins, so split this pile into two piles of $5$, which we label $C_1$ and $C_2$. If they weigh the same, move to step $4$, else move to step $8$. Step 4: We know both $C_1$ and $C_2$ have a fake coin. Take $2$ coins from $C_1$ and weigh against $2$ coins from $B$. If they weigh the same, move to step $5$, else move to step $6$. Step 5: We know that the fake coin is one of $3$ coins in $X$ that weren't measured in step $4$. Take two of these coins and weigh them against each other. If they are different, move to step $6$, else we know that the unmeasured coin is the fake coin. Move to step $4$, but instead of $C_1$, apply the steps to $C_2$. Finish at step $5$ or $6$. Step 6: We know that the fake coin is one of $2$ coins, so we weigh one of these coins against a coin from $B$. If it is the same, the unweighed coin is fake, otherwise the weighed coin is fake. After this step, we also know whether the fake coin is lighter or heavier than the normal coin. Move to step $7$. Step 7: Split $C_2$ into piles of $2$, $2$, and $1$. Weigh the two piles of two against each other. If they are the same, we know that the unmeasured coin is the fake one. If they are different, depending on which pile is heavier, we know which pile contains the fake coin. Move to step $6$ and finish there. Step 8: We know one of the piles of $5$ contains two fake coins, so weigh one of these piles against a pile of $5$ from $B$. If they are the same, move to step $9$, otherwise, move to step $13$. Step 9: We know that the unweighed pile of $5$ has $2$ fakes. Split the pile into $2$, $2$, and $1$, and weigh the piles of $2$ against each other. If they are the same, move to step $10$, else move to step $11$. Step 10:: We know both piles of $2$ have one fake coin. For each pile, weigh one coin against a coin from $B$. If they are the same, the unmeasured coin is fake, otherwise the measured coin is fake. Step 11: We know that one of the piles has no fakes, and one pile has either one fake coin (and the unmeasured coin is also fake) or has two fake coins. Take one of the piles of $2$ and measure it against a pile of $2$ from $B$. We now know whether the fake coins are lighter or heavier than the normal coin, and which pile of $2$ contains at least one fake. Move to step $12$ Step 12: Measure the two coins from the pile with at least one fake against each other. If they are the same, then they both are fake. Otherwise, the unmeasured coin is fake, as is the coin that coincides with whether the fake is lighter/heavier than the normal coin. Step 13: We know that the weighed pile of $5$ has $2$ fakes, so split it into piles of $2$, $2$, and $1$, and weigh the piles of $2$ against each other. If they weigh the same, move to step $10$, else move to step $12$ (we know whether the fake is lighter/heavier than the normal coin already, so we know which pile has at least one fake). Step 14: We know that either $A$ or $B$ has two fakes, or that one of them has $1$ fake and $C$ has one fake. Split $C$ into piles of $5$ and compare them. If they are the same, move to step $15$. Else, move to step $22$. Step 15: We know that either $A$ or $B$ has $2$ fakes. Compare $A$ with $C$. Regardless of result, we will have a pile of $10$ coins with $2$ fakes, and we will know whether the fake coins are lighter or heavier than the normal coins. Rename $C$ to $B$. Move to step $16$. Step 16: Split the pile of $10$ into $2$ $5$ coin piles called $C_1$, $C_2$. Compare them. If they are the same, move to step $4$. Else, we know that we have a pile of $5$ coins with $2$ fakes. Move to step $13$. Step 17: We now have two piles of $10$, each with one fake, and one pile of $10$ with no fakes. Call the piles with fakes $A,\;C$, and the pile without a fake $B$. From the previous step, we also have $2$ sub-piles of $A$ of size $5$, which we will call $A_1$, $A_2$, such that $A_1$ is lighter than $A_2$. Compare $A_1$ with $5$ coins from $B$. Regardless of result, move to step $18$. Step 18: We now know which sub-pile of $A$ contains a fake, and whether the fake is lighter or heavier than a normal coin. Split this sub-pile into groups of $2$, $2$, and $1$, and weigh the groups of $2$ against each other. If they are equal, we know that the unmeasured coin is the fake one in $A$. Otherwise, measure the two coins from the group with the fake coin against each other to figure out which coin is fake. Move to step $19$. Step 19: We now focus on $C$. Split $C$ into groups of $3$, $3$, and $4$, and compare the groups of $3$. If they are equal, move to step $20$. Else, move to step $21$. Step 20: We know that the fake coin is in the group of $4$. Take two coins from this group and compare. If they are unequal, we know which coin in $C$ is fake. If they are equal, compare the two remaining coins to see which coin is fake. Step 21: We know which group of $3$ the fake coin is in. Take two coins from the group and compare them. If they are equal, the unmeasured coin is fake. If not, we know which of the two is fake. Step 22: Split $A$ into two piles, and compare. This tells us whether $A$ or $B$ has the fake. Move to step $17$. A: There are ${30 \choose 2} = 435$ ways of selecting 2 coins out of 30. Since the fakes can be heavy or light, that yields $435 \times 2 = 870$ possible combinations. Since each test yeilds one of 3 outcomes, and $3^6 = 729 < 870 < 2187 = 3^7$, at least 7 tests are needed. Below is proof that 7 tests will always work. This would be easier if we had only $27$ coins, as ${27 \choose 2}\times 2 = 702 < 729$, so we could complete the task in 6 tests. To solve 27 coins, make a $3 \times 3 \times 3$ cube, and put one coin in each cell. Then weigh the top layer versus bottom layer, near layer versus far layer, and left layer versus right layer. No matter what the outcome of the 3 tests, there will remain 13 possible combinations of heavy fakes and 13 possible combinations of light fakes (the combinations may not be the same). For example, if all three tests came out level, then each cell pairs with its direct opposite, except the middle cell, which would pair with itself. This is the same whether the fakes are heavy or light. If the results were top > bottom, left > right, and near > far, then the heavy combinations are (using $tln$ to signify top-left-near, and $m$ for middle): $(tln,mmm), (tln,tmm), (tln,mlm), (tln,mmn), (tln,tlm),$ $(tln,tmn), (tln,mln), (tlm,mmn), (tlm,mln), (tlm,tmn),$ $(tmn,mln),(tmn,mlm),(tmm,mln)$ The 13 combinations if the fake coins are light are the opposite combinations to these. At this point, you would have 13 possible combinations for light, 13 for heavy, and one known genuine coin. There is a standard solution for the problem of 13 coins including one fake plus one known genuine coin. This can be solved in 3 tests. In this case, it's slightly tricky as the combinations are different if the fakes are heavy versus light. But we don't have 27 coins, we have 30. So, to try something similar: make the same cube, put one coin in each cell, then add three more coins: pick two opposite corners and put an extra coin in each cell and the last coin in the middle cell. Then proceed as above to identify a combination of cells that contain the fake coins. Given the symmetry of coin placement, each test will weigh 10 coins against 10 coins. Note that it is possible for a 14th combination to appear, as a cell can now match itself. For example, if all the tests balance, then it could be the two coins in the middle cell that are the fakes. This means that there can be up to 17 combinations for each of heavy-light after the first 3 tests, for a net of 34 options. For example, if all tests balance, then the fakes are either in two cells that are opposite one another, as above, or both in the middle cell. Since two of the corner cells have 2 coins each, that cell-pair has four coin-pairs, instead of the usual 1. These additional 3, plus the 1 for the middle cell, lead to a total of 17 pairs. And since we do not yet know if the fakes are heavy or light, that yields 34 combinations to sort through. So now the problem is how to solve the 34 possible remaining combinations with 4 weighings. It's impossible to do in 3, as $34 > 27 = 3^3$. But since 34 is far less than $81 = 3^4$ it should be straightforward to solve the puzzle. Update with more details If all the first three tests balance, then the fakes are in opposite cells in the cube or both in the middle. If you number the cells using a standard grid, 1-27, number each coin and put it in that cell, then add coin 28 to cell 1, 29 to cell 14, and 30 to cell 27, then the combinations are: (1,27), (2,26), (3,25), ..., (13, 15), & (1,30), (28, 27), (28, 30), and (14,29). For test 4, weigh (1,2,3,4,28) vs (5,6,7,8,9). Test 4 balances: No combination includes any 2 of the coins used in test 4, so if the scale balances, it means neither fake is in that set. Thus, one of 10, 11, 12, 13, or 14 is fake, and all the coins weighed (and their counterparts) are genuine. Use the standard solution for 12 or fewer coins containing a fake to determine which of these 5 coins is fake and whether heavy or light. This takes 3 more tests. Once a fake is determined, the other fake is the partner listed above. Test 4 tilts left, in this case, either (1, 2, 3, 4, 28) contains a heavy fake or (5, 6, 7, 8, 9) contains a light fake. In addition, if either 1 or 28 is fake, then the other fake is either 27 or 30. This yields 12 possible combinations. For test 5, weigh (1,2,5,6) vs (3,4,7,8). Test 5 Balances: Either 28 or 9 is fake. Test 6: weigh 27 vs 30, yielding (9,19) if it balances or (27,28) if it tilts left or (27,30) if it tilts right. Test 5 tilts left: One of (1,2,7,8) is fake, for 5 options (since 1 can pair with 27 or 30). Test 6: weigh 7 vs 8 and if they balance, then Test 7: 27 vs 30. If 7 & 8 balance and 27 & 30 balance, then (2,26) are the fakes. Test 5 tilts right: One of (3,4,5,6) is the fake. Weigh 3 vs 4, then 5 vs 6 to determine the fakes. Test 4 tilts right: This is the same as for the "tilts left" case, but with heavy and light reversed. Similar strategies work for the cases where 1, 2, or all three of the first three tests balanced.
[ "stackoverflow", "0038738228.txt" ]
Q: Sign In Sorry, but we’re having trouble signing you in. We received a bad request I am using azure AD authentication to authenticate a user in my MVC application.And I published my application on azure and it is working fine. But, when I run my application locally then it Microsoft's login page comes up and when I enter credentials and click on SignIn button then it is giving "Sorry, but we’re having trouble signing you in.We received a bad request." But the same application is on azure and if I access it from there then it allow me to login. To create this apllication I follwed link to add azure AD authentication A: If you notice the error message, it clearly indicates that you have not configured https://localhost:44320 as one of the reply addresses. Please go back to application configuration screen in your Azure AD and add https://localhost:44320 as additional reply address. That should take care of this problem.
[ "stackoverflow", "0016580885.txt" ]
Q: Google Play Game Services - unable to sign in Right after yesterday's Google I/O keynote I've updated my Android SDK to integrate the game services into one of my apps. Things I've done so far: added and linked my app in the Dev Console (game services) included the OAuth client id into my app/manifest added BaseGameActivity and GameHelper to my project (from GitHub) added the google-play-services library to my project extended BaseGameActivity, added a com.google.android.gms.common.SignInButton I've also set up game meta data and, of course, some achievements. The dev console states that it is ready to release. To test the login flow and achievements, I've added two Google+ accounts as test users. But when I test the SignInButton, an alert pops up: Unknown error. Here's the logcat: ERROR/Volley: il.a: Unexpected response code 403 for https://www.googleapis.com/games/v1/players/me ERROR/SignInIntentService: Access Not Configured ERROR/LoadSelfFragment: Unable to sign in - application does not have a registered client ID I've built my application in production mode - using ProGuard and the right certificate. Did I miss something? Update - some more attempts Here's a short overview about what I've tried in the meantime. Nothing helped. remove and recreate the linked Android app entry (double checked certificate fingerprint) disable anti-piracy skip proguard create a new (test) game and use its client id The problem is not related to the accounts for testing section. Using an account which is not enabled for testing will lead to another error message: E/GameAgent: Unable to retrieve 1P application 547xxxxxx457 from network E/CheckGameplayAcl: Unable to load metadata for game Solution by Hartok! Hartok's solution helped me a lot to fix this issue. I've never visited the Google APIs Console before. It's important to know, that the OAuth Client ID is not deleted when you remove a linked app from your game or even delete a game (in the Dev Console). You have to visit the APIs Console and remove it manually. The auto-selected SHA1 fingerprint is (always) wrong! You have to lookup your own: keytool -exportcert -alias <your-alias> -keystore <path-to-keystore> -list -v The new client id of my (correctly) linked app looked like 89xxxxxxxx73-2u6mXXXXXXXXXXXXXXXXXXX8903.apps.goo..., not just 12 digits as before. I finally figured out that you have to exclude the dash and alphanumeric stuff and have to use the 12 digits only. A: I've fixed this issue. In my case, when I've linked my app (not yet published) to my Google Play Game Services project, the Certificate Fingerprint auto-selected by Google Play was not the good one. To fix that, I've deleted my app client ID on Google APIs Console, unlinked my app, then relinked it with the proper Certificate Fingerprint. This Fingerprint is displayed when exporting your app in Eclipse (if your ADT plugin is up-to-date). Hope it helps. A: Had the same problem. My solution was to link the same package twice in the Dev Console, the first using the SHA1 fingerprint from my own certificate and the second using my debug key SHA1. I had tried using just one or just the other before this and it hadn't worked for either. A: After a long 2 weeks trying to fix this problem I have created steps for me to resolve this problem, and decided to share it with every one who is suffering from the same issue, this comes without publishing the game . it is used for testing. when publish time comes I will share the steps used to publish the app and make sure it works with Google play game service. note that all I was trying to do is sign in using the Google sign in button with no action as to what should happen after sign it, also note that I have used BaseGameUtils from the Google play example as a library, and my IDE of choice to get all of this done was Eclipse. Below are the steps one by one using eclipse: 1-import BaseGameUtils as a library in your eclipse work space, make sure no error occurs after the import. if an error occurred do the following: a- right click on the BaseGameUtil project in project explorer b-Click on Java build path c-Click add external jars from there navigate to your SDK location and find Google-Play-services.jar d-select it and click ok ---> you should see the jar added in the JARs and class folders window. e-Go to the Order and export tab, on the right hand side of libraries and make sure "Android private libraries" and "Android Dependencies" are checked also ensure that the google-play-services.jar is selected. 2- Now make sure you reference your imported BaseGameUtility correctly in the app you want to use ," You can Create a simple hello world application to test this " , so now we will reference the BaseGameUtility in the hello world application as follows: (important ensure Both hello world and BaseGameUtil are both in the same drive two drives will not work) a-right click on the hello world application in the right hand side in project explorer b-click on Java build path c-Click on Libraries d- add the android support-v4 if needed from an external or internal source (Not Required) e- add the base game utils .jard by clicking on add class folder --> then select the BaseGameUtilProject ---Then select the /bin folder --This should import it to your application f-add google-play-services.jar from an external source also if needed g-in "order and export" ensure that you have the following selected --->"Android Private Libraries,Android dependancies ,BasegameUtils.jar,GooglePlayGameServices.jar" along with the normal SRC and GEN that should be selected by default. 3- now in your java file helloworld.java ensure that your main screen has all the required imports and then extend the BaseGameUtil and make sure the project implements the ViewOnClickListener. 4- Edit your android manifest to include the following: <meta-data android:name="com.google.android.gms.games.APP_ID" android:value="@string/app_id" /> and <uses-permission android:name="android.permission.INTERNET"></uses-permission> 5- ensure that you have a ids.xml file in your resource to include your application ID after you create it. <string name="app_id"></string> You can leave it blank for now as later you will have to place the application ID in it 6-copy the debug key you have on your eclipse IDE before you add this application in the developer console. doing so in eclipse happens as follows: a-click on Window b- select android c-Click build d- copy the SHA1 fingerprint and keep it to use it when creating your app in Developers console. 7- Create your game in developers console and use the SHA1 retrieved from step 6. 8- place the application ID in the ids.xml highlighted in step 5 9- double check your values and ensure that the package names are all correct between the developers console and the manifest file . <manifest xmlns:android="http://schemas.android.com/apk/res/android" **package="com.helloword.check"** android:versionCode="1" android:versionName="1.0" > 10- When done ensure that the application in the developer console matches the SHA1 that is assigned in developer console using the keytool. This is the step that took me 2 weeks just to figure out a- locate your application APK from the bin folder of your hello world project, and copy it to another location to check its ID with key tool later b-locate your keytool --> usually located under the JAVA folder of your computer, in my case it was under C:\Program Files\Java\jdk1.7.0_09\jre\bin c- Extract your apk in the temp location d- run the following command keytool -printcert -file "TempLocation\Meta-INF\CERT.RSA" you will get an MD5 along with SHA1 and SHA256 Ensure that the SHA1 matches the one in the developers console. 11- Here is how to check your SHA1 from developers console, a- go to Game Services b- click the name of the game in our case helloWorld c- Scroll down to "API Console Project" d- You should see " this game is linked to the API console Project called helloworld" e- helloworld should be a hyperlink click it, f- this will open the Google APis Console g- in APconsole click on API Access h- scroll down to "Client IDs for installed application" , you should see the SHA1 ensure it is the same as the one generated from the keytool earlier in step 10 . ( if they don't match you have to delete the game from developers console and recreate it with the correct SHA1 ) " make sure not to change the SHA1 from Google APIs console this will cause issues. I-Ensure the package name is the same package name in your android manifest, by that I mean everywhere package name is mentioned ensure it matches the one in " Client ID for installed applications" ( in my case it didn't match the one in the line 4 of my manifest) And that is it you should now be able to test your sign in using google play game service
[ "stackoverflow", "0007771165.txt" ]
Q: Rails: Best practice for handling development data I have the following scenario: I'm starting development of a long project (around 6 months) and I need to have some information on the database in order to test my features. The problem is that right now, I don't have the forms to insert this information (I will in the future) but I need the information loaded on the DB, what's the best way to handle this? Specially considering that once the app is complete, I won't need this process anymore. As an example, lets say I have tasks that need to be categorized. I've begun working on the tasks, but I need to have some categories loaded on my db already. I'm working with Rails 3.1 btw. Thanks in advance! Edit About seeds:I've been told that seeds are not the way to go if your data may vary a bit, since you'd have to delete all information and reinsert it again. Say.. I want to change or add categories, then I'd have to edit the seeds.rb file, do my modifications and then delete and reload all data...., is there another way? Or are seeds the defenitely best way to solve this problem? A: So it sounds like you'll possibly be adding, changing, or deleting data along the way that will be intermingled amongst other data. So seeds.rb is out. What you need to use are migrations. That way you can search for and identify the data you want to change through a sequential process, which migrations are exactly designed for. Otherwise I think your best bet is to change the data manually through the rails console. EDIT: A good example would be as follows. You're using Capistrano to handle your deployment. You want to add a new Category, Toys, to your system. In a migration file then you would add Category.create(:name => "Toys") or something similar in your migration function (I forget what they call it now in Rails 3.1, I know there's only a single method though), run rake db:migrate locally, test your changes, commit them, then if it's acceptable deploy it using cap:deploy and that will run the new migration against your production database, insert the new category, and make it available for use in the deployed application. That example aside, it really depends on your workflow. If you think that adding new data via migrations won't hose your application, then go for it. I will say that DHH (David Heinemeier Hansson) is not a fan of it, as he uses it strictly for changing the structure of the database over time. If you didn't know DHH is the creator of Rails. EDIT 2: A thought I just had, which would let you skip the notion of using migrations if you weren't comfortable with it. You could 100% rely on your db/seeds.rb file. When you think of "seeds.rb" you think of creating information, but this doesn't necessarily have to be the case. Rather than just blindly creating data, you can check to see if the pertinent data already exists, and if it does then modify and save it, but if it doesn't exist then just create a new record plain and simple. db/seeds.rb toys = Category.find_by_name("Toys") if toys then toys.name = "More Toys" toys.save else Category.create(:name => "More Toys") end Run rake db:seeds and that code will run. You just need to consistently update the seeds.rb file every time you change your data, so that 1) it's searching for the right data value and 2) it's updating the correct attributes. In the end there's no right or wrong way to do this, it's just whatever works for you and your workflow.
[ "stackoverflow", "0006831825.txt" ]
Q: Remove combobox item from combobox WPF How to delete combobox item? i tried this code but it does not work. private void btnAdd_Click(object sender, RoutedEventArgs e) { foreach (var item in cbRooms.Items) { if (((ComboBoxItem)item).Content.ToString() == cbRooms.Text.ToString()) { cbRooms.Items.Remove(((ComboBoxItem)item).Content.ToString()); } }} A: Instead of trying to remove a string try: cbRooms.Items.Remove((ComboBoxItem)item))
[ "stackoverflow", "0007692957.txt" ]
Q: Web PHP behaving differently from PHP CLI I obfuscated a code with this (I got it from another SO question) via CLI <?php $infile=$_SERVER['argv'][1]; $outfile=$_SERVER['argv'][2]; if (!$infile || !$outfile) { die("Usage: php {$_SERVER['argv'][0]} <input file> <output file>\n"); } echo "Processing $infile to $outfile\n"; $data="ob_end_clean();?>"; $data.=php_strip_whitespace($infile); // compress data $data=gzcompress($data,9); // encode in base64 $data=base64_encode($data); // generate output text $out='<?ob_start();$a=\''.$data.'\';eval(gzuncompress(base64_decode($a)));$v=ob_get_contents();ob_end_clean();?>'; // write output text file_put_contents($outfile,$out); The obfuscated code is this <?php ob_start();$a='eNq1UtFq2zAUfS/0Hy4mUItkrVdIHuaqobCUwdKnPpUxjC1fx6KaZCR5JZTt2ycpspMm3d72Zt97zrnnHl1VFSjrggksZUry5e3Nsmu78zPUWulCY6e05XKT/l4Vd+s1yWGCkn3FLdDrzP0ILhEoNFxgsUFbMCUtSmvSxKl8urrisuttEml629mVLCvhKaavjNVpUJhls49kr/am5Ru8Sd/yKU2eEvI6MmpkoVs4nncb6iT/BZNWGet3OJ24CCMrVW8/l7Y87i8ODF1c5DuhA9Cg64TmmYceDRn7c7dbAHBjkPUa3wMtsnHPATauGAcnxggXaHIZCjm43Rqjnn34RrFn1aFM3fI/dqoEZsCl/VmKWPRjCNnNuL9bP66A0qhA4BVZqyB5UJULrwRu4AtqTHLQaHstwQXZvGhuMQ2M2UFs+9VdStHr8OXrFPzfAA9RvrTuWiAdb0djWQ/C1/Msy4hz9Lc3h2A1No6eG1AY3AFCxYfUMKFM9O0QTS+Z5UqeKIRD9XM3QlWlGM483gBNXBiNck/GaZZP+I2jCRd4pLnKdDqe4yUF1upU6Tr2v034dzKNisS7irnuXQ62Tg75v/v68C9fy9vzsz+nc1ZO';eval(gzuncompress(base64_decode($a)));$v=ob_get_contents();ob_end_clean();?> I ran the code on CLI it responded appropriately, but in my browsers it didn't echo anything, just blank. Both are PHP 5.3.0 from WAMP. Why is it not echoing anything on web? I also ran it on ideone http://ideone.com/o6PAw and it works properly. What could be the problem? A: The reason it doesn't output anything is that you capture all the output into $v and then do nothing with it. I'm not sure why it would work from the CLI, though, because it certainly shouldn't. Perhaps, as Frank Farmer suggests, your PHP CLI doesn't have output buffering enabled, and so all the ob_*() calls are failing silently.
[ "stackoverflow", "0062508324.txt" ]
Q: Sorting different arrays in typescript I am trying to sort some parameter in my typescript model. My model is as follows. export class DataModel { ID: String point1: Point point2 : Point point3: Point AnotherPoint1: AnotherPoint[] AnotherPoint2: AnotherPoint[] AnotherPoint3: AnotherPoint[] } export class Point { Name: String Timestamp: String } export class AnotherPoint { Name: String Timestamp: String } I have sorting logic in my component which take this above Data Model and sorts point as follows: private sortByNameAndID(dataModel: DataModel[]): DataModel[] { return dataModel.sort(function (a, b) { const pointA = a.point1.Name.toLowerCase(); const pointB = b.point1.Name.toLowerCase(); if (pointA === pointB) { const timeA = a.point1.Timestamp; const timeB = b.point1.Timestamp; return Service.compareDate(new Date(timeA), new Date(timeB)); //here again comparing dates } if (pointA < pointB ) { return -1; } if (pointA > pointB ) { return 1; } }); } } Above sorting logic is working fine for Points but now with this I also need to sort AnotherPoint as well. Means I have to sort all Points and AnotherPoints together as above. How can I do that? A: I would start creating two helper functions, to compare two Points and two arrays of AnotherPoints respectively. I'm assuming that the arrays are to be compared element by element, stopping as soon as a pair of elements does not compare to 0. function comparePoints(pA: Point | AnotherPoint, pB: Point | AnotherPoint) { const pointA = pA.Name.toLowerCase(); const pointB = pB.Name.toLowerCase(); if (pointA < pointB ) { return -1; } if (pointA > pointB ) { return 1; } const timeA = pA.Timestamp; const timeB = pB.Timestamp; return Service.compareDate(new Date(timeA), new Date(timeB)); } function comparePointArrays(arrayA: AnotherPoint[], arrayB: AnotherPoint[]) { const len = Math.min(arrayA.length, arrayB.length); for (let i = 0; i < len; ++i) { const result = comparePoints(arrayA[i], arrayB[i]); if (result !== 0) { return result; } } return 0; } Then the sorting function can be rewritten using the new helper comparators: private sortByNameAndID(dataModel: DataModel[]): DataModel[] { return dataModel.sort(function (a, b) { return comparePoints(a.point1, b.point1) || comparePoints(a.point2, b.point2) || comparePoints(a.point3, b.point3) || comparePointArrays(a.AnotherPoint1, b.AnotherPoint1) || comparePointArrays(a.AnotherPoint2, b.AnotherPoint2) || comparePointArrays(a.AnotherPoint3, b.AnotherPoint3); }); } Note that the || operator only performs the operation on the right if the result of the operation on the left is falsy (0), meaning that we will stop comparing points as soon as a comparison reports a nonzero result.
[ "ru.stackoverflow", "0001098009.txt" ]
Q: C++ - SFML ошибка при компиляции: ‘Window’ does not name a type Есть 2 класса: 1) Window.hpp 2) Spaceship.hpp Подключил Window.hpp к классу Spaceship.hpp а Spaceship.hpp подключил к Window.hpp Window.hpp: #pragma once #include <SFML/Graphics.hpp> #include "Spaceship.hpp" #include <bits/stdc++.h> using namespace std; class Window{ public: Window(){ settings.antialiasingLevel=8; window.create(sf::VideoMode(width, height), "Game", sf::Style::Close, settings); window.setPosition(sf::Vector2i(desktop_width/2-width/2, desktop_height/2-height/2)); Background(); Spaceship(); while(window.isOpen()){ while(window.pollEvent(event)){ if(event.type==sf::Event::Closed) window.close(); if(sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)) window.close(); } window.clear(); window.draw(background_sprite); window.draw(spaceship.ship_sprite); window.display(); } } private: void Background(){ background_texture.loadFromFile("textures/background.png"); background_sprite.setTexture(background_texture); background_sprite.setPosition(0, 0); } public: const int width=500, height=900; const int desktop_width=sf::VideoMode::getDesktopMode().width, desktop_height=sf::VideoMode::getDesktopMode().height; Spaceship spaceship; sf::RenderWindow window; sf::Event event; sf::ContextSettings settings; sf::Texture background_texture; sf::Sprite background_sprite; }; Spaceship.hpp: #pragma once #include <SFML/Graphics.hpp> #include "Window.hpp" #include <bits/stdc++.h> using namespace std; class Spaceship{ public: Spaceship(){ Ship(); } void Ship(){ ship_texture.loadFromFile("textures/Ship.png"); ship_sprite.setTextureRect(sf::IntRect(0, 0, 48, 32)); ship_sprite.setPosition(window.width/2-ship_sprite.getTextureRect().width/2, window.height-ship_sprite.getTextureRect().height); } Window window; sf::Texture ship_texture; sf::Sprite ship_sprite; }; При компиляции выдаёт ощибку: Spaceship.hpp:19:5: error: ‘Window’ does not name a type 19 | Window window; | ^~~~~~ In file included from Window.hpp:3, from Game.cpp:1: Spaceship.hpp: In member function ‘void Spaceship::Ship()’: Spaceship.hpp:16:33: error: ‘window’ was not declared in this scope 16 | ship_sprite.setPosition(window.width/2-ship_sprite.getTextureRect().width/2, window.height-ship_sprite.getTextureRect().height); | ^~~~~~ make: *** [makefile:2: output] Error 1 Кто может подсказать как исправить? A: У Вас классическая циклическая зависимость. Когда создается один из классов, ему нужно знать размер второго. Но второму нужно знать размер первого. Как это решать? Вариант первый. В одном из мест сделать указатель плюс forward declaration - то есть, просто написать перед объявлением класса краткое объявление другого - class Window; или class Spaceship;. Указатель конечно потребует вызова new/delete или использование unique_ptr. В конструкторе Window есть такой вызов Spaceship(); - Вы просто вызываете конструктор корабля, создаете временный объект, который тут же удаляется... Это точно не то, что Вам нужно. Но давайте посмотрим на это по другому. Класс корабля знает имеет свою переменную для window. Но оно ему нужно только что бы размеры посчитать. Так может передать эти размеры? Перепишем class Spaceship{ public: Spaceship(){ } void Ship(int width, int height){ ship_texture.loadFromFile("textures/Ship.png"); ship_sprite.setTextureRect(sf::IntRect(0, 0, 48, 32)); ship_sprite.setPosition(width/2-ship_sprite.getTextureRect().width/2, height-ship_sprite.getTextureRect().height); } sf::Texture ship_texture; sf::Sprite ship_sprite; }; И теперь вызываем правильно - передав параметры. И вместо Background(); Spaceship(); пишем Background(); spaceship.Ship(window.width(), window.height()); Все, осталось удалить лишний инклуд. И ещё почитать о том, что такое конструкторы и классы.
[ "stackoverflow", "0020948394.txt" ]
Q: iOS - Copying NSDictionary to SQLite3 I have a method that receives a table name and an NSDictionary. In that method I want a loop to create an SQL Insert statement for each record that will copy the contents of the NSDictionary into the corresponding table. The NSDictionary was populated via a JSON web service in a previous method. The problem I am having is getting the information out of the NSDictionary and into the Insert statement in the correct format. What I want is for every record to have an Insert statement similar to this: INSERT INTO speaker VALUES (0f32ae3f-ad56-e311-a863-000c29beef51,<null>,1385478793, Mike Smith,<null>,BVSc PhD DSAM DipECVIM-ca MRCVS) But what I am getting is: INSERT INTO speaker VALUES ( { ID = "0f32ae3f-ad56-e311-a863-000c29beef51"; ImageURL = "<null>"; LastMod = 1385478793; Name = "Mike Smith"; Profile = "<null>"; Qualifications = "BVSc PhD DSAM DipECVIM-ca MRCVS"; } ) Here is my code so far: -(void)populateTable:(NSString *)tableName dictonary:(NSMutableDictionary *)tempDict { sqlite3_stmt *stmt; NSMutableString *keys = [NSMutableString string]; NSMutableString *values = [NSMutableString string]; for (NSString *key in tempDict.allKeys) { //edited from tempDict to tempDict.allKeys [keys appendFormat:@"%@,", key]; [values appendFormat:@"%@,", [tempDict objectForKey:key]]; } [values deleteCharactersInRange:NSMakeRange([values length] -1, 1)]; NSString *queryStr = [NSString stringWithFormat:@"INSERT INTO %@ VALUES %@", tableName, values]; NSLog(@"Query = %@", queryStr); NSLog(@"GetData - populateTable - qry : %@",queryStr); const char *sql = [queryStr UTF8String]; ; if((sqlite3_open([[self filePath] UTF8String], &congressDB)==SQLITE_OK)) { NSLog(@"GetData - populateTable - str = %@", queryStr); if (sqlite3_prepare(congressDB, sql, -1, &stmt, NULL)==SQLITE_OK) { NSLog(@"GetData - populatTable - About to carry out SQL statement"); sqlite3_step(stmt); sqlite3_finalize(stmt); } else { NSLog(@"GetData - populateTable - Problem with prepare statement: %s", sqlite3_errmsg(congressDB)); NSLog(@"GetData - populateTable - stmt = %@", stmt); } sqlite3_close(congressDB); } } A: Try this correction: - (void)populateTable:(NSString *)tableName dictonary:(NSMutableDictionary *)tempDict { sqlite3_stmt *stmt; NSMutableString *values = [NSMutableString string]; for (NSString *key in tempDict.allKeys) { [values setString:@""]; NSArray *array = [tempDict objectForKey:key]; if (array.count) { NSDictionary * dict = [array objectAtIndex:0]; for (NSString *keyInDict in dict.allKeys) { [values appendFormat:@"%@,", [dict objectForKey:keyInDict]]; } [values deleteCharactersInRange:NSMakeRange([values length] -1, 1)]; NSString *queryStr = [NSString stringWithFormat:@"INSERT INTO %@ VALUES %@", tableName, values]; NSLog(@"Query = %@", queryStr); NSLog(@"GetData - populateTable - qry : %@",queryStr); const char *sql = [queryStr UTF8String]; ; if((sqlite3_open([[self filePath] UTF8String], &congressDB)==SQLITE_OK)) { NSLog(@"GetData - populateTable - str = %@", queryStr); if (sqlite3_prepare(congressDB, sql, -1, &stmt, NULL)==SQLITE_OK) { NSLog(@"GetData - populatTable - About to carry out SQL statement"); sqlite3_step(stmt); sqlite3_finalize(stmt); } else { NSLog(@"GetData - populateTable - Problem with prepare statement: %s", sqlite3_errmsg(congressDB)); NSLog(@"GetData - populateTable - stmt = %@", stmt); } sqlite3_close(congressDB); } } } }
[ "stackoverflow", "0005530777.txt" ]
Q: How to get a list of the assets in the WP7 Content Project? I can load a textures with: Texture2D texture = ContentManager.Load<Texture2D>(assetName); But this throws an exception if the file doesn't exist. Is there a way to determine if a requested asset of a given name actually exists first? I'm storing a series of assets using suffixed number counters (art001.png, art002.png, ...) and would like to have a simple call preload the textures by just counting through them. A: It is not possible to iterate through the contents of your XAP file. You'll just have to maintain a list of the assets you wish to load. I had a similar problem with my app, I ended up writing a simple script that looked in a particular folder for a matching filename pattern and updating a text file. So, I'd run the script before building the app, the text file gets packaged and read in the app to determine what files could be loaded. Or you can skip the trouble and maintain a list in code by hand.
[ "stackoverflow", "0041427942.txt" ]
Q: How to check if a fence key is registered for Awareness API? I have 2 questions about Googles Awareness Fences API: Do we have a method to check if a fence with a given fence key is registered? What will happen if I accidentally register 2 fences with the same fence key ? A: To check if a fence is registered, make a FenceQueryRequest and check if FenceStateMap contains the fence key. Here is example code: protected void queryFence(final String fenceKey) { Awareness.FenceApi.queryFences(mGoogleApiClient, FenceQueryRequest.forFences(Arrays.asList(fenceKey))) .setResultCallback(new ResultCallback<FenceQueryResult>() { @Override public void onResult(@NonNull FenceQueryResult fenceQueryResult) { if (!fenceQueryResult.getStatus().isSuccess()) { Log.e(TAG, "Could not query fence: " + fenceKey); return; } FenceStateMap map = fenceQueryResult.getFenceStateMap(); if (!map.getFenceKeys().contains(fenceKey)) { // Fence is not registered. } } }); } If you register 2 fences with the same fence key, the second fence will replace the first fence. See the FenceUpdateRequest documentation.
[ "stackoverflow", "0044847476.txt" ]
Q: How to store records in a HashMap or ArrayList in Android I have a general question about HashMaps vs. ArrayLists. Ian a project I am working on I am scanning a barcode from a ticket, like entering a ballpark or concert. As part of this scan there is also static information that the user has pre-selected, like userName, location. I also capture the Date and time of when the barcode is scanned. So I end up with a record consisting of Date/Time, userName,location,barcode scanned. I need to store this information for 100 to 200 scans, then at the end of the day, convert this to a JSON object. I am a bit confused on how to store this data. Can someone give me some pointers on this? I have googled it but am still confused. Thanks much! A: I would suggest not solely keeping this records to a hashmap or arraylist in memory. Maybe the phone will turn off or your application will crash. So the user will lose everything stored in memory so far. What I would do is this. I would create a DTO object with the fields you want eg: public class MyDTO{ private String field1; private LocalDateTime field2; [...] } Then each object when created use Gson or whatever you like and store it as json either to a db or a file(s). At the end of the day read the saved json objects. Combine them to an ArrayList of MyDTOs and use Gson to create an array of json and send them. After you have successfully submitted the JSON just clean up the db or file(s).
[ "stackoverflow", "0031767934.txt" ]
Q: Incrementally updating screen buffer for OpenGL ES When the render function of an OpenGL app is called, can I rely on the fact that the screen-buffer still contains whatever I drew into it during the last call to my render function that was working on that buffer? In other words, would it be possible to draw only incremental updates to the buffer or do I need to redraw the entire screen every time, just in case? I realize that the logic required to make such an approach work would be quite involved as there are multiple screen buffers, so the update needs to be incremental not relative to the last call to the render function, but the last call that actually drew into this particular screen buffer. But depending on the type of screen updates and the required performance, this might still be a worthwhile thing to investigate. So, any answers to the effect of "don't do it!" should be based on actual reliability issues with this idea like possible random buffer corruption and not just "it's way too hard to debug"... A: Depends on what you have EGL_SWAP_BEHAVIOR set to on your surface: eglSwapBuffers(): ... The contents of the color buffer are left unchanged if the value of the EGL_SWAP_BEHAVIOR attribute of surface is EGL_BUFFER_PRESERVED, and are undefined if the value is EGL_BUFFER_DESTROYED. The value of EGL_SWAP_BEHAVIOR can be set for some surfaces using eglSurfaceAttrib. eglSurfaceAttrib notes that: The initial value of EGL_SWAP_BEHAVIOR is chosen by the implementation. ...so make sure you actually set the value you need and don't rely on the (unreliable) default.
[ "stackoverflow", "0008597138.txt" ]
Q: Moai grid with tile colors I'm trying to create a grid for a game using the Moai SDK. Each tile in the grid should have the ability to be filled with a color. So actually I have two questions: What is the best way to build a grid using Moai How can I fill each tile individually with a color Thanks A: What is the best way to build a grid using Moai Moai has an object for creating grids: MOAIGrid. Using the framework's jargon, you create a grid and give it a deck. Then you attach it to a prop and add the prop to a layer. (That layer also needs a viewport which is attached to a window.) How can I fill each tile individually with a color A Moai deck is an image or collection of images. If you wanted your tiles to be different colors then you would create a deck with images of the square in those colors. Example This code will create a 4x4 grid in a window: -- Open the window and create a viewport MOAISim.openWindow("Example", 512, 512) viewport = MOAIViewport.new() viewport:setSize(512, 512) viewport:setScale(512, 512) -- Create a layer layer = MOAILayer2D.new() layer:setViewport(viewport) MOAISim.pushRenderPass(layer) -- Create a 4x4 grid of 64x64px squares grid = MOAIGrid.new() grid:initGrid(4, 4, 64) grid:setRow(1, 1, 1, 1, 1) grid:setRow(2, 1, 1, 1, 1) grid:setRow(3, 1, 1, 1, 1) grid:setRow(4, 1, 1, 1, 1) -- Load the image file deck = MOAITileDeck2D.new() deck:setTexture("squares.png") deck:setSize(2, 2) -- Make a prop with that grid and image set prop = MOAIProp2D.new() prop:setDeck(deck) prop:setGrid(grid) prop:setLoc(-256, -256) -- Add it to the layer so it will be rendered layer:insertProp(prop) After that, if you want to change the color of a specific cell, use the setTile method to choose which item in the deck that cell uses. -- Change the color of cell 1,1 to the second item in the deck grid:setTile(1, 1, 2)
[ "money.stackexchange", "0000012561.txt" ]
Q: How to reconcile a credit card that has an ongoing billing dispute? I currently have an ongoing billing dispute/inquiry on my American Express Business Charge Card that is causing me problems when reconciling this account in Quickbooks. Since my statement balance doesn't reflect the dollar amount in dispute, how can I reconcile? A: You could make an entry for the disputed charge as if you were going to lose the dispute, and a second entry that reverses the charge as if you were going to win the dispute. You could then reconcile the account by including the first charge in the reconciliation and excluding the reversal until the issue has been resolved.
[ "gis.stackexchange", "0000081864.txt" ]
Q: Intersect and MBR in POSTGIS and Mysql I would like to know if POSTGIS and MySql with Spatial Extension use true geometry to find intersections/overlaps between geospatial objects. But i don't find it precisely in the documentation. I know that doing an ST_Intersects is more precise than only using the && command. I want to know if in this example the round geospatial objects would intersect/overlap: https://dl.dropboxusercontent.com/u/13064345/example.jpg The squares are the minimum bounding boxes, they overlap. But i am not sure of the ouput in POSTGIS and MySQl. Hope you can help me. A: In PostGIS, the && operator uses the MBR to test for for overlap of two geometries. ST_Intersects uses the true geometry. In MySQL versions prior to 5.6.1, ST_Intersects used the bounding box instead of actual geometry to test for intersection. From MySQL 5.6.1 onward, ST_Intersects uses the actual geometry. The MySQL function Intersects still uses the MBR. In your example image, you should use ST_Intersects in PostGIS, or MySQL 5.6.1+ to test intersection of the two circles.
[ "stackoverflow", "0046924469.txt" ]
Q: How to implement deferred-deep-link in android Recently, I have learned about deep linking and deferred deep linking and want to implement deferred deep linking in my app. Provide a step by step implementation or any tutorials available for this. A: Deep linking is a wide topic in android it was making good sense in theory but it's implementation was not perfect and we could not track any useful analytical data, This problem was solved by branch.io initially and worked nicely,the only problem with that was it was a third party tool and free upto a certain limit and it caused few issues with progaurd, Now google has come out with its own implementation using firebase called Dynamic links I would recommend Dynamic links over branch.io. About the pricing the dynamic links are completely free but branch.io has a limit for free usage
[ "stackoverflow", "0030959532.txt" ]
Q: Getting document from CouchDB with PhantomJS I'm writing a function to read a document out of CouchDB with PhantomJS: function getDocument(dbName, id) { var dbPage = webpage.create(); dbPage.open('http://127.0.0.1:5984/' + dbName + '/' + id, function (status) { console.log("GOT REPLY FROM SERVER:"); console.log(dbPage.content); var foo = JSON.parse(dbPage.content); //Do something with foo... } }); } The content returned from CouchDB (dbPage.content) looks like this: GOT REPLY FROM SERVER: <html><head></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">{"_id":"1","_rev":"1-3d3190e791500c179bdd02716add5280","myData": "d"]} </pre></body></html> What is the best way for me to strip off the html, so that I can run JSON.parse to get a javascript object representing the document? A: You can use page.plainText instead of page.content for non-html content.
[ "stackoverflow", "0007311203.txt" ]
Q: Looping over a list of objects within a Django template Can't seem to see where I am going wrong here. Forgive me because I am new to this. I am trying to display the 10 newest objects within a model. Here is the loop I used to put all of these objects within a list: # put the top 10 newest Recipe objects in a list entries_list = [] all_recipes = Recipes.objects.annotate(Count('id')) newest_recipe_index = len(all_recipes) index = 0 while index < 10: try: x = Recipes.objects.get(id=newest_recipe_index) entries_list.append(x) newest_recipe_index = newest_recipe_index - 1 index = index + 1 except: index = index + 1 pass I then render this to the page like so: c = RequestContext(request, {'form' : form, 'entries_list' : entries_list}) return render_to_response("main.html", c) And here is my html: {% for entries in entries_list %} <i><b>Name:</i></b> {{ entries_list.name }}<br> <img src="/images{{ entries_list.picture }}" height="300" width="300"></img><br> <i><b>Ingredients:</i></b> {{ entries_list.ingredients }}<br> <p><i>{{ entries_list.description }}</i></p> <i><b>Created by:</i></b> {{ entries_list.user }}<br><br> {% endfor %} And here is models.py: class Recipes(models.Model): name = models.CharField(max_length=50) ingredients = models.CharField(max_length=300) picture = models.ImageField(upload_to = 'recipes/%Y/%m/%d') user = models.CharField(max_length=30) date = models.DateTimeField(auto_now=True) description = models.TextField() comments = models.ManyToManyField(Comments) It seems that the loop is working. The correct amount of entries are there. It is just that the template tags aren't working. They are just blank. So it seems this is working just fine putting the objects inside the list, it just won't retrieve my individual fields. A: A couple of things. There is a method by which you can order your query and just get the first ten entries. It would be more efficient than the loop you have. The reason your template doesn't work is that you're referring to the list rather than the individual entry. It should be: {% for entry in entries_list %} <i><b>Name:</i></b> {{ entry.name }}<br> <img src="/images{{ entry.picture }}" height="300" width="300"></img><br> <i><b>Ingredients:</i></b> {{ entry.ingredients }}<br> <p><i>{{ entry.description }}</i></p> <i><b>Created by:</i></b> {{ entry.user }}<br><br> {% endfor %} Once you get your template working, try this to get your entries_list: entries_list = Recipes.objects.order_by('-id')[0:10] Here's the docs on sorting and slicing queries: https://docs.djangoproject.com/en/dev/topics/db/queries
[ "stackoverflow", "0001934684.txt" ]
Q: Report the time spent on a page to the server Is it possible to report the time spend on a page back to server when the visitor leaves the page by closing the tab or the browser? Using Javascript. And it will work on Firefox, Google Chrome, Safari, Opera, and IE8 (IE7 and 6 are not important). But it will work in any case; even while the browser is closing, or it is typed another address. A: You can try windows.onbeforeunload but there is no guarantee that it will work in all cases. Anyway I suggest you use google analytics which has that feature among many others (I doubt you can do better than google!). It's free.
[ "stackoverflow", "0017267780.txt" ]
Q: Exception when creating a list saying: I have the following code: try { var result = from entry in feed.Descendants(a + "entry") let content = entry.Element(a + "content") let properties = content.Element(m + "properties") let notes = properties.Element(d + "DetailsJSON") let questionMessage = properties.Element(d + "QuestionText") let title = properties.Element(d + "Title") let partitionKey = properties.Element(d + "PartitionKey") where partitionKey.Value == "0001I" && title != null select new Question { Notes = notes.Value ?? "n/a", Title = title.Value, QuestionMessage = questionMessage.Value }; // xx IList<Question> resultx = null; foreach (var question in result) { resultx.Add(question); } // yy return result; } catch (Exception ex) { throw new InvalidOperationException("GetQuestions.Get problem", ex); }; If I comment out the part of the code between xx and yy then it works. Otherwise I get an exception saying: ex {"Object reference not set to an instance of an object."} System.Exception {System.NullReferenceException} Can someone give me some ideas about what I might be doing wrong? A: Your list is null, hence the NullReferenceException: IList<Question> resultx = null; foreach (var question in result) { resultx.Add(question); // Ouch. resultx is set to null above here } You need to initialize the list to actually be a List<Question>, not null: IList<Question resultx = new List<Question>(); // .. the rest of the code
[ "stackoverflow", "0002936505.txt" ]
Q: SendMessage videocapture consts I am using a code sample to connect to a webcam, and don't really understand the meaning of the variables passed to the SendMessage method. SendMessage(DeviceHandle, WM_CAP_SET_SCALE, -1, 0) SendMessage(DeviceHandle, WM_CAP_SET_PREVIEW, -1, 0) What does the -1 mean? To scale/preview or not to scale/preview? I'd prefer that zero/one would be used, zero meaning false, and have no idea what the -1 means. SendMessage(DeviceHandle, WM_CAP_EDIT_COPY, 0, 0); What does the zero mean in this case? Or does this message is simply void and the zero has no meaning, similar to the last zero argument? Btw, what DOES the last zero argument mean? Thank you very much in advance :) A: You've probably found sample code that was originally written in Visual Basic. The WParam argument for SendMessage() is documented to be a BOOL. It should be either FALSE (0) or TRUE (1). A quirk of VB6 is that its boolean TRUE value is -1. The reason is a bit obscure and related to the way its AND and OR operators work. Your current code works by accident, the Windows code that interprets the message simply treats any non-zero value as "TRUE". There is a bigger problem though, your SendMessage() declaration is wrong. The WParam and LParam arguments are probably declared as "int", a 32-bit value. On 64-bit operating systems they are however a 64-bit value. On such an operating system your SendMessage() call will fail badly. There's also some odds that you are already on a 64-bit operating system and have these arguments declared as Long, the way they were declared in VB6. In which case your code will fail on a 32-bit operating system. The proper declaration for SendMessage: [DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp); And the proper way to send the message: SendMessage(DeviceHandle, WM_CAP_SET_SCALE, (IntPtr)1, IntPtr.Zero); That will work correctly on both 32-bit and 64-bit operating systems.
[ "stackoverflow", "0038562774.txt" ]
Q: How to create HTML select option from JSON I have a JSON file { "1990": [ 1, 2, 3 ], "1991": [ 4, 5, 6 ] // and so on... }; I have a HTML file I have loop through it because a have large amount of data. <select name="year" id="year"> <option value="1990">1</option> <option value="1990">2</option> <option value="1990">3</option> <option value="1991">4</option> <option value="1991">5</option> </select> I have tried this way but it does not work for this does any suggest me how to solve it. http://jsfiddle.net/MuGj7/ Thanks in advance and welcome suggestions. A: Just iterate the object and append an option element for each iteration: var obj = { "1990": [ 1, 2, 3 ], "1991": [ 4, 5, 6 ] }; for (var i in obj) { for (var y in obj[i]) { $('#year').append($('<option value="' + i + '" data-value="' + i + '">' + obj[i][y] + '</option>')); } } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <select name="year" id="year"><select>
[ "stackoverflow", "0005903095.txt" ]
Q: google wifi Access Point geo location by MAC I found on certain web site that it is possible to find location of wifi Access Point location by providing MAC address. my question is : what is the name of API used for that , and what api do i use to get wifi AP location from MAc address (on windows)? A: Look at the Google's Geolocation API Network Protocol. There you can see the example JSON object like that: "wifi_towers": [ { "mac_address": "01-23-45-67-89-ab", "signal_strength": 8, "age": 0 }, { "mac_address": "01-23-45-67-89-ac", "signal_strength": 4, "age": 0 } ] **Google Gears API is no longer available
[ "unix.stackexchange", "0000593244.txt" ]
Q: Parsing .json in Bash Have a json file I am trying to parse from podfox to allow me to rename the downloaded files in a "friendly" way. Here's a snippet of json I am working with: { "episodes": [ { "title": "Hired and Fired by Little Richard and Jimi\u2019s first trip on LSD", "url": "https://www.podtrac.com/pts/redirect.mp3/chtbl.com/track/5899E/traffic.megaphone.fm/HSW2392375869.mp3", "downloaded": true, "listened": false, "published": 1582203660.0 }, { "title": "Stolen Cars, Broken Taboos, and the Search for Billy Davis", "url": "https://www.podtrac.com/pts/redirect.mp3/chtbl.com/track/5899E/traffic.megaphone.fm/HSW5134475908.mp3", "downloaded": true, "listened": false, "published": 1581598860.0 }, ] "shortname": "27 Club", "title": "27 Club", "url": "https://feeds.megaphone.fm/HSW5142951139" } I am trying to, based on the url get the title and pass that to a variable in bash. I can (for the most part) use grep but I know that jq is a better method, I just cannot figure out the syntax to make jq work. This works with grep on the command line: grep -B 1 HSW2392375869.mp3 < feed.json | grep "title" | cut -d"\"" -f4 but seems like it is a potentially error prone solution. When I try: jq -c '.["episodes"].url' the shell just hangs indefinitely. I do not require to use jq here, so any method to allow me to search for the url and return (ultimately) the value for published and title will do just fine. A: Actually first need to filter .episodes then the inner array jq ".episodes | .[0]" jsonfile { "title": "Hired and Fired by Little Richard and Jimi’s first trip on LSD", "url": "https://www.podtrac.com/pts/redirect.mp3/chtbl.com/track/5899E/traffic.megaphone.fm/HSW2392375869.mp3", "downloaded": true, "listened": false, "published": 1582203660 } title: jq ".episodes| .[0].title" jsonfile "Hired and Fired by Little Richard and Jimi’s first trip on LSD" published: jq ".episodes| .[0].published" jsonfile 1582203660 For query based on url value jq '.episodes | .[] | select(.url=="https://www.podtrac.com/pts/redirect.mp3/chtbl.com/track/5899E/traffic.megaphone.fm/HSW2392375869.mp3").title' jsonfile "Hired and Fired by Little Richard and Jimi’s first trip on LSD" jq '.episodes | .[] | select(.url=="https://www.podtrac.com/pts/redirect.mp3/chtbl.com/track/5899E/traffic.megaphone.fm/HSW2392375869.mp3").published' jsonfile 1582203660
[ "stackoverflow", "0026761053.txt" ]
Q: Doxygen C++ - Not documenting virtual functions in a template class I have a template class that has a bunch of pure virtual and implemented virtual functions. I then have children inherit from this class. I want to document the functions in the virtual parent class and have children inherit this documentation in Doxygen. For example (I can't post the real source). template <typename A> class Parent { /** Documentation */ virtual void pure() = 0; /** More Docs */ virtual void notpure() { ... } }; In a different file with all proper includes (at least for the compiler) class Child: public Parent<int> { void pure() { ... } }; I then want Doxygen to generate documentation for both classes with the same documentation for each function unless I re-document the overridden function. I run Ubuntu 14.04 and use the repository Doxygen 1.8.6 in case it matters. Thank you A: According to the INHERIT_DOCS tag, it should already do that if you have it set to 'yes'. AFAIK doxygen has had some problems with parsing templates classes and that might be the reason why your documentation isn't being duplicated (i.e. doxygen thinks Child inherits from a different Parent class). You might try to force this behavior by using the \copydoc command. If that still doesn't work you might have to either ask for a patch or fix it yourself. A: So, I will answer my own question. Sort of. If anyone has this same problem, be sure to check for comment bugs. Doxygen handled my templates fine, but I did have a problem because I have the habit of putting /* code /**/ in my programs so I can quickly uncomment large blocks of code quickly while debugging. Doxygen does not like this!. I had the error message File ended in the middle of a comment block! Perhaps a missing \endcode? It took me a while to wade through the warnings generated because I had several undocumented files. This was taken care of by using EXTRACT_ALL = YES In my config file. HERE is someone who has a similar problem as I was.
[ "mathoverflow", "0000312901.txt" ]
Q: What is the current status of the Arnold conjecture? Let $(M, \omega)$ be a symplectic manifold. V.Arnold conjectured that the number of fixed points of a Hamiltonian symplectomorphism is bounded below by the number of critical points of a smooth function on $M$. The conjecture was proved in a weaker (homological) version using Floer homology, with two additional conditions: Compactness of $M$; Non-degeneracy of the fixed points of the considered Hamiltonian symplectomorphism. In this setting, it is now fully understood that the number of fixed points is at least the sum of Betti number of $M$. I am wondering where the general statement stands today. More precisely: is compactness really necessary to Floer's framework ? what is known for degenerate Hamiltonians ? what is known for the critical points lower bound, rather than the Betti sum ? Thanks a lot A: A recent (2017) overview of the status of Arnold's conjecture is given in The number of Hamiltonian fixed points on symplectically aspherical manifolds.
[ "stackoverflow", "0063589107.txt" ]
Q: How to disallow closing a parent work item when it has non-closed child work items in Azure Boards? I would like to avert the "invalid" state change up front by notifying the user or even preventing the change via a Rule. However, I do not see any rule capability's when conditions that are based on the state of linked work items. It would be nice if it would prompt the user if they want to change the state of all children, but I'm pretty sure that would be a feature request. (Extension?) As of now, I have figured out how to write a query to identify these occurrences after the fact. SELECT [System.Id], [System.WorkItemType], [System.Title], [System.State], [System.AssignedTo], [Microsoft.VSTS.Common.ResolvedBy], [Microsoft.VSTS.Common.ClosedBy], [Microsoft.VSTS.Common.ResolvedDate], [Microsoft.VSTS.Common.ClosedDate], [System.AreaPath], [System.IterationPath] FROM workitemLinks WHERE ( [Source].[System.TeamProject] = @project AND [Source].[System.State] = 'Closed' ) AND ( [System.Links.LinkType] = 'System.LinkTypes.Hierarchy-Forward' ) AND ( [Target].[System.TeamProject] = @project AND NOT [Target].[System.State] IN ('Closed', 'Removed') ) ORDER BY [System.Id] MODE (MustContain) A: I'm afraid there is no such way to meet your needs. We cannot judge whether to close the parent work item based on the status of the child work item. On the other hand, the state field cannot be used in the rule now. The state of work items are independent of all other work items, including linked work items. Now this requirement can only be achieved by manually monitoring the status of the work item. Since you can create query to get parent and child work items, you could monitor them via the query. However, this feature is very meaningful. I posted a similar Suggestion Ticket in the UserVoice forum before. You can vote and add comments to express your suggestions.
[ "stackoverflow", "0035804746.txt" ]
Q: Php query, hide content Microsoft sql I am trying to do some paging to my blog that iam working on, it is working, and now i have added so i can reach each individual post from an url like index.php?postID=1, 2, 3 and so on. However, one thing is not working as i want it, when i go to a post with that url, the post will load on top, but the 2 other paged posts will also show, so my question is simply: how do i not load those posts when i just want to go to a single post? This is what the script looks like now, i know it might be a big mess in a more experienced coders eyes, bare in mind i am a rookie that wants to learn :) <?php error_reporting(E_ALL); ini_set('display_errors', 1); $rowsPerPage = 2; try { $conn = new PDO( "sqlsrv:server=localhost ; Database=blog", "******", "*****"); $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); } catch(Exception $e) { die( print_r( $e->getMessage() ) ); } try { $tsql = "SELECT COUNT(blogID) FROM blog_posts"; $stmt = $conn->query($tsql); $rowsReturned = $stmt->fetch(PDO::FETCH_NUM); if($rowsReturned[0] == 0) { echo "Inga rader hittades."; } else { $numOfPages = ceil($rowsReturned[0]/$rowsPerPage); for($i = 1; $i<=$numOfPages; $i++) { $pageNum = "index.php?pageNum=$i"; print("<a href='$pageNum' class='btn btn-primary active btn-sm'>$i</a>&nbsp;&nbsp;"); } } $tsql = "SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY blogID DESC) AS RowNumber, blog_title, blog_post, blog_author, blog_category, blog_date, blogID, blog_short FROM blog_posts) AS Temp WHERE RowNumber BETWEEN ? AND ?"; $stmt2 = $conn->prepare($tsql); if (isset($_GET['postID'])){ $value = $_GET['postID']; $result = "SELECT * FROM blog_posts WHERE blogID='$value'"; $aa = $conn->query($result); $post = $aa->fetch(PDO::FETCH_NUM); if($post[0] == 0) { echo "Inget inlägg med det ID't hittades!"; } else { echo "$post[1]"; echo "$post[2]"; echo "$post[3]"; echo date_format( new DateTime($post['5']), 'd M Y, H:i' ); echo "$post[4]"; echo "$post[0]"; } } if(isset($_GET['pageNum'])) { $highRowNum = $_GET['pageNum'] * $rowsPerPage; $lowRowNum = $highRowNum - $rowsPerPage + 1; } else { $lowRowNum = 1; $highRowNum = $rowsPerPage; } $params = array(&$lowRowNum, &$highRowNum); $stmt2->execute(array($lowRowNum, $highRowNum)); while($row = $stmt2->fetch(PDO::FETCH_NUM) ) { echo "$row[1]" echo "$row[7]"; echo '<a href="?postID='.$row[6].'">Read more</a>'; echo "$row[3]"; echo date_format( new DateTime($row['5']), 'd M Y, H:i' ); echo "$row[4]"; echo "$row[6]"; } } catch(Exception $e) { die( print_r( $e->getMessage() ) ); } EDIT: if (isset($_GET['postID'])) { $id = $_GET['postID']; $tsql2 = "SELECT * FROM blog_posts WHERE blogID=':id'"; $stmt3 = $conn->prepare($tsql2); $stmt3->execute(array(':id' => $id)); while($post = $stmt3->fetch(PDO::FETCH_BOTH) ) { echo $post 1-6 here A: If you want to display only the single post or only paged posts, you should do sth like this: if (isset($_GET['postID'])) { //single post logic } else { //paged posts logic }
[ "stackoverflow", "0008013433.txt" ]
Q: How do I remove this blue selection background in a TreeViewItem? Print screen: http://imageshack.us/photo/my-images/253/bluebackground.png/ I have a treeViewItem and when I click on it, this damn blue selection appear inside it! Ive already tried to get the trigger isSelected in style. But doesnt SOLVE! Help please! A: Oh the rage. <TreeView.Resources> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"> Transparent </SolidColorBrush> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}"> Black </SolidColorBrush> </TreeView.Resources>
[ "stackoverflow", "0028000633.txt" ]
Q: How to split text file into multiple .txt files or data frames based on conditions in R? I have an XML file in .txt format. I want to split this file in such a way I get only the text between <TEXT> and </TEXT> and save it as a different text file or data frame. Can anyone please help me on how I can do this in R? I have tried using grep function to extract the text, however I am not able to achieve my objective. I am very new to text mining and it would be really great if anyone can help me in this. test_2=grep("[^<TEXT>] [$</TEXT>]",test,ignore.case=T,value=T) A: First I did install.packages("XML") library(XML) Now this is a little tricky because your document (as shown above) doesn't have a root. If you wrap it in <mydoc> ... </mydoc> or something like that, you could use this: doc <- xmlRoot(xmlTreeParse("text.xml")) df <- vector(length=length(doc)) for (i in 1:length(doc)) { text_node <- doc[[i]]$children$text text <- xmlToList(text_node) df[i] <- text } Now suppose you can't add the artificial root I did above. You can still parse it as HTML, which is more tolerant of invalid documents. I also use XPath in this example (which you could in the one above too): doc <- htmlTreeParse("text_noroot.xml") content <- doc$children$html textnodes <- getNodeSet(content, "//text") df <- vector(length=length(textnodes)) for (i in 1:length(textnodes)) { text_node <- textnodes[[i]]$children$text text <- xmlToList(text_node) df[i] <- text }
[ "stackoverflow", "0033726968.txt" ]
Q: Use a cross sectional monthly time series to analyse seasonal effect of rainfall using R I am working on a panel data set. I have 20 sites' production data over 10 years. I want to estimate the effect of different pattern of rainfall (RF) on monthly production. My data is stored in Google and looks like this: I want to get the effect of the seasonal rainfall pattern on monthly production. My rainfall seasons are as follows: December (of the previous year) to February (following year) is the NE monsoon (NEM) March to April is 1st Inter monsoon (IM1) May to September is SW monsoon (SWM) October to November is 2nd Inter monsoon (IM2) I need to get the total of these four patterns year wise over the 10 years from 2000 to 2010 across the cross sectional sites (n=20). I don't have the RF data for December month of year 1999 and in that case we could assume that December 1999 RF is the same as January 2000 (another suggestions would be appreciated). So far I have coded this: dat<-read.csv("my_data.csv") # get rainfall (RF) and other data RF <- dat$RF Y <- dat$Year Mon <- dat$Mon Site <- dat$Site #Specify new data frame with 4 seasons of RF over the years across different sites Year <- vector(mode="numeric",length = ((Y[length(dat$Y)]-Y[1])+1)*(length(levels(Site)))) Site <- vector(mode="numeric",length = ((Y[length(dat$Y)]-Y[1])+1)*(length(levels(Site)))) Season1 <- vector(mode="numeric",length = ((Y[length(dat$Y)]-Y[1])+1)*(length(levels(Site)))) Season2 <- vector(mode="numeric",length = ((Y[length(dat$Y)]-Y[1])+1)*(length(levels(Site)))) Season3 <- vector(mode="numeric",length = ((Y[length(dat$Y)]-Y[1])+1)*(length(levels(Site)))) Season4 <- vector(mode="numeric",length = ((Y[length(dat$Y)]-Y[1])+1)*(length(levels(Site)))) Year <- rep(seq(from = Y[1],to=Y[length(Y)]),length(levels(Site))) number_of_Y <-Y[length(Y)]-Y[1]+1 #Site_index <- 2 for (Site_index in 1 : length(levels(Site))){ start_row <- 1+(Site_index-1)*number_of_Y end_row <- (Site_index-1)*number_of_Y + number_of_Y Site[start_row:end_row] <- rep(levels(Site)[Site_index],(Y[length(Y)]-Y[1]+1)) } But it doesn't work. I am not understanding why the "Site" does not get its levels from the above codes and how to get the total of each RF pattern yearly across sites as a new data frame. A: First of all, open your file in google, and export the file as a .csv file. It will land in your downloads folder. Read it in: dat <- read.csv(file = "~/Downloads/my_data - my_data.csv", stringsAsFactors = FALSE) The next challenge is to identify the monsoon season. We'll create a new column, fill it with the default value, and then change it according to the month. dat$monsoon.season <- "Second Inter monsoon" dat$monsoon.season[((dat$Mon == "Dec") | (dat$Mon == "Jan") | (dat$Mon == "Feb"))] <- "NE Monsoon" dat$monsoon.season[((dat$Mon == "Mar") | (dat$Mon == "Apr"))] <- "First inter monsoon" dat$monsoon.season[((dat$Mon == "May") | (dat$Mon == "Jun") | (dat$Mon == "Jul") | (dat$Mon == "Aug") | (dat$Mon == "Sep"))] <- "SW Monsoon" Now, because December 200x is actually in the same monsoon period as January 200x+1, we have to create a "monsoon year" variable to catch that: dat$monsooon.year <- dat$Year dat$monsooon.year[dat$Mon == "Dec"] <- dat$Year[dat$Mon == "Dec"] +1 And we can see that this is the next year by typing dat: Year Mon Site Prod RF Region monsoon.season monsooon.year 1 2000 Jan Grave 161521 261 Mid NE Monsoon 2000 2 2000 Feb Grave 142452 334 Mid NE Monsoon 2000 3 2000 Mar Grave 365697 156 Mid First inter monsoon 2000 4 2000 Apr Grave 355789 134 Mid First inter monsoon 2000 5 2000 May Grave 376843 159 Mid SW Monsoon 2000 6 2000 Jun Grave 258762 119 Mid SW Monsoon 2000 7 2000 Jul Grave 255447 41 Mid SW Monsoon 2000 8 2000 Aug Grave 188545 247 Mid SW Monsoon 2000 9 2000 Sep Grave 213663 251 Mid SW Monsoon 2000 10 2000 Oct Grave 273209 62 Mid Second Inter monsoon 2000 11 2000 Nov Grave 317468 525 Mid Second Inter monsoon 2000 12 2000 Dec Grave 238668 217 Mid NE Monsoon 2001 Now we want the total production over each season, each monsoon year, for each site (I think). We can use aggregate for that. dat.summary <- aggregate(cbind(RF,prod) ~ monsoon.year + monsoon.season + Site, dat, sum) This gives you a data frame containing the rainfall and production by site, season, and monsoon year: monsoon.season Site Prod RF 1 First inter monsoon Bay 1271818 1221 2 NE Monsoon Bay 934326 2728 3 Second Inter monsoon Bay 880541 1776 4 SW Monsoon Bay 2071107 606 5 First inter monsoon Grave 2095116 1262 6 NE Monsoon Grave 1783144 2108 7 Second Inter monsoon Grave 1347449 1469 8 SW Monsoon Grave 3626227 1464 9 First inter monsoon Horton 2006018 1628 10 NE Monsoon Horton 2264599 1828 11 Second Inter monsoon Horton 1443698 1938 12 SW Monsoon Horton 3470907 1394 You can adjust the aggregate command to get different sums. For example, to just get the sum by monsoon period at each site, use dat.summary <- aggregate(cbind(Prod, RF) ~ monsoon.season + Site, data = dat, sum) which gives you.. monsoon.season Site Prod RF 1 First inter monsoon Bay 1271818 1221 2 NE Monsoon Bay 934326 2728 3 Second Inter monsoon Bay 880541 1776 4 SW Monsoon Bay 2071107 606 5 First inter monsoon Grave 2095116 1262 6 NE Monsoon Grave 1783144 2108 7 Second Inter monsoon Grave 1347449 1469 8 SW Monsoon Grave 3626227 1464 9 First inter monsoon Horton 2006018 1628 10 NE Monsoon Horton 2264599 1828 11 Second Inter monsoon Horton 1443698 1938 12 SW Monsoon Horton 3470907 1394
[ "stackoverflow", "0027737227.txt" ]
Q: Finding End of File in the Redirected Input file in C I execute my program from shell like that : $main.exe < input.txt in input.txt I have digits (Count of these digits is unknown) in my program I doing something like : while(1) { int xCoordinate, yCoordinate; scanf("%d %d", &xCoordinate, &yCoordinate); ...... } How can I break this loop when there is no value to read? A: Assuming that the input is consistent, you can do it like this: if (scanf("%d %d", &xCoordinate, &yCoordinate) != 2) break; The reason this would work is that scanf family of functions return the number of entries that they assigned. In your code, you want scanf to assign two items; if EOF is reached instead, a value smaller than 2 would be returned. Note: that this approach will break at the first spot where the input file is not consistent with the format that you expect. For example, if your input has a string in place of one of the numbers, the loop would exit after making a failed attempt to interpret that string as a number.
[ "stackoverflow", "0047050418.txt" ]
Q: Regular expression: How to name a group using match result I want to name a group using the result of matched group. For example in python: I want : import re match = re.search(WHAT_I_NEED, 'name = tom') assert match.groupdict()['name'] == 'tom' if match.groupdict() == {'name': 'tom'}: print('better') I have tried: import re WHAT_I_NEED = r'(?P<attr_name>\w+) = (?P<(?P=attr_name)>\w+)' match = re.search(WHAT_I_NEED, 'name = tom') I get: sre_constants.error: bad character in group name '(?P=attr_name)' A: You can't assign group names in the regex dynamically. But you can do something like this: >>> data = "name = tom, age = 12, language = Python" >>> regex = re.compile(r"(?P<key>\w+) = (?P<value>\w+)") >>> matches = {k: v for k,v in regex.findall(data)} >>> matches {'age': '12', 'language': 'Python', 'name': 'tom'}
[ "stackoverflow", "0016222430.txt" ]
Q: Getting an ArrayIndexOutOfBoundsException I have this code : public class OddSum1 { public OddSum1() { } public static void main(String[] args) { int OddLimit = Integer.parseInt(args[0]); int sum = 0; for (int i = 1; i <= OddLimit; i += 2) { sum += i; } System.out.println("The sum of odd numbers from 1 to " + OddLimit + " is " + sum); } } Whenever I run it I get this error: java.lang.ArrayIndexOutOfBoundsException: 0 at OddSum1.main(OddSum1.java:7) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) at java.lang.reflect.Method.invoke(Unknown Source) at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272) It's supposed to prompt user for a number and then sums the odd number from 1 to the number entered, I'm guessing it's a problem with this int OddLimit = Integer.parseInt(args[0]); but I just don't know how to fix it, any help would be awesome. A: It's supposed to prompt user for a You need to pass arguments to main, Command line argument and then change index to 0 for example: $java YourMainClass 5 A: You can take either of the two approaches from below : Approach 1 : You can specify the oddLimit by passing it as an argument to the main method as : Code : public class OddSum1 { public OddSum1() { } public static void main(String[] args) { int OddLimit = Integer.parseInt(args[0]); int sum = 0; for (int i = 1; i <= OddLimit; i += 2) sum += i; System.out.println("The sum of odd numbers from 1 to " + OddLimit + " is " + sum); } } To compile and run the code : javac OddSum1.java java OddSum1 20 Approach 2 : Read the OddLimit interactively from the prompt Code: public class OddSum1 { public OddSum1() { } public static void main(String[] args) { int OddLimit = Integer.parseInt(System.console().readLine()); int sum = 0; for (int i = 1; i <= OddLimit; i += 2) sum += i; System.out.println("The sum of odd numbers from 1 to " + OddLimit + " is " + sum); } }
[ "stackoverflow", "0025973630.txt" ]
Q: Navigating storyboard and sending data This link is my storyboard, i want to sent data from VC 1 to VC 3. I can travel from VC 1 to VC 3 with segue perfectly,but I cant sent data from VC 1 to VC 3, as i cant create an instance that is holding the destination VC. Help is very much appreciated EDIT: From VC1 am firing [self performSegueWithIdentifier:@"firstSegueFromleft" sender:self]; This is the segue that is the first segue from the left (topone) But I cannot sent data to VC3 by this method, but it is traveling to it. I am getting an error "Unrecognized selector" when i try to access a property declared in VC3 in prepareForSegue of VC1. A: Solved : I was able to do it by NSUserDefault. Looked at the apple documentation at how it is to be implemented and voila.
[ "stackoverflow", "0043603287.txt" ]
Q: jQuery - Delete items in a list I want to add different items to a list and then delete each one of them using a 'click' event. However, the bellow snippet only allows me to delete those preset items but not those I have added. Could anyone tell me what I'm doing wrong ? HTML <body> <div id="page"> <h1 id="header">List</h1> <h2>Buy groceries</h2> <ul> <li id="one" class="hot"><em>fresh</em> figs</li> <li id="two" class="hot">pine nuts</li> <li id="three" class="hot">honey</li> <li id="four">balsamic vinegar</li> </ul> <div id="newItemButton"><button href="#" id="showForm">new item</button></div> <form id="newItemForm"> <input type="text" id="itemDescription" placeholder="Add description..." /> <input type="submit" id="addButton" value="add" /> </form> </div> <script src="js/jquery-1.11.0.js"></script> <script src="js/form.js"></script> jQuery $(function() { var $newItemButton = $('#newItemButton'); var $newItemForm = $('#newItemForm'); var $textInput = $('input:text'); $newItemButton.show(); $newItemForm.hide(); $('#showForm').on('click', function(){ $newItemButton.hide(); $newItemForm.show(); }); $newItemForm.on('submit', function(e){ e.preventDefault(); var newText = $textInput.val(); $('li:last').after('<li>' + newText + '</li>'); $('li:last').attr('class','hot'); $newItemForm.hide(); $newItemButton.show(); $textInput.val(''); }); var $listItems = $('li'); $listItems.on('click', function(){ $(this).animate({ opacity: 0.0, paddingLeft: 50 }, 500, function(){ $(this).remove(); }); }); }); A: Please check below snippet $(function() { var $newItemButton = $('#newItemButton'); var $newItemForm = $('#newItemForm'); var $textInput = $('input:text'); $newItemButton.show(); $newItemForm.hide(); $('#showForm').on('click', function(){ $newItemButton.hide(); $newItemForm.show(); }); $newItemForm.on('submit', function(e){ e.preventDefault(); var newText = $textInput.val(); $('li:last').after('<li>' + newText + '</li>'); $('li:last').attr('class','hot'); $newItemForm.hide(); $newItemButton.show(); $textInput.val(''); }); }); $(document).ready(function(){ $("#page").on("click","li",function(){ $(this).animate({ opacity: 0.0, paddingLeft: 50 }, 500, function(){ $(this).remove(); }); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <div id="page"> <h1 id="header">List</h1> <h2>Buy groceries</h2> <ul> <li id="one" class="hot"><em>fresh</em> figs</li> <li id="two" class="hot">pine nuts</li> <li id="three" class="hot">honey</li> <li id="four">balsamic vinegar</li> </ul> <div id="newItemButton"><button href="#" id="showForm">new item</button></div> <form id="newItemForm"> <input type="text" id="itemDescription" placeholder="Add description..." /> <input type="submit" id="addButton" value="add" /> </form> </div>
[ "stackoverflow", "0006437682.txt" ]
Q: Create an instance of a class known at runtime I have this code but it returns "nil" instead of a new class. Here it is useless but in my programme it makes sens. Class myClass = [SettingsTableViewController class]; UIViewController *targetViewController = [[myClass alloc] initWithNibName:nil bundle:nil]; [[self navigationController] pushViewController:targetViewController animated:YES]; A: You are forgetting something or you might don't know. Here is the proper code. Class myClass = NSCLassFromString(@"yourClassName"); if(myClass){ myClass = [[yourclassName alloc] init]; }
[ "stackoverflow", "0036408393.txt" ]
Q: ios and android push notifications to multiple devices I am really struggling with this. This piece of code wasn't created by me but I have changed it so it sort of works. My goal is for it to be able to send push notifications to all devices that use the app. I am an ios and andriod programmed so I will try my best. I have cleaned up and changed the code that was given to me so that it will now send a notification to just one device. This is the code <?php include 'conn.php'; if ( $_REQUEST['key'] == 'notification' ) { include 'notifications.php'; $message = $_REQUEST['text']; $text = mysql_real_escape_string( $_REQUEST['text'] ); $start = $_REQUEST['start']; $end = $_REQUEST['end']; $date = date( "Ymd", strtotime( $_REQUEST['date'] ) ); $callus = $_REQUEST['callus']; $in = "INSERT INTO `notifications` (`date`, `start_time`, `end_time`, `text`, `call_us`) VALUES ('$date', '$start', '$end', '$text', '$callus');"; mysql_query($in); } else { $message = mysql_real_escape_string( $_REQUEST['text'] ); $time = date( 'Y-m-d H:i:s' ); $in = "INSERT INTO `alerts` (`text`, `time`) VALUES ('$message', '$time');"; mysql_query( $in ); $sel="SELECT * FROM `users` GROUP by device_token"; $rs = mysql_query( $sel ) or die(''); if ( mysql_num_rows( $rs ) != 0 ) { while( $row=mysql_fetch_array( $rs ) ) { $regi = array(); $regi[] = $row['device_token']; $dev = $row['device_token']; if( strlen ( $dev ) > 65 ) { $regis[] = $row['device_token']; } else { $ios[] = $dev; } } } $url = 'https://android.googleapis.com/gcm/send'; $fields = array( 'registration_ids' => $regis, 'data' => array( 'message'=>$message,'count'=>1 ) ); $headers = array( 'Authorization: key=AIzaSyCMysH7TySEgdbvRoCLoZk8uFF1x_A3uxg', 'Content-Type: application/json' ); $ch = curl_init(); curl_setopt( $ch, CURLOPT_URL, $url ); curl_setopt( $ch, CURLOPT_POST, true ); curl_setopt( $ch, CURLOPT_HTTPHEADER, $headers ); curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false ); curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode ( $fields ) ); $result = curl_exec( $ch ); curl_close ( $ch ); //Apple Push notification // This this a fake device id: $deviceToken = "5d8b3165fc03645d23c2651badd69f07d028aee801acf1d25a4d230882156755"; // fake password: $passphrase = '123456789'; $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem'); stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); // Open a connection to the APNS server $fp = stream_socket_client( 'ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) exit("Failed to connect: $err $errstr" . PHP_EOL); echo 'Connected to APNS' . PHP_EOL; // Create the payload body $body['aps'] = array( 'alert' => $message, 'sound' => 'default', 'badge' => '1' ); // Encode the payload as JSON $payload = json_encode($body); // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); if (!$result) echo 'Message not delivered' . PHP_EOL; else echo 'Message successfully delivered' . PHP_EOL; // Close the connection to the server fclose($fp); } include 'index.php'; ?> I add the ios device token to the $deviceToken and the android device token to the $regi and it will send to the phones. The only part I have changed is the Apple push notification part which didn't work. Before I changed it the apple push notification was using the $dev variable and android was using $regi. Now I know that the device tokens are being sent to the server when the app is launched so my guess is that they are not being stored in the variables. Is there any problems you can see and how can I print them out to see if they are empty? Thanks A: I figured this out a while ago and though I would share for anyone else that is struggling. <?php include 'conn.php'; if ( $_REQUEST['key'] == 'notification' ) { $message = $_REQUEST['text']; $text = mysql_real_escape_string( $_REQUEST['text'] ); $start = $_REQUEST['start']; $end = $_REQUEST['end']; $date = date( "Ymd", strtotime( $_REQUEST['date'] ) ); $callus = $_REQUEST['callus']; $in = "INSERT INTO `notifications` (`date`, `start_time`, `end_time`, `text`, `call_us`) VALUES ('$date', '$start', '$end', '$text', '$callus');"; mysql_query($in); include 'notifications.php'; } else { $message = mysql_real_escape_string( $_REQUEST['text'] ); $time = date( 'Y-m-d H:i:s' ); $in = "INSERT INTO `alerts` (`text`, `time`) VALUES ('$message', '$time');"; mysql_query( $in ); $sel="SELECT * FROM `users` GROUP by device_token"; $rs = mysql_query( $sel ) or die(''); if ( mysql_num_rows( $rs ) != 0 ) { while( $row=mysql_fetch_array( $rs ) ) { $regi = array(); $regi[] = $row['device_token']; $dev = $row['device_token']; if( strlen ( $dev ) > 65 ) { $regis[] = $row['device_token']; } else if ( strlen ($dev) > 25 ) { $ios[] = $dev; } } } $deviceToken=$_REQUEST['device']; $json=json_decode($deviceToken); //google Push notification // API access key from Google API's Console define( 'API_ACCESS_KEY', 'AIzaSyCMysH7TySEgdbvRoCLoZk8uFF1x_A3uxg' ); //build the message $fields = array ( 'registration_ids' => $regis, 'data' => array( 'message'=> $message,'count'=>1 ) ); $headers = array ( 'Authorization: key=' . API_ACCESS_KEY, 'Content-Type: application/json' ); $ch = curl_init(); curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' ); curl_setopt( $ch,CURLOPT_POST, true ); curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers ); curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true ); curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false ); curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) ); $result = curl_exec($ch ); curl_close( $ch ); //Apple Push notification // Certificate password: $passphrase = '123456789'; $ctx = stream_context_create(); stream_context_set_option($ctx, 'ssl', 'local_cert', 'ckStudioeast.pem'); stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase); // Open a connection to the APNS server $fp = stream_socket_client( 'ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) exit("Failed to connect: $err $errstr" . PHP_EOL); // Create the payload body $body['aps'] = array( 'alert' => $message, 'sound' => 'default', 'badge' => '1' ); // Encode the payload as JSON $payload = json_encode($body); // Loop though device tokens foreach($ios as $dev) { if($dev!=''){ // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $dev) . pack('n', strlen($payload)) . $payload; //Send it to the server $result = fwrite($fp, $msg, strlen($msg)); } } if (!$result) echo 'Message not delivered' . PHP_EOL; // Close the connection to the server fclose($fp); include 'index.php'; } ?> The problem seemed to be that the app was sending the database a development device token so I updated my didRegisterForRemoteNotificationsWithDeviceToken function in xcode to this: - (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{ #ifdef DEBUG // Update the database with our development device token NSLog(@"IN DEVELOPMENT MODE!!!!!!!"); #else // Update the database with our production device token NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet: [NSCharacterSet characterSetWithCharactersInString:@"<>"]]; token = [token stringByReplacingOccurrencesOfString:@" " withString:@""]; NSLog(@"content---%@", token); kSetValueForKey(@"device_token", token); [self updateDeviceToken:token]; #endif } Also I found that if a user denies the request to allow push notifications that it send a device token of 0 to my database, which if used stops the notifications from being sent. So where I'm sorting my device tokens in my php file I added more logic to ignore all the tokens that where just 0. I simply just checked that the length was more than 25 characters before I added it to my $ios array, where as before I wasn't Old code: if( strlen ( $dev ) > 65 ) { $regis[] = $row['device_token']; } else { $ios[] = $dev; } New code: if( strlen ( $dev ) > 65 ) { $regis[] = $row['device_token']; } else if ( strlen ($dev) > 25 ) { $ios[] = $dev; } One of the main problems I found is if you send a device token to apples production push notification server that isn't a valid production device token, it just doesn't send the notification to any device. This is why I It wasn't working and I have added in the extra logic to my php code and Objective-c code to filter out all the invalid device tokens. Hope this helps people.
[ "stackoverflow", "0015752695.txt" ]
Q: OAuth2 multiple servers accessing service I have a server-side app that does some work with an API secured with OAuth 2.0. When I launch the app, I go through the OAuth authentication flow and get the access and refresh tokens. Now, the problem is: my app works across multiple servers doing its thing. Can I share the access token across all three servers or do I have to go and get a new one for each (which requires user interaction -- what a hassle!) ?? I noticed that Google's APIs call the access tokens "Bearer" tokens, which I'm assuming means they can be used by whomever has them in hand, but: Is that common with other OAuth 2.0 APIs? Are there better recommended practices? Is that really the intended meaning? Suggestions appreciated. A: According to this site, Any party in possession of a bearer token (a "bearer") can use it to get access to the associated resources This means that yes, you can share it across all three servers. The document I referenced isn't particular to an API, so it shouldn't matter whether it is Google or some other site.
[ "math.stackexchange", "0000476022.txt" ]
Q: System of Linear Equations with dependence on $a$ I gotta solve this System of linear equations dependent on $a$: $$x+y+z=1$$ $$-2x+2y+az=3$$ $$-ax+y+2z=2$$ I'm transforming this to a matrix. $$ M_1 = \left[\begin{array}{ccc|c} 1 & 1 & 1 & 1\\ -2 & 2 & a & 3\\ -a & 1 & 2 & 2 \end{array}\right] $$ I'm switching x with y column and sort. $$ M_2 = \left[\begin{array}{ccc|c} 1 & 1 & 1 &1\\ 1 & -a & 2 &3\\ 2 & -2 & a &2 \end{array}\right] $$ Solving this: $$ M_3 = \left[\begin{array}{ccc|c} 1 & 1 & 1&1\\ 0 & -a-1 & 1&2 \\ 0 & 0 & a+2 &5 \end{array}\right] $$ Therefore I'm getting $$a= 3$$ Putting it into the $M1$ yields no result, as I end up with. $$ M = \left[\begin{array}{ccc|c} 1 & 1 & 1 & 1\\ 0 & 4 & 5 & 1\\ 0 & 4 & 5 & 5 \end{array}\right] $$ Is there an error in my calculation? A: I have severely edited my original answer. Your first error occurs when forming $M2$. You did a combination of swapping the second and third row (which you are allowed to do) with swapping the first and second column (which you are not allowed to do). Each row of the matrices $M1$, $M2$, and $M3$ represents an equation in $x, y,$ and $z$. By swapping rows, you just change the order in which the equations are listed; this is perfectly find because it does not change the solutions to the system. Swapping rows however corresponds to interchanging variables; this is not allowed because it effects the solutions of the system. For example, the solutions of $x + 2y = 0$ are not the same as the solutions of $y + 2x = 0$. Your next error occurs when forming $M3$. You have done the row reduction incorrectly. Your final error occurs when you conclude that $a = 3$. The third row of $M3$ represents the equation $(a + 2)z = 5$. That does not imply that $a = 3$. However, by imposing a restriction on $a$, you can find $z$ in terms of $a$. I advise you try again. Start with $M1$ (which is the correct augmented matrix for the system) and row reduce it, making sure to only use the allowed row operations.
[ "stackoverflow", "0013767699.txt" ]
Q: boost test - 'undefined reference' errors I have two simple files: runner.cpp: #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE Main #include <boost/test/unit_test.hpp> and test1.cpp: #define BOOST_TEST_DYN_LINK #ifdef STAND_ALONE # define BOOST_TEST_MODULE Main #endif #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_SUITE( Foo) BOOST_AUTO_TEST_CASE( TestSomething ) { BOOST_CHECK( true ); } BOOST_AUTO_TEST_SUITE_END() To compile, I'm using: $ g++ -I/e/code/boost_1_52_0 -o runner -lboost_unit_test_framework runner.cpp test1.cpp I get the following error: C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\ccU0cDSz.o:runner.cpp:(.text+0x8c): multiple definition of `main' c:/pdev/mingw/bin/../lib/gcc/i686-pc-mingw32/4.7.2/../../../libboost_unit_test_framework.a(unit_test_main.o):unit_test_main.cpp:(.text.startup+0x0): first defined here c:/pdev/mingw/bin/../lib/gcc/i686-pc-mingw32/4.7.2/../../../libboost_unit_test_framework.a(unit_test_main.o):unit_test_main.cpp:(.text.startup+0x14): undefined reference to `init_unit_test_suite(int, char**)' C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\ccU0cDSz.o:runner.cpp:(.text+0x52): undefined reference to `_imp___ZN5boost9unit_test9framework17master_test_suiteEv' C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\ccU0cDSz.o:runner.cpp:(.text+0xb0): undefined reference to `_imp___ZN5boost9unit_test14unit_test_mainEPFbvEiPPc' C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\ccU0cDSz.o:runner.cpp:(.text$_ZN5boost9unit_test13test_observerD2Ev[__ZN5boost9unit_test13test_observerD2Ev]+0xe): undefined reference to `_imp___ZTVN5boost9unit_test13test_observerE' C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\ccU0cDSz.o:runner.cpp:(.text$_ZN5boost9unit_test13test_observerC2Ev[__ZN5boost9unit_test13test_observerC2Ev]+0xe): undefined reference to `_imp___ZTVN5boost9unit_test13test_observerE' C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\ccU0cDSz.o:runner.cpp:(.text$_ZN5boost9unit_test15unit_test_log_tC1Ev[__ZN5boost9unit_test15unit_test_log_tC1Ev]+0x22): undefined reference to `_imp___ZTVN5boost9unit_test15unit_test_log_tE' C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\cciSdkmB.o:test1.cpp:(.text+0x88): undefined reference to `_imp___ZN5boost9unit_test15unit_test_log_t14set_checkpointENS0_13basic_cstringIKcEEjS4_' C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\cciSdkmB.o:test1.cpp:(.text+0x136): undefined reference to `_imp___ZN5boost10test_tools9tt_detail10check_implERKNS0_16predicate_resultERKNS_9unit_test12lazy_ostreamENS5_13basic_cstringIKcEEjNS1_10tool_levelENS1_10check_typeEjz' C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\cciSdkmB.o:test1.cpp:(.text+0x21d): undefined reference to `_imp___ZN5boost9unit_test9ut_detail24auto_test_unit_registrarC1ENS0_13basic_cstringIKcEE' C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\cciSdkmB.o:test1.cpp:(.text+0x284): undefined reference to `_imp___ZN5boost9unit_test9ut_detail24auto_test_unit_registrarC1EPNS0_9test_caseEm' C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\cciSdkmB.o:test1.cpp:(.text+0x2a4): undefined reference to `_imp___ZN5boost9unit_test9ut_detail24auto_test_unit_registrarC1Ei' C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\cciSdkmB.o:test1.cpp:(.text$_ZN5boost9unit_test14make_test_caseERKNS0_9callback0INS0_9ut_detail6unusedEEENS0_13basic_cstringIKcEE[__ZN5boost9unit_test14make_test_caseERKNS0_9callback0INS0_9ut_detail6unusedEEENS0_13basic_cstringIKcEE]+0x1d): undefined reference to `_imp___ZN5boost9unit_test9ut_detail24normalize_test_case_nameENS0_13basic_cstringIKcEE' C:\DOCUME~1\ADMINI~1\LOCALS~1\Temp\cciSdkmB.o:test1.cpp:(.text$_ZN5boost9unit_test14make_test_caseERKNS0_9callback0INS0_9ut_detail6unusedEEENS0_13basic_cstringIKcEE[__ZN5boost9unit_test14make_test_caseERKNS0_9callback0INS0_9ut_detail6unusedEEENS0_13basic_cstringIKcEE]+0x5b): undefined reference to `_imp___ZN5boost9unit_test9test_caseC1ENS0_13basic_cstringIKcEERKNS0_9callback0INS0_9ut_detail6unusedEEE' collect2.exe: error: ld returned 1 exit status I'm using g++ 4.7.2 on MinGW, with boost 1.52.0. I get the same errors when only trying to compile test1.cpp - except the "multiple main definition" one. I perused the official documentation for quite a while, but its scarce on details regarding linking options. When I compiled the boost libs, besides unit_test_framework, I also got prg_exec_monitor and test_exec_monitor; perhaps I should link these somehow ? I tried many combinations, but all resulted in some kind of undefined reference linker error. Complete list of boost generated libraries - I have them all in the project root: libboost_prg_exec_monitor-mgw47-mt-1_52.a libboost_prg_exec_monitor-mgw47-mt-1_52.dll libboost_prg_exec_monitor-mgw47-mt-1_52.dll.a libboost_prg_exec_monitor-mgw47-mt-d-1_52.a libboost_prg_exec_monitor-mgw47-mt-d-1_52.dll libboost_prg_exec_monitor-mgw47-mt-d-1_52.dll.a libboost_test_exec_monitor-mgw47-mt-1_52.a libboost_test_exec_monitor-mgw47-mt-d-1_52.a libboost_unit_test_framework-mgw47-mt-1_52.a libboost_unit_test_framework-mgw47-mt-1_52.dll libboost_unit_test_framework-mgw47-mt-1_52.dll.a libboost_unit_test_framework-mgw47-mt-d-1_52.a libboost_unit_test_framework-mgw47-mt-d-1_52.dll libboost_unit_test_framework-mgw47-mt-d-1_52.dll.a A: With help from @llonesmiz, a number of issues were identified. 1. Libraries need to be specified after objects and sources which use them. As described here: The traditional behavior of linkers is to search for external functions from left to right in the libraries specified on the command line. This means that a library containing the definition of a function should appear after any source files or object files which use it. This includes libraries specified with the short-cut -l option, as shown in the following command: $ gcc -Wall calc.c -lm -o calc (correct order) With some linkers the opposite ordering (placing the -lm option before the file which uses it) would result in an error, $ cc -Wall -lm calc.c -o calc (incorrect order) main.o: In function 'main': main.o(.text+0xf): undefined reference to 'sqrt' because there is no library or object file containing sqrt after ‘calc.c’. The option -lm should appear after the file ‘calc.c’ 2. Library paths should be explicitly specified. If no lib paths are specified, the linker might look for the libs in a series of default folders, thus loading a different library then intended. This is what happened in my case - I wanted to link boost_unit_test_framework, but did not specify a path because I assumed the linker would look in the current folder. That's what happens at runtime, after all - if the dll is in the same folder with the exe, it will find it. I found it a little bit strange the linker would find the lib, since it was named ibboost_unit_test_framework-mgw47-mt-1_52.dll. When I tried to link to a non-existing lib, the linker complained though, so I assumed this isn't an issue, and MinGW 's linker ignores those suffixes. After some more research, I found this article about MinGW library paths. The folders MinGW searches for libs can be found in the output of gcc -print-search-dirs. The article also contains some bash magic to make sense of that output: gcc -print-search-dirs | sed '/^lib/b 1;d;:1;s,/[^/.][^/]*/\.\./,/,;t 1;s,:[^=]*=,:;,;s,;,; ,g' | tr \; \\012 | grep -v '^ */' This will print a nice list of those folders. gcc will not, by default, look in the current directory for libs. I looked in each of them, and found the lib that was being loaded - libboost_unit_test_framework.a, a static lib. This brings into light another issue worth mentioning: 3. Static versus dynamic linking I did not specify whether I want boost_unit_test_framework linked statically or dynamically. In this case, gcc prefers dynamic linking: Because of these advantages gcc compiles programs to use shared libraries by default on most systems, if they are available. Whenever a static library ‘libNAME.a’ would be used for linking with the option -lNAME the compiler first checks for an alternative shared library with the same name and a ‘.so’ extension. (so is the extension for dynamic libraries on Unix - on Windows, the equivalent is dll.) So, what happened is that gcc looked for libboost_unit_test_framework.dll in all it's default folders, but couldn't find it. Then it looked for libboost_unit_test_framework.a, and statically linked that. This resulted in linking errors because the sources have #define BOOST_TEST_DYN_LINK, and therefore expect to have the lib dynamically linked. To enforce static or dynamic linking, the -Wl,-Bstatic and -Wl,-Bdynamic linker options come into play, described here. If I tell the linker that I want dynamic linking: $ g++ -I/e/code/boost_1_52_0 runner.cpp test1.cpp -o runner -Wl,Bdynamic -lboost_unit_test_framework This will fail, because the linker will not be able to find the dll. 4.Summary The issues were: libraries where specified before the sources which used them the lib path wasn't specified the type of linking wasn't specified the name of the library was not correct Final, working command: $ g++ -I/e/code/boost_1_52_0 -o runner runner.cpp test1.cpp -L. -Wl,-Bdynamic -lboost_unit_test_framework-mgw47-mt-1_52
[ "stackoverflow", "0001605821.txt" ]
Q: Transform string into image with jQuery Another jQuery question for you guys. Say I have a url of an image in my web page surrounded by square brackets. [http://www.example.com/picture.jpg] How could I, with jQuery transform that string like so... [http://www.example.com/picture.jpg] into... <img src="http://www.example.com/picture.jpg" /> ? A: I'd do something like this $("some-selector").each(function(){ $(this).html($(this).html().replace(/\[(http:.*?)\]/gi, function(str, p1){ return "<img src='"+p1+"' />"; })); }); "some-selector" should try to pinpoint where these string occur. If there is nothing like it... just put "body" and see what happens :)