source
stringclasses 1
value | task_type
stringclasses 1
value | in_source_id
stringlengths 1
8
| prompt
stringlengths 209
40.4k
| gold_standard_solution
stringlengths 0
56.7k
| verification_info
stringclasses 1
value | metadata
stringlengths 138
225
| problem_id
stringlengths 9
10
|
---|---|---|---|---|---|---|---|
stackexchange | llm_judgeable_groundtruth_similarity | 177277 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a dataset for which Mathematica easily creates a Histogram . However I also need Mathematica to show error bars corresponding to 3 standard deviations for each bar. This is something similar to the ErrorBar function for BarChart . I cannot find any way to do this. The difference between my case and the ErrorBar package avaliable ( http://reference.wolfram.com/language/ErrorBarPlots/ref/ErrorBar.html ) is that it requires data for the magnitude of error for each bin/bar. In my case, I am giving Mathematica a raw data file to plot into a Histogram . It should be able to calculate the error by itself. There is no way in which I can give Mathematica the bar heights, bin boundaries and corresponding errors from which it will give me a histogram. If someone can point that out, even that would be a potential solution to my problem. The ErrorBar method works for BarChart s, not Histogram s as I understand.Could anyone help? Update: Using the code @kglr helped me with I could implement the error bars in my Histogram. It is a Histogram that takes its y-values as {"Log","Count"}. So some modification was required. ceF[d_: .2, nsd_: 3, color_: Automatic][cedf_: "Rectangle"] := Module[{e = nsd Sqrt[Exp[#[[2, 2]]]]}, {ChartElementData[cedf][##], Thick, color /. Automatic -> Darker[Charting`ChartStyleInformation["Color"]], If[Exp[#[[2, 2]]] - e != 0, {Line[{{Mean@#[[1]], Log[Exp[#[[2, 2]]] - e]}, {Mean@#[[1]], Log[Exp[#[[2, 2]]] + e]}}], Line[{{#[[1, 1]] + d/2, Log[Exp[#[[2, 2]]] - e]}, {#[[1, 2]] - d/2, Log[Exp[#[[2, 2]]] - e]}}], Line[{{#[[1, 1]] + d/2, Log[Exp[#[[2, 2]]] + e]}, {#[[1, 2]] - d/2, Log[Exp[#[[2, 2]]] + e]}}]}, {Line[{{Mean@#[[1]], 0}, {Mean@#[[1]], Log[Exp[#[[2, 2]]] + e]}}], Line[{{#[[1, 1]] + d/2, 0}, {#[[1, 2]] - d/2, 0}}], Line[{{#[[1, 1]] + d/2, Log[Exp[#[[2, 2]]] + e]}, {#[[1, 2]] - d/2, Log[Exp[#[[2, 2]]] + e]}}]} ] }] & Incidentally the highest bin of my histogram faces this issue where Exp[#[[2, 2]]] - e is exactly zero. This modification should have been able to solve the issue but what I get is this, and I don't know why the Bars dont start from the zero of the axis. That is to say, the bars should be starting from the y-tic marked "1", but they are starting from somewhere above "3." Why is that so? What do I do to make it start from "1"? Incidentally, for the people who think this is a duplicate of the linked Q/A's, I'm sorry I could not make the connection since I am not an expert at Mathematica. However, the last time I looked it was not called Mathematica StackExchange for Experts Only. Please have this much respect for another person to realise that he would not have posted the question explaining why it is not a duplicate if he could solve the problem from there. I am a professional and my time and energy has some value. I would not be here if I could solve the problem by myself.
Now provide the response and nothing else.
| For the case where the height function is "Count" , we can use the formula from the linked page in a custom ChartElementFunction with the sample size ( Length[data] ) passed as metadata: ceF[d_: .2, nsd_: 3, color_: Automatic][cedf_: "Rectangle"] := Module[{e = nsd /2 Sqrt[#[[2, 2]] (1 - #[[2, 2]]/ #3[[1]])]}, {ChartElementData[cedf][##], Thick, color /. Automatic -> Darker[Charting`ChartStyleInformation["Color"]], Line[{{Mean@#[[1]], #[[2, 2]] - e}, {Mean@#[[1]], #[[2, 2]] + e}}], Line[{{#[[1, 1]] + d/2, #[[2, 2]] - e}, {#[[1, 2]] - d/2, #[[2, 2]] - e}}], Line[{{#[[1, 1]] + d/2, #[[2, 2]] + e}, {#[[1, 2]] - d/2, #[[2, 2]] + e}}]}]& Examples: SeedRandom[1]data = RandomVariate[NormalDistribution[0, 1], 200];Histogram[data -> Length[data], ChartStyle -> 43, ChartElementFunction -> ceF[][]] Histogram[data -> Length@data, ChartStyle -> 43, ChartElementFunction -> ceF[.2, 3, Black]["GlassRectangle"]] Update: to make it work with non-default BarOrigin settings: ClearAll[ceF]ceF[d_: .2, nsd_: 3, color_: Automatic][cedf_: "Rectangle"] := Module[{bo = Charting`ChartStyleInformation["BarOrigin"], col = Darker[Charting`ChartStyleInformation["Color"]], box = #, tf, e}, tf = Switch[bo, Left | Right, Reverse, _, Identity]; box = Switch[bo, Bottom, box, Top, {box[[1]], Reverse[box[[2]]]}, Left, Reverse@box, Right, {box[[2]], Reverse@box[[1]]}]; e = nsd /2 Sqrt[Abs@box[[2, 2]] (1 - Abs@box[[2, 2]]/#3[[1]])]; {ChartElementData[cedf][##], Thick, color /. Automatic -> col, Line[tf /@ {{Mean@box[[1]], box[[2, 2]] - e}, {Mean@box[[1]], box[[2, 2]] + e}}], Line[tf /@ {{box[[1, 1]] + d/2, box[[2, 2]] - e}, {box[[1, 2]] - d/2, box[[2, 2]] - e}}], Line[tf /@ {{box[[1, 1]] + d/2, box[[2, 2]] + e}, {box[[1, 2]] - d/2, box[[2, 2]] + e}}]}] & Example: Grid[Partition[Histogram[data -> Length@data, ChartStyle -> 43, ChartElementFunction -> ceF[][], ImageSize -> 300, BarOrigin -> #] & /@ {Bottom, Top, Left, Right}, 2], Dividers -> All] | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/177277', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/40416/']} | jdg_77941 |
stackexchange | llm_judgeable_groundtruth_similarity | 4071258 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to create a multiplayer game with NodeJS and I want to synchronize the action between clients. What would be the best way to find the latency (the time that a request take to come back to the client) between the client and the server? My first idea was that the client #1 could send a timestamp with is request, so when client #2 will receive the action of the client #1 he will adjust is action speed to remove the delay of the request.But the problem is that maybe the system date time of the two clients are not identical so it is not possible two know the reel delay on the request of client #1. The other solution was to use the timestamp of the server, but now how can I know the latency of a client?
Now provide the response and nothing else.
| I'm going to assume you are using WebSockets or Socket.IO since you are implementing a game where latency matters (and you tagged it as such). I would think the server should probably measure and keep track of this for each client. You probably want to implement some sort of ping action that the server can request of the client. As soon as the client receives the request, it sends back a response to the server. The server then divides by 2 and updates the latency for that client. You probably want the server to do this periodically with each client and probably average the last several so that you don't get strange behavior from sudden but temporary spikes. Then, when there is a message from one client that needs to be sent (or broadcast) to another client, the server can add client1's latency to client2's latency and communicate this as the latency offset to client2 as part of the message. client2 will then know that the event on client1 happened that many milliseconds ago. An additional reason to do this on the server is that some browser Javascript timestamps are inaccurate: http://ejohn.org/blog/accuracy-of-javascript-time/ . I suspect node.js timestamps are just as accurate (or more so) than V8 (which is one of the few accurate ones). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4071258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/93216/']} | jdg_77942 |
stackexchange | llm_judgeable_groundtruth_similarity | 3760593 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm developing on an application at the moment which contains quite a lot of personal user information - things like Facebook contacts, etc ... Now, one of the things I want to be able to do (and have done, quite effectively) is open up parts of the application to "3rd Party" applications, using Android's build-in inter-process communication protocol (AIDL). So far so good. Here's the catch: because we're involved in handling quite a lot of personal information, we have to be quite careful about who can and can't access it; specifically, only "Trusted" applications should be able to do so. So the natural way to do this is to use a custom permission within the AndroidManifest.xml file where we declare the services. My problem is this: I want to be able to enact signature-level protection (similar to the normal "signature" permission level), but with a bit of a catch: I don't only want application signed with our internal signature to be able to access the services. I'd like to be able to build a list of "trusted signatures" & at runtime (or if there's a better way, then maybe some other time?) be able to check incoming requests against this list of trusted keys. This would satisfy the security constraints in the same way as the normal "signature" permission level I think - only programs on the "trusted keys list" would be able to access the services, and keys are hard to spoof (if possible at all?) - but with the added bonus that we wouldn't have to sign every application making use of the APIs with our internal team's key. Is this possible at the moment in Android? And if so, are there any special requirements? Thanks
Now provide the response and nothing else.
| I've now found the answer to this question, but I'll leave it for the sake of anyone looking in the future. I opened up a discussion on android-security-discuss where it was answered. Link: http://groups.google.com/group/android-security-discuss/browse_thread/thread/e01f63c2c024a767 Short answer: private boolean checkAuthorised(){ PackageManager pm = getPackageManager(); try { for (Signature sig : pm.getPackageInfo(pm.getNameForUid(getCallingUid()), PackageManager.GET_SIGNATURES).signatures){ LogUtils.logD("Signature: " + sig.toCharsString()); if (Security.trustedSignatures.get(sig.toCharsString()) != null) { return true; } } } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } LogUtils.logD("Couldn't find signature in list of trusted keys! Possibilities:"); for(String sigString : Security.trustedSignatures.keySet()){ LogUtils.logD(sigString); } /* Crash the calling application if it doesn't catch */ throw new SecurityException(); } Where Security.trustedSignatures is a Map of the form: Map<String,String>().put("public key","some description eg. name"); Put this method inside any code that is being called by the external process (ie. within your interface). Note that this will not have the desired effect inside the onBind() method of your RemoteService. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3760593', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/227224/']} | jdg_77943 |
stackexchange | llm_judgeable_groundtruth_similarity | 115453 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've got an educational game in the work that challenges players to redraw U.S. state borders in a way that reduce the inequality between big-population and small-population states. As they play, they need to get real-time feedback on the effect of assigning counties from one state to another. So I need some sort of single parameter of "equalness" that is derived from the distribution of populations in the new hypothetical set of states. I've thought about just displayed the standard deviation in the state populations. Is there a better way to succinctly express a power distribution? I'd prefer something as simple to understand as possible since I want to appeal to a broad audience. State populations as of 2010 Census below for reference.
Now provide the response and nothing else.
| Perhaps the best known measure would be the Gini index . The R package ineq (See here ) implements the Herfindahl and Rosenbluth concentration measures (in function conc ). It also implements a number of inequality indexes (including the Gini) in function ineq -- the Gini coefficient, Ricci-Schutz coefficient (also called Pietra’s measure), Atkinson’s measure, Kolm’s measure, Theil’s entropy measure, Theil’s second measure, the coefficient of variation and the squared coefficient of variation. This answer mentions the Simpson diversity index, and derives a concentration measure from that. There are numerous other diversity indices (and thereby, other concentration measures). You'll probably note that there's a connection to the Herfindahl index (the Simpson diversity index is the Herfindahl, and the corresponding concentration measure is the normalized Herfindahl. In fact I just edited the other answer to point this out.) [When dealing with count data, or proportions derived from counts, it's also possible to define measures derived from chi-square goodness-of-fit statistics (they can be normalized to 0-1), for example. For one such measure, see here .] Many of these are either suitable or can be rescaled to be suitable as measures of the kind of thing you want. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/115453', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/54426/']} | jdg_77944 |
stackexchange | llm_judgeable_groundtruth_similarity | 1256509 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How would I go about calculating: $ \left( \begin{array}{cc}3 & -\sqrt{3} \\\sqrt{3} & -1 \end{array} \right)^{13}$ I have already attempted to find eigenvalues/eigenvectors, but I believe I am missing a much simpler method.
Now provide the response and nothing else.
| Another approach you may use is to break $13$ down into powers of two. We see that $13=8+4+1$. You can compute $A^8$, $A^4$ and then find your desired product by $A^8 \cdot A^4 \cdot A = A^{13}$. Powers of two are easier to handle than other powers, and so this method is used often when computing large powers. This is because $A^2=A\cdot A$, $A^4 = A^2 \cdot A^2$, and $A^8=A^4 \cdot A^4$. Therefore three multiplications are needed to find $A^8$ and $A^4$. Then two more multiplications are needed to compute $A^{13} = A^8 \cdot A^4 \cdot A$. Thus only five multiplications are needed. This is in contrast to the necessary 12 products that need to be computed in a direct method. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1256509', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/118176/']} | jdg_77945 |
stackexchange | llm_judgeable_groundtruth_similarity | 105727 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $k$ be a field and $q\in k^{*}$. The quantum plane $k_{q}[x,y]$ is the algebra $k\langle x,y\rangle/\langle xy=qyx \rangle$ (i.e. the quotient of the free non-commutative $k$-algebra on two variables $x$ and $y$ modulo the ideal given). Question: For $q,r\in k^{*}$ and $q\neq r$, when is $k_{q}[x,y]$ isomorphic (as an algebra) to $k_{r}[x',y']$? I fully expect this is known but after (what I think is) fairly comprehensive literature searching, including a large proportion of the best-known quantum groups texts, I have been unable to find an answer. A reference would be appreciated just as much as a proof. Some comments: I know the (algebra) automorphism group: by work of Alev-Chamarie this is $(k^{*})^2$ unless $q=-1$ (when it is a semi-direct product of the torus with the group of order two generated by the map that interchanges the two variables). Hence I don't need to worry about $q=r$. I want algebra isomorphisms but information on Hopf algebra maps would be nice too (NB. the Hopf automorphisms for the usual Hopf structure are also those just described) if $q$ has finite order $N$ in $k^{*}$ and $r$ is of infinite order then the corresponding quantum planes are not isomorphic, as in the first case the centre is non-trivial (generated by $x^{N}$ and $y^{N}$) but in the second the centre is just $k$ if $q$ has order $M$ and $r$ has order $N\neq M$, then the quotients by the centres are both finite-dimensional but of different dimension, hence the quantum planes are not isomorphic I would be happy to know the answer just for $k=\mathbb{C}$
Now provide the response and nothing else.
| This answer feels so glib I'm quite worried it's wrong, but anyway: Write $D_q$ for the full ring of fractions of $k_q[x,y]$. By Alev-Dumas, "Sur le corps des fractions de certaines algebres quantiques", Corollary 3.11c, we know that for $q$, $r$ non-roots of unity, $D_q \cong D_r$ iff $r = q^{\pm1}$. It's clear that $k_q[x,y] \cong k_r[x',y'] \Rightarrow D_q \cong D_r$, so we have\[k_q[x,y] \cong k_r[x',y'] \Rightarrow r = q^{\pm1},\] and the converse should also be clear. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/105727', 'https://mathoverflow.net', 'https://mathoverflow.net/users/13215/']} | jdg_77946 |
stackexchange | llm_judgeable_groundtruth_similarity | 13488419 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For some reason, the OK button is not clickable when I try to create an AVD. Does anyone know what I'm doing wrong?
Now provide the response and nothing else.
| Simply because CPU/ABI says "No system images installed for this target". You need to install system images. In the Android SDK Manager check that you have installed "ARM EABI v7a System Image" (for each Android version from 4.0 and on you have to install a system image to be able to run a virtual device) In your case only ARM system image exsits (Android 4.2). If you were running an older version, Intel has provided System Images (Intel x86 ATOM). You can check on the internet to see the comparison in performance between both. In my case (see image below) I haven't installed a System Image for Android 4.2, whereas I have installed ARM and Intel System Images for 4.1.2 As long as I don't install the 4.2 System Image I would have the same problem as you. UPDATE : This recent article Speeding Up the Android Emaulator on Intel Architectures explains how to use/install correctly the intel system images to speed up the emulator. EDIT/FOLLOW UP What I show in the picture is for Android 4.2, as it was the original question, but is true for every versions of Android. Of course (as @RedPlanet said), if you are developing for MIPS CPU devices you have to install the "MIPS System Image". Finally, as @SeanJA said, you have to restart eclipse to see the new installed images. But for me, I always restart a software which I updated to be sure it takes into account all the modifications, and I assume it is a good practice to do so. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/13488419', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1649971/']} | jdg_77947 |
stackexchange | llm_judgeable_groundtruth_similarity | 6035848 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When I run the following script, both lambda's run os.startfile() on the same file -- junk.txt. I would expect each lambda to use the value "f" was set to when the lambda was created. Is there a way to get this to function as I expect? import osdef main(): files = [r'C:\_local\test.txt', r'C:\_local\junk.txt'] funcs = [] for f in files: funcs.append(lambda: os.startfile(f)) print funcs funcs[0]() funcs[1]()if __name__ == '__main__': main()
Now provide the response and nothing else.
| One way is to do this: def main(): files = [r'C:\_local\test.txt', r'C:\_local\junk.txt'] funcs = [] for f in files: # create a new lambda and store the current `f` as default to `path` funcs.append(lambda path=f: os.stat(path)) print funcs # calling the lambda without a parameter uses the default value funcs[0]() funcs[1]() Otherwise f is looked up when the function is called, so you get the current (after the loop) value. Ways I like better: def make_statfunc(f): return lambda: os.stat(f)for f in files: # pass the current f to another function funcs.append(make_statfunc(f)) or even (in python 2.5+): from functools import partialfor f in files: # create a partially applied function funcs.append(partial(os.stat, f)) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6035848', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_77948 |
stackexchange | llm_judgeable_groundtruth_similarity | 114069 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Introduction: Consider the EM field. There was a time when the field was defined in a similar manner to that of the gravitational field. This changed when the view on gravitation evolved to this new idea which suggested it was a consequence of space-time curvature. Now consider the equivalence principle, it was due to this principle that the view on gravitation was changed from that of a classical field to one which suggested a more geometric nature. I cannot help but think that we should of owed the same respect to the EM field since it doesn't seem unreasonable to think that an some equivalence principle of some kind may be assigned EM field. If we may assign an equivalence principle to the EM field then perhaps we can define the electromagnetic field in some geometric way as well. I understand and certainly agree that EM energy stored in a volume of a space will contribute to the mass-energy content in that volume and hence curvature but this is not what I am talking about, rather I am considering the possibility of a newer description of the EM field which may complement the geometric description of the gravitational field in a more explicit way. Consider gravity before it was described by Einstein, I claim that one could derive an gravitational tensor in the same way as one can derive an electromagnetic tensor $F^{\mu\nu}$. I say this because gravity possesses a gravito-magnetic property. This isn't surprising to me since magnetism is nothing more than a relativistic effect of static fields. What I am trying to say is that before Einstein, one could in principle derive a gravitational tensor which was analogous to the electromagnetic tensor yet after getting to this point it would still remain a special-relativistic compatible classical description of a gravitational field (meaning it doesn't necessarily take gravitational time dilation into account) ; in this sense the electromagnetic tensor describes the EM field classically. Of course this is not important anymore since we DO have a more powerful set of machinery for describing the gravitational field. All this to me only suggests that the EM field could be better described at the macroscopic scales. Conclusions: 1) The principle of equivalence made it possible to assign a geometric description to the gravitational interaction. 2) If gravitational fields may be defined in a geometric way then perhaps the EM field can be as well (if a principle of equivalence may be defined for the EM field). Questions: 1) Is it impossible to assign an equivalence principle of some kind to the EM field? If not, why? 2) If it is possible to assign an equivalence principle to the EM field then what may be the first steps in constructing the EM field in a more geometric way? 3) Where is my logic / thought process flawed?
Now provide the response and nothing else.
| The fact that gravitational field can be simulated/canceled by inertial forces relies upon the following elementary but fundamental fact. The gravitational coupling constant of a given body, i.e. its gravitational mass ,$M$, coincides with the other universal constant associated with that body, appearing in the general law of motion, i.e. the inertial mass $m$. So if a gravitational field $\vec{g}(t,x)$ is given, the equation of motion of a body with mass $m$, immersed in that field of acceleration is,$$m\frac{d^2\vec{x}}{dt^2} = M\vec{g}(t,\vec{x})$$and, since $m=M$$$\frac{d^2\vec{x}}{dt^2} = \vec{g}(t,\vec{x})\:.$$The motion, therefore, depends only on initial position and velocity of the body but not on other properties. Exactly as geodesics do in a spacetime. So, a description in terms of geodesics in spacetime is allowed this way and the geometrization of gravitational theory enters physics. Referring to Electromagnetic field, this story stops at the first step. Indeed the corresponding of gravitational mass is the electric charge $q$ and, evidently, $q \neq m$ and so,$$m\frac{d^2\vec{x}}{dt^2} = q\vec{E}(t,\vec{x})\:,$$whose solution depends on the ratio $q/m$, not only on the initial position and velocity. This is the reason why there is no equivalent of equivalence principle for electric forces and any attempt to geometrically describe electromagnetic interaction must be constructed following other approaches (gauge theories) without involving things like metrics and geodesics. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/114069', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/46853/']} | jdg_77949 |
stackexchange | llm_judgeable_groundtruth_similarity | 14670586 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Last Branch Record refers to a collection of register pairs (MSRs) that store the source and destination addresses related to recently executed branches. http://css.csail.mit.edu/6.858/2012/readings/ia32/ia32-3b.pdf document has more information in case you are interested. a) Can someone give an idea of how much LBR slows down program execution of common programs - both CPU and IO intensive ? b) Will branch prediction be turned OFF when LBR tracing is ON ?
Now provide the response and nothing else.
| The paper Intel Code Execution Trace Resources (by Arium workers, Craig Pedersen and Jeff Acampora, Apr 29, 2012 ) lists three variants of branch tracing: Last Branch Record (LBR) flag in the DebugCtlMSR and corresponding LastBranchToIP and LastBranchFromIP MSRs as well as LastExceptionToIP and LastExceptionFromIP MSRs. Branch Trace Store (BTS) using either cache-as-RAM or system DRAM. Architecture Event Trace (AET) captured off the XDP port and storedexternally in a connected In-Target Probe. As said in page 2, LBR save information in MSRs, "does not impede any real-time performance," but is useful only for very short code ("effective trace display is very shallow and typically may only show hundreds of instructions."). Only saves info about 4-16 branches. BTS allows to capture many pairs of branch "From"s and "To"s, and stores them in cache (Cache-as-RAM, CAR) or in system DRAM. In case of CAR, trace depth/length is limited by cache sizes (and some constant); with DRAM trace length is almost unlimited. The paper estimates overhead of BTS as from 20 up to 100 percents due to additional memory stores. BTS on Linux is easy to use with proposed perf branch record (not yet in vanilla) or btrax project . perf branch presentation gives some hints about BTS organisation: there is BTS buffer, which contains "from", "to" fields, and "predicted flag". So, branch prediction is not turned off when using BTS. Also, when BTS buffer is filled up to max size, interrupt is generated. BTS-handling module in kernel (perf_events subsystem or btrax kernel module) should copy data from BTS buffer to other location in case of such interrupt. So, in BTS mode there are two sources of overhead: Cache/Memory stores and interrupts from BTS buffer overflow. AET uses external agent to save debug and trace data. This agent is connected via eXtended Debug Port (XDP) and interfaces with In-Target Probe (ITP). Overhead of AET "can have a significant effect on system performance, which can be several orders of magnitude greater" according to this paper, because AET can generate/capture more types of events. But the collected data storage is external to debugged platform. Paper's "Summary" says: LBR has no overhead, but is very shallow (4–16 branch locations, depending on the CPU). Trace data is available immediately out of reset. BTS is much deeper, but has an impact on CPU performance and requires on-board RAM. Trace data is available as soon as CAR is initialized. AET requires special ITP hardware and is not available on all CPU architectures. It has the advantage of storing the trace data off board. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14670586', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/655617/']} | jdg_77950 |
stackexchange | llm_judgeable_groundtruth_similarity | 13927 |
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Some programs like firefox have buttons that when clicked open a file manager for browsing files. How do I make it to open in emacs with dired mode on Debian Linux?
Now provide the response and nothing else.
| Dependent on your desktop environment the method to set a default application may differ. That said, many desktop environments respect the associations in ~/.local/share/applications/mimeapps.list , where you can set up an association for the application/x-directory and/or inode/directory types. My mimeapps.list looks like this now: [Default Applications]application/x-directory=emacs-dired.desktopinode/directory=emacs-dired.desktop In the same directory I have a file called emacs-dired.desktop with the following contents: [Desktop Entry]Encoding=UTF-8Version=1.0Type=ApplicationNoDisplay=trueExec=emacsclient --eval '(dired "%f")'Name=DiredComment=Emacs Dired When my long-lived instance of Emacs runs a server ( M-x server-start ) and I click on, say, the folder icon in the list of Downloads in Icecat a new dired buffer is opened. This actually works for me now. Thanks for asking the question --- otherwise I would not have set this up. | {} | {'log_upvote_score': 5, 'links': ['https://emacs.stackexchange.com/questions/13927', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/4036/']} | jdg_77951 |
stackexchange | llm_judgeable_groundtruth_similarity | 1645837 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Find the exact value of $$ \int_{0}^{a} \frac{1}{\sqrt {a^2-x^2}} \mathrm {dx} $$ Where, $a$ is a positive constant Hi, guys can give me tips to solve this ? Should we use like u substitution?
Now provide the response and nothing else.
| Here is a tip, for $a>0$ Factor a out:$$\frac {1} {a}\int_{0}^{a}\frac{1}{\sqrt{1-\dfrac{x^2}{a}}}\, \mathrm dx$$ And then set $t=x/a$ threfore $\mathrm dt=\frac 1 a\,\mathrm dx$ $$\int_{0}^{1}\frac{1}{\sqrt{1-t^2}}\,\mathrm dt\\=\arcsin\left(\frac x a\right)\bigg|_0 ^a\\$$ for $a<0$ switch the order of the integration bounds, factor $|a|$ out: $$-\frac {1} {|a|}\int_{-a}^{0}\frac{1}{\sqrt{1-\dfrac{x^2}{a}}}\, \mathrm dx$$ And then set $t=x/a$ threfore $\mathrm dt=\frac 1 a\,\mathrm dx$ $$=-\int_{-1}^{0}\frac{1}{\sqrt{1-t^2}}\,\mathrm dt\\=(-\arcsin\left(\frac x a\right))\bigg|_{-a} ^{0}\\$$ For $a=0,$ $I=0$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1645837', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/192718/']} | jdg_77952 |
stackexchange | llm_judgeable_groundtruth_similarity | 41228 |
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
According to this article Berlin seems to be a strange capital city when it comes to debt: In almost every European country the capital is the engine of the economy. But a new study shows there is one exception to this rule. The study by the Cologne Institute for Economic Research looked at how severely the income per head in a country would be hit if it had to survive without its capital. The results showed that across Europe, capital cities were the focal points of their countries’ economies. (..) If Berlin were cut adrift from the rest of the Bundesrepublik, the average German would become 0.2 percent wealthier. In 2015, the capital received €3.61 billion in subsidies, the most of any of the German states. The majority of this money came from wealthy Bavaria, which paid €5.45 billion of the total €9.6 billion which rich states gave to poorer ones, ARD reported in March. I am wondering why this exception? Question: Why does Berlin have debt issues in opposition to many other European capital cities?
Now provide the response and nothing else.
| During the Cold War, Germany was divided into three parts. There was the FRG, previously the US, UK and French occupation zones. There was the GDR, formerly the Soviet occupation zone and the Soviet sector of Berlin. And there were the three Western sectors of Berlin, legally not quite part of the FRG and not quite apart from it. Surface transport to West Berlin went through the GDR, which always complicated things. There were massive tax subsidies to keep West Berlin going as a shining beacon between the Communist lands. Yet industry did not go to West Berlin. With Reunification, East and West Berlin were reunified as well. The five East German states, the Neue Länder , are still economically weaker than the West German states. Berlin is a mixture between the two. In addition, there are a couple of "relatively small" issues which add up at the level of a city with 3 or 4 million people. A bank scandal in 2001 cost Berlin billions. Berlin provides "services" like museums, theaters, transportation hubs, and jobs to surrounding municipalities in Brandenburg. People who work in Berlin live in Brandenburg and pay taxes there. Berlin claims that running a capital has costs which are only partly compensated from the Federal budget. Embassies must be guarded. There are more political demonstrations than average. | {} | {'log_upvote_score': 5, 'links': ['https://politics.stackexchange.com/questions/41228', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/11278/']} | jdg_77953 |
stackexchange | llm_judgeable_groundtruth_similarity | 29219451 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm going through the neo4j server-extension example that is posted in github---and when running mvn package I get the "java.net.BindException:Address already in use" for port 7474 on the MovieServiceIntegrationTest. I've looked at the port through the commands 'lsof -i:7474' and 'netstat -n' and I do not see anything interfering. I've also tried on linux (initially on os X) and I get the same problem. What is the best next step to investigate the error? ------------------------------------------------------- T E S T S-------------------------------------------------------Running example.extension.movies.MovieServiceIntegrationTestserver.baseUri() = http://localhost:7474/05:46:21.067 [main] WARN o.e.j.server.handler.ContextHandler - o.e.j.s.ServletContextHandler@29314cc9{/,null,null} contextPath ends with /05:46:21.070 [main] WARN o.e.j.server.handler.ContextHandler - Empty contextPath05:46:21.078 [main] INFO org.eclipse.jetty.server.Server - jetty-9.0.5.v2013081505:46:21.133 [main] INFO o.e.j.server.handler.ContextHandler - Started o.e.j.s.h.MovedContextHandler@7b208b45{/,null,AVAILABLE}Mar 23, 2015 5:46:21 AM com.sun.jersey.api.core.PackagesResourceConfig initINFO: Scanning for root resource and provider classes in the packages: example.extension.moviesMar 23, 2015 5:46:21 AM com.sun.jersey.api.core.ScanningResourceConfig logClassesINFO: Root resource classes found: class example.extension.movies.MovieResourceMar 23, 2015 5:46:21 AM com.sun.jersey.api.core.ScanningResourceConfig initINFO: No provider classes found.Mar 23, 2015 5:46:21 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiateINFO: Initiating Jersey application, version 'Jersey: 1.9 09/02/2011 11:17 AM'05:46:21.588 [main] INFO o.e.j.server.handler.ContextHandler - Started o.e.j.s.ServletContextHandler@ba354ca{/movie,null,AVAILABLE}Mar 23, 2015 5:46:21 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiateINFO: Initiating Jersey application, version 'Jersey: 1.9 09/02/2011 11:17 AM'05:46:21.757 [main] INFO o.e.j.server.handler.ContextHandler - Started o.e.j.s.ServletContextHandler@7b4acdc2{/db/manage,null,AVAILABLE}Mar 23, 2015 5:46:21 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiateINFO: Initiating Jersey application, version 'Jersey: 1.9 09/02/2011 11:17 AM'05:46:21.957 [main] INFO o.e.j.server.handler.ContextHandler - Started o.e.j.s.ServletContextHandler@736048ed{/db/data,null,AVAILABLE}05:46:22.061 [main] INFO o.e.j.w.StandardDescriptorProcessor - NO JSP Support for /browser, did not find org.apache.jasper.servlet.JspServlet05:46:22.078 [main] INFO o.e.j.server.handler.ContextHandler - Started o.e.j.w.WebAppContext@64693226{/browser,jar:file:/Users/brianchase/.m2/repository/org/neo4j/app/neo4j-browser/2.1.4/neo4j-browser-2.1.4.jar!/browser,AVAILABLE}Mar 23, 2015 5:46:22 AM com.sun.jersey.server.impl.application.WebApplicationImpl _initiateINFO: Initiating Jersey application, version 'Jersey: 1.9 09/02/2011 11:17 AM'05:46:22.191 [main] INFO o.e.j.server.handler.ContextHandler - Started o.e.j.s.ServletContextHandler@29314cc9{/,null,AVAILABLE}05:46:22.251 [main] WARN o.e.j.u.component.AbstractLifeCycle - FAILED ServerConnector@3f985a86{HTTP/1.1}{localhost:7474}: java.net.BindException: Address already in usejava.net.BindException: Address already in use Port investigation (7474 neo4j server in listen): Computer:~ user$ lsof -i:7474COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAMEjava 421 user 137u IPv6 0x4c075845f5b86ccd 0t0 TCP localhost:7474 (LISTEN) Netstat: Active Internet connectionsProto Recv-Q Send-Q Local Address Foreign Address (state) tcp4 0 0 192.168.44.208.49303 65.115.96.238.80 SYN_SENT tcp4 0 0 192.168.44.208.49301 209.197.20.103.80 ESTABLISHEDtcp4 0 0 192.168.44.208.49300 4.31.28.74.80 ESTABLISHEDtcp4 164 0 192.168.44.208.49276 52.0.233.188.80 CLOSE_WAIT tcp4 0 0 192.168.44.208.49208 108.160.170.34.80 ESTABLISHEDtcp4 37 0 192.168.44.208.49186 108.160.165.211.443 CLOSE_WAIT tcp4 37 0 192.168.44.208.49185 108.160.165.211.443 CLOSE_WAIT tcp4 37 0 192.168.44.208.49184 108.160.165.211.443 CLOSE_WAIT tcp4 37 0 192.168.44.208.49183 108.160.165.211.443 CLOSE_WAIT tcp4 0 0 192.168.44.208.49178 17.172.233.120.5223 ESTABLISHEDtcp4 0 0 192.168.44.208.49177 17.110.227.101.5223 ESTABLISHEDtcp4 37 0 192.168.44.208.49170 108.160.166.141.443 CLOSE_WAIT udp4 0 0 *.58920 *.* udp4 0 0 *.17500 *.* udp4 0 0 *.53249 *.* udp4 0 0 192.168.44.208.123 *.* udp6 0 0 fe80::2ef0:eeff:.123 *.* udp6 0 0 fe80::8402:97ff:.123 *.* udp6 0 0 fe80::1%lo0.123 *.* udp4 0 0 127.0.0.1.123 *.* udp6 0 0 ::1.123 *.* udp6 0 0 *.123 *.* udp4 0 0 *.123 *.* udp6 0 0 *.5353 *.* udp4 0 0 *.5353 *.* udp4 0 0 *.* *.* udp4 0 0 *.58003 *.* udp4 0 0 *.* *.* udp4 0 0 *.* *.* udp4 0 0 *.* *.* udp4 0 0 *.* *.* udp6 0 0 *.5353 *.* udp4 0 0 *.* *.* udp4 0 0 *.* *.* udp4 0 0 *.* *.* udp4 0 0 *.* *.* udp4 0 0 *.* *.* udp4 0 0 *.* *.* udp6 0 0 *.5353 *.* udp4 0 0 *.5353 *.* udp46 0 0 *.* *.* udp4 0 0 *.* *.* udp4 0 0 *.* *.* udp4 0 0 *.* *.* udp4 0 0 *.* *.* udp4 0 0 *.* *.* udp4 0 0 *.* *.* udp4 0 0 *.* *.* udp4 0 0 *.* *.* udp4 0 0 *.* *.* udp46 0 0 *.* *.* udp4 0 0 *.* *.* udp4 0 0 *.* *.* udp4 0 0 *.137 *.* udp4 0 0 *.138 *.*
Now provide the response and nothing else.
| I was wondering if there is anything like a VB's Step n You have the right C# equivalent: for (int i = 0; i < x; i += 2) What if I want to change a loop that increments i BEFORE it goes into it I may be missing something, but it sounds like you just want to change your starting value: for (int i = 1; i < x; i++) Also note that: using ++i or i++ makes no real difference here, since you're not doing anything with the return value within the for statement, which is the only difference between using ++i and i++ you can't do the following: i += 2;for (int i = 0; i < x; i += 2) because you can't re-declare i as part of the for loop if it;'s already declared outside of the loop. EDIT The for loop for (initializer; condition; iterator) is functionally equivalent to: { initializer; while(condition) { .. do something iterator; }} It sounds like you want some sort of for loop that is equivalent to: { initializer; while(condition) { iterator; .. do something }} there is no such single-statement construct in C#. If you want that series of events you'll have to use a while loop like the above or change the statements in your for loop to provide equivalent functionality. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29219451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4700218/']} | jdg_77954 |
stackexchange | llm_judgeable_groundtruth_similarity | 825194 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to run a script which exists as visible by ls but when I try to run it, it says "No such file or directory" What gives? root@rx-texas:/home/7days/linux32#root@rx-texas:/home/7days/linux32# lslibstdc++.so.6 steamcmdroot@rx-texas:/home/7days/linux32# ./steamcmd-bash: ./steamcmd: No such file or directoryroot@rx-texas:/home/7days/linux32# less steamcmd"steamcmd" may be a binary file. See it anyway? I'm running 64-bit Debian but the file is linux32 could it be related? Also here is the output of ls -la : drwxrwxrwx 2 7days 7days 4096 Apr 22 2013 .drwxrwxrwx 3 7days 7days 4096 Jan 9 22:44 ..-rwxrwxrwx 1 7days 7days 3807525 Apr 22 2013 libstdc++.so.6-rwxrwxrwx 1 7days 7days 5642610 Feb 5 2013 steamcmd output of ldd steamcmd : not a dynamic executable
Now provide the response and nothing else.
| I'm running 64-bit debian but the file is linux32 could it be related? It's not only related, but is the direct cause of the error. When you try to run 32-bit executable on a 64-bit system without support for 32-bit runtime installed, this misleading error is displayed. It is not the ./steamcmd that is missing, but its loader. For a detailed explanation see the answer under Getting "Not found" message when running a 32-bit binary on a 64-bit system on Unix.SE. The suggested solution for Debian is to install multi-architecture support with: dpkg --add-architecture i386 && apt-get update | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/825194', 'https://serverfault.com', 'https://serverfault.com/users/118957/']} | jdg_77955 |
stackexchange | llm_judgeable_groundtruth_similarity | 2611747 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have site running rails application and resque workers running in production mode, on Ubuntu 9.10, Rails 2.3.4, ruby-ee 2010.01, PostgreSQL 8.4.2 Workers constantly raised errors: PGError: server closed the connection unexpectedly. My best guess is that master resque process establishes connection to db (e.g. authlogic does that when use User.acts_as_authentic), while loading rails app classes, and that connection becomes corrupted in fork()ed process (on exit?), so next forked children get kind of broken global ActiveRecord::Base.connection I could reproduce very similar behaviour with this sample code imitating fork/processing in resque worker. (AFAIK, users of libpq recommended to recreate connections in forked process anyway, otherwise it's not safe ) But, the odd thing is that when I use pgbouncer or pgpool-II instead of direct pgsql connection, such errors do not appear. So, the question is where and how should I dig to find out why it is broken for plain connection and is working with connection pools? Or reasonable workaround?
Now provide the response and nothing else.
| After doing a bit of research / trial and error. For anyone who is coming across the same issue. To clarify what gc mentioned. Resque.after_fork = Proc.new { ActiveRecord::Base.establish_connection } Above code should be placed in: /lib/tasks/resque.rake For example: require 'resque/tasks'task "resque:setup" => :environment do ENV['QUEUE'] = '*' Resque.after_fork do |job| ActiveRecord::Base.establish_connection endenddesc "Alias for resque:work (To run workers on Heroku)"task "jobs:work" => "resque:work" Hope this helps someone, as much as it did for me. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2611747', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/313262/']} | jdg_77956 |
stackexchange | llm_judgeable_groundtruth_similarity | 24840033 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
sorry for asking you a stupid question, but I just can't figure out why I keep on getting this output.So here is my code: #include <cstdio>#include <iostream>using namespace std;unsigned n = 4242;int getRemainderOf(int m, int n, int& quotient);static int l = 0; int main(){ int quotient; // the value of which should be changed after calling the func. for(int i=-1; i<=1; ++i) { for(int j=-1; j<=1; ++j) { if( i && j ) { cout << "("<< i*3 << "," << j*7 << ") " <<( getRemainderOf(i*3, 7*j, quotient) ) << " " << quotient <<endl; cout << "("<< i*7 << "," << j*3 << ") " << getRemainderOf(i*7, 3*j, quotient) << " "; cout << quotient <<endl; } } } return 0;}int getRemainderOf(int m, int n, int& quotient){ ++l; cout << l <<endl; quotient = m / n; cout << " quotient " << quotient <<endl; return m % n;} so what I expected to see in the first line of my output was the remainder and then the quotient that I get after calling the function getRemainderOf(). But instead when I cout the value of quotient like that I see that the value of quotient is a garbage value. So the value of the variable is not changed even though I've passed it to the function by using reference.The funny thing is that if I cout the remainder (got by calling the function) and the quotient separately I will get it right.I see that the problem might be in calling the function as a argument of the operator << function but I don't get it why the value of the quotient isn't changed since I call the function before I output it. This operator's associativity is left-to-right so what's wrong?So could you please tell me what is the reason of this output.
Now provide the response and nothing else.
| After creating a target such as a library or executable, put a line like this in your CMakeLists.txt file: set_property(TARGET tgt PROPERTY C_STANDARD 99) where tgt is the name of your target. I think this was added in CMake 3.1, and the documentation is here: http://www.cmake.org/cmake/help/latest/prop_tgt/C_STANDARD.html If you need to support versions of CMake older than 3.1, you can use this macro: macro(use_c99) if (CMAKE_VERSION VERSION_LESS "3.1") if (CMAKE_C_COMPILER_ID STREQUAL "GNU") set (CMAKE_C_FLAGS "-std=gnu99 ${CMAKE_C_FLAGS}") endif () else () set (CMAKE_C_STANDARD 99) endif ()endmacro(use_c99) After putting that macro in your top-level file so it is visible everywhere, you can just write use_c99() at the top of any CMakeLists file that defines a target with C99 code in it. CMake issue #15943 for clang users targeting macOS If you are using CMake and clang to target MacOS there is a bug that can cause the CMAKE_C_STANDARD feature to simply not work (not add any compiler flags). Make sure that you do one of the following things: Use cmake_minimum_required to require CMake 3.0 or later, or Set policy CMP0025 to NEW with the following code at the top of your CMakeLists.txt file before the project command: # Fix behavior of CMAKE_C_STANDARD when targeting macOS. if (POLICY CMP0025) cmake_policy(SET CMP0025 NEW) endif () | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24840033', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3576192/']} | jdg_77957 |
stackexchange | llm_judgeable_groundtruth_similarity | 15063890 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm a beginner in CodeIgniter and OOP. I was reading a page of CI tutorial here . I found something that made a question in my mind. Look at this code: <?phpclass News extends CI_Controller { public function __construct() { parent::__construct(); $this->load->model('news_model'); } I think if we made a class that extends CI_Controller, we assume it must have all methods and properties in its parent class (Although we can override them). So, why there is parent::__construct(); in the code?
Now provide the response and nothing else.
| __construct() is the constructor method of a class. It runs if you declare a new object instance from it. However, if a class implemented its own __construct() , PHP would only run the constructor of itself, not of its parent. For example: <?phpclass A { public function __construct() { echo "run A's constructor\n"; }}class B extends A { public function __construct() { echo "run B's constructor\n"; }}// only B's constructor is invoked// show "run B's constructor\n" only$obj = new B();?> In this case, if you need to run class A's constructor when $obj is declared, you'll need to use parent::__construct() : <?phpclass A { public function __construct() { echo "run A's constructor\n"; }}class B extends A { public function __construct() { parent::__construct(); echo "run B's constructor\n"; }}// both constructors of A and B are invoked// 1. show "run A's constructor\n"// 2. show "run B's constructor\n"$obj = new B();?> In CodeIgniter's case, that line runs the constructor in CI_Controller. That constructor method should have helped your controller codes in some way. And you'd just want it to do everythings for you. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15063890', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/789090/']} | jdg_77958 |
stackexchange | llm_judgeable_groundtruth_similarity | 9745853 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to get this to crossfade, but I'm not entirely sure how. How can I make this jQuery method crossfade the images? $('a.thumb').click(function () { var src = $(this).attr('href'); if (src != $('div#imageDisplay > img').attr('src')) { $('div#imageDisplay > img').stop().animate({ opacity: '0', duration: 500 }, function () { $(this).attr('src', src); }).load(function () { $(this).stop().animate({ opacity: '1', duration: 500 }); }); } return false;});
Now provide the response and nothing else.
| A cross fade between two images (where one fades out and the other fades in) requires two images, each with their own animation. You can't do it with just one image tag. You will need two images. There are ways to use a background image for one of the images, but frankly that's just more complicated than using two <img> tags. Here's some jQuery that implements a cross fade using two image tags: // precache all images so they will load on demandvar imgs = [];$('a.thumb').each(function() { var img = new Image(); img.src = this.href; imgs.push(img);}).click(function () { var oldImg = $("#fadeContainer img"); var img = new Image(); img.src = this.href; var newImg = $(img).hide(); $("#fadeContainer").append(img); oldImg.stop(true).fadeOut(500, function() { $(this).remove(); }); newImg.fadeIn(500); return false;}); You can see it work here: http://jsfiddle.net/jfriend00/frXyP/ This is basically how it works: Get the current image Create new image object Fetch URL from the clicked on link and assign to new image tag Hide the new image Insert the new image into the fadeContainer Initiate fadeOut of existing image and fadeIn or new image When fadeOut finishes, remove that image so it's ready for the next cycle | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9745853', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/124069/']} | jdg_77959 |
stackexchange | llm_judgeable_groundtruth_similarity | 45647928 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I tried using getString() to get a string from my string.xml However. I just found the getText() method can fetch HTML tags from my resources! Say: <string name="mySTring"><b><i>Hello Guys</i></b></string> it surprised me, because I had to use Html.fromHtml() to fetch the HTML tags - which is deprecated. Which is the difference between the two methods? Is there any advantage or disadvantage?
Now provide the response and nothing else.
| From the doc, For Resources.getString() : Return the string value associated with a particular resource ID. It will be stripped of any styled text information. For Resources.getText() : Return the string value associated with a particular resource ID. The returned object will be a String if this is a plain string; it will be some other type of CharSequence if it is styled. [Note that Context.getText() and Context.getString() internally calls the methods from Resources .] The doc says that getText() retains the styling while the getString() not. But you can use either one to get the string resource with HTML tags from strings.xml , but the way is different. Using Resources.getText(): strings.xml : <string name="styled_text">Hello, <b>World</b>!</string> You can just call getText() (note that it returns a CharSequence not a String , so it has the styling properties) and set the text to TextView . No need for Html.fromHtml() . mTextView.setText(getText(R.string.styled_text)); But the doc says only a limited HTML tags, such as <b>, <i>, <u> are supported by this method. The source code seems to suggest it supports more than that: <b>, <i>, <u>, <big>, <small>, <sup>, <sub>, <strike>, <li>, <marquee>, <a>, <font> and <annotation> Using Resources.getString(): strings.xml : <string name="styled_text"><![CDATA[Hello, <b>World</b>!]></string> You have to surround your string in a CDATA block and calling getString will return the string with HTML tags. Here you have to use Html.fromHtml() . mTextView.setText(Html.fromHtml( getString(R.string.styled_text))); Html.fromHtml() is deprecated in favor of a new method with flags parameter. So use it like this: HtmlCompat.fromHtml(getString(R.string.styled_text)) Implementation of the util method HtmlCompat.fromHtml : public class HtmlCompat { public static CharSequence fromHtml(String source) { if(Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { //noinspection deprecation return Html.fromHtml(source); } else { return Html.fromHtml(source, Html.FROM_HTML_MODE_COMPACT); } }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45647928', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7779786/']} | jdg_77960 |
stackexchange | llm_judgeable_groundtruth_similarity | 320285 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm really struggling to understand git , so here's a tighter rephrasing of a previous question I had asked. I'm going to explain a hypothetical scenario, detailing what I think happens when you download some code using git and install it on a machine, and hopefully somebody can tell me which part I am incorrect about! I run git clone git://github.com/foo/foo.git This creates a local directory foo , and downloads the source code and git data This source code effectively contains all the versions of the software: source files, header file, and git data for the different versions I run git checkout release-1.0 This tells my system that I want to deal with version 1.0 of the software I run make , which compiles the code for version 1.0 This creates a library called libfoo.so.1 I run make install , which installs the library This copies over libfoo.so.1 into the directory /usr/local/lib It also copies over the header file foo.h into the directory /usr/local/include This header file is the version of foo.h that corresponds to version 1.0 of the software I now also want to install version 2 of the software, so I run git checkout release-2.0 This tells my system that I want to deal with version 2.0 of the software I run make , which compiles the code for version 2.0 This creates a library called libfoo.so.2 I run make install , which installs the library This copies over libfoo.so.2 into the directory /usr/local/lib It also copies over the header file foo.h into the directory /usr/local/include This header file is the version of foo.h that corresponds to version 2.0 of the software I now try to create a project which depends on version 2.0 of the software, and link it to libfoo.so.2 which is at /usr/local/lib , and include foo.h which is at /usr/local/include This project compiles and runs fine I now try to create a project which depends on version 1.0 of the software, and link it to libfoo.so.1 which is at /usr/local/lib , and include foo.h which is at /usr/local/include This project does not compile ok, because foo.h is the header file for version 2.0 of the software, not version 1.0. So, the thing I am puzzled about is how you can have two versions of some software installed on your machine. The actual library files libfoo.so.1 and libfoo.so.2 are both created and can be linked to by two different projects, but there is only one version of foo.h installed on the local machine. Therefore, only the version which was installed the latest will have the correct header file, because the two versions require different versions of foo.h . Please can somebody explain where I am getting confused? Thanks!
Now provide the response and nothing else.
| It's not a git problem at all. In fact, it has nothing to do with Git or even a program you're trying to install. It's just a version conflict. To solve this type of problems, there are many possible approaches: Installing each version in a separate virtual machine ... in a separate Docker containers Using smart package managers like nix which would allow you to have any number of versions of a same program installed probably something else... In cases like this, I prefer use Docker since its' containers are lightweight (compared to virtual machines). This way, I can have any kind of environment to build and run any program. Any dependencies are installed directly in a container, so when I run my build against it, everything is already there, and my host machine is not polluted with random software. Regarding to your approach with Git. You're doing it right, but it would work anyway exactly because you can't have two versions of a same header file simultaneously. You seem to understand the problem. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/320285', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/231073/']} | jdg_77961 |
stackexchange | llm_judgeable_groundtruth_similarity | 10245 |
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Why is weight of 1 mole of substance equal to atomic/molecular mass in grams? According to me, it happens because mole has been defined in such a way. It is defined as the numbers of particles in $\pu{12 g}$ of $\ce{^{12}C}$. If it were $\pu{24 g}$ instead of $\pu{12 g}$, then the weight of 1 mole of substance would equal 2 times the atomic/molecular mass in grams. Please correct me if I am wrong somewhere (or maybe everywhere).
Now provide the response and nothing else.
| Why is weight of 1 mole of substance equal to atomic/molecular mass in grams? According to me, it happens because mole has been defined in such a way. Yes! That is correct. It is defined as the numbers of particles in 12 g of C12. If it were 24 g, instead of 12 g, then the weight of 1 mole of substance would equal 2 times the atomic/molecular mass in grams. Also correct, assuming that the definition of unified atomic mass units (amu) remained the same. @Martin's answer is correct, but we can also arrive at the same conclusion using a simple dimensional analysis approach. First we need the definition of an amu: $$\pu{1 atom}~ \ce{^12C} = \pu{12 amu}$$ Now take the real definition of a mole: $$\pu{1 mol}~ \ce{^12C} = \pu{12 g}$$ Now, divide the first equation by the second: $$\frac{\pu{1 atom}~ \ce{^12C}}{\pu{1 mol}~ \ce{^12C}} = \frac{\pu{12 amu}}{\pu{12 g}}$$ Cross-multiply and reduce: $$1~\frac{\pu{g}}{\pu{mol}~ \ce{^12C}} = 1~\frac{\pu{amu}}{\pu{atom}~ \ce{^12C}}$$ What this tells us is that the ratio of g/mol to amu/atom is exactly one - and we made sure it would work out that way by carefully choosing how we defined moles and amus. Since the masses of all elements are defined in terms of amu, which are ultimately based on the mass relative to carbon-12, this ratio holds for all any atom or molecule. Let's take it further and put in your hypothetical doubling of the number of grams of carbon-12 per mole: $$\frac{\pu{1 atom}~ \ce{^12C}}{\pu{1 mol}~ \ce{^12C}} = \frac{\pu{12 amu}}{\pu{24 g}}$$ Now when we cross-multiply and reduce, we get: $$2~\frac{\pu{g}}{\pu{mol}~ \ce{^12C}} = 1~\frac{\pu{amu}}{\pu{atom}~ \ce{^12C}}$$ Since we kept the definition of an amu the same, but changed that of the mole, what we see is that 1 mole of carbon-12 using these units would have to weigh 24 g (the molar mass ), even though its atomic mass would still be 12. That's a lot harder to keep track of mentally, and so it is a good thing for us that the definitions of amus and moles were chosen so carefully! | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/10245', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/2586/']} | jdg_77962 |
stackexchange | llm_judgeable_groundtruth_similarity | 28905131 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there an ActivityIndicator (or something like it) in WatchKit for Apple Watch? How do you all give the user feedback about some longer lasting background activity?
Now provide the response and nothing else.
| Edit : This answer was originally posted prior to the introduction of Apple Watch models with cellular and wifi connectivity, and thus may no longer apply on newer models of the device (considering significant performance improvements). This thread on the Apple Developer forums has an authoritative answer from an Apple engineer about why you shouldn't be performing network operations with Apple Watch. There are two big reasons not to perform networking operations from your watch app / extension: Users are interacting with their watches for only a brief period of time. See the Human Interface guidelines on this one. If you measure interactions with your iOS app in minutes, you can expect interactions with your WatchKit app to be measured in seconds. So interactions should be brief and interfaces should be simple. The system may deadlock if the network request does not complete. Our recommendation is that, in general, you should not perform complex networking operations inside a WatchKit Extension... [Apple recommends that developers] have a single process that is in charge of updating the information in your database (likely your iOS app), and then your extensions would have (essentially) read-only access to this [cached] database.... That being said. If you really need a UIActivityIndicator, rdar://19363748 (I don't think this one has been open radar-ed yet), developers have already filed requests for official support. You can create a series of images in the activity indicator style of your choice and then animate them using the startAnimatingWithImagesInRange:duration:repeatCount: API. See Apple's Lister app for an example of wkinterfaceimage animation. Alternatively, look here for a WatchKit Animation tutorial and included "spinner" graphics . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28905131', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/727742/']} | jdg_77963 |
stackexchange | llm_judgeable_groundtruth_similarity | 4557356 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a project that takes about 8 seconds to link with g++ and ld. It uses a bunch of static libraries, most of the code is c++. I'm interested in a general list of tips on how to reduce link time.Anything from "dont include debug symbols" to "make your code less spagetti"
Now provide the response and nothing else.
| I dealt with this for years at a previous job. The GNU linker simply has serious performance problems when linking large numbers of static libraries. At one point, link time was on par with compile time, which we found so strange we actually investigated this and figured it out. You can try to merge your static libraries into a "super-object" before linking. Instead of linking like this: $ g++ -o program program.o $STATIC_LIBS You could try this: $ ld -r -o libraries.o --whole-archive $STATIC_LIBS$ g++ -o program program.o libraries.o Note that this method gives the linker less opportunity to exclude unused object code, so your binaries may increase in size somewhat. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4557356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47901/']} | jdg_77964 |
stackexchange | llm_judgeable_groundtruth_similarity | 4269069 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Strange things happen when i try to find the cube root of a number. The following code returns me undefined. In cmd : -1.#IND cout<<pow(( double )(20.0*(-3.2) + 30.0),( double )1/3) While this one works perfectly fine. In cmd : 4.93242414866094 cout<<pow(( double )(20.0*4.5 + 30.0),( double )1/3) From mathematical way it must work since we can have the cube root from a negative number.Pow is from Visual C++ 2010 math.h library. Any ideas?
Now provide the response and nothing else.
| pow(x, y) from <cmath> does NOT work if x is negative and y is non-integral. This is a limitation of std::pow , as documented in the C standard and on cppreference : Error handling Errors are reported as specified in math_errhandling If base is finite and negative and exp is finite and non-integer, a domain error occurs and a range error may occur. If base is zero and exp is zero, a domain error may occur. If base is zero and exp is negative, a domain error or a pole error may occur. There are a couple ways around this limitation: Cube-rooting is the same as taking something to the 1/3 power, so you could do std::pow(x, 1/3.) . In C++11, you can use std::cbrt . C++11 introduced both square-root and cube-root functions, but no generic n-th root function that overcomes the limitations of std::pow . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4269069', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/419330/']} | jdg_77965 |
stackexchange | llm_judgeable_groundtruth_similarity | 90101 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am an undergraduate studying quantum physics with the book of Griffiths. in 1-D problems, it said a free particle has un-normalizable states but normalizable states can be obtained by sum up the solutions to independent Schrodinger equations. in my view the book also suggests that a scattering state with E>V(infinity) is to be un-normalizable. Is it true in 1-D situations? If so can it be generalized to 3-D situations? And why?
Now provide the response and nothing else.
| Neuneck's answer is the pithiest description of how you get normalisable states as superpositions of non-normalisable states, but the following is more of a "why" these states happen. Hopefully, you should see that this discussion is independent of the number of dimensions. Practically speaking, the reason why there are always such states it is because observables fulfilling the canonical commutation relationship $[X,P]=i\,\hbar\,I$ have eigenvectors which are non-normalisable. Actually there is no reason why we have to have eigenvectors, so at a deeper level, the basic reasons why there are always non-normalised states are (1) convenience - the need for wieldiness of mathematical description and (2) the mathematical ingenuity of the people who gave us this wieldy and handy mathematical description - most notably the genius of (in rough historical order), Paul Dirac, Laurent Schwartz, Alexander Grothendieck and Israel Gel'Fand. This discussion keeps the intuitive ideas of eigenvectors and other convenient tools on a unified and rigorous footing. Grounding Ideas The basic setting for quantum mechanics is Hilbert space, namely a complete (in the sense that every Cauchy sequence converges to a member of the space) vector space kitted with an inner product (Banach spaces are a weaker and more general concept - being complete vector spaces kitted simply with a norm. The norm in a Hilbert space comes from the inner product of a vector with itself). So, intuitively, it is a complex vector space like $\mathbb{C}^N$ with "no holes in it" so we can talk about limits and do calculussy kind of stuff without worrying whether limits exist and, wherein we can talk about linear superposition and wherein we can "resolve" vectors uniquely into components through the inner product. So it's pretty much the state space of any physical system, aside from being complex, which is slightly unusual. Now we look at the idea of a linear functional on a Hilbert space $\mathcal{H}$. This is simply a linear function $L:\mathcal{H}\to\mathbb{C}$ mapping the Hilbert space $\mathcal{H}$ to the underlying field (in this case $\mathbb{C}$. The inner product for some fixed "bra" $\ell\in\mathcal{H}$, namely the function $x\mapsto\left<\ell,x\right>$ is clearly a special case of this linear functional notion. However, in Hilbert space, every continuous linear functional can indeed be represented by a "fixed bra" inner product and, since every fixed bra inner product clearly induces a continuous linear functional, the ideas of continuous linear functional and inner product with a fixed bra are precisely the same notion : this equivalence does NOT hold in any old vector space. This key equivalence property is special to Hilbert spaces is the subject matter of the Riesz representation theorem (see Wiki page of this name) . So the continuous (topological) dual $\mathcal{H}^*$ of $\mathcal{H}$, being a poncy name for the vector space of continuous linear fucntionals on $\mathcal{H}$, is isomorphic to the original Hilbert space . It can be shown to be an alternative and altogether equivalent definition of "Hilbert space" as the one above (i.e. a complete inner product space) is: An inner product space which is isomorphic to its dual space of continuous linear functionals . All this is very slick and attractive for describing things like quantum mechanics. It is also very easy in finite dimensional quantum systems, such as e.g. an electron constrained to a being a superposition of spin up and down states. In finite dimensions, there is no difference at all between the notions of continuous linear functional and the more general one of simply a linear functional (*i.e. without to heed to continuity). Rigging the Hilbert Space: Nonnormalisable States In infinite dimensions - as with the quantum state space of the harmonic oscillator or the electron bound to a potential, we meet a glitch: Not all linear functionals are continuous. OOOPS: so just as we covet our neighbour's iPhone 5 when we have "only" model 4, so too we covet a stronger concept than Hilbert space wherein a software upgrade would make all "useful" linear functionals continuous! Less flippantly, here is where we get practical. In quantum mechanics, we need to implement the Heisenberg uncertainty principle, so we need Hermitian observables $\hat{X}$ and $\hat{P}$ fulfilling the canonical commutation relationship (CCR) $[\hat{X},\,\hat{P}]=i\,\hbar\,I$ (see my answer here and here ). It's not too hard to show that a quantum space truly implementing the HUP cannot be finite dimensional - if it were, then $\hat{X}$ and $\hat{P}$ would have square matrix representations and the Lie bracket $[\hat{X}, \hat{P}]$ between any pair of finite square matrices has a trace of nought, whereas the right hand side of the CCR certainly does not have zero trace. So we consider them to be operators on the Hilbert space $\mathbf{L}^2(\mathbb{R}^N)$, which is a Hilbert space with dimensionality $\aleph_0$, i.e. it has countably infinite basis vectors, for example, the eigenfunctions of the $N$-dimensional harmonic oscillator. Vectors in this Hilbert space are "everyday wavefunctions" $\psi:\mathbb{R}^N\to\mathbb{R}^N$ as conceived by Schrödinger with the crucial normalisability property: $$\int\limits_{\mathbb{R}^N} |\psi(\vec{x})|^2\,{\rm d}^N x < \infty$$ Now, for convenience, we want to work in co-ordinates wherein one of $\hat{X}$ and $\hat{P}$ is the simple multiplication operator $X \psi(x) = x\,\psi(x)$. In my answer here I show that this means that there are co-ordinates where $X \psi(x) = x\,\psi(x)$ and, needfully $\hat{P} \psi(x) = -i\,\hbar \,{\rm d}_x \psi(x)$. However, neither of these operators is defined on our whole Hilbert space $\mathcal{H} = \mathbf{L}^2(\mathbb{R}^N)$: there are vectors (functions) $f$ in $\mathbf{L}^2(\mathbb{R}^N)$ ( e.g. functions with jump discontinuities) which have no defined $P\,f\in\mathcal{H}$, owing to the derivative's being undefined at the discontinuity. Likewise, some normalisable functions $g$ have no defined $X\,g\in\mathcal{H}$; multiplication by $\vec{x}$ makes them unnormalisable (witness for example the function $f(x) = (1+x^2)^{-1}$). Furthermore, neither of these functions has eigenvectors in $\mathcal{H}$: if $X\,f(x) = \lambda f(x) = x f(x)\,\forall x\in\mathbb{R}$ then $f(x) = 0$ for $x\neq\lambda$ and the eigenfunction $e^{i\,k\,x}$ of $P$ is not normalisable. But we want to salvage the idea of eigenstates and still be able to write our states in position or momentum co-ordinates. Here is where the notion of Rigged Hilbert Space comes in - the ingenious process where we kit a dense subset $S\subset H$ of the original Hilbert space $H$ ("rig it") with a stronger topology, so that things like the Dirac delta are included in the topological dual space $S^*$ where $S\subset H\subset S^*$. For QM we take the dense subset $S$ to be the "smooth" functions that still belong to $\mathcal{H}$ when mapped by any member of the algebra of operators generated by $X$ and $P$. That is, $S$ is invariant under this algebra and comprises precisely the Schwartz space of functions than can be multiplied by any polynomial and differentiated any number of times and still belong to $\mathcal{H}$. Any function in $\mathcal{H}$ can be arbitrarily well approximated (with respect to the Hilbert space norm) by some function in $S$. At the same time, we kit the dense subset $S$ out with a stronger topology than the original Hilbert space one. Why do we do this? One of the basic problems with $\mathcal{H}$ is that the Dirac delta $\delta:\mathbf{L}^2(\mathbb{R})\to \mathbb{C};\;\delta\;f(x) = f(0)$, which can be construed as an eigenvector of $X$, is not a continuous linear functional on $\mathcal{H}$ even though of course it is a linear functional. To see this, consider the image of $f(x) + \exp(-x^2/(2 \sigma^2)$ under the delta funcional: we can choose a $\sigma$ to make this function arbitrarily near to $f(x)$ as measured by the $\mathbf{L}^2$ norm, but with images $f(0)$ and $f(0)+1$, respectively, under the Dirac $\delta$. So we kit the dense subset $S$ out a topology that is strong enough to "ferret out" all useful linear functionals and make them continuous. We now have a topological dual (space of all linear functionals continuous with respect to the stronger topology) $S^*$ of $S$ such that $S\subset\mathcal{H} = \mathcal{H}^*\subset S^*$. $S^∗$ is the space of tempered distributions as discussed in my answer here . $S^∗$ includes the Dirac delta, $e^{i\,k\,x}$ and is bijectively, isometrically mapped onto itself by the Fourier transform. Intuitively, functions and their Fourier transforms are precisely the same information for the tempered distributions. This ties in with the fact that position and momentum co-ordinate are mapped into each other by the Fourier transform and its inverse. So there we have it. We now have a space of bras $S^*$ that is strictly bigger than the space of kets $\mathcal{H}$ and it needfully includes, by the construction of the rigged Hilbert space, nonnormalisable bras in $S^*\sim\mathcal{H}$ simply so that we can discuss eigenstates of all the observables we need in a rigorous way. Good references for these notion are: This answer to the Physics Stack Exchange question "Rigged Hilbert space and QM" and also The discussions under the Math Overflow Question "Good references for Rigged Hilbert spaces?" In the latter, Todd Trimble's suspicions are correct that the usual Gel'Fand triple is $S\subset H = \mathbf{L}^2(\mathbb{R}^N)\subset S^*$ with $S$ , $S^∗$ being the Schwartz space and tempered distributions as discussed in my answer here . The Wikipedia article on rigged Hilbert space is a little light on here: there's a great deal of detail about nuclear spaces that's glossed over so at the first reading I'd suggest you should take a specific example $S$ = Schwartz space and $S^∗$ = Tempered Distributions and keep this relatively simple (and, for QM most relevant) example exclusively in mind - for QM you won't need anything else. The Schwarz space and space of tempered distributions are automatically nuclear, so you don't need to worry too much about this idea at first reading. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/90101', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/35767/']} | jdg_77966 |
stackexchange | llm_judgeable_groundtruth_similarity | 21905169 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm playing around with java8 lambdas and I came across a compiler error which I didn't expect. Say I have a functional interface A , an abstract class B and a class C with overloaded methods that take either A or B as arguments: public interface A { void invoke(String arg); }public abstract class B { public abstract void invoke(String arg); }public class C { public void apply(A x) { } public B apply(B x) { return x; }} Then I can pass a lambda into c.apply and it is correctly resolved to c.apply(A) . C c = new C();c.apply(x -> System.out.println(x)); But when I change the overload that takes B as argument to a generic version the compiler reports that the two overloads are ambiguous. public class C { public void apply(A x) { } public <T extends B> T apply(T x) { return x; }} I thought the compiler would see that T has to be a subclass of B which is not a functional interface. Why can't it resolve the correct method?
Now provide the response and nothing else.
| There is a lot of complexity at the intersection of overload resolution and type inference. The current draft of the lambda specification has all the gory details. Sections F and G cover overload resolution and type inference, respectively. I don't pretend to understand it all. The summary sections in the introduction are fairly understandable, though, and I recommend that people read them, particularly the summaries of sections F and G, to get an idea of what's going on in this area. To recap the issues briefly, consider a method call with some arguments in the presence of overloaded methods. Overload resolution has to choose the right method to call. The "shape" of the method (arity, or number of arguments) is most significant; obviously a method call with one argument can't resolve to a method that takes two parameters. But overloaded methods often have the same number of parameters of different types. In this case, the types start to matter. Suppose there are two overloaded methods: void foo(int i); void foo(String s); and some code has the following method call: foo("hello"); Obviously this resolves to the second method, based on the type of the argument being passed. But what if we are doing overload resolution, and the argument is a lambda? (Especially one whose types are implicit, that relies on type inference to establish the types.) Recall that a lambda expression's type is inferred from the target type, that is, the type expected in this context. Unfortunately, if we have overloaded methods, we don't have a target type until we've resolved which overloaded method we're going to call. But since we don't yet have a type for the lambda expression, we can't use its type to help us during overload resolution. Let's look at the example here. Consider interface A and abstract class B as defined in the example. We have class C that contains two overloads, and then some code calls the apply method and passes it a lambda: public void apply(A a) public B apply(B b) c.apply(x -> System.out.println(x)); Both apply overloads have the same number of parameters. The argument is a lambda, which must match a functional interface. A and B are actual types, so it's manifest that A is a functional interface whereas B is not, therefore the result of overload resolution is apply(A) . At this point we now have a target type A for the lambda, and type inference for x proceeds. Now the variation: public void apply(A a) public <T extends B> T apply(T t) c.apply(x -> System.out.println(x)); Instead of an actual type, the second overload of apply is a generic type variable T . We haven't done type inference, so we don't take T into account, at least not until after overload resolution has completed. Thus both overloads are still applicable, neither is most specific, and the compiler emits an error that the call is ambiguous. You might argue that, since we know that T has a type bound of B , which is a class, not a functional interface, the lambda can't possibly apply to this overload, thus it should be ruled out during overload resolution, removing the ambiguity. I'm not the one to have that argument with. :-) This might indeed be a bug in either the compiler or perhaps even in the specification. I do know that this area went through a bunch of changes during the design of Java 8. Earlier variations did attempt to bring more type checking and inference information into the overload resolution phase, but they were harder to implement, specify, and understand. (Yes, even harder to understand than it is now.) Unfortunately problems kept arising. It was decided to simplify things by reducing the range of things that can be overloaded. Type inference and overloading are ever in opposition; many languages with type inference from day 1 prohibit overloading (except maybe on arity.) So for constructs like implicit lambdas, which require inference, it seems reasonable to give up something in overloading power to increase the range of cases where implicit lambdas can be used. -- Brian Goetz, Lambda Expert Group, 9 Aug 2013 (This was quite a controversial decision. Note that there were 116 messages in this thread, and there are several other threads that discuss this issue.) One of the consequences of this decision was that certain APIs had to be changed to avoid overloading, for example, the Comparator API . Previously, the Comparator.comparing method had four overloads: comparing(Function) comparing(ToDoubleFunction) comparing(ToIntFunction) comparing(ToLongFunction) The problem was that these overloads are differentiated only by the lambda return type, and we actually never quite got the type inference to work here with implicitly-typed lambdas. In order to use these one would always have to cast or supply an explicit type argument for the lambda. These APIs were later changed to: comparing(Function) comparingDouble(ToDoubleFunction) comparingInt(ToIntFunction) comparingLong(ToLongFunction) which is somewhat clumsy, but it's entirely unambiguous. A similar situation occurs with Stream.map , mapToDouble , mapToInt , and mapToLong , and in a few other places around the API. The bottom line is that getting overload resolution right in the presence of type inference is very difficult in general, and that the language and compiler designers traded away power from overload resolution in order to make type inference work better. For this reason, the Java 8 APIs avoid overloaded methods where implicitly typed lambdas are expected to be used. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21905169', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3119615/']} | jdg_77967 |
stackexchange | llm_judgeable_groundtruth_similarity | 36591498 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an android app with renewable monthly subscriptions. In this app I want to notify user some info when his subcription continues in next month. As I can see renewals in merchant center(orderId ends with eg. ..0, ..1), but when querying the inventory my purchase orderId is same as befor eq. { "orderId": "GPA.XXXX-YYYY-XXXX-ZZZZZ", "packageName": "my.packageName", "productId": "my.sku", "purchaseTime": 1456398623654, "purchaseState": 0, "developerPayload": "mypayload", "purchaseToken": "token", "autoRenewing": true} What bothers me more is that purchaseTime also doesn't change. So my question is: If there is any way to detect in app that renewal occured? Edit: I'm using Google Play Developer API to get subscription info and then calculate number of renewals myself.
Now provide the response and nothing else.
| Order id for all recurrences are returned in orderId field of the INAPP_PURCHASE_DATA JSON field (in V3) with each recurring transaction appended by an integer. Subscription order numbers To help you track transactions relating to a given subscription, Google payments provides a base Merchant Order Number for all recurrences of the subscription and denotes each recurring transaction by appending an integer as follows: GPA.1234-5678-9012-34567 (base order number)GPA.1234-5678-9012-34567..0 (first recurrence orderID)GPA.1234-5678-9012-34567..1 (second recurrence orderID)GPA.1234-5678-9012-34567..2 (third recurrence orderID) ... But due to local caching you might not get the latest information. So try clearing cache from application manager to first see if you get correct purchase information. Since purchase query this way is not reliable, it makes more sense to call Google Play Developer Purchases.subscriptions: get API from a backend to get Purchases.subscriptions resource which will return expiryTimeMillis of current subscription. { "kind": "androidpublisher#subscriptionPurchase", "startTimeMillis": long, "expiryTimeMillis": long, "autoRenewing": boolean, "priceCurrencyCode": string, "priceAmountMicros": long, "countryCode": string, "developerPayload": string, "paymentState": integer, "cancelReason": integer} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36591498', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/598641/']} | jdg_77968 |
stackexchange | llm_judgeable_groundtruth_similarity | 2625178 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm doing an INSERT INTO query in order to initialize a new table.The primary key is RFQ_ID and Action_Time How could add 1 millisecond to each Action_Time on a new record in order to avoid "Violation of PRIMARY KEY constraint" INSERT INTO QSW_RFQ_Log (RFQ_ID, Action_Time, Quote_ID)SELECT RFQ_ID, GETDATE() AS Action_Time, Quote_ID, 'Added to RFQ on Initialization' AS NoteFROM QSW_Quote
Now provide the response and nothing else.
| I think the real problem is that RFQ_ID, Action_Time shouldn't be a primary key. Create a surrogate primary key and put a non-unique index on RFQ_ID, Action_Time . Update : If you really want to stick with your existing design you could do what you asked but using 10 milliseconds instead of one millisecond between each row, to compensate for the low precision of datetime. You can use the row number to determine how many milliseconds to add so that you get a different timestamp for each row: INSERT INTO QSW_RFQ_Log(RFQ_ID, Action_Time, Quote_ID, Note)SELECT RFQ_ID, DATEADD(millisecond, 10 * ROW_NUMBER() OVER (ORDER BY Quote_ID), GETDATE()) AS Action_Time, Quote_ID, 'Added to RFQ on Initialization' AS NoteFROM QSW_Quote | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2625178', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/275404/']} | jdg_77969 |
stackexchange | llm_judgeable_groundtruth_similarity | 39485067 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I add users to a group in Django admin interface of "Change Group"? I have seen dirty hacks to get this working for older django version. How to solve this with Django 1.10? Emphasize: I want this on the page "Change Group", not on "Change User". I would like to have this in django-admin-style: No coding, just doing some configuration. Maybe like this: class GroupAdmin(admin.ModelAdmin): show_reverse_many_to_many = ('user',)
Now provide the response and nothing else.
| You need to write some code. Note that the Django admin site is normal Django views and forms! First create a ModelForm: from django import formsfrom django.contrib import adminfrom django.contrib.auth import get_user_modelfrom django.contrib.admin.widgets import FilteredSelectMultiple from django.contrib.auth.models import GroupUser = get_user_model()# Create ModelForm based on the Group model.class GroupAdminForm(forms.ModelForm): class Meta: model = Group exclude = [] # Add the users field. users = forms.ModelMultipleChoiceField( queryset=User.objects.all(), required=False, # Use the pretty 'filter_horizontal widget'. widget=FilteredSelectMultiple('users', False) ) def __init__(self, *args, **kwargs): # Do the normal form initialisation. super(GroupAdminForm, self).__init__(*args, **kwargs) # If it is an existing group (saved objects have a pk). if self.instance.pk: # Populate the users field with the current Group users. self.fields['users'].initial = self.instance.user_set.all() def save_m2m(self): # Add the users to the Group. self.instance.user_set.set(self.cleaned_data['users']) def save(self, *args, **kwargs): # Default save instance = super(GroupAdminForm, self).save() # Save many-to-many data self.save_m2m() return instance We added a custom Group ModelForm. The second step is to unregister the original Group admin and register a new Group admin that displays our ModelForm: # Unregister the original Group admin.admin.site.unregister(Group)# Create a new Group admin.class GroupAdmin(admin.ModelAdmin): # Use our custom form. form = GroupAdminForm # Filter permissions horizontal as well. filter_horizontal = ['permissions']# Register the new Group ModelAdmin.admin.site.register(Group, GroupAdmin) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/39485067', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/633961/']} | jdg_77970 |
stackexchange | llm_judgeable_groundtruth_similarity | 1120725 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I need some help proving that $X=\{(x,x)~|~x \in \mathbb{R}, x \neq 1\}$ is not an affine variety. I would like to proceed by supposing it is an affine variety and then finding a contradiction. So assume $X=V(f_1,...,f_s)$. Now I want to show that if $f \in \mathbb{R}[x,y]$ vanishes on $X$ then $f$ also vanishes at the point $(1,1)$. I have thought about how to proceed form here for about an hour now and have not got anywhere. Please help. Thanks
Now provide the response and nothing else.
| Here is an alternative to the above answers with a more algebra-y flavor. (For those interested, this is exercise 1.2.8 of Cox, Little, and O'Shea.) Given $f(x,y) \in \mathbb{V}(X)$, let $g(t) = f(t,t)$. Then $g \in \mathbb{R}[t]$ vanishes on $\mathbb{R} \setminus \{1\}$. But a nonzero polynomial of one variable over a field has only finitely many roots, so we must have $g=0$. Then $f(1,1) = g(1) = 0$, so $f$ vanishes at $(1,1)$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1120725', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/151852/']} | jdg_77971 |
stackexchange | llm_judgeable_groundtruth_similarity | 15113272 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following example, to explain better what i'm trying to do: String text = "a,b,,,,c,,";String[] split = text.split(",");for(int i=0;i<split.length;i++){ System.out.println("I = "+i+" "+split[i]);} The output is: I = 0 aI = 1 bI = 2 I = 3 I = 4 I = 5 c But, what i want is to get an array of size 8, containing also: I = 6 I = 7 Of course, the last 2 elements will be empty strings, but it is essential for me to get them. Also, i think it's logical to have them. I mean, if i had: String text = "a,b,,,,c,,d"; The result would be an array of size 8 and i don't think there is a big difference between the 2 examples.
Now provide the response and nothing else.
| String[] split = text.split(",", -1); This behavior actually looks tricky but it is actually explained (not very well IMHO, that said) in the official documentation . If n is non-positive then the pattern will be applied as many times as possible and the array can have any length The problem with text.split(",") is that it's equivalent to text.split(",", 0) . Using a 0 limit, as explained in the documentation: If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded . You definitely do not want the empty strings to be discarded. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15113272', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1691018/']} | jdg_77972 |
stackexchange | llm_judgeable_groundtruth_similarity | 15582504 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a sorted container in the STL? What I mean is following: I have an std::vector<Foo> , where Foo is a custom made class. I also have a comparator of some sort which will compare the fields of the class Foo . Now, somewhere in my code I am doing: std::sort( myvec.begin(), myvec.end(), comparator ); which will sort the vector according to the rules I defined in the comparator. Now I want to insert an element of class Foo into that vector. If I could, I would like to just write: mysortedvector.push_back( Foo() ); and what would happen is that the vector will put this new element according to the comparator to its place. Instead, right now I have to write: myvec.push_back( Foo() );std::sort( myvec.begin(), myvec.end(), comparator ); which is just a waste of time, since the vector is already sorted and all I need is to place the new element appropriately. Now, because of the nature of my program, I can't use std::map<> as I don't have a key/value pairs, just a simple vector. If I use stl::list , I again need to call sort after every insertion.
Now provide the response and nothing else.
| Yes, std::set , std::multiset , std::map , and std::multimap are all sorted using std::less as the default comparison operation. The underlying data-structure used is typically a balanced binary search tree such as a red-black tree. So if you add an element to these data-structures and then iterate over the contained elements, the output will be in sorted order. The complexity of adding N elements to the data-structure will be O(N log N), or the same as sorting a vector of N elements using any common O(log N) complexity sort. In your specific scenario, since you don't have key/value pairs, std::set or std::multiset is probably your best bet. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15582504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/945871/']} | jdg_77973 |
stackexchange | llm_judgeable_groundtruth_similarity | 27966453 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Apple added a private helper _printHierarchy in iOS8 that can be used in LLDB console: po [[[UIWindow keyWindow] rootViewController] _printHierarchy] which prints out the whole view controller hierarchy in text form. This works only if you are debugging code on Objective C. In Swift, however, this doesn't work: (lldb) po [[[UIWindow keyWindow] rootViewController] _printHierarchy]error: <EXPR>:1:13: error: expected ',' separator[[[UIWindow keyWindow] rootViewController] _printHierarchy] ^ ,<EXPR>:1:24: error: expected ',' separator[[[UIWindow keyWindow] rootViewController] _printHierarchy] ^ ,<EXPR>:1:44: error: expected ',' separator[[[UIWindow keyWindow] rootViewController] _printHierarchy] ^ , An equivalent usage in Swift doesn't work either: po UIApplication.sharedApplication().keyWindow!.rootViewController!._printHierarchy ends up with an error (probably because _printHierarchy is a private property): (lldb) po UIApplication.sharedApplication().keyWindow!.rootViewController!._printHierarchy()error: <EXPR>:1:64: error: 'UIViewController' does not have a member named '_printHierarchy'UIApplication.sharedApplication().keyWindow!.rootViewController!._printHierarchy ^ ~~~~~~~~~~~~~~~ The question is: How to print out the view controller hierarchy in Swift? Or is there a way how to use ObjC in LLDB console even in Swift projects?
Now provide the response and nothing else.
| You point out how one shows the view controller hierarchy with: po [[[UIWindow keyWindow] rootViewController] _printHierarchy] You then say: This works only if you are debugging code on Objective C. In Swift, however, this doesn't work. Actually, this depends a little upon how you pause the execution of your Swift program. The issue is that the expression command (which po uses) will use Swift expressions in Swift frames, and Objective-C expressions in Objective-C frames. Thus this means that the po behavior varies depending upon how the execution pauses: You can, for example, press the "pause" button while the app is running: If you do this, you will be able to use the above po syntax with the Objective-C expression without incident. If, on the other hand, you set a breakpoint inside your Swift code, you'll be in a Swift frame when you get to the (lldb) prompt. But you can explicitly tell the expression command that you want to use the Objective-C syntax with the -l (or --language ) option: expr -l objc++ -O -- [[[UIWindow keyWindow] rootViewController] _printHierarchy] This ability to specify the language in the expr command is discussed in WWDC 2014 video Advanced Swift Debugging in LLDB . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/27966453', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1161723/']} | jdg_77974 |
stackexchange | llm_judgeable_groundtruth_similarity | 28350292 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm looking for a method for JavaScript that returns true or false when it's empty... something like Ruby any? or empty? [].any? #=> false[].empty? #=> true
Now provide the response and nothing else.
| JavaScript has the Array.prototype.some() method: [1, 2, 3].some((num) => num % 2 === 0); returns true because there's (at least) one even number in the array. In general, the Array class in JavaScript's standard library is quite poor compared to Ruby's Enumerable . There's no isEmpty method and .some() requires that you pass in a function or you'll get an undefined is not a function error. You can define your own .isEmpty() as well as a .any() that is closer to Ruby's like this: Array.prototype.isEmpty = function() { return this.length === 0;}Array.prototype.any = function(func) { return this.some(func || function(x) { return x });} Libraries like underscore.js and lodash provide helper methods like these, if you're used to Ruby's collection methods, it might make sense to include them in your project. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/28350292', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3622415/']} | jdg_77975 |
stackexchange | llm_judgeable_groundtruth_similarity | 4418703 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I develop an application which uses Core Data. In one UITableView, I want to display a list of my entities, sorted by the saved date of the objects. When I do this: fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:@"date" cacheName:nil]; I get for each object a new section because this code groups the dates according to the seconds, too. But I want a list of the objects, grouped by date, but only according to the day, month and year. Is it possible and how? Thank you very much for your help!! ;)
Now provide the response and nothing else.
| This should do the trick for you: - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { NSString *rawDateStr = [[[self.fetchedResultsController sections] objectAtIndex:section] name]; // Convert rawDateStr string to NSDate... NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease]; [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZ"]; NSDate *date = [formatter dateFromString:rawDateStr]; // Convert NSDate to format we want... [formatter setDateFormat:@"d MMMM yyyy"]; NSString *formattedDateStr = [formatter stringFromDate:date]; return formattedDateStr; } [EDIT] Jus saw your comment and for what you are trying to achieve, you could create a transient NSDate attribute (non persistent) that is formatted in a similar way to the above code (i.e. without H:mm:ss ZZZZ) and use that attribute as your sectionNameKeyPath value. So in a nutshell for a foo object, with fooDate and fooDateTransient attributes, you would: Get your foo.fooDate attribute Transform it using the code above (or similar) and assign the NSDate result to foo.fooDateTransient Use fooDateTransient as your sectionNameKeyPath when creating the fetchedResultsController object. PS: I haven't tested this myself but should be worth a shot! Good luck,Rog | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4418703', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/470630/']} | jdg_77976 |
stackexchange | llm_judgeable_groundtruth_similarity | 38399337 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a page which contains a form and few fields. My issues are as follow: I am trying to force jQuery UI datepicker to display below the input field. When I click in the input field, I want the field to scroll to the top of the page also. I think I have this working. Here is my jQuery: JQUERY: $( document ).ready(function() { // Set Datepicker $(".datepicker").datepicker(); $("input").focus(function () { $('html, body').animate({ scrollTop: $(this).offset().top - 25 }, 10); });}); Link to a fiddle: https://jsfiddle.net/MauriceT/0qfycgm1/10/ Here is what I want to avoid: Datepicker displays above the input field Any suggestions would be greatly appreciated. Thanks!
Now provide the response and nothing else.
| you can achieve your goal by setting the css of the date picker pop. Use the below code to set the CSS, the use of setTimeout is to avoid the overriding of the CSS. Here i am finding out the top and left of the date time picker text box and using these value to set the position of the date time picker popup On the information about beforeShow event check here. https://api.jqueryui.com/datepicker/#option-beforeShow $(".datepicker").datepicker({ beforeShow: function (input, inst) { setTimeout(function () { inst.dpDiv.css({ top: $(".datepicker").offset().top + 35, left: $(".datepicker").offset().left }); }, 0); }}); Here is the fiddle : https://jsfiddle.net/0qfycgm1/14/ | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38399337', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6542033/']} | jdg_77977 |
stackexchange | llm_judgeable_groundtruth_similarity | 14244390 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is for academic purposes, please no responses of "why would you want to do that" If I have a page called Home.aspx and it has a code behind Home.aspx.cs. In Home.aspx.cs I have some public properties, e.g. public string Name { get; set; } I have another page called Error.aspx Can I create an instance of Home.aspx.cs from within Error.aspx.cs and access the Name property? And if not, why not.
Now provide the response and nothing else.
| CountDistinct() counts non-null values, so you could use an expression to null out those values you don't want to count and do something similar to your first value. Type B+C: =CountDistinct( IIf ( Fields!Type.Value = "B" or Fields!Type.Value = "C" , Fields!ClientId.Value , Nothing ) , "datasource1") Type C: =CountDistinct( IIf ( Fields!Type.Value = "C" , Fields!ClientId.Value , Nothing ) , "datasource1") | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14244390', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1721823/']} | jdg_77978 |
stackexchange | llm_judgeable_groundtruth_similarity | 1083 |
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Take an ice cube for example. Heat is applied in a closed container until it is vaporized completely. Will the molecule's size be larger (on average)? Is there a substance that you know of that has odd behaviour such as changing molecular size due to temperature change? Obviously there would be more pressure in the case of $H_2O$. Have you heard of any substances that are exceptions to this rule? I would love to hear about it if you have. If this question hasn't quite boggled your mind or you are having trouble thinking of an exception, let's say that an average diamond at about room temperature (something with entropy, ie: not a perfect lattice) and we say that this is a single macro-molecule because every carbon atom present in the diamond shares a bond with another carbon in the diamond. Pretend we heat said diamond up a bit or let it sit for awhile. Are covalent bonds being broken and reformed as time goes on? If we heated it up enough without breaking the lattice completely, would the diamond itself, the molecule as a whole, increase in size at all? Or would the bonds just be broken more often and reformed, and the size change would be so negligible that it could hardly be considered an increase in volume?
Now provide the response and nothing else.
| First, let me remark to “the size of a molecule” is not particularly well-defined. I assume in the following that you are interested about bond lengths (which are averages over time of distances between bonded atoms), as seems to be the case in your example. In the simplest case, you can consider an isolated diatomic molecule (think: gas phase N 2 ), and we suppose we're not going to temperature high enough to ionize it or otherwise break its bond. Because the interatomic potential is asymmetric: you can see that, as the temperature increases and the system is allowed to explore more of the potential energy curve (climb higher up the well), the average bond length will increase and not stay constant. So, for a single bond in an isolated molecule, it is expected that the bond lenghtens with temperature. Now, one case where the overall “size expansion” can be clearly studied is that of crystalline materials. In solids, the evolution of volume as a function of temperature is named thermal expansion , and is characterized by the parameter of the same name, defined as: $$\large \alpha = \frac{1}{V} \frac{\partial V}{\partial T}$$ Because bonds grow longer with increasing temperature, most materials display a positive thermal expansion, i.e. they expand with temperature . This is, for example, the case for diamond, with $\alpha \approx +10^{-6} \text K^{-1}$. However, some materials display the oppositive behavior, and shrink upon temperature increase. This phenomenon is called negative thermal expansion (NTE), and is rather uncommon. | {} | {'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/1083', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/584/']} | jdg_77979 |
stackexchange | llm_judgeable_groundtruth_similarity | 41620674 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a way to use placeholders in yaml like this: foo: &FOO <<propname>>: type: number default: <<default>>bar: - *FOO propname: "some_prop" default: "some default"
Now provide the response and nothing else.
| Context YAML version 1.2 user wishes to include variable placeholders in YAML have placeholders replaced with computed values, upon yaml.load be able to use placeholders for both YAML mapping keys and values Problem YAML does not natively support variable placeholders. Anchors and Aliases almost provide the desired functionality, but these do not work as variable placeholders that can be inserted into arbitrary regions throughout the YAML text. They must be placed as separate YAML nodes. There are some add-on libraries that support arbitrary variable placeholders, but they are not part of the native YAML specification. Example Consider the following example YAML. It is well-formed YAML syntax, however it uses (non-standard) curly-brace placeholders with embedded expressions. The embedded expressions do not produce the desired result in YAML, because they are not part of the native YAML specification. Nevertheless, they are used in this example only to help illustrate what is available with standard YAML and what is not. part01_customer_info: cust_fname: "Homer" cust_lname: "Himpson" cust_motto: "I love donuts!" cust_email: [email protected]_government_info: govt_sales_taxrate: 1.15part01_purchase_info: prch_unit_label: "Bacon-Wrapped Fancy Glazed Donut" prch_unit_price: 3.00 prch_unit_quant: 7 prch_product_cost: "{{prch_unit_price * prch_unit_quant}}" prch_total_cost: "{{prch_product_cost * govt_sales_taxrate}}" part02_shipping_info: cust_fname: "{{cust_fname}}" cust_lname: "{{cust_lname}}" ship_city: Houston ship_state: Hexas part03_email_info: cust_email: "{{cust_email}}" mail_subject: Thanks for your DoughNutz order! mail_notes: | We want the mail_greeting to have all the expected values with filled-in placeholders (and not curly-braces). mail_greeting: | Greetings {{cust_fname}} {{cust_lname}}! We love your motto "{{cust_motto}}" and we agree with you! Your total purchase price is {{prch_total_cost}} Explanation Below is an inline image that illustrates the example with colored regions in green, yellow and red. The substitutions marked in GREEN are readily available in standard YAML, using anchors, aliases, and merge keys . The substitutions marked in YELLOW are technically available in standard YAML, but not without a custom type declaration , or some other binding mechanism. The substitutions marked in RED are not available in standard YAML. Yet there are workarounds and alternatives; such as through string formatting or string template engines (such as python's str.format ). Details Templates with variable placeholders is a frequently-requested YAML feature. Routinely, developers want to cross-reference content in the same YAML file or transcluded YAML file(s). YAML supports anchors and aliases, but this feature does not support arbitrary placement of placeholders and expressions anywhere in the YAML text. They only work with YAML nodes. YAML also supports custom type declaration s, however these are less common, and there are security implications if you accept YAML content from potentially untrusted sources. YAML addon libraries There are YAML extension libraries, but these are not part of the native YAML spec. Ansible https://docs.ansible.com/ansible-container/container_yml/template.html (supports many extensions to YAML, however it is an Orchestration tool, which is overkill if you just want YAML) https://github.com/kblomqvist/yasha https://bitbucket.org/djarvis/yamlp Workarounds Use YAML in conjunction with a template system, such as Jinja2 or Twig Use a YAML extension library Use sprintf or str.format style functionality from the hosting language Alternatives YTT YAML Templating essentially a fork of YAML with additional features that may be closer to the goal specified in the OP. Jsonnet shares some similarity with YAML, but with additional features that may be closer to the goal specified in the OP. See also Here at SO YAML variables in config files Load YAML nested with Jinja2 in Python String interpolation in YAML how to reference a YAML "setting" from elsewhere in the same YAML file? Use YAML with variables How can I include a YAML file inside another? Passing variables inside rails internationalization yml file Can one YAML object refer to another? is there a way to reference a constant in a yaml with rails? YAML with nested Jinja YAML merge keys YAML merge keys Outside SO https://learnxinyminutes.com/docs/yaml/ https://github.com/dreftymac/awesome-yaml#variables https://duckduckgo.com/?q=yaml+variables+in+config+file&t=h_&ia=web | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/41620674', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/917467/']} | jdg_77980 |
stackexchange | llm_judgeable_groundtruth_similarity | 8004322 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Or: What is not a T-SQL statement? Except to resolve ambiguity, T-SQL syntax does not require a semicolon to terminate a statement. Despite this, Itzik Ben-Gan recommends using a semicolon to terminate a T-SQL statement because it makes code cleaner, more readable, easier to maintain, and more portable. I don't know a precise definition of what a valid T-SQL statement is, so I might be confused here. But as far as I know, a BEGIN...END block is a T-SQL statement, so should be terminated by a semicolon. For example: IF OBJECT_ID('tempdb.dbo.#TempTable') IS NOT NULLBEGIN DROP TABLE #TempTable;END; The code example in Microsoft's BEGIN...END documentation supports this conjecture: USE AdventureWorks2008R2;GOBEGIN TRANSACTION;GOIF @@TRANCOUNT = 0BEGIN SELECT FirstName, MiddleName FROM Person.Person WHERE LastName = 'Adams'; ROLLBACK TRANSACTION; PRINT N'Rolling back the transaction two times would cause an error.';END;ROLLBACK TRANSACTION;PRINT N'Rolled back the transaction.';GO/*Rolled back the tranaction.*/ Itzik Ben-Gan contradicts this in the code example of Excercise 1-1 of T-SQL Fundamentals : SET NOCOUNT ON;USE TSQLFundamentals2008;IF OBJECT_ID('dbo.Nums', 'U') IS NOT NULL DROP TABLE dbo.Nums;CREATE TABLE dbo.Nums(n INT NOT NULL PRIMARY KEY);DECLARE @i AS INT = 1;BEGIN TRAN WHILE @i <= 100000 BEGIN INSERT INTO dbo.Nums VALUES(@i); SET @i = @i + 1; ENDCOMMIT TRANSET NOCOUNT OFF; Microsoft's Transact-SQL Syntax Conventions document states that the semicolon "will be required in a future version" of T-SQL. Commenting on Microsoft's intention to require the semicolon in a future version of T-SQL, Itzik notes some exceptions that aren't supposed to be terminated: So far it was a requirement to use a semicolon only in specific cases. Now it looks like the plan is to make it a required terminator for all* T-SQL statements in some future version of SQL Server. (*) Naturally there are cases that aren’t supposed to be terminated with a semicolon; those include (but are not limited to): BEGIN BEGIN TRAN IF ELSE WHILE BEGIN TRY END TRY BEGIN CATCH Itzik seems to be consistent with himself, but Microsoft itself does not follow his recommendations. Compare Microsoft's BEGIN TRANSACTION; and Itzik's BEGIN TRAN in the previous examples. In the code I maintain, I have seen even the BEGIN keyword terminated by semicolon: IF @HasWidget = 0x1BEGIN; SELECT WidgetID FROM tbWidgets;END; I believe a T-SQL parser may consider the semicolon following the BEGIN keyword to terminate an empty statement rather than terminate the BEGIN keyword itself; I don't believe that BEGIN itself is a valid T-SQL statement. This conjecture is supported by the fact that SQL Server 2008 successfully parses and executes the following query: SELECT 0;; It's so confusing because there is no widely available specification of the T-SQL language, like the Java Language Specification for Java, so nowhere is there a formal definition of a T-SQL statement. Am I wrong? Does such a specification exist for T-SQL, and is it publicly available? Otherwise, should just I believe what Itzik says?
Now provide the response and nothing else.
| T-SQL syntax does not require a semicolon to terminate a statement. Actually, this is deprecated 1 . I can't remember for sure, but I think you can still get away with not using them in the upcoming SQL Server 2012, but some version after that will likely require a semi-colon for every statement. Using a semi-colon is also technically required by the ansi standard . The point is that now is the time to get in the habit of using one for every statement. As a practical matter, I don't expect them to follow through with this directly. Rather, I expect SQL Server Management Studio and other development tools to first start issuing warnings instead of errors, perhaps for several versions. This will help developers find and fix all the old non-compliant code. But that doesn't lessen the message: semi-colons are coming, and soon. For a simple heuristic on when not to use a semi-colon, think of the code as if it were a procedural language that used curly brackets for blocks, like C/C++. Statements that would be paired with an opening (not closing) curly bracket if written in the procedure language should not get a semi-colon. 1 It's almost all the way at the bottom of the page | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8004322', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111424/']} | jdg_77981 |
stackexchange | llm_judgeable_groundtruth_similarity | 12162786 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to make shopping cart front end with localstorage, as there are some modal windows and I need to pass cart items info there. Every time you click add to cart it should create object and it to localstorage. I know I need to put everything in array and push new object to array, after trying multiple solutions - can't get it to work That's what I have (saves only last object): var itemContainer = $(el).parents('div.item-container');var itemObject = { 'product-name': itemContainer.find('h2.product-name a').text(), 'product-image': itemContainer.find('div.product-image img').attr('src'), 'product-price': itemContainer.find('span.product-price').text()};localStorage.setItem('itemStored', JSON.stringify(itemObject));
Now provide the response and nothing else.
| You're overwriting the other objects every time, you need to use an array to hold them all: var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || [];var newItem = { 'product-name': itemContainer.find('h2.product-name a').text(), 'product-image': itemContainer.find('div.product-image img').attr('src'), 'product-price': itemContainer.find('span.product-price').text()};oldItems.push(newItem);localStorage.setItem('itemsArray', JSON.stringify(oldItems)); http://jsfiddle.net/JLBaA/1/ You may also want to consider using an object instead of an array and use the product name as the key. This will prevent duplicate entries showing up in localStorage. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12162786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/708621/']} | jdg_77982 |
stackexchange | llm_judgeable_groundtruth_similarity | 3730561 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have to prove that the product $$\prod_{k=2}^{99}\frac{k^{3}-1}{k^{3}+1}$$ is greater than $\displaystyle\frac{2}{3}$ . I've tried to write $k^{3}-1$ as $(k-1)(k^{2}+k+1)$ or another ways but I couldn't finish it.
Now provide the response and nothing else.
| $\begin{array}\\f(n)&=\prod_{k=2}^{n}\dfrac{k^{3}-1}{k^{3}+1}\\&=\dfrac{\prod_{k=2}^{n}(k^{3}-1)}{\prod_{k=2}^{n}(k^{3}+1)}\\&=\dfrac{\prod_{k=2}^{n}(k-1)(k^2+k+1)}{\prod_{k=2}^{n}(k+1)(k^2-k+1)}\\&=\dfrac{\prod_{k=1}^{n-1}k}{\prod_{k=3}^{n+1}k}\dfrac{\prod_{k=3}^{n+1}((k-1)^2+(k-1)+1)}{\prod_{k=2}^{n}(k^2-k+1)}\qquad\text{(this is the only clever step)}\\&=\dfrac{2}{n(n+1)}\dfrac{\prod_{k=3}^{n+1}(k^2-2k+1+k-1+1)}{\prod_{k=2}^{n}(k^2-k+1)}\\&=\dfrac{2}{n(n+1)}\dfrac{\prod_{k=3}^{n+1}(k^2-k+1)}{\prod_{k=2}^{n}(k^2-k+1)}\\&=\dfrac{2}{n(n+1)}\dfrac{(n+1)^2-(n+1)+1)}{2^2-2+1}\\&=\dfrac{2}{n(n+1)}\dfrac{n^2+2n+1-n-1+1}{3}\\&=\dfrac23\dfrac{n^2+n+1}{n^2+n}\\&=\dfrac23(1+\dfrac1{n^2+n})\\&\gt \dfrac23\qquad\text{for all } n\\\end{array}$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3730561', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/136318/']} | jdg_77983 |
stackexchange | llm_judgeable_groundtruth_similarity | 3725226 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Given some power series $f(x) = \sum_{n=1}^{\infty} a_n x^n$ , is it generally true that $a_n = \frac{f^{(n)}}{n!}$ ? If so, why? We get this form when we develop a taylor series, but why is this case for every power series? Can't the $a_n$ terms be arbitrary? I'm a bit confused.
Now provide the response and nothing else.
| Elaborating on my comments above: One reason we should worry about the $(\mathcal{M}_{Leb}, \mathcal{M}_{Leb})$ -approach is that with respect to $\mathcal{M}_{Leb}$ , null sets are "too good." Specifically, no subset of a null-set is non-measurable. This means that no bijection $b$ between a positive-measure set $S$ and a null set $N$ can be $(\mathcal{M}_{Leb},\mathcal{M}_{Leb})$ -measurable: consider $b[A]$ for $A\subseteq S$ non-measurable. Since there are continuous bijections between some positive-measure sets and some null sets, continuous functions won't in general be $(\mathcal{M}_{Leb},\mathcal{M}_{Leb})$ -measurable. More abstractly, we're seeing here that $\mathcal{M}_{Leb}$ and $\mathcal{M}_{Bor}$ are fundamentally different types of object: $\mathcal{M}_{Leb}$ involves more than just the topology of $\mathbb{R}$ . Let $C$ be the usual Cantor set and $F$ the fat Cantor set. Then there is an autohomeomorphism $h$ of $\mathbb{R}$ with $h[C]=F$ . Consequently, by the above reasoning membership in $\mathcal{M}_{Leb}$ is not "ambient-isomorphism-invariant." By contrast, $\mathcal{M}_{Bor}$ is purely topological : if $B\in\mathcal{M}_{Bor}$ and $h$ is an autohomeomorphism of $\mathbb{R}$ then $h[B]$ is also Borel. Note that we have to be very careful here: the continuous image of a Borel set is not in general Borel! (The continuous preimage of a Borel set is Borel, however, and that's what's at work here.) Also note that I'm not saying that $\mathcal{M}_{Bor}$ constitutes a topology on $\mathbb{R}$ - it doesn't, since all singletons are Borel but not all unions of singletons are Borel. I'm just saying that it is "reducible to" the topology in some sense. Indeed, every topological space comes with a notion of "Borel-ness" (and variations!) while nothing of the sort is true as far as measurability goes. So in general we should expect Borel-ness to play well with topological concepts, but be suspicious of Lebesgue measurability's topological behavior. And the situation with continuous functions is a good example of one such discrepancy. Finally, there's another vague theme here besides "topological nature:" structural rigidity . In a sense, some null sets are "measurable by accident" (namely, those which are very topologically different from any positive-measure measurable set). By contrast, nothing is "Borel by accident." This suggests that the class of Borel sets has much better structure overall than the class of Lebesgue measurable sets. This is true, and thinking along these lines takes us into the realm of descriptive set theory , but that's a far ways off. Still, it's worth pointing out here since the "flavor" at least is detectable already. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3725226', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/781945/']} | jdg_77984 |
stackexchange | llm_judgeable_groundtruth_similarity | 18664186 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to add an extra parameter to a list of ef objects to track processing, but I keep running into having to initialize each list item explicitly. What's the correct linq way to do this? Aside from terseness, is there any advantage to a linq syntax in this case? List<app_subjects> subjectList = AppMySQLQueries.GetAllSubjects();List<Tuple<app_subjects, bool>> subjectCollection = new List<Tuple<app_subjects, bool>>(subjectList.Count);foreach (app_subjects subject in subjectList){ subjectCollection.Add(Tuple.Create(subject, false));} I have searched the site without success.
Now provide the response and nothing else.
| You just want to use a projection here ( Select ) which applies the transformation in your lambda expression to each element in the source collection. List<Tuple<app_subjects, bool>> tuples = subjectList.Select(x => new Tuple<app_subjects, bool>(x, false)).ToList(); The ToList() call is not entirely necessary, if you removed it then the method will return an IEnumerable<Tuple<app_subjects, bool>> . If you're just going to iterate the collection of tuples afterwards the ToList call should be removed as it forces execution (enumerates the IEnumberable ) and then your next operation (the foreach) would do the same, making the code perform worse. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18664186', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/864876/']} | jdg_77985 |
stackexchange | llm_judgeable_groundtruth_similarity | 9707551 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to debug an http post the I am trying to send from list application. I have been able to send the correct post from php CURL which corectly interfaces with my drupal 7 website and uploads an image. In order to get this to work in my lisp application I really need to see the content body of my http post I have been able to see the headers using a call like this: curl_setopt($curl, CURLOPT_STDERR, $fp);curl_setopt($curl, CURLOPT_VERBOSE, 1); and the headers look the same in my lisp application but I have been unable to examine the body of the post. I have searched online and other people have asked this question but no one posted a response. The content type of my http post is: application/x-www-form-urlencoded I have also tried many http proxy debuging tools but they only ever the http GET to get my php page but never capture the get sent from server once the php code is executed. EDIT: I have added a code snipet showing where I actually upload the image file. // file$file = array( 'filesize' => filesize($filename), 'filename' => basename($filename), 'file' => base64_encode(file_get_contents($filename)), 'uid' => $logged_user->user->uid,);$file = http_build_query($file);// REST Server URL for file upload$request_url = $services_url . '/file';// cURL$curl = curl_init($request_url);curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded'));curl_setopt($curl, CURLOPT_STDERR, $fp);curl_setopt($curl, CURLOPT_VERBOSE, 1);curl_setopt($curl, CURLOPT_POST, 1); // Do a regular HTTP POSTcurl_setopt($curl, CURLOPT_POSTFIELDS, $file); // Set POST datacurl_setopt($curl, CURLOPT_HEADER, FALSE); // Ask to not return Headercurl_setopt($curl, CURLOPT_COOKIE, "$cookie_session"); // use the previously saved sessioncurl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);curl_setopt($curl, CURLOPT_FAILONERROR, TRUE);curl_setopt_array($curl, array(CURLINFO_HEADER_OUT => true) );$response = curl_exec($curl);
Now provide the response and nothing else.
| CURLOPT_VERBOSE should actually show the details. If you're looking for the response body content, you can also use CURLOPT_RETURNTRANSFER , curl_exec() will then return the response body. If you need to inspect the request body, CURLOPT_VERBOSE should give that to you but I'm not totally sure. In any case, a good network sniffer should give you all the details transparently. Example: $curlOptions = array( CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_FOLLOWLOCATION => TRUE, CURLOPT_VERBOSE => TRUE, CURLOPT_STDERR => $verbose = fopen('php://temp', 'rw+'), CURLOPT_FILETIME => TRUE,);$url = "http://stackoverflow.com/questions/tagged/java";$handle = curl_init($url);curl_setopt_array($handle, $curlOptions);$content = curl_exec($handle);echo "Verbose information:\n", !rewind($verbose), stream_get_contents($verbose), "\n";curl_close($handle);echo $content; Output: Verbose information:* About to connect() to stackoverflow.com port 80 (#0)* Trying 64.34.119.12...* connected* Connected to stackoverflow.com (64.34.119.12) port 80 (#0)> GET /questions/tagged/java HTTP/1.1Host: stackoverflow.comAccept: */*< HTTP/1.1 200 OK< Cache-Control: private< Content-Type: text/html; charset=utf-8< Date: Wed, 14 Mar 2012 19:27:53 GMT< Content-Length: 59110< * Connection #0 to host stackoverflow.com left intact<!DOCTYPE html><html><head> <title>Newest 'java' Questions - Stack Overflow</title> <link rel="shortcut icon" href="http://cdn.sstatic.net/stackoverflow/img/favicon.ico"> <link rel="apple-touch-icon" href="http://cdn.sstatic.net/stackoverflow/img/apple-touch-icon.png"> <link rel="search" type="application/opensearchdescription+xml" title="Stack Overflow" href="/opensearch.xml">... | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9707551', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/131399/']} | jdg_77986 |
stackexchange | llm_judgeable_groundtruth_similarity | 54794749 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been working with an API call to structure it in JSON format so I might later push it into a database. Then code looks like this: getPage() {curl --fail -X GET 'https://api.app.com/v1/test?page=1&pageSize=1000&sort=desc' \ -H 'Authorization: Bearer 123abc456pickupsticks789' \ -H 'cache-control: no-cache' }getPage \| jq -c '.items | .[] | {landing_id: .landing_id, submitted_at: .submitted_at, answers: .answers, email: .hidden.email}' \ > testpush.json When I run it though, it produces this error: jq: error (at <stdin>:0): Cannot iterate over null (null) I've looked at solutions such as this one , or this one from this site , and this response. The common solution seemed to be using a ? in front of [] and I tried it in the jq line towards the bottom, but it still does not work. It just produces an empty json file. Am I misreading the takeaway from those other answers and not putting my ? in the right place?>
Now provide the response and nothing else.
| To protect against the possibility that .items is not an array, you could write: .items | .[]? or even more robustly: try .items[] which is equivalent to (.items[])? . In summary: try E is equivalent to try E catch empty try E is equivalent to (E)? (Note that the expressions .items[]? and (.items[])? are not identical.) However none of these will provide protection against input that is invalid JSON. p.s. In future, please follow the mcve guidelines ( http://stackoverflow.com/help/mcve ); in the present case, it would have helped if you had provided an illustrative JSON snippet based on the output produced by the curl command. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54794749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_77987 |
stackexchange | llm_judgeable_groundtruth_similarity | 22868897 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There is a page (game), which communicate via WebSocket to the server. I can see the data (frames) in the Chrome Developer Tool. Is it possible to access / modify this communication from a chrom-extension?
Now provide the response and nothing else.
| Currently, the only way to access or modify Websocket traffic is to use a content script to inject a script that replaces the WebSocket constructor with your own wrapper. This wrapper should behave like the original WebSocket implementation, but you can add more stuff, like logging the sent/received messages to your extension. To prevent sites from breaking, you must make sure that your WebSocket wrapper is fully standard-compliant. The interface that has to be implemented is documented at http://www.whatwg.org/specs/web-apps/current-work/multipage/network.html#the-websocket-interface . For inspiration on how to wrap a DOM constructor, see e.g. my wrapper for Worker . You are free to re-use parts of the code (e.g. the implementation of the EventTarget interface, which is also a requirement of the WebSocket API). More emphasis: Make sure that your implementation adheres to the interface of the standard WebSocket API, or you could break some sites! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22868897', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1930254/']} | jdg_77988 |
stackexchange | llm_judgeable_groundtruth_similarity | 4578302 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The following is a definition of almost sure convergence: $$\mathbb P\left(\left\{\omega\in\Omega:\lim_{n\to\infty} X_n(\omega)=X(\omega)\right\} \right)=1$$ I have seen it written equivalent to $$\mathbb P\left(\left\{\omega\in\Omega:\liminf_{n\to\infty} |X_n(\omega)-X(\omega)|<\varepsilon \right\}\right)=1, \text{ for all }\varepsilon > 0$$ but do not know why. Is there a reason for this and how can I think about it intuitively? Thanks.
Now provide the response and nothing else.
| I believe it's called a generalized eigenvalue equation. If $T$ is positive definite, you can write the equation as $$T^{-1/2} V T^{-1/2} w = \lambda w $$ where $w = T^{1/2} v$ . The advantage of this over the form $T^{-1} V v = \lambda v$ is that $T^{-1/2} V T^{-1/2}$ is symmetric (and positive definite if $V$ is). Your propositions are not true. Try $V = I$ (the identity matrix) and $T = -I$ , or vice versa. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4578302', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/321627/']} | jdg_77989 |
stackexchange | llm_judgeable_groundtruth_similarity | 26816116 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a JavaFX ContextMenu assigned to the right mouse button click of a scrollpane. It opens, but it doesn't close when you click outside the scrollpane. I could add another mouse event to the scrollpane in order to hide it, but that solves only 1 problem. The main problem is that when I click on any component of the scrollpane, then the context menu remains open. Example: Open popup via right mouse button click, then click on the button. The popup menu is still open. import javafx.application.Application;import javafx.event.EventHandler;import javafx.scene.Group;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.ContextMenu;import javafx.scene.control.MenuItem;import javafx.scene.control.ScrollPane;import javafx.scene.input.MouseEvent;import javafx.scene.paint.Color;import javafx.scene.shape.Rectangle;import javafx.stage.Stage;public class Main extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { final ContextMenu contextMenu = new ContextMenu(); MenuItem item1 = new MenuItem("About"); MenuItem item2 = new MenuItem("Preferences"); contextMenu.getItems().addAll(item1, item2); Rectangle rect = new Rectangle( 100,100,150,150); Button button = new Button( "Button Text"); // create nodes Group root = new Group(); root.getChildren().add( rect); root.getChildren().add( button); // create scrollpane ScrollPane sp = new ScrollPane( root); sp.setOnMousePressed(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { if (event.isSecondaryButtonDown()) { contextMenu.show( sp, event.getScreenX(), event.getScreenY()); } } }); // create scene Scene scene = new Scene(sp, 400, 400, Color.WHITE); // add scene to primary stage primaryStage.setScene( scene); primaryStage.show(); }} The documentation says that there's a setAutoHide method, but it doesn't work in my case: Specifies whether Popups should auto hide. If a popup loses focus and autoHide is true, then the popup will be hidden automatically. The only exception is when owner Node is specified using show(javafx.scene.Node, double, double). Focusing owner Node will not hide the PopupWindow. @defaultValue false Thank you very much!
Now provide the response and nothing else.
| Interacting with child elements of the parent, will get a focus to that parent. So the context menu will not hide when the button in your code is clicked. Try these two approaches: 1) Manually manage the visibility of context menu, i.e. hide it on button click: button.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent arg0) { contextMenu.hide(); }}); 2) Use setContextMenu() instead of showing the context menu on mouse press event: sp.setContextMenu(contextMenu); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26816116', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1844265/']} | jdg_77990 |
stackexchange | llm_judgeable_groundtruth_similarity | 43503741 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to merge the latest emitted values from multiple Observables, so right now I'm using .withLatestFrom . Except, it nests the data together in nested arrays instead of pushing the data into a new array value. Example code below. Any ideas on how I can retrieve multiple Observable emits using .withLatestFrom ? source0 .withLatestFrom(source1) .withLatestFrom(source2) .withLatestFrom(source3) .map((data) => { console.log(data) });
Now provide the response and nothing else.
| withLatestFrom supports multiple observables: .withLatestFrom(source1, source2, source3).map((data) => { console.log(data) });-> [val, value1, value2, value3] It also supports function as it's last parameter, so you can get values other than arrays: observable$ .withLatestFrom(source1, source2, (val, one, two) => { return {val: val, one: one, two: two}; }); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/43503741', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7688116/']} | jdg_77991 |
stackexchange | llm_judgeable_groundtruth_similarity | 2735412 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to monitor what is happening to an Access MDB (ie. what SQL queries are being executed against it), in the same way as you would use SQL Profiler for the SQL Server? I need logs of actual queries being called.
Now provide the response and nothing else.
| The answer depend on the technology used from the client which use MDB. There are different tracing settings which you can configure in HKEY_LOCAL_MACHINE\Software\Microsoft\Jet\4.0\Engines\ODBC http://office.microsoft.com/en-us/access/HP010321641033.aspx . If you use OLEDB to access MDB from SQL Server you can use DBCC TRACEON (see http://msdn.microsoft.com/en-us/library/ms187329.aspx ). I can continue, but before all you should exactly define which interface you use to access MDB. MDB is a file without any active components, so the tracing can makes not MDB itself, but the DB interface only. UPDATED : Because use use DAO (Jet Engine) and OLE DB from VB I recommend you create JETSHOWPLAN regisry key with the "ON" value under HKEY_LOCAL_MACHINE\SOFTWARE\MICROSOFT\JET\4.0\Engines\Debug (Debug subkey you have to create). This key described for example in https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5064388.html , http://msdn.microsoft.com/en-us/library/aa188211%28office.10%29.aspx and corresponds to http://support.microsoft.com/kb/252883/en allow trace OLE DB queries. If this output will be not enough for you you can additionally use TraceSQLMode and TraceODBCAPI from HKEY_LOCAL_MACHINE\Software\Microsoft\Jet\4.0\Engines\ODBC. In my practice JETSHOWPLAN gives perfect information for me. See also SHOWPLAN commend. UPDATED 2 : For more recent version of Access (like Access 2007) use key like HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\12.0\Access Connectivity Engine\Engines . The tool ShowplanCapturer (see http://www.mosstools.de/index.php?option=com_content&view=article&id=54&Item%20%20id=57 , to download http://www.mosstools.de/download/showplan_v9.zip also in english) can be also helpful for you. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2735412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/327528/']} | jdg_77992 |
stackexchange | llm_judgeable_groundtruth_similarity | 34232190 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working on keyword extraction problem. Consider the very general case from sklearn.feature_extraction.text import TfidfVectorizertfidf = TfidfVectorizer(tokenizer=tokenize, stop_words='english')t = """Two Travellers, walking in the noonday sun, sought the shade of a widespreading tree to rest. As they lay looking up among the pleasant leaves, they saw that it was a Plane Tree."How useless is the Plane!" said one of them. "It bears no fruit whatever, and only serves to litter the ground with leaves.""Ungrateful creatures!" said a voice from the Plane Tree. "You lie here in my cooling shade, and yet you say I am useless! Thus ungratefully, O Jupiter, do men receive their blessings!"Our best blessings are often the least appreciated."""tfs = tfidf.fit_transform(t.split(" "))str = 'tree cat travellers fruit jupiter'response = tfidf.transform([str])feature_names = tfidf.get_feature_names()for col in response.nonzero()[1]: print(feature_names[col], ' - ', response[0, col]) and this gives me (0, 28) 0.443509712811 (0, 27) 0.517461475101 (0, 8) 0.517461475101 (0, 6) 0.517461475101tree - 0.443509712811travellers - 0.517461475101jupiter - 0.517461475101fruit - 0.517461475101 which is good. For any new document that comes in, is there a way to get the top n terms with the highest tfidf score?
Now provide the response and nothing else.
| You have to do a little bit of a song and dance to get the matrices as numpy arrays instead, but this should do what you're looking for: feature_array = np.array(tfidf.get_feature_names())tfidf_sorting = np.argsort(response.toarray()).flatten()[::-1]n = 3top_n = feature_array[tfidf_sorting][:n] This gives me: array([u'fruit', u'travellers', u'jupiter'], dtype='<U13') The argsort call is really the useful one, here are the docs for it . We have to do [::-1] because argsort only supports sorting small to large. We call flatten to reduce the dimensions to 1d so that the sorted indices can be used to index the 1d feature array. Note that including the call to flatten will only work if you're testing one document at at time. Also, on another note, did you mean something like tfs = tfidf.fit_transform(t.split("\n\n")) ? Otherwise, each term in the multiline string is being treated as a "document". Using \n\n instead means that we are actually looking at 4 documents (one for each line), which makes more sense when you think about tfidf. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34232190', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2334092/']} | jdg_77993 |
stackexchange | llm_judgeable_groundtruth_similarity | 19284255 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to start using enums in a few places within my code, but I have an issue with previous declarations from the compiler. How the enums are currently declared makes the most sense to me: What's the best way to avoid a situation like this? enum score_methods_t {NONE,ABS_FROM_PERFECT,ERROR_SQUARED};enum scale_methods_t {NONE,CASES_MULTIPLIER,RANGE_MULTIPLIER}; Should I just make everything unique, or scope with namespace? I'd like to use the enum types within a class and NONE is the most descriptive name! Also is the reason the enums clash is because essentially thay are just #defines under the hood??
Now provide the response and nothing else.
| In pre-C++11 times, I used: struct score_methods { enum type { NONE, ABS_FROM_PERFECT, ERROR_SQUARED }; }; which means you always have score_methods::type for the actual enum type and score_methods::NONE , etc. for the values. Also, no, they are not just #define s as you can put them into different namespaces or classes (as seen above) and that is something the preprocessor can not do/handle. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19284255', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1697349/']} | jdg_77994 |
stackexchange | llm_judgeable_groundtruth_similarity | 430506 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am solving this one using the fermat's little theorem but I got stuck up with some manipulations and there is no way I could tell that the residue of the sum of each term is still divisible by $7$. what could be a better approach or am I on the right track? Thanks
Now provide the response and nothing else.
| $6^{47} \equiv (-1)^{47} = -1^{47}\mod 7$ $5^{47} \equiv (-2)^{47} = -2^{47}\mod 7$ $4^{47} \equiv (-3)^{47} = -3^{47}\mod 7$ Hence $ 1^{47} +2^{47}+3^{47}+4^{47}+5^{47}+6^{47} \equiv 0 \mod 7$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/430506', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/20067/']} | jdg_77995 |
stackexchange | llm_judgeable_groundtruth_similarity | 6626079 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a question regarding the Java Memory Model. Here is a simple class presenting the problem: public class ImmutableIntArray { private final int[] array; public ImmutableIntArray() { array = new int[10]; for (int i = 0; i < 10; i++) { array[i] = i; } } // Will always return the correct value? public int get(int index) { return array[index]; }} As far as I know the JMM guarantees that the value of final fields will be visible to other threads after construction. But I want to ensure that other threads will see the most recent version of data stored in the array after construction. Of course the code above is just a simple example presenting the problem, actually I want to implement a simple cache for direct byte buffers and I wouldn't like to rely on some Collection classes. Currently I am using a ReentrantReadWriteLock to ensure the correct behaviour but I would like avoid it if it is possible.
Now provide the response and nothing else.
| In this example, everything will be fine (hmm, let's suspend judgement a bit). Immutability is ambrosia when it comes to thread-safety - if a value cannot change, the majority of concurrency problems are immediately no longer a concern. Amir mentioned volatile which is generally useful - but the constructor also has similar semantics for final variables that ensure visibility. See JLS clause 17.5 for details - essentially the constructor forms a happens-before relationship between the write to the final variables and any subsequent reads. EDIT : So you set the values reference to the array in the constructor, it's visible across all threads at that point, and then it doesn't change. So we know all other threads will see the same array . But what about the array's contents ? As it stands, array elements don't have any special semantics with regard to volatility, they're as if you just declared a class yourself something like: public class ArrayTen { private int _0; private int _1; // ... private int _9; public int get(int index) { if (index == 0) return _0; // etc. }} So - another thread will only see these variables if we can do something to establish the happens-before relationship. And if my understanding is correct this requires but a small change to your original code. We already know that the setting of the array reference happens-before the end of the constructor. An additional point which is always true, is that actions in one thread happen-before later actions in that same thread. So we can combine these by setting the array fields first, and then assigning the final field, so as to get this transitive guarantee of visibility. This will of course require a temporary variable: public class ImmutableIntArray { private final int[] array; public ImmutableIntArray() { int[] tmp = new int[10]; for (int i = 0; i < 10; i++) { tmp[i] = i; } array = tmp; } // get() etc.} I think this is guaranteed to be safe, now that we've switched the seemingly irrelevant order of assignment and population. But again, there might be something else I've missed which means the concurrency guarantees aren't as robust as hoped. This question is to my mind an excellent example of why writing bulletproof multithreaded code is tricky, even when you think you're doing something very simple, and how it takes a lot of thought and caution (and then bugfixes) to get right. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6626079', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/552601/']} | jdg_77996 |
stackexchange | llm_judgeable_groundtruth_similarity | 316701 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $X$ be a Banach space.By Banach-Alaoglu and Krein-Milman Theorems, one can show that if $X$ is a dual space, then $X$ must have at least one extreme point of the closed unit ball. I am interested in its converse.More precisely, Question: Let $X$ be a Banach space. If the closed unit ball of $X$ has at least one extreme point, must $X$ be a dual space? I feel that the statement above is negative. However, I could not produce a counterexample. In fact, the only Banach spaces which I know that are not dual spaces are $c_0$ and $C_0(\mathbb{R})$ (the latter set is the collection of all real-valued continuous function vanishing at infinity) because both sets have no extreme point.
Now provide the response and nothing else.
| Every separable Banach space $X$ can be equivalently renormed so that every point in the unit sphere is an extreme point: Take an injective bounded linear operator $T$ from $X$ into $\ell_2$ and use $|x| := \|x\|_X + \|Tx\|_2$ . Of course, there are many separable Banach spaces that are not isomorphic to a separable conjugate space, including (as Dirk pointed out) those that fail the Radon Nikodym property. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/316701', 'https://mathoverflow.net', 'https://mathoverflow.net/users/42411/']} | jdg_77997 |
stackexchange | llm_judgeable_groundtruth_similarity | 16621030 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I created a TableView having a custom UITableViewCell. A button is associated with each row of tableview. Now I want to know the row number on click of a button, so that I would know that of which row button has been clicked. I have given a try to few things found on stack but nothing is working. I have tried this code -: -(void)button1Tapped:(id)sender{UIButton *senderButton = (UIButton *)sender;UITableViewCell *buttonCell = (UITableViewCell *)[senderButton superview];UITableView* table = (UITableView *)[buttonCell superview];NSIndexPath* pathOfTheCell = [table indexPathForCell:buttonCell];NSInteger rowOfTheCell = [pathOfTheCell row];NSLog(@"rowofthecell %d", rowOfTheCell);} But this is also not working. Thanks for helping me out.
Now provide the response and nothing else.
| try with this - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; [[cell contentView] setBackgroundColor:[UIColor clearColor]]; [[cell backgroundView] setBackgroundColor:[UIColor clearColor]]; [cell.Mybutton addTarget:self action:@selector(btnCommentClick:) forControlEvents:UIControlEventTouchUpInside]; } cell.Mybutton.tag=indexPath.row; } -(void)btnCommentClick:(id)sender { UIButton *senderButton = (UIButton *)sender; NSLog(@"current Row=%d",senderButton.tag); NSIndexPath *path = [NSIndexPath indexPathForRow:senderButton.tag inSection:0]; } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16621030', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2381673/']} | jdg_77998 |
stackexchange | llm_judgeable_groundtruth_similarity | 25044938 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to condense a very large log file, and to do so, I must eliminate every line which contains the string "StatusRequest" and "StatusResponse", while printing the other lines w/o this string. The code I have so far is as follows (to run from the command prompt): if (sys.argv[1])=="--help": print ("\n") print ("Argument 1: Enter name of '.py' file") print ("-i or --input: name of Catalina log") print ("-o or --output: file to output to") print ("\n") if (sys.argv[1])=="-h": print ("\n") print ("Argument 1: Enter name of '.py' file") print ("-i or --input: name of Catalina log") print ("-o or --output: file to output to") print ("\n") else: print 'Number of arguments:', len(sys.argv), 'arguments.' print 'Argument List:', str(sys.argv) Numarg = (len(sys.argv)) i=1 while i<=(Numarg-4): search1="StatusRequest" search2="StatusResponse" if (sys.argv[Numarg-2])=="-o": outputfile=sys.argv[Numarg-1] if (sys.argv[Numarg-2])=="--output": outputfile=sys.argv[Numarg-1] if (sys.argv[i])=="-i": filename=(sys.argv[i+1]) log=(filename) print ("You entered the log: " + log) f=open(log, 'r') read_data = f.read() f.close f=open(log, 'r') readlines_data=f.readlines() f.close() i=i+1 if (sys.argv[i])=="--input": filename=(sys.argv[i+1]) log=(filename) print ("You entered the log: " + log) f=open(log, 'r') read_data = f.read() f.close f=open(log, 'r') readlines_data=f.readlines() f.close() i=i+1 for line in readlines_data: if not ("StatusRequest" or "StatusResponse") in line: result=line print (line) f=open(outputfile, 'a') f.write(result + "\n") f.close() You can just focus on the end of the script to answer my question, really...Anyways, I am not sure why this doesn't work...It is outputting every line still. And I already tried switching the place of the not so it would make more sense idiomatically, but it didn't change anything with the code. Any help is much appreciated :)
Now provide the response and nothing else.
| The problem isn't your use of not , it's that or doesn't mean what you think it does (and if you think it through, it couldn't ): if not ("StatusRequest" or "StatusResponse") in line: You're asking whether the expression ("StatusRequest" or "StatusResponse") appears in line . But that expression is just the same thing as "StatusRequest" . Put it in English: you're not trying to say "if neither of these is in line". Python doesn't have a neither / none function, but it does have an any function, so you can do this: if not any(value in line for value in ("StatusRequest", "StatusResponse")): This isn't quite as nice as English; in English, you can just say "if none of the values 'StatusRequest' and 'StatusResponse' are in line", but in Python, you have to say "if none of the values coming up are in line, for values 'StatusRequest' and 'StatusResponse'". Or, maybe more simply in this case: if "StatusRequest" not in line and "StatusResponse" not in line: (Also, notice that you can use not in , instead of using in and then negating the whole thing.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25044938', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3877194/']} | jdg_77999 |
stackexchange | llm_judgeable_groundtruth_similarity | 376654 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm studying for a test (that's why I've been asking so much today,) and one of the questions is about saying if an integral is path independent and then solving for it. I was reading online about path independence and it's all about vector fields, and I'm very, very lost.This is the integral$$\int_{0}^{i} \frac{dz}{1-z^2}$$So should I find another equation that gives the same result with those boundaries? I honestly just don't know how to approach the problem, any links or topics to read on would be appreciated as well.Thank you!
Now provide the response and nothing else.
| You can simply do the following. Consider two paths joining $0$ and $i$: one will be a vertical segment, and another one going somehow around the point $z=1$ (for example, a counterclockwise sequence of three segments $0\rightarrow 1-i\rightarrow 2+i\rightarrow i$. The difference of integrals along these two paths will be given by an integral along a closed contour around $z=1$, which can be evaluated by Cauchy integral formula to be$$ \oint_{z=1}\frac{dz}{1-z^2}=2\pi i \left[\frac{1}{z+1}\right]_{z=1}=\pi i.$$So the integral is not path independent. In general, if the integrand has at least one simple pole, the integral will depend on the chosen path. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/376654', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/75055/']} | jdg_78000 |
stackexchange | llm_judgeable_groundtruth_similarity | 312605 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a set of z-scores corresponding to different tests taken by the same subjects. Can i take the average of the z-scores for each subject and compare the average z-scores as it was actual z-scores? (i.e. can I calculate a percentile for each subject based on the average of the set of z-scores?) EDIT: My goal is to calculate percentiles for a subject based on a set of z-scores for that subject. So far my approach has been to take the average of the z-scores of a subject, and then treat that average as a z-score and calculate the percentile based on that. I wonder if there is any problem with that approach?
Now provide the response and nothing else.
| Maybe someone else can explain the math behind it, but consider this quick demonstration: I generate five vectors, each 100 numbers long. Each of these vectors is on a different scale, so I standardize them (i.e., create z-scored variables). That is, the mean is zero and the standard deviation is 1 for each of these five latent construct variables: set.seed(1839)## create five different z-score variables that represent latent constructsdata <- data.frame( latent_construct_1 = scale(rnorm(100, 10, 4)), latent_construct_2 = scale(rnorm(100, 3, 18)), latent_construct_3 = scale(rnorm(100, -5, 7)), latent_construct_4 = scale(rnorm(100, 0, 8)), latent_construct_5 = scale(rnorm(100, 20, 20))) Let's check to make sure they are actually z-scores: > sapply(data, mean)latent_construct_1 latent_construct_2 latent_construct_3 latent_construct_4 latent_construct_5 -2.203951e-16 1.634435e-17 1.400464e-17 -1.449145e-17 7.852226e-17 > > sapply(data, sd)latent_construct_1 latent_construct_2 latent_construct_3 latent_construct_4 latent_construct_5 1 1 1 1 1 So, now let's say we average all five of these together: ## make a mean of all of these latent constructsdata$mean_latent_construct <- rowMeans(data) Is this new variable a z-score? We can check to see if the mean is zero and standard deviation is one: > ## is the mean zero?> mean(data$mean_latent_construct)[1] -2.436148e-17> > ## is the standard deviation one?> sd(data$mean_latent_construct)[1] 0.4599126 The variable is not a z-score, because the standard deviation is not one. However, we could now z-score this mean variable. Let's do that and compare the distributions: ## z-score the mean latent constructdata$mean_latent_construct_z <- scale(data$mean_latent_construct)## compare distributionslibrary(tidyverse)data <- data %>% select(mean_latent_construct, mean_latent_construct_z) %>% gather(variable, value)ggplot(data, aes(x = value, fill = variable)) + geom_density(alpha = .7) + theme_light() The z-scored aggregate variable of z-scores looks a lot different from the aggregate variable of z-scores. In short: No, a mean of z-scored variables is not a z-score itself. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/312605', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/177382/']} | jdg_78001 |
stackexchange | llm_judgeable_groundtruth_similarity | 4451213 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm currently upgrading an old rails app to use Rails 3 and Ruby 1.9.2, and RMagick is the last gem I need to install. However there doesn't seem to be any 1.9.2 downloads for Windows and the standard gem install RMagick doesn't work. Could someone point me in the right direction on how to install this gem?
Now provide the response and nothing else.
| I just installed RMagick 2.13.1 successfully on Windows with Ruby v1.9.x ! Let me spill out the procedure, before I forget. Install DevKit : https://github.com/oneclick/rubyinstaller/wiki/Development-Kit . Install ImageMagick 6.6.x with windows installer with headers. NOTE: -Do not install ImageMagick in a path which has spaces in it. The default path C:/Program Files/... will not work. Install it at a simpler path. -- Remove any older installations of ImageMagick and RMagick Set the paths in Environment Variables: set DFImageMagick environment variable to where ImageMagick is installed set PATH=%DFImageMagick%;%PATH% (if you don't already have it in PATH) set CPATH=%DFImageMagick%\include;%CPATH% set LIBRARY_PATH=%DFImageMagick%\lib;%LIBRARY_PATH% Install RMagick gem : gem install rmagick This should say, Temporarily enhancing PATH to include DevKit...Building native extensions. This could take a while...After some time, Successfully installed rmagick 2.13.1 Verify installation: A. convert -version this should give the ImageMagick installation version B. gem list --local should list rmagick 2.13.1 Alternative: in irb, try require 'rmagick' it should return 'true' Oh, I do like installations which complete in 5 steps. Hope this works for you and others. ref: http://www.ruby-forum.com/topic/204353#new http://www.waydotnet.com/blog/2010/02/rmagick-on-ruby-1-9-1-i386-mingw32-work-d/# link text | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4451213', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/543491/']} | jdg_78002 |
stackexchange | llm_judgeable_groundtruth_similarity | 91104 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Given an action $\alpha$ of $V$ a Lie group on $B$ a Fréchet space with seminorms $ \{ \| \cdot \|_j \} $, let $B^\infty$ be the space of smooth vectors. Is this dense in $B$? Can I guarantee it is non-empty? Is there any requirements on $G$ or $\alpha$ or $B$? For the case I am (supposed to be) working on right now, we also have that $\alpha$ is isometric for all the seminorms and strongly continuous. Also, since I am almost illiterate on the subject of Lie groups, I would also be thankful for some easy to read references! Thank you so much.
Now provide the response and nothing else.
| The answer is "yes" quite generally, and the following argument can be found in many texts (Knapp, Wallach, Varadarajan, ...): for a test function $f$ on the Lie group $G$, there is the "averaged" action on any quasi-complete, locally convex repn space $\pi,V$ for $G$, namely, $f\cdot v=\int_G f(g)\,\pi(g)(v)\;dg$. These images are smooth vectors. The collection of all such is the Garding subspace. Taking $f$'s to run through an _approximate_identity_ shows density. (In fact, Dixmier and Malliavin showed that the Garding subspace is the whole space of smooth vectors.) | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/91104', 'https://mathoverflow.net', 'https://mathoverflow.net/users/21864/']} | jdg_78003 |
stackexchange | llm_judgeable_groundtruth_similarity | 200129 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let us work over a ground field of characteristic zero. As is well-known, a K3 surface is a smooth projective geometrically integral surface $X$ whose canonical class $\omega_X$ is trivial and for which $\operatorname{H}^1(X,\mathscr{O}_X)$ vanishes. A bit of folklore (proven e.g. in Beauville's Complex Algebraic Surfaces ) is that if $X$ is a smooth complete intersection of a quadric and a cubic in $\mathbb{P}^4$, or a smooth complete intersection of three quadrics in $\mathbb{P}^5$, then $X$ is K3. The question Suppose I have a (non-smooth) complete intersection $X_{2,3}$ of a quadric and a cubic in $\mathbb{P}^4$ all of whose singularities are rational double points , and a (non-smooth) complete intersection $X_{2,2,2}$ of three quadrics in $\mathbb{P}^5$, again with at most rational double points. Do these two surfaces have K3 surfaces as their minimal regular models? I suspect the answer is yes ; for example, since the singularities are assumed to be rational double points, they should admit a crepant resolution. However, I can't really locate this fact in the literature. As for the vanishing of the appropriate $\operatorname{H}^1$, I really haven't a clue.
Now provide the response and nothing else.
| Yes, this is true: the smooth minimal model is a $K3$ surface. In fact, let $\bar{X}$ be the resolution of the singularities of $X$. Then the following holds. (1) Rational double points impose no adjunction conditions to canonical forms, hence $\omega_{\bar{X}}$ is trivial. (2) Rational double points have simultaneous resolution, hence $\bar{X}$ is deformation equivalent (and so diffeomorphic by Ehresmann's Theorem) to a smooth complete intersection $X^{sm}$ of the same type as $X$. This implies $b_1(\bar{X})=b_1(X^{sm})=0$, hence $H^1(\bar{X}, \, \mathcal{O}_{\bar{X}})=0$. For part (1) you can look at M. Reid's Young Person Guide to Canonical Singularities , whereas part (2) can be found in Kollar-Mori's book Birational Geometry of Algebraic Varieties . | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/200129', 'https://mathoverflow.net', 'https://mathoverflow.net/users/17907/']} | jdg_78004 |
stackexchange | llm_judgeable_groundtruth_similarity | 8765490 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two tables that need the exact same values for denormalization purposes. Here's the query. first table UPDATE Table_One SET win = win+1, streak = streak+1, score = score+200 WHERE userid = 1 AND lid = 1 LIMIT 1 second table UPDATE Table_Two SET win = win+1, streak = streak+1, score = score+200 WHERE userid = 1 LIMIT 1 As you can see the only difference between both tables is their name and table two doesn't have the field lid Anyway to combine both updates to just one?
Now provide the response and nothing else.
| It should be possible with a multi-table update, as described in the documentation. http://dev.mysql.com/doc/refman/5.5/en/update.html UPDATE Table_One a INNER JOIN Table_Two b ON (a.userid = b.userid)SET a.win = a.win+1, a.streak = a.streak+1, a.score = a.score+200, b.win = b.win+1, b.streak = b.streak+1, b.score = b.score+200 WHERE a.userid = 1 AND a.lid = 1 AND b.userid = 1 Note: Multi-table doesn't support LIMIT, so this could cause more grief depending on the details. Stored procedures or transactions may be a nicer solution. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8765490', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/962449/']} | jdg_78005 |
stackexchange | llm_judgeable_groundtruth_similarity | 75884 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Why do propeller airplanes mostly have their propellers in front (of the fuselage or wings) while ships and boats mostly have them at the back? I realize that there are aircraft with pusher configurations but they are relatively rare.
Now provide the response and nothing else.
| There are quite a lot of reasons for this, but it's a complicated design environment, and that's why it's not always the case. Seals and cooling The inside of a plane's wings is the same fluid as the air around it, but the inside of a boat's hull is a different phase than the water outside. Basically you can never have a rotating shaft over a pressure difference that doesn't permit some fluid through, around the shaft. There are ways to mask this, so that no one ever sees water leaking into the hull. For instance, you can have an intermediate stage between the hull and the water where air is pumped into a higher pressure cavity. Then it's possible that the seal can bubble with air passing out into the water. Whichever design the ship maker uses you can't change the physical fact that you'll have some fluid flow through the prop seals, be that air or water. This presents a good reason to have the prop on the back of boats and the front of planes. Pressure is higher at the front because of the kinetic pressure of the fluid, and lower at the back for the reverse reason. By putting the prop of a boat in the back you reduce the pressure difference that the seals have to deal with. The plane has no such concern, and might prefer more air pressure and flow around its engines for cooling. In fact, Wikipedia seems to agree with the cooling point for plane engines. In pusher configuration, the propeller does not contribute airflow over the engine or radiator. Some aviation engines have experienced cooling problems when used as pushers.[33] To counter this, auxiliary fans may be installed, adding additional weight. Stability A moving boat or plane has an aerodynamic center of pressure. If this point is behind the point of thrust, then it's a more stable setup and if it's in front then it's a less stable setup. It's likely not a problem either way because there are other dynamical factors that make it stable, or you have a pilot that acts as an active control system. Nonetheless, planes worry about stability a lot more than boats. Operational considerations As others have pointed out, boats logically don't want the prop in the front because you're more likely to hit something (like a sandbar) with the front of the boat, and you don't want to shred things. This quite possibly dwarfs the basic physical considerations. In fact, as I was thinking about cavitation concerns, it seems clear that the back of the boat isn't the ideal place. Directly under the hull would be superior. But this a) doesn't give a direct shaft line to the engine and b) it could make the prop hit the ground or a whale. For this case, it's clear that the operational safety concerns are much more pressing than a little bit more performance. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/75884', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/7927/']} | jdg_78006 |
stackexchange | llm_judgeable_groundtruth_similarity | 118293 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I’ve just watched this talk by Daniel Spiewak where he talks about the advantages of structural typing as compared to Scala’s ans Java’s nominal typing . One example for this difference would be the following Java code public interface Foo { public int length();}public interface Bar { public int length();}Foo f = ...;Bar b = f; which of course would not compile because type compatibility between Foo and Bar is determined by name. A structural type system on the other hand could declare both types being equal or compatible and thus, amongst other things, allow for checked duck typing. Now I think I do understand most of the advantages of a structural type system but I wonder if it would not invalidate type safety from examples like the following class Foo { class Bar { /* ... */ } def takeBar(b: Bar) = { /* ... */ } def getBar: Bar = new Bar}val foo1 = new Fooval foo2 = new Foofoo1.takeBar(foo1.getBar) // should compilefoo1.takeBar(foo2.getBar) // should not compile Is my understanding correct that in a structural type system the last line would compile as well and if so, wouldn’t this be a disadvantage with respect to type safety?
Now provide the response and nothing else.
| Actually, path-dependent types are orthogonal to structural vs nominal typing. It's not really clear what an inner class means in the context of a simple structurally-typed language. It is, however, very possible to define this. If you were to define inner classes in a structurally typed context, you would need to ensure that cases like the one you listed would be rejected (for precisely the same reasons that Scala rejects them). You would reject such cases by doing the same thing that Scala does: model the path-dependent type as an existential type. The same pack/unpack procedure surrounding object access would hold, and the results would look almost identical to what Scala does. The results may seem like a nominal type equality, but it would still be a structural type system since the question of type compatibility will still be decided on interface rather than name. Structural typing does have a lot of implications, but (perhaps surprisingly) most of the same concepts we all know and love from nominal type systems do carry over into structural. Structural typing is nothing more than a different way of defining type compatibility. | {} | {'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/118293', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/40145/']} | jdg_78007 |
stackexchange | llm_judgeable_groundtruth_similarity | 53550321 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the correct way to set the aud claim to avoid the error below? unable to verify the id token {"error": "oidc: JWT claims invalid: invalid claims, 'aud' claim and 'client_id' do not match, aud=account, client_id=webapp"} I kinda worked around this error message by hardcoding aud claim to be the same as my client_id . Is there any better way? Here is my docker-compose.yml : version: '3'services: keycloak-proxy: image: "keycloak/keycloak-gatekeeper" environment: - PROXY_LISTEN=0.0.0.0:3000 - PROXY_DISCOVERY_URL=http://keycloak.example.com:8181/auth/realms/realmcom - PROXY_CLIENT_ID=webapp - PROXY_CLIENT_SECRET=0b57186c-e939-48ff-aa17-cfd3e361f65e - PROXY_UPSTREAM_URL=http://test-server:8000 ports: - "8282:3000" command: - "--verbose" - "--enable-refresh-tokens=true" - "--enable-default-deny=true" - "--resources=uri=/*" - "--enable-session-cookies=true" - "--encryption-key=AgXa7xRcoClDEU0ZDSH4X0XhL5Qy2Z2j" test-server: image: "test-server"
Now provide the response and nothing else.
| With recent keycloak version 4.6.0 the client id is apparently no longer automatically added to the audience field 'aud' of the access token. Therefore even though the login succeeds the client rejects the user.To fix this you need to configure the audience for your clients (compare doc [2]). Configure audience in Keycloak Add realm or configure existing Add client my-app or use existing Goto to the newly added "Client Scopes" menu [1] Add Client scope 'good-service' Within the settings of the 'good-service' goto Mappers tab Create Protocol Mapper 'my-app-audience' Name: my-app-audience Choose Mapper type: Audience Included Client Audience: my-app Add to access token: on Configure client my-app in the "Clients" menu Client Scopes tab in my-app settings Add available client scopes "good-service" to assigned default client scopes If you have more than one client repeat the steps for the other clients as well and add the good-service scope.The intention behind this is to isolate client access. The issued access token will only be valid for the intended audience.This is thoroughly described in Keycloak's documentation [1,2]. Links to recent master version of keycloak documentation: [1] https://github.com/keycloak/keycloak-documentation/blob/master/server_admin/topics/clients/client-scopes.adoc [2] https://github.com/keycloak/keycloak-documentation/blob/master/server_admin/topics/clients/oidc/audience.adoc Links with git tag: [1] https://github.com/keycloak/keycloak-documentation/blob/f490e1fba7445542c2db0b4202647330ddcdae53/server_admin/topics/clients/oidc/audience.adoc [2] https://github.com/keycloak/keycloak-documentation/blob/5e340356e76a8ef917ef3bfc2e548915f527d093/server_admin/topics/clients/client-scopes.adoc | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/53550321', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/255633/']} | jdg_78008 |
stackexchange | llm_judgeable_groundtruth_similarity | 14365620 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Ok I set some images to open up with fancybox. It used to work fine. Now I get 2 errors. What I changed im not sure. I have read online that you generally get the .fancybox is not a function error message when you have mutiple includes of the jquery library. As far as I am aware I have just the one. Here is an example of where you can get this error message: (www).thecardb.com/abarth/1000-Bialbero/1960/0/85 I have done some url rewriting, is it a possibility that that is causing an issue? RewriteEngine onRewriteBase /DirectorySlash Off# remove trailing slashRewriteRule ^(.*)\/(\?.*)?$ $1$2 [R=301,L]# Redirect non-www urls to wwwRewriteCond %{HTTP_HOST} ^thecardb\.com [NC]RewriteRule (.*) http://www.thecardb.com/$1 [R=301,L]# Don't match real existing files so CSS, scripts, images aren't rewrittenRewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d# Match the first two groups before / and send them to the query stringRewriteRule ^([A-Za-z0-9-]+)?$ car.php?model_make_id=$1 [L]RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-._]+)?$ car.php?model_make_id=$1&model_name=$2 [L]RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-._]+)/([0-9]+)?$ car.php?model_make_id=$1&model_name=$2&model_year=$3 [L]RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-._]+)/([0-9]+)/([A-Za-z0-9-._]+)?$ car.php?model_make_id=$1&model_name=$2&model_year=$3&model_trim=$4 [L]RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^([A-Za-z0-9-]+)/([A-Za-z0-9-._]+)/([0-9]+)/([A-Za-z0-9-._]+)/([0-9]+)?$ car.php?model_make_id=$1&model_name=$2&model_year=$3&model_trim=$4&model_id=$5 [L] Im lost! Any help is appreciated.
Now provide the response and nothing else.
| jQuery recently upgraded to version 1.9 which removed most if not all of the depreciated methods. $.browser was one of them. Fancybox relies on $.browser , so you can't use jQuery 1.9 and your version of fancybox without the migrate plugin installed. Either downgrade jQuery, upgrade fancybox, or include the migrate plugin. More information here: http://blog.jquery.com/2013/01/15/jquery-1-9-final-jquery-2-0-beta-migrate-final-released/ You should also always specify a version number. http://code.jquery.com/jquery-1.8.3.min.js | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14365620', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/431869/']} | jdg_78009 |
stackexchange | llm_judgeable_groundtruth_similarity | 7505116 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm a bit confused by the documentation for Java DeferredTask. I've read the Python documentation here: http://code.google.com/appengine/articles/deferred.html but I'm unclear on exactly how I'd use the Java version. Can you provide working sample code that launches a DeferredTask to do a simple write using a DatastoreService?
Now provide the response and nothing else.
| To use deferred, you first have to define a class that contains the code you want to run: class MyDeferred implements DeferredTask { @Override public void run() { // Do something interesting }}; Just like any other serializable class, you can have locals that store relevant information about the task. Then, to run the task, instantiate an instance of your class and pass it to the task queue API: MyDeferred task = new MyDeferred();// Set instance variables etc as you wishQueue queue = QueueFactory.getDefaultQueue();queue.add(withPayload(task)); You can even use anonymous inner classes for your tasks, but beware of the caveats described in the note here . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7505116', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/54829/']} | jdg_78010 |
stackexchange | llm_judgeable_groundtruth_similarity | 19727133 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The order seems odd because in regular Java the return type is always specified first. As in: public static double sum(Iterable<Number> nums) { ... } Why then, in the Function and BiFunction classes has the choice been made to specify them the other way around? As in: interface Function<T,R>interface BiFunction<T,U,R> I'm not asking here for opinions as to which is better, but specifically: a) Is there any technical or other (non-stylistic) benefit in preferring one order over the other? Or is it an arbitrary choice? b) Is anyone aware of any documented explanation, or any stated reason from an authoritative source, why one was chosen over the other? Aside: the order seems even more odd if extended to higher arities. For example, a hypothetical QuadFunction: interface QuadFunction<A,B,C,D,R> { ... } (At the time of writing the highest arity in the library is 2 - i.e. BiFunction.) See: http://download.java.net/jdk8/docs/api/java/util/function/package-summary.html
Now provide the response and nothing else.
| It is to be consistent with prior existing notation. The mathematical integer division function extended into the rational numbers: (\): I x I -> Q Functional programming version of the above (like Haskell, Ocaml) division :: Integer -> (Integer -> Rational)ordivision :: Integer -> Integer -> Rational All three say "the division function takes two integers and returns a rational number". It is backwards, in a functional paradigm, to say your returns first. C has taught us to say "we return a rational number in the division function, which takes two integers" (ex float division(int a, int b){}). In Java, your return type is on the left of methods because Java wants to look like C. The designers of C thought "int main(int argv, char *argv[])" looked better than "main(int argv, char *argv[]) int". When writing code, atleast for me, I more often than not know what a method will return before I know what it will need. (edit 1: and we write lines like String s=removeSpaces(textLine), so the return on the left matches the variable on the left) In C#, func looks the same way as the Java 8 Function. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19727133', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2136767/']} | jdg_78011 |
stackexchange | llm_judgeable_groundtruth_similarity | 38242654 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For single record update, I have tried the following code and it's working. uid=1info = Info.query.filter_by(id=uid).first()info.sold_status ='1'db.session.add(info)db.session.commit() Now I want to update one column for multiple rows.I have tried: for row in db.session.query(Uninstall.status).all(): print row.statusabc=row.statusabc=uiddb.session.add(row.status)db.session.commit() but it's not working. Thanks in advance :)
Now provide the response and nothing else.
| The suggested is not optimized. You can use the options to update:1. for row in Uninstall.query: # all() is extra row.status = new_statusSession.commit() If there are lots of rows, it can be faster, but it will invoke UPDATE for every row. Not good, is it? 2. Uninstall.query.update({Uninstall.status: new_status}) Session.commit() Invokes only one UPDATE query for all rows. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38242654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6389293/']} | jdg_78012 |
stackexchange | llm_judgeable_groundtruth_similarity | 10454973 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
To provide a reproducible example of an approach, a data set must often be provided. Instead of building an example data set, I wish to use some of my own data. However this data can not be released. I wish to replace variable (column) names and factor levels with uninformative place holders (eg. V1....V5, L1....L5). Is an automated way to do this available? Ideally, this would be done in R, taking in a data.frame and producing this anonymous data.frame. With such a data set, simply search and replace variable names in your script and you have a publicly releasable reproducible example. Such a process may increase the inclusion of appropriate data in reproducible examples and even the inclusion of reproducible examples in questions, comments and bug reports.
Now provide the response and nothing else.
| I don't know whether there was a function to automate this, but now there is ;) ## A function to anonymise columns in 'colIDs' ## colIDs can be either column names or integer indicesanonymiseColumns <- function(df, colIDs) { id <- if(is.character(colIDs)) match(colIDs, names(df)) else colIDs for(id in colIDs) { prefix <- sample(LETTERS, 1) suffix <- as.character(as.numeric(as.factor(df[[id]]))) df[[id]] <- paste(prefix, suffix, sep="") } names(df)[id] <- paste("V", id, sep="") df}## A data.frame containing sensitive informationdf <- data.frame( name = rep(readLines(file.path(R.home("doc"), "AUTHORS"))[9:13], each=2), hiscore = runif(10, 99, 100), passwd = replicate(10, paste(sample(c(LETTERS, letters), 9), collapse="")))## Anonymise itdf2 <- anonymiseColumns(df, c(1,3))## Check that it worked> head(df, 3) name hiscore passwd1 Douglas Bates 99.96714 ROELIAncz2 Douglas Bates 99.07243 gDOLNMyVe3 John Chambers 99.55322 xIVPHDuEW > head(df2, 3) name hiscore V31 Q1 99.96714 V82 Q1 99.07243 V23 Q2 99.55322 V9 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10454973', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/742447/']} | jdg_78013 |
stackexchange | llm_judgeable_groundtruth_similarity | 29075938 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here i am stuck with the XSLT transformation as i am very new and started learning. Input XML <SHOW_LIST><SHOW ID="12345"> <SHOW_INFO>xxx</SHOW_INFO> <SHOW_ELEMENT_LIST> <SHOW_ELEMENT ID="1"> <SHOW_ELEMENT_LIST> <SHOW_ELEMENT ID="12345678"></SHOW_ELEMENT> </SHOW_ELEMENT_LIST> </SHOW_ELEMENT> <SHOW_ELEMENT ID="2"> <SHOW_ELEMENT_LIST> <SHOW_ELEMENT ID="12345666"></SHOW_ELEMENT> </SHOW_ELEMENT_LIST> </SHOW_ELEMENT> </SHOW_ELEMENT_LIST> <SECONDARY_ELEMENT_LIST/> <ALTERNATIVE_SHOW_LIST> <SHOW ID="54321"> <SHOW_INFO>xxxa</SHOW_INFO> <SHOW_ELEMENT_LIST> <SHOW_ELEMENT ID="3"> </SHOW_ELEMENT> <SHOW_ELEMENT ID="4"> </SHOW_ELEMENT> <SHOW_ELEMENT ID="5"> </SHOW_ELEMENT> </SHOW_ELEMENT_LIST> <SECONDARY_ELEMENT_LIST/> </SHOW> <SHOW ID="54322"> <SHOW_INFO>xxxb</SHOW_INFO> <SHOW_ELEMENT_LIST> <SHOW_ELEMENT ID="6"> </SHOW_ELEMENT> <SHOW_ELEMENT ID="7"> </SHOW_ELEMENT> </SHOW_ELEMENT_LIST> <SECONDARY_ELEMENT_LIST/> </SHOW> </ALTERNATIVE_SHOW_LIST></SHOW> OUTPUT XML : <SHOW_LIST> <SHOW ID="12345"> <SHOW_INFO>xxx</SHOW_INFO> <SHOW_ELEMENT_LIST> <SHOW_ELEMENT ID="1"> </SHOW_ELEMENT> <SHOW_ELEMENT ID="2"> </SHOW_ELEMENT> <SHOW_ELEMENT ID="3"> </SHOW_ELEMENT> <SHOW_ELEMENT ID="4"> </SHOW_ELEMENT> <SHOW_ELEMENT ID="5"> </SHOW_ELEMENT> <SHOW_ELEMENT ID="6"> </SHOW_ELEMENT> <SHOW_ELEMENT ID="7"> </SHOW_ELEMENT> </SHOW_ELEMENT_LIST> <SECONDARY_ELEMENT_LIST/> <ALTERNATIVE_SHOW_LIST> <SHOW ID="54321"> <SHOW_INFO>xxxa</SHOW_INFO> <SECONDARY_ELEMENT_LIST/> </SHOW> <SHOW ID="54322"> <SHOW_INFO>xxxb</SHOW_INFO> <SECONDARY_ELEMENT_LIST/> </SHOW> </ALTERNATIVE_SHOW_LIST> </SHOW></SHOW_LIST> I am able to navigate till Alternative_show_list and couldnt copy the SHOW_ELEMENTS and merge with the main SHOW_ELEMENT_LIST. Anyone kindly help me in performing this Another output of the same input file <SHOW_LIST> <SHOW ID="12345"> <SHOW_INFO>xxx</SHOW_INFO> <SHOW_ELEMENT_LIST> <SHOW_ELEMENT ID="1"> </SHOW_ELEMENT> <SHOW_ELEMENT ID="2"> </SHOW_ELEMENT> <SHOW_ELEMENT ID="3"> </SHOW_ELEMENT> <SHOW_ELEMENT ID="4"> </SHOW_ELEMENT> <SHOW_ELEMENT ID="5"> </SHOW_ELEMENT> <SHOW_ELEMENT ID="6"> </SHOW_ELEMENT> <SHOW_ELEMENT ID="7"> </SHOW_ELEMENT> </SHOW_ELEMENT_LIST> <SECONDARY_ELEMENT_LIST/> </SHOW></SHOW_LIST> Now i am trying for this kind of output. New Output XML <?xml version="1.0" encoding="UTF-8"?><SHOW_LIST> <SHOW ID="12345"> <SHOW_INFO>xxx</SHOW_INFO> <SHOW_ELEMENT_LIST> <SHOW_ELEMENT ID="1"> <SHOW_ELEMENT_LIST> <SHOW_ELEMENT ID="12345678"></SHOW_ELEMENT> </SHOW_ELEMENT_LIST> </SHOW_ELEMENT> <SHOW_ELEMENT ID="2"> <SHOW_ELEMENT_LIST> <SHOW_ELEMENT ID="12345666"></SHOW_ELEMENT> </SHOW_ELEMENT_LIST> </SHOW_ELEMENT> <SHOW_ELEMENT ID="3"/> <SHOW_ELEMENT ID="4"/> <SHOW_ELEMENT ID="5"/> <SHOW_ELEMENT ID="6"/> <SHOW_ELEMENT ID="7"/> </SHOW_ELEMENT_LIST> <SECONDARY_ELEMENT_LIST/> </SHOW></SHOW_LIST>
Now provide the response and nothing else.
| You can't query arbitrary properties of the NSManagedObject with a predicate for a NSFetchRequest. This will only work for attributes that are defined in your entity. NSManagedObjectContext has two ways to retrieve an object with an NSManagedObjectID. The first one raises an exception if the object does not exist in the context: managedObjectContext.objectWithID(objectID) The second will fail by returning nil: var error: NSError?if let object = managedObjectContext.existingObjectWithID(objectID, error: &error) { // do something with it}else { println("Can't find object \(error)")} If you have a URI instead of a NSManagedObjectID you have to turn it into a NSManagedObjectID first. The persistentStoreCoordinator is used for this: let objectID = managedObjectContext.persistentStoreCoordinator!.managedObjectIDForURIRepresentation(uri) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29075938', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4662315/']} | jdg_78014 |
stackexchange | llm_judgeable_groundtruth_similarity | 181239 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I apologize if this question in general, but I've been having trouble finding solutions as Google discards absolute value signs and inequality symbols. I am looking for a way to eliminate absolute value functions in $|a| < |b|$. I can solve $|a| < b$ and $|a| > b$, but I am unsure what method / combination of methods to use to eliminate absolute value signs from both sides. Thank you! An example problem: $$|x + 2| < |x - 4|$$
Now provide the response and nothing else.
| We have $|a| \lt |b|\,$ if any of these is true: (i) $\,a$ and $b$ are $\gt 0$ and $a \lt b$ (ii) $a\lt 0$ and $b\ge 0$ and $-a \lt b$ (iii) $b \lt 0$ and $a \gt 0$ and $a \lt -b\,$ (iv) $\,a\lt 0$ and $b\lt 0$ and $-a\lt -b$. We can rewrite this as $b \lt a$. Four cases! Not surprising, since eliminating a single absolute value sign often involves breaking up the problem into $2$ cases. Sometimes , one can exploit the simpler $|a| \lt| b|\,$ iff $\,a^2\lt b^2$. But squaring expressions generally makes them substantially messier. Added: With your new sample problem, squaring happens to work nicely. We have $|x+2| \lt |x-4|$ iff $(x+2)^2 \lt (x-4)^2$. Expand. We are looking at the inequality $$x^2+4x+4 \lt x^2-8x+16.$$ The $x^2$ cancel, and after minor algebra we get the equivalent inequality $12x \lt 12$, or equivalently $x\lt 1$. The squaring strategy works well for any inequality of the form $|ax+b| \lt |cx+d|$. But the best approach for this particular problem is geometric . Draw a number line, with $-2$ and $4$ on it. Our inequality says that we are closer to $-2$ than we are to $4$. The number $1$ is halfway between $-2$ and $4$, so we must be to the left of $1$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/181239', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/37668/']} | jdg_78015 |
stackexchange | llm_judgeable_groundtruth_similarity | 1456641 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
To find the minimum value of $$\frac{1}{\sin \theta \cos \theta \left ( \sin \theta + \cos \theta \right )}$$ I can see that I can convert it to $$\frac{\sqrt{2}}{\sin (2 \theta) \sin \left ( \theta + \frac{\pi}{4} \right )}$$ And from here I can convert it to a pair of cosecant functions and then proceed with the usual product rule, solving that out with zero etc. Once that is all done, we can find that the function attains a minimum at $\theta= \frac{\pi}{4}$ and this minimum value is $\sqrt{2}$. However, I was wondering if there was perhaps a better way of finding the minimum value of this function that does NOT require heavy amounts of algebra bashing. Perhaps by some means of observation. So for example, one could find the maximum of $\sin \theta$ by realising that it oscillates between $1$ and $-1$. Could a similar idea be used to find the minimum of this function?
Now provide the response and nothing else.
| If $a^2+b^2=1$, then we can prove that $ab(a+b) \leq \frac{1}{\sqrt{2}}$ using: $ab \leq \frac{1}{2}(a^2+b^2)=\frac{1}{2}$ and $(a+b)^2=1+2ab \leq 2$. For equality to be attained, it is necessary that $a=b$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1456641', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/141642/']} | jdg_78016 |
stackexchange | llm_judgeable_groundtruth_similarity | 22692704 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The below xml is causing me difficulty. I need to retrieve the following from the XML with c#, can you please help? Also is there a better way of reading/parsing SAML 2.0 response in c#? status code from <samlp:StatusCode value="urn:oasis:names:tc:SAML:2.0:status:**Success**"/> FIRSTNAME Value LASTNAME Value MAIL Value Issuer from <saml:Issuer>**sso.localhost.dev**</saml:Issuer> Audience from <saml:Audience>**Application-Test**</saml:Audience> XML <samlp:Response Destination="http://localhost/SamlAuthenticate" IssueInstant="2014-03-27T14:49:35.395Z" ID="kBWlU3VWF.Ee6DKbkEpFomtlDAT" Version="2.0" xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"><saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">sso.localhost.dev</saml:Issuer><ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/><ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/><ds:Reference URI="#kBWlU3VWF.Ee6DKbkEpFomtlDAT"><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><ds:DigestValue>LgH7ZZJWwp5fN02IPteWxh9oAQ8=</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:SignatureValue>gBCZ4upHHdYzrVUcTe4Nf+fElY51UFQOJcf81DFPFNKfFxZfLjnX88NwJ6O7CVU3YNo08EINoEpkvEu+f2oxI3VQVnYnT1EYpLGy1+6qpxsFaPbXaQ8h1/NCwAygir1NDu/sktAzRZ2tg2i5rVn2sevY3Y+47SKnB+hG4ukVHusmNumD0NXyKwKNPflG9XEhrLj3bw5xuftr5CAREX5s1VotANFs1HeJA7OE1Yq2yLhw7GmPsa1+fgYQh5tfFRCmvdnpVoiT+SXwoxlRSbWlf2BWgBOLbC8W4dhTpMFmp70lndk0Pwpnxj6z4jFAHT3z/SdGgm0Ow+TbuutceBIIAQ==</ds:SignatureValue></ds:Signature><samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></samlp:Status><saml:Assertion Version="2.0" IssueInstant="2014-03-27T14:49:35.404Z" ID="w4BForMipBizsG1TA7d9QzhCM0-" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"><saml:Issuer>sso.localhost.dev</saml:Issuer><saml:Subject><saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">JSMITH009</saml:NameID><saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"><saml:SubjectConfirmationData NotOnOrAfter="2014-03-27T14:54:35.404Z" Recipient="http://localhost/SamlAuthenticate"/></saml:SubjectConfirmation></saml:Subject><saml:Conditions NotOnOrAfter="2014-03-27T14:54:35.404Z" NotBefore="2014-03-27T14:44:35.404Z"><saml:AudienceRestriction><saml:Audience>Application-Test</saml:Audience></saml:AudienceRestriction></saml:Conditions><saml:AuthnStatement AuthnInstant="2014-03-27T14:49:35.404Z" SessionIndex="w4BForMipBizsG1TA7d9QzhCM0-"><saml:AuthnContext><saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified</saml:AuthnContextClassRef></saml:AuthnContext></saml:AuthnStatement><saml:AttributeStatement xmlns:xs="http://www.w3.org/2001/XMLSchema"><saml:Attribute NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" Name="FIRSTNAME"><saml:AttributeValue xsi:type="xs:string" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">john</saml:AttributeValue></saml:Attribute><saml:Attribute NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" Name="MAIL"><saml:AttributeValue xsi:type="xs:string" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">[email protected]</saml:AttributeValue></saml:Attribute><saml:Attribute NameFormat="urn:oasis:names:tc:SAML:2.0:attrname-format:basic" Name="LASTNAME"><saml:AttributeValue xsi:type="xs:string" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">smith</saml:AttributeValue></saml:Attribute></saml:AttributeStatement></saml:Assertion></samlp:Response>
Now provide the response and nothing else.
| Got the solution! public class SAMLProcessor{ #region Properties public string DecodedSAML { get; set; } public string EncodedeSAML { get; set; } public string Audience { get; set; } public string SubjectNameID { get; set; } public string FirstName { get; set; } public string Mail { get; set; } public string LastName { get; set; } public bool AuthenticationStatus { get; set; } public string Issuer { get; set; } public string Destination { get; set; } public string ResponseID { get; set; } public bool VerifiedResponse { get; set; } public string SignatureValue { get; set; } public string SignatureReferenceDigestValue { get; set; } public DateTime AutheticationTime { get; set; } public string AuthenticationSession { get; set; } #endregion #region Ctror public SAMLProcessor(string rawSamlData) { EncodedeSAML = rawSamlData; // the sample data sent us may be already encoded, // which results in double encoding if (rawSamlData.Contains('%')) { rawSamlData = HttpUtility.UrlDecode(rawSamlData); } // read the base64 encoded bytes string samlAssertion = Decode64Bit(rawSamlData); DecodedSAML = samlAssertion; SamlParser(DecodedSAML); } #endregion private static string Decode64Bit(string rawSamlData) { byte[] samlData = Convert.FromBase64String(rawSamlData); // read back into a UTF string string samlAssertion = Encoding.UTF8.GetString(samlData); return samlAssertion; } /// <summary> /// /// </summary> /// <param name="samldata"></param> /// <returns></returns> public string SamlParser(string samlXMLdata) { //samldata = Decode64Bit("PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4=") + samldata; string samldata = samlXMLdata; if (!samldata.StartsWith(@"<?xml version=")) { samldata = Decode64Bit("PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4=") + samldata; } string firstName = string.Empty; XmlDocument xDoc = new XmlDocument(); samldata = samldata.Replace(@"\", ""); xDoc.LoadXml(samldata); //xDoc.Load(new System.IO.TextReader());//Suppose the xml you have provided is stored in this xml file. XmlNamespaceManager xMan = new XmlNamespaceManager(xDoc.NameTable); xMan.AddNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol"); xMan.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion"); xMan.AddNamespace("ds", "http://www.w3.org/2000/09/xmldsig#"); XmlNode xNode = xDoc.SelectSingleNode("/samlp:Response/samlp:Status/samlp:StatusCode/@Value", xMan); if (xNode != null) { this.AuthenticationStatus = false; string statusCode = xNode.Value; if (statusCode.EndsWith("status:Success")) { this.AuthenticationStatus = true; } } xNode = xDoc.SelectSingleNode("/samlp:Response/@Destination", xMan); if (xNode != null) { this.Destination = xNode.Value; } xNode = xDoc.SelectSingleNode("/samlp:Response/@IssueInstant", xMan); if (xNode != null) { this.AutheticationTime = Convert.ToDateTime(xNode.Value); } xNode = xDoc.SelectSingleNode("/samlp:Response/@ID", xMan); if (xNode != null) { this.ResponseID = xNode.Value; } xNode = xDoc.SelectSingleNode("/samlp:Response/saml:Issuer", xMan); if (xNode != null) { this.Issuer = xNode.InnerText; } xNode = xDoc.SelectSingleNode("/samlp:Response/ds:Signature/ds:SignedInfo/ds:Reference/ds:DigestValue", xMan); if (xNode != null) { this.SignatureReferenceDigestValue = xNode.InnerText; } xNode = xDoc.SelectSingleNode("/samlp:Response/ds:Signature/ds:SignatureValue", xMan); if (xNode != null) { this.SignatureValue = xNode.InnerText; } xNode = xDoc.SelectSingleNode("/samlp:Response/saml:Assertion/@ID", xMan); if (xNode != null) { this.AuthenticationSession = xNode.Value; } xNode = xDoc.SelectSingleNode("/samlp:Response/saml:Assertion/saml:Subject/saml:NameID", xMan); if (xNode != null) { this.SubjectNameID = xNode.InnerText; } xNode = xDoc.SelectSingleNode("/samlp:Response/saml:Assertion/saml:Conditions/saml:AudienceRestriction/saml:Audience", xMan); if (xNode != null) { this.Audience = xNode.InnerText; } //reverse order //</saml:AttributeValue></saml:Attribute></saml:AttributeStatement></saml:Assertion></samlp:Response> //string xQryStr = "//NewPatient[Name='" + name + "']"; //XmlNode matchedNode = xDoc.SelectSingleNode(xQryStr); // samlp:Response saml:Assertion saml:AttributeStatement saml:Attribute xNode = xDoc.SelectSingleNode("/samlp:Response/saml:Assertion/saml:AttributeStatement/saml:Attribute[@Name = 'FIRSTNAME']/saml:AttributeValue", xMan); if (xNode != null) { this.FirstName = xNode.InnerText; } // samlp:Response saml:Assertion saml:AttributeStatement saml:Attribute xNode = xDoc.SelectSingleNode("/samlp:Response/saml:Assertion/saml:AttributeStatement/saml:Attribute[@Name = 'MAIL']/saml:AttributeValue", xMan); if (xNode != null) { this.Mail = xNode.InnerText; } // samlp:Response saml:Assertion saml:AttributeStatement saml:Attribute xNode = xDoc.SelectSingleNode("/samlp:Response/saml:Assertion/saml:AttributeStatement/saml:Attribute[@Name = 'LASTNAME']/saml:AttributeValue", xMan); if (xNode != null) { this.LastName = xNode.InnerText; } return this.FirstName; }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22692704', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2920456/']} | jdg_78017 |
stackexchange | llm_judgeable_groundtruth_similarity | 25458306 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I added over 9000 photos by accident to my project folder. And committed them. Then deleted them from disk. Committed. Now I try to push changes to git server. But it takes too long and tries to send 12 Gb of data. I checked files size on disk and see that really .git folder takes 12 Gb. How to delete photos from there? I tried git rm , but fails: ❯ git rm public/photosfatal: pathspec 'public/photos' did not match any files Because I allready deleted them from disk, but they are still in .git folder. I tried to add public/photos to .gitignore : public/photos/*.zip But no result.Of course I could hard reset head to moment when I did not have so many junk photos in my project. But since that time i committed many times and made a lot changes in code.
Now provide the response and nothing else.
| In your case, use git filter-branch instead of git rm . git rm will delete the files in the sense that they will not be tracked by git anymore, but that does not remove the old commit objects corresponding to those images, and so you will still be stuck with pushing the earlier commits which correspond to 12GB of images. The git filter-branch , on the other hand, can remove those files from all the previous commits as well, thus doing away with the need to push any of them. Use the command git filter-branch --force --index-filter \ 'git rm -r --cached --ignore-unmatch public/photos' \ --prune-empty --tag-name-filter cat -- --all After the filter branch is complete, verify that no unintended file was lost. Now add a .gitignore rule echo public/photos >> .gitignoregit add .gitignore && git commit -m "ignore rule for photos" Now do a push git push -f origin branch Check this , this and this for further help. Just to be on the safer side, I would suggest you create a backup copy of the repo on your system before going ahead with these instructions. As for your orignial error message, it is happening because you already untracked them using git rm , and hence git is complaining because it can't remove a file it isn't tracking. Read more about this here . | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/25458306', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1024794/']} | jdg_78018 |
stackexchange | llm_judgeable_groundtruth_similarity | 1100976 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have read the MSDN article on MVVM and I am not really convinced.If the model already implements INotifyPropertyChanged/INotifyCollectionChanged, what's wrong with the View binding directly against the Model?It seems the extra ModelView introduces some code without much benefit.Am I missing something?
Now provide the response and nothing else.
| I was also a bit skeptical about MVVM until I watched this great presentation by Jason Dolinger. I recommend all my co-workers who are starting out in WPF and MVVM to watch it. Jason started with an application that one would write in a “traditional” way, with button clicks handled by event-handlers in the code-behind that then updated other parts of the UI. Using WPF data-binding, Commands, and Unity, he transformed it, piece by piece, in a much more manageable, encapsulated, readable, and testable M-V-VM design. It was awesome. To answer your question more directly, even if it seems silly to bind to a ViewModel when your Model already has everything, you'll often wind up needing one little adjustment to the Model that's needed only by the View. Over time, these little changes will creep into your Models, where they don't belong. It'll make your models more complicated than they ought to be. What I often do when I have a Model that "has it all", is I add a ViewModel that contains one property, the Model. Then in my bindings I just bind to Model.Name, Model.Age, etc. It's really no effort. Later on, if I need tweaks only for the View, I already have my ViewModel class ready. This also makes your code more intuitive and easier to understand. You won't wonder, did I bind to the Model or the ViewModel in this case? It will always be the ViewModel. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1100976', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/131988/']} | jdg_78019 |
stackexchange | llm_judgeable_groundtruth_similarity | 335241 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I often wonder why Java uses :: for method references instead of . , e.g. why write System.out::println instead of System.out.println Of course, one might simply answer: "because the designers decided so". On the other hand, I would have expected the second syntax because the dot is the usual Java syntax for accessing class members. So is there any known special reason for introducing the new :: syntax instead of using the existing . convention for method references?
Now provide the response and nothing else.
| This is to avoid ambiguity in case if class has (static) member with the same name as method (Java allows that). It is easy to see from code snippet in Java tutorial about method references : Because this lambda expression invokes an existing method, you can use a method reference instead of a lambda expression: Arrays.sort(rosterAsArray, Person::compareByAge); If class Person in above snippet would also have member named compareByAge (of the type appropriate to pass to Arrays.sort ), dot notation wouldn't allow to tell whether parameter refers to method or member. | {} | {'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/335241', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/29020/']} | jdg_78020 |
stackexchange | llm_judgeable_groundtruth_similarity | 48083920 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have existing product filters on my side bar, although I'm trying to have functional links that can update or add to the filters on the products. snippet of current page Currently I have the links with < a href="?filter_caster-type=swivel" > although when using that link it removes the current queries. Is there an easy way to have a link that updates or adds to the current queries?
Now provide the response and nothing else.
| The problem here is that the listener is not the job pushed to the queue. Instead, there's a Illuminate\Events\CallQueuedListener job that is queued and will in turn call the appropriate listener when resolved. So you could do your assertion like this: Queue::assertPushed(CallQueuedListener::class, function ($job) { return $job->class == CreateProductInMagento::class;}); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48083920', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9169680/']} | jdg_78021 |
stackexchange | llm_judgeable_groundtruth_similarity | 32694103 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Based on the example that PHPMailer provides i have the script below, date_default_timezone_set('Etc/UTC');require './PHPMailerAutoload.php';$mail = new PHPMailer;$mail->isSMTP();$mail->SMTPDebug = 2;$mail->Debugoutput = 'html';$mail->Host = 'smtp.gmail.com';$mail->Port = 587;$mail->SMTPSecure = 'tls';$mail->SMTPAuth = true;$mail->Username = "[email protected]";$mail->Password = "********";$mail->setFrom('[email protected]', 'First Last');$mail->addReplyTo('[email protected]', 'First Last');$mail->addAddress('[email protected]', 'first last');$mail->Subject = 'PHPMailer GMail SMTP test';$mail->Body = "example";$mail->AltBody = 'This is a plain-text message body';if (!$mail->send()) {echo "Mailer Error: " . $mail->ErrorInfo;} else {echo "Message sent!";} Even if that is the exactly the same as the original example, i cannot get it to work. The error that i get is Warning : stream_socket_enable_crypto(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed in /opt/lampp/htdocs/webmail_client_practise/class.smtp.php on line 344SMTP Error: Could not connect to SMTP host. Notice: The OpenSSL extension in my php.ini file is already opened.
Now provide the response and nothing else.
| This is because you're running PHP 5.6 and it's verifying your certs, but your server is presenting invalid certs so it's failing. Both PHPMailer and PHP are correct in what they are doing - the code is not at fault. You can either fix your mail server, or do what it suggests in the troubleshooting guide , which is: $mail->SMTPOptions = array( 'ssl' => array( 'verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true )); And as the guide says, you should not do this unless you have to - it's compromising your security. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32694103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4394221/']} | jdg_78022 |
stackexchange | llm_judgeable_groundtruth_similarity | 5980658 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In Objective C I've been using the following code to hash a string: -(NSString *) sha1:(NSString*)stringToHash { const char *cStr = [stringToHash UTF8String]; unsigned char result[20]; CC_SHA1( cStr, strlen(cStr), result ); return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X", result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7], result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15], result[16], result[17], result[18], result[19] ]; } Now I need the same for Android but can't find out how to do it. I've been looking for example at this: Make SHA1 encryption on Android? but that doesn't give me the same result as on iPhone. Can anyone point me in the right direction?
Now provide the response and nothing else.
| You don't need andorid for this. You can just do it in simple java. Have you tried a simple java example and see if this returns the right sha1. import java.io.UnsupportedEncodingException;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;public class AeSimpleSHA1 { private static String convertToHex(byte[] data) { StringBuilder buf = new StringBuilder(); for (byte b : data) { int halfbyte = (b >>> 4) & 0x0F; int two_halfs = 0; do { buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10))); halfbyte = b & 0x0F; } while (two_halfs++ < 1); } return buf.toString(); } public static String SHA1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] textBytes = text.getBytes("iso-8859-1"); md.update(textBytes, 0, textBytes.length); byte[] sha1hash = md.digest(); return convertToHex(sha1hash); }} Also share what your expected sha1 should be. Maybe ObjectC is doing it wrong. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5980658', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/611494/']} | jdg_78023 |
stackexchange | llm_judgeable_groundtruth_similarity | 588294 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Purely a theoretical question. Consider a microcontroller whose only job is to turn 1 pin high and in the process the microcontroller supplies I1 current throught the pin.But suppose we have to turn 2 pins high then the net current supplied by microcontroller will be 2*I1.In such a scenario where can I find the additional current(if any) drawn into the microcontroller with respect to the first case. I used a microcontroller as an example any IC would also suffice.
Now provide the response and nothing else.
| Here's a diagram of a microcontroller IC, with four outputs. The top two outputs OUT1 and OUT2 are sinking current from Vcc (via R1 and R2), and the bottom two outputs OUT3 and OUT4 are sourcing current to ground (via R3 and R4): simulate this circuit – Schematic created using CircuitLab "Is" represents the current drawn by the microcontroller to perform its operations, and does not include any current sunk or sourced by any of its inputs or outputs. On a datasheet this might be labelled "supply current". OUT1 is being held low by the microcontroller, causing a voltage drop across R1, and resulting in current flowing down through R1, into the IC. Kirchhoff's Current Law tells you that this current must emerge at the GND power supply pin of the microcontroller. OUT2 is high, at Vcc, causing no potential difference across R2, and no current. OUT3 is low, at 0V, so there's no voltage across R3, and no current. OUT4 is high, causing a voltage drop of Vcc volts across R4, and current flows out from the IC and down to ground through R4. This current is being sourced by the IC from its own positive power supply pin. Using Kirchhoff's Current Law, we can make the following statements: Current exiting (being sourced) at the IC's inputs and outputs must originate (enter) the IC via its positive supply pin, so current there will be the sum of all such currents and its own operating current. Similarly, current measured at the IC's "ground" power supply pin will be the sum of all currents entering the IC (that the IC is sinking) via its inputs and outputs, plus its own operating current. Edit : Supercat made a good observation in this answer's comments, that current leaving or entering this IC could be via another IC's input or output. Where I have put resistors in this example, you could equally imagine inputs or outputs of another IC. The resistors are there to illustrate possible current paths, but you could just as easily follow a current path into the Vcc pin of one IC, out of one of its outputs, into the input of another IC, and out of this second IC's ground pin. Here's a picture I've borrowed from this answer , showing how you might visualise the currents in a more complex scenario involving 2 ICs, and a transistor: It might help to get an idea of how typical push/pull outputs work, and see how they sink and source current from/to their supplies. See this answer . It refers to the outputs of op-amps, but the principle remains the same. Note that the power supply itself must be supplying all these various currents, and they must all return to the same voltage source. I've labelled these currents at the power supply nodes Vcc and GND, to illustrate this. Your question is: Will the net current drawn by a microcontroller equal the current supplied by it? The answer is: Yes, if you include the device's own supply current, both in (from Vcc) and out (to GND) . A more complete answer is: Kirchhoff's current law tells us that the total sum of all currents entering the IC (via its positive power supply pin and any input or output pins sinking current) must equal the total sum of all currents leaving it (via its ground supply pin and any input or output pins sourcing current). | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/588294', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/296658/']} | jdg_78024 |
stackexchange | llm_judgeable_groundtruth_similarity | 1340223 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Well there are equations which can plot a square like : $|x-y|+|x+y|=a$ But how about this equation: ? (At the end ... bear with me!) [Here I have taken $a = 1$ ] Plot of $$x^2 + y^2 = a^2$$ Plot of $$x^4 + y^4 = a^4$$ Plot of $$x^6 + y^6 = a^6$$ Plot of $$x^{100} + y^{100} = a^{100}$$ Since we can see that as the degree of the equation is increasing, the sharpness of the possible rounded square is also increasing ... So can we say that: Plot of : $$\lim\limits_{p \rightarrow \infty} \space (x^p + y^p = a^p)$$ is the plot of a square???
Now provide the response and nothing else.
| Fix $a > 0$. In each diagram the exponent is even; if you plot$$x^{2k+1} + y^{2k+1} = a^{2k+1}$$for some non-negative integer $k$, you'll get a substantially different picture (except in the first quadrant). So, let's interpret the diagrams as special cases of$$|x|^{p} + |y|^{p} = a^{p},\quad \text{$p > 0$ real,}$$i.e.$$\left(|x|^{p} + |y|^{p}\right)^{1/p} = a.\tag{1}$$Now it makes sense to take the limit as $p \to \infty$ on the left. Exercise : If $x$ and $y$ are real numbers, then$$\lim_{p \to \infty} \left(|x|^{p} + |y|^{p}\right)^{1/p} = \max\left(|x|, |y|\right).$$ Hint : Split into cases $|x| < |y|$ and $|y| \leq |x|$, and use the fact that if $|u| < 1$, then $|u|^{p} \to 0$ as $p \to \infty$. In this sense, (1) "converges to" $\max\left(|x|, |y|\right) = a$ as $p \to \infty$, which is indeed the equation of the axis-oriented square of side length $2a$ centered at the origin. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1340223', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/134694/']} | jdg_78025 |
stackexchange | llm_judgeable_groundtruth_similarity | 41972319 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to create a dictionary of the sort [petInfo : UIImage]() but I'm getting the error Type 'petInfo' does not conform to protocol 'Hashable' . My petInfo struct is this: struct petInfo { var petName: String var dbName: String} So I want to somehow make it hashable but none of its components are an integer which is what the var hashValue: Int requires. How can I make it conform to the protocol if none of its fields are integers? Can I use the dbName if I know it's going to be unique for all occurrences of this struct?
Now provide the response and nothing else.
| Simply return dbName.hashValue from your hashValue function. FYI - the hash value does not need to be unique. The requirement is that two objects that equate equal must also have the same hash value. struct PetInfo: Hashable { var petName: String var dbName: String var hashValue: Int { return dbName.hashValue } static func == (lhs: PetInfo, rhs: PetInfo) -> Bool { return lhs.dbName == rhs.dbName && lhs.petName == rhs.petName }} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/41972319', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3509099/']} | jdg_78026 |
stackexchange | llm_judgeable_groundtruth_similarity | 29729063 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using JSON.NET and C# 5. I need to serialize/de-serialize list of objects into line delimited json. http://en.wikipedia.org/wiki/Line_Delimited_JSON . Example, {"some":"thing1"}{"some":"thing2"}{"some":"thing3"} and {"kind": "person", "fullName": "John Doe", "age": 22, "gender": "Male", "citiesLived": [{ "place": "Seattle", "numberOfYears": 5}, {"place": "Stockholm", "numberOfYears": 6}]}{"kind": "person", "fullName": "Jane Austen", "age": 24, "gender": "Female", "citiesLived": [{"place": "Los Angeles", "numberOfYears": 2}, {"place": "Tokyo", "numberOfYears": 2}]} Why I needed because its Google BigQuery requirement https://cloud.google.com/bigquery/preparing-data-for-bigquery Update: One way I found is that serialize each object seperataly and join in the end with new-line.
Now provide the response and nothing else.
| You can do so by manually parsing your JSON using JsonTextReader and setting the SupportMultipleContent flag to true . If we look at your first example, and create a POCO called Foo : public class Foo{ [JsonProperty("some")] public string Some { get; set; }} This is how we parse it: var json = "{\"some\":\"thing1\"}\r\n{\"some\":\"thing2\"}\r\n{\"some\":\"thing3\"}";var jsonReader = new JsonTextReader(new StringReader(json)){ SupportMultipleContent = true // This is important!};var jsonSerializer = new JsonSerializer();while (jsonReader.Read()){ Foo foo = jsonSerializer.Deserialize<Foo>(jsonReader);} If you want list of items as result simply add each item to a list inside the while loop to your list. listOfFoo.Add(jsonSerializer.Deserialize<Foo>(jsonReader)); Note: with Json.Net 10.0.4 and later same code also supports comma separated JSON entries see How to deserialize dodgy JSON (with improperly quoted strings, and missing brackets)? ) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29729063', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/960567/']} | jdg_78027 |
stackexchange | llm_judgeable_groundtruth_similarity | 2581025 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to make (or learn how to make) VST plugins. Is there a special SDK for this? how does one yield a .vst instead of a .exe? Also, if one is looking to make Audio Units for Logic Pro, how is that done?Thanks
Now provide the response and nothing else.
| Start with this link to the wiki, explains what they are and gives links to the sdk.Here is some information regarding the deve How to compile a plugin - For making VST plugins in C++Builder, first you need the VST sdk by Steinberg. It's available from the Yvan Grabit's site (the link is at the top of the page). The next thing you need to do is create a .def file (for example : myplugin.def). This needs to contain at least the following lines: EXPORTS main=_main Borland compilers add an underscore to function names, and this exports the main() function the way a VST host expects it. For more information about .def files, see the C++Builder help files. This is not enough, though. If you're going to use any VCL element (anything to do with forms or components), you have to take care your plugin doesn't crash Cubase (or another VST host, for that matter). Here's how: Include float.h. In the constructor of your effect class, write _control87(PC_64|MCW_EM,MCW_PC|MCW_EM); That should do the trick. Here are some more useful sites: http://www.steinberg.net/en/company/developer.html how to write a vst plugin (pdf) via http://www.asktoby.com/#vsttutorial | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2581025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/146780/']} | jdg_78028 |
stackexchange | llm_judgeable_groundtruth_similarity | 12243549 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have coded a webpage meant for retina display. I currently do not have a retina display monitor. Is there any simulator application or tool to test web pages for retina display? Or, are there monitors(not Apple's MacBook or iPad) which are similar to Apple's retina display? Thanks in advance.
Now provide the response and nothing else.
| about:config hack on Firefox You actually can using Firefox: Go to about:config Find layout.css.devPixelsPerPx Change it to your desired ratio (1 for normal, 2 for retina, etc.) Screenshot: (source: staticflickr.com ) Refresh your page - boom, your media query has now kicked in! Hats off to Firefox for being awesome for web developing! This was done on Windows 7 with Firefox 21.0. The advantage of this solution is that it will trigger media queries and other advanced logic. If you're not doing that, and you're just feeding everyone the HiDPI images, you can just zoom in with Chrome etc (or write CSS to zoom for you, if that floats your boat). Zooming on Firefox & Edge Currently on Firefox and Edge, if you zoom it triggers dppx-based media queries. So this easier approach may be sufficient, but be aware that the functionality is reported as a "won't fix" bug for Firefox, so this could change. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12243549', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/666008/']} | jdg_78029 |
stackexchange | llm_judgeable_groundtruth_similarity | 1141302 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a sleep function in JavaScript?
Now provide the response and nothing else.
| If you are looking to block the execution of code with call to sleep , then no, there is no method for that in JavaScript . JavaScript does have setTimeout method. setTimeout will let you defer execution of a function for x milliseconds. setTimeout(myFunction, 3000);// if you have defined a function named myFunction // it will run after 3 seconds (3000 milliseconds) Remember, this is completely different from how sleep method, if it existed, would behave. function test1(){ // let's say JavaScript did have a sleep function.. // sleep for 3 seconds sleep(3000); alert('hi'); } If you run the above function, you will have to wait for 3 seconds ( sleep method call is blocking) before you see the alert 'hi'. Unfortunately, there is no sleep function like that in JavaScript . function test2(){ // defer the execution of anonymous function for // 3 seconds and go to next line of code. setTimeout(function(){ alert('hello'); }, 3000); alert('hi');} If you run test2, you will see 'hi' right away ( setTimeout is non blocking) and after 3 seconds you will see the alert 'hello'. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1141302', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/120324/']} | jdg_78030 |
stackexchange | llm_judgeable_groundtruth_similarity | 52289 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a 1200 watt PC power supply (yeah that's for a gaming rig!). Unfortunately it's failing on me after about 3 years. As the guarantee is over and I don't want to have shipping costs, I want to open it myself and see what can be wrong. I have low to no experience with power supplies of this wattage and rating. So my question is, how can I make sure when I open the PSU casing, I am not going to kill myself. Is it enough to just leave it off for few days? Maybe not, because I can see huge capacitors inside. Maybe connecting it to PC and trying to turn it on without plugging it into wall socket could discharge the caps? And a silly question, the huge inductors inside are not a threat while it's not connected to wall socket, right?
Now provide the response and nothing else.
| The best method is using a power resistor (3...5 W, 30...100 k\$\Omega\$), insulated with heat shrink tubes over the body and most of the wires. If you are absolutely sure you will not connect the resistor across the capacitors of a power supply that is still turned on, lower resistor values may be useful for faster discharging. With 330 \$\Omega\$, your discharge current will start at something like 320 V / 330 \$\Omega\$ = 0.97 A, a safe value for most electrolytic capacitors. Just remember that this resistor will dissipate (320 V) 2 / 330 \$\Omega\$ = 310 W for a brief duration when used for discharging only ( safe! ) - but the power will be dissipated continuously when your resistor is used over a live power supply's capacitors ( shock hazard from the voltage, burn and fire hazard from the large power dissipated by a relatively smallish resistor! ). Here's a discharge resistor I built for developing and fixing switching power supplies. The wire ends are (hollow) ferrules as used for connecting stranded wires into screw-on terminal blocks. They connect really well to the ends of the PCB-mounted capacitors' wires pointing through the solder connections - and they won't slip off and produce shorts to neighboring components. Y'all, feel free to copy the design and work safely ;-) Also a neon lamp with a series resistor of ca. 100 k\$\Omega\$ is a fairly good indicator of lethal voltages. It will glow above ca. 70 V. Ok, 70 V is more than SELV, but the lamp is still better than nothing. Shorting the electrolytic capacitors with a screwdriver may cause a very high discharge current, possibly damaging them. See here for some details . A plain short is really quite the redneck way to go... | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/52289', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/3757/']} | jdg_78031 |
stackexchange | llm_judgeable_groundtruth_similarity | 42930241 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider view controller with strong(or weak, the same) NSTimer property: __weak __typeof(self) ws = self;self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:ws selector:@selector(timerTigger:) userInfo:nil repeats:YES]; But why does this view controller not invoke dealloc method, whether I pass strong or weak reference to self ? Here is the detailed code: #import "SecondViewController.h"@interface SecondViewController ()@property (nonatomic, weak) NSTimer *timer;@end@implementation SecondViewController- (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; __weak __typeof(self) ws = self; self.timer = [NSTimer scheduledTimerWithTimeInterval:2 target:ws selector:@selector(timerTigger:) userInfo:nil repeats:YES];}- (void)timerTigger:(id)timer { NSLog(@"do someting");}- (void)dealloc { NSLog(@"SecondViewController dealloc");}
Now provide the response and nothing else.
| NSTimer maintains strong reference to its target until the timer is invalidated. You don't get to choose whether NSTimer establishes a weak or strong reference. When you pass a weak reference, as long as ws is not nil by the time you start the timer (which it obviously won't be, in this case), NSTimer will establish a strong reference to whatever target pointed. Whether scheduledTimerWithTimeInterval establishes a strong or weak reference is not some inherent characteristic of the pointer that you passed to it, but rather a question of what that method does with that pointer it was provided. To fix this strong reference behavior, you can adopt one of the following patterns: use the block based rendition of NSTimer and use "weak self" pattern inside the block; @interface ViewController ()@property (nonatomic, weak) NSTimer *timer;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; typeof(self) __weak weakSelf = self; self.timer = [NSTimer scheduledTimerWithTimeInterval:2 repeats:true block:^(NSTimer * _Nonnull timer) { [weakSelf timerTigger]; }];}- (void)timerTigger { NSLog(@"do something");}- (void)dealloc { [self.timer invalidate];}@end use GCD timer, which is also block based and therefore can also easily be configured to not keep strong reference; or @interface ViewController ()@property (nonatomic, strong) dispatch_source_t timer;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; typeof(self) __weak weakSelf = self; self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_main_queue()); dispatch_source_set_timer(self.timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC); dispatch_source_set_event_handler(self.timer, ^{ [weakSelf timerTigger]; }); dispatch_resume(self.timer);}- (void)timerTigger { NSLog(@"do something");}@end use NSTimer with target/selector, but invalidate the timer somewhere logical (e.g. viewDidDisappear or the like). @interface ViewController ()@property (nonatomic, weak) NSTimer *timer;@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerTigger:) userInfo:nil repeats:true];}- (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; [self.timer invalidate];}- (void)timerTigger:(NSTimer *)timer { NSLog(@"do something");}@end | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42930241', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7645431/']} | jdg_78032 |
stackexchange | llm_judgeable_groundtruth_similarity | 32038177 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
As JPA requires, @Entity classes should have a default (non-arg) constructor to instantiate the objects when retrieving them from the database. In Kotlin, properties are very convenient to declare within the primary constructor, as in the following example: class Person(val name: String, val age: Int) { /* ... */ } But when the non-arg constructor is declared as a secondary one it requires values for the primary constructor to be passed, so some valid values are needed for them, like here: @Entityclass Person(val name: String, val age: Int) { private constructor(): this("", 0)} In case when the properties have some more complex type than just String and Int and they're non-nullable, it looks totally bad to provide the values for them, especially when there's much code in primary constructor and init blocks and when the parameters are actively used -- when they're to be reassigned through reflection most of the code is going to be executed again. Moreover, val -properties cannot be reassigned after the constructor executes, so immutability is also lost. So the question is: how can Kotlin code be adapted to work with JPA without code duplication, choosing "magic" initial values and loss of immutability? P.S. Is it true that Hibernate aside of JPA can construct objects with no default constructor?
Now provide the response and nothing else.
| As of Kotlin 1.0.6 , the kotlin-noarg compiler plugin generates synthetic default construtors for classes that have been annotated with selected annotations. If you use gradle, applying the kotlin-jpa plugin is enough to generate default constructors for classes annotated with @Entity : buildscript { dependencies { classpath "org.jetbrains.kotlin:kotlin-noarg:$kotlin_version" }}apply plugin: "kotlin-jpa" For Maven: <plugin> <artifactId>kotlin-maven-plugin</artifactId> <groupId>org.jetbrains.kotlin</groupId> <version>${kotlin.version}</version> <configuration> <compilerPlugins> <plugin>jpa</plugin> </compilerPlugins> </configuration> <dependencies> <dependency> <groupId>org.jetbrains.kotlin</groupId> <artifactId>kotlin-maven-noarg</artifactId> <version>${kotlin.version}</version> </dependency> </dependencies></plugin> | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/32038177', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2196460/']} | jdg_78033 |
stackexchange | llm_judgeable_groundtruth_similarity | 70098133 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been looking for the answer to this for a good solid week now, with no success. I've looked at every StackOverflow post, every article from Google and every related Github issue I could find. Most related errors seem to be older, so I'm wondering if my issue is slightly different due to me being on macOS Big Sur. The issue: When I try to run yarn install in my local repo, I receive an error related to node-gyp and a python executable that is unable to be found. Here is what my terminal shows: yarn install v1.22.17...other stuff[4/4] Building fresh packages...[6/13] ⠐ node-sass[2/13] ⠐ node-sass[10/13] ⠐ metrohash[4/13] ⠐ fseventserror /Users/jimmiejackson/Documents/repositories/repo-name/node_modules/metrohash: Command failed.Exit code: 1Command: node-gyp rebuildArguments:Directory: /Users/jimmiejackson/Documents/repositories/repo-name/node_modules/metrohashOutput:gyp info it worked if it ends with okgyp info using [email protected] info using [email protected] | darwin | x64gyp ERR! configure errorgyp ERR! stack Error: Can't find Python executable "/usr/local/opt/[email protected]/bin/python3", you can set the PYTHON env variable.gyp ERR! stack at PythonFinder.failNoPython (/Users/jimmiejackson/Documents/repositories/repo-name/node_modules/node-gyp/lib/configure.js:484:19)gyp ERR! stack at PythonFinder.<anonymous> (/Users/jimmiejackson/Documents/repositories/repo-name/node_modules/node-gyp/lib/configure.js:406:16)gyp ERR! stack at F (/Users/jimmiejackson/Documents/repositories/repo-name/node_modules/which/which.js:68:16)gyp ERR! stack at E (/Users/jimmiejackson/Documents/repositories/repo-name/node_modules/which/which.js:80:29)gyp ERR! stack at /Users/jimmiejackson/Documents/repositories/repo-name/node_modules/which/which.js:89:16gyp ERR! stack at /Users/jimmiejackson/Documents/repositories/repo-name/node_modules/isexe/index.js:42:5gyp ERR! stack at /Users/jimmiejackson/Documents/repositories/repo-name/node_modules/isexe/mode.js:8:5gyp ERR! stack at FSReqCallback.oncomplete (fs.js:167:21)gyp ERR! System Darwin 20.6.0gyp ERR! command "/Users/jimmiejackson/.nvm/versions/node/v12.18.0/bin/node" "/Users/jimmiejackson/Documents/repositories/repo-name/node_modules/metrohash/node_modules/.bin/node-gyp" "rebuild"gyp ERR! cwd /Users/jimmiejackson/Documents/repositories/repo-name/node_modules/metrohash I'm not entirely sure what this error means or why this node module is searching for python3. I've tried running npm set config /path/to/python , downloading python3, setting the PYTHON path in my .zshrc profile, but nothing seems to be working. It's entirely possible that my lack of understanding of the issue means that I'm on the right path but didn't quite get something right. Any ideas?
Now provide the response and nothing else.
| This one also plagued me for a week because node-gyp could actually find my Python instance just fine, but then a later build step was not properly configured and all of the popular answers weren't able to pick up Python. My steps to resolve on macOS Monterey ( 12.3.1 )... $ brew install pyenv# Any modern version python should do. I don't think Python 2 is required any more.$ pyenv install 3.10.3$ pyenv global 3.10.3# Add pyenv to your PATH so that you can reference python (not python3)$ echo "export PATH=\"\${HOME}/.pyenv/shims:\${PATH}\"" >> ~/.zshrc# open a new terminal window and confirm your pyenv version is mapped to python$ which python$ python --version# Now try to re-run yarn install$ yarn | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/70098133', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3394654/']} | jdg_78034 |
stackexchange | llm_judgeable_groundtruth_similarity | 11062028 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have to deploy a C# application on a 64 bit machine though there is a slight probability that it could also be deployed on a 32 bit machine. Should I build two separate executables targeting x86 and x64 platform or should I go for a single executable built targeting 'AnyCPU' platform (specified in the project property's Build option'. Would there be any performace difference between a C# assembly built targeting 'AnyCPU' is deployed on a 64 bit machine vs the same assembly built targeting specifically 'x64' platform ?
Now provide the response and nothing else.
| No, there is no difference in performance between AnyCPU application running on a 64-bit Windows and an x64 application running on it. The only thing that flag changes are some flags in the header of the compiled assembly and the CLR uses it only to decide whether to use x86 or x64, nothing else If you were asking whether there is a difference between x86 application running on a 64-bit Windows and an x64 (or AnyCPU), then the answer would be yes. The differences between the two are: 64-bit obviously uses references that are twice as big as 32-bit, which means larger memory consumption, but it also means you can use more memory 64-bit can use more registers that are available only in the 64-bit mode of CPUs 64-bit JIT is different from 32-bit JIT, it has different set of optimizations: for example 64-bit JIT sometimes uses the tail call optimization even if you don't specifically request it using the tail. instruction (which for example C# never does) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11062028', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/800031/']} | jdg_78035 |
stackexchange | llm_judgeable_groundtruth_similarity | 7391168 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to do some validations sequentially and some of them involve complex database operations. So, I need to do this in a separated thread of UI Thread, ok?But some validations show messages to user, what need confirmation andwhen user confirm, the next validation should be call. This code example explains what I want to implement: void makeValidation1(){ if(condition1Valid()){ makeValidation2(); }else{ DialogInterface.OnClickListener onClick = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { makeValidation2(); } }; AlertDialog.Builder builder = new AlertDialog.Builder(this) .setMessage("really want to do this?") .setPositiveButton("Yes", onClick); builder.create().show(); }}void makeValidation2(){ if(condition2Valid()){ }else{ //... }}boolean condition1Valid() { // complex database Operations return false;}boolean condition2Valid() { //complex database Operations return false;} //... void makeValidation9(){ //... } My question is: What the best way/pattern to implement this? 1 - Create one asyncTask for each validation? (I cant create only one AsyncTask, because confirmation messages can stop flux). 2 - Create a Runnable for each validation and create thread to run that when need call next validation? 3 - ??? edit I tested this code @BinaryBazooka, but isnt work. Any help? public class MainActivity extends Activity implements OnClickListener { Thread mThread;ProgressDialog mProgressDialog;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Button button = new Button(this); button.setText("Start"); setContentView(button, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); button.setOnClickListener(this);}@Overridepublic void onClick(View v) { mThread = new Thread(new Runnable() { @Override public void run() { validations(); } }); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Start Thread?"); builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); mProgressDialog = new ProgressDialog(MainActivity.this); mProgressDialog.show(); mThread.run(); } }); builder.create().show();}void validations(){ //this method go on separated thread validation1(); validation2(); validation3();}void validation1(){ if(true){ final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setMessage("Validation 1 failed. Go validation 2?"); builder.setPositiveButton("Go", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); mProgressDialog.show(); //if user confirm, continue validation thread mThread.notify(); } }); builder.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { //if user cancel, stop validation thread mThread.interrupt(); } }); runOnUiThread(new Runnable() { @Override public void run() { mProgressDialog.hide(); builder.create().show(); } }); try { synchronized (mThread) { //wait for user confirmation mThread.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } }}private void validation2() { if(true){ final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setMessage("validacao 2 failed. Go validation 3?"); builder.setPositiveButton("Go", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); mProgressDialog.show(); mThread.notify(); } }); builder.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { mThread.interrupt(); } }); runOnUiThread(new Runnable() { @Override public void run() { mProgressDialog.hide(); builder.create().show(); } }); try { synchronized (mThread) { mThread.wait(); } } catch (InterruptedException e) { e.printStackTrace(); } }}private void validation3() { Log.i("TAG", "<<<<<<<<<< >>>>>>>>>>>>"); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, "finished", Toast.LENGTH_SHORT); } });} }
Now provide the response and nothing else.
| From the OpenCL 1.1 specification : Section 6.8 (Restrictions) (a): The use of pointers is somewhat restricted. The following rules apply: Arguments to kernel functions declared in a program that are pointers must be declared with the __global, __constant or __local qualifier. A pointer declared with the __constant, __local or __global qualifier can only be assigned to a pointer declared with the __constant, __local or __global qualifier respectively. Pointers to functions are not allowed . The usual work around I use for this is with macros. Evil, but currently inescapable. So I typically end up with something like: #define FEATURENAME_START impl1_start#define FEATURENAME_END impl1_end I then either inject this into the kernel at compilation time or pass it as an argument to the OpenCL compiler. It's not quite runtime in the usual sense, but it can be runtime from the Host's perspective still, even if not the device. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7391168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/740394/']} | jdg_78036 |
stackexchange | llm_judgeable_groundtruth_similarity | 38282612 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a problem with loading google map with the Advanced Custom Field plugin. I make everything like in the instruction on the plugin page here https://www.advancedcustomfields.com/resources/google-map . I add google-map field in ACF, but on the page where it should be it appears for a second, and then disappears with the inscription "Oops! Something went wrong. This page didn't load Google Maps correctly. See the JavaScript console for technical details." (see the screenshot). Console says that I need to set the Google API key. I guess I also need to modify some strings in .js file from the ACF instruction, but I don't know which ones. May be someone could help. Thank you in advance. screenshot
Now provide the response and nothing else.
| ACF updated the Google Map documentation You first have to get a Maps API key and make sure you activate the following APIs : Maps JavaScript API Geocoding API Places API Then register the API key in your functions.php If using ACF free function my_acf_google_map_api( $api ){ $api['key'] = 'xxx'; return $api;}add_filter('acf/fields/google_map/api', 'my_acf_google_map_api'); If using ACF pro function my_acf_init() { acf_update_setting('google_api_key', 'xxx');}add_action('acf/init', 'my_acf_init'); In my case I had to delete & recreate the field so that it saves correctly. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/38282612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6352886/']} | jdg_78037 |
stackexchange | llm_judgeable_groundtruth_similarity | 5745298 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was wondering the other day if StackOverflow had an API I could access from Mathematica, and apparently it does: "Saving plot annotations" What's the best way to get data from StackOverflow into Mathematica? Sjoerd used the information to make a plot. I'm interested in adding SO-related notifications into a docked cell I keep in my notebooks, so I can tell when there are updates or responses without leaving Mathematica.
Now provide the response and nothing else.
| By popular demand, the code to generate the top-10 SO answerers plot (except annotations ) using the SO API (it's a pretty neat and complete API; lots of goodies there. Easy too - see my code). Update : added App-key to ensure the code co-operates better with the SO-API (higher daily call cap). Please use it only for this app. April 2011 August 2011 MMA 8 version! MMA7 version further down getRepChanges[userID_Integer] := Module[{totalChanges}, totalChanges = "total" /. Import["http://api.stackoverflow.com/1.1/users/" <> ToString[userID] <> "/reputation?key=NgVJ4Y6vFkuF-oqI-eOvOw&fromdate=0&pagesize=1&page=1", "JSON" ]; Join @@ Table[ "rep_changes" /. Import["http://api.stackoverflow.com/1.1/users/" <> ToString[userID] <> "/reputation?key=NgVJ4Y6vFkuF-oqI-eOvOw&fromdate=0&pagesize=100&page=" <> ToString[page], "JSON" ], {page, 1, Ceiling[totalChanges/100]} ] ]topAnswerers = ({"display_name","user_id", "email_hash"} /. #) & /@ ("user" /. ("top_users" /. Import[ "http://api.stackoverflow.com/1.1/tags/mathematica/top-answerers/all-time", "JSON" ] ) )topAnswerers = {#, #2, Import["http://www.gravatar.com/avatar/" <> #3 <> ".jpg?s=36&d=identicon&d=identicon"] } & @@@ topAnswerersrepChangesTopUsers = Table[ repChange = ReleaseHold[ ( Hold[ { DateList["on_date" + AbsoluteTime["January 1, 1970"]], "positive_rep" - "negative_rep" } ] /. # ) & /@ getRepChanges[userID] ] // Sort; accRepChange = {repChange[[All, 1]],Accumulate[repChange[[All, 2]]]}\[Transpose], {userID, topAnswerers[[All, 2]]} ];pl = DateListLogPlot[ Tooltip @@@ Take[({repChangesTopUsers, Row /@ topAnswerers[[All, {3, 1}]]}\[Transpose]), 10], Joined -> True, Mesh -> None, ImageSize -> 1000, PlotRange -> {All, {10, All}}, BaseStyle -> {FontFamily -> "Arial-Bold", FontSize -> 16}, DateTicksFormat -> {"MonthNameShort", " ", "Year"}, GridLines -> {True, None}, FrameLabel -> (Style[#, FontSize -> 18] & /@ {"Date", "Reputation", "Top-10 answerers", ""})] EDIT Note that you can plot up to and including a top-20 by changing the value in the Take function. It gets busy pretty soon. Tried to improve the readability of Markup code somewhat. I'm afraid this will yield some spurious spaces when copied. EDIT Page size back to 100 elements/page ==> fewer API calls Please note that the first call to the API is to determine the amount of posts the user has. This data is present no matter the page size, so this is preferably chosen small (10 or so, possibly 1, didn't check). Then the data is fetched in successive pages until the last page is reached. You can use the maximum page size (100) for that. Just take care that the maximum number of pages in the loop count is adjusted accordingly. EDIT: better MMA 7 code (Fri Apr 22) MMA 7 doesn't do JSON imports, so I do a text import instead followed by a bare-bones JSON translation. I've tested this version several times now (in MMA 8) and it seems to work without the errors I got yesterday. getRepChanges[userID_Integer] := Module[{totalChanges}, totalChanges = "total" /. ImportString[ StringReplace[(Import[ "http://api.stackoverflow.com/1.1/users/" <> ToString[userID] <> "/reputation?key=NgVJ4Y6vFkuF-oqI-eOvOw&fromdate=0&pagesize=1&page=1", "Text"]), {":" -> "->", "[" -> "{", "]" -> "}"}], "NB"]; Join @@ Table["rep_changes" /. ImportString[ StringReplace[ Import["http://api.stackoverflow.com/1.1/users/" <> ToString[userID] <> "/reputation?key=NgVJ4Y6vFkuF-oqI-eOvOw&fromdate=0&pagesize=100&page=" <> ToString[page], "Text"], {":" -> "->", "[" -> "{", "]" -> "}"}], "NB"], {page, 1, Ceiling[totalChanges/100]}]]topAnswerers = ({"display_name", "user_id", "email_hash"} /. #) & /@ ("user" /. ("top_users" /. ImportString[ StringReplace[ " " <> Import[ "http://api.stackoverflow.com/1.1/tags/mathematica/top-answerers/all-time", "Text"], {":" -> "->", "[" -> "{", "]" -> "}"}], "NB"]))topAnswerers = {#, #2, Import["http://www.gravatar.com/avatar/" <> #3 <> ".jpg?s=36&d=identicon&d=identicon"]} & @@@ topAnswerersrepChangesTopUsers = Table[repChange = ReleaseHold[(Hold[{DateList[ "on_date" + AbsoluteTime["January 1, 1970"]], "positive_rep" - "negative_rep"}] /. #) & /@ getRepChanges[userID]] // Sort; accRepChange = {repChange[[All, 1]], Accumulate[repChange[[All, 2]]]}\[Transpose], {userID, topAnswerers[[All, 2]]}];DateListLogPlot[ Tooltip @@@ Take[({repChangesTopUsers, Row /@ topAnswerers[[All, {3, 1}]]}\[Transpose]), 10], Joined -> True, Mesh -> None, ImageSize -> 1000, PlotRange -> {All, {10, All}}, BaseStyle -> {FontFamily -> "Arial-Bold", FontSize -> 16}, DateTicksFormat -> {"MonthNameShort", " ", "Year"}, GridLines -> {True, None}, FrameLabel -> (Style[#, FontSize -> 18] & /@ {"Date", "Reputation", "Top-10 answerers", ""})] EDIT: auxiliary functions to filter on post tags These functions can be used to filter reputation gains, in order to find gains for certain tags only. tagLookup gets a post_ID integer as input and yields the specific post's tags. getQuestionIDs and getAnswerIDsFrom... go the other way. Given a tag they find all the question and answer IDs so that one can test with MemberQ whether a given post_ID belongs to this tag. Both tagLookup and getAnswerIDs are slow since many API calls are necessary. I couldn't test the last two function as either API access is down or my IP has been capped. tagLookup[postID_Integer] := Module[{im}, im = Import["http://api.stackoverflow.com/1.1/questions/" <> ToString[postID],"JSON"]; If[("questions" /. im) != {}, First[("tags" /. ("questions" /. im))], im = Import["http://api.stackoverflow.com/1.1/answers/" <> ToString[postID],"JSON"]; First[("tags" /. ("questions" /. Import["http://api.stackoverflow.com/1.1/questions/" <> ToString[First["question_id" /. ("answers" /. im)]], "JSON"]))] ] ]getQuestionIDs[tagName_String] := Module[{total}, total = "total" /. Import["http://api.stackoverflow.com/1.1/questions?tagged=" <> tagName <> "&pagesize=1", "JSON"]; Join @@ Table[("question_id" /. ("questions" /. Import["http://api.stackoverflow.com/1.1/questions?key=NgVJ4Y6vFkuF-oqI-eOvOw&tagged=" <> tagName <> "&pagesize=100&page=" <> ToString[i], "JSON"])), {i, 1, Ceiling[total/100]}] ]getAnswerIDsFromQuestionID[questionID_Integer] := Module[{total}, total = Import["http://api.stackoverflow.com/1.1/questions/" <> ToString[questionID] <> "/answers?key=NgVJ4Y6vFkuF-oqI-eOvOw&pagesize=1", "JSON"]; If[total === $Failed, Return[$Failed], total = "total" /. total]; Join @@ Table[ "answer_id" /. ("answers" /. Import["http://api.stackoverflow.com/1.1/questions/" <> ToString[questionID] <> "/answers?key=NgVJ4Y6vFkuF-oqI-eOvOw&pagesize=100&page=" <> ToString[i], "JSON"]), {i, 1, Ceiling[total/100]}] ]getAnswerIDsFromTag[tagName_String] := Module[{}, Join @@ (getAnswerIDsFromQuestionID /@ Cases[getQuestionIDs[tagName], Except[$Failed]]) ] | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5745298', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/512715/']} | jdg_78038 |
stackexchange | llm_judgeable_groundtruth_similarity | 25402331 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My Symfony2 application displays a main page, and from there on it primarily uses AJAX requests to display content to the user via modals. I've noticed that after the user is idle for some period of time (around 15-30 minutes) the session is destroyed, and the user is logged out and needs to log in again. This is incredibly frustrating, since I can't expect users to log in again every time they've been idle for a few minutes. As far as I can tell, this problem should not be happening according to my config.yml file, which is as follows: framework: session: cookie_lifetime: 0 # Session lifetime in seconds gc_maxlifetime: 28800 # Seconds after which data will be seen # as garbage and potentially cleaned up handler_id: ~ # Current using the default session handler For completeness, my current environment is as follows: Symfony 2.4.8 PHP 5.4 Session handler: default (file-based according to php.ini ) Ubuntu Server 12.10 Summary: What should be happening: users should not be logged out, even after being idle for hours What is actually happening: users are being logged out after being idle for 15-30 minutes How can I fix this?
Now provide the response and nothing else.
| The problem: It turns out that on Debian / Ubuntu systems, there is a system cronjob which runs every 30 minutes, cleaning out all "old" sessions. Herein lies the problem. The cronjob doesn't actually know what constitutes "old". The cronjob simply calls a PHP-CLI script located at /usr/lib/php5/maxlifetime which then removes all session files that exceed a certain age. Since the script is involved by PHP-CLI, and independently of Symfony2, it has no idea what values you specified for gc_maxlifetime and cookie_lifetime in your Symfony2 config file. Instead, if just defaults to using the session.cookie_lifetime and session.gc_maxlifetime values from the /etc/php5/cli/php.ini config file, which by default, is 24 minutes. So no matter what you specify in your Symfony2 config file, if you are idle for too long, your session will be removed. The solution: Either delete the cronjob file at /etc/cron.d/php5 or, Store your sessions in a database where they can't be touched by the cronjob | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25402331', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/724788/']} | jdg_78039 |
stackexchange | llm_judgeable_groundtruth_similarity | 531140 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How strong would the combined forces of electromagnetism on the earth and planets need to be, to mimic, and therefore, replace gravity?
Now provide the response and nothing else.
| There is no strength that the EM field could be to mimic gravity. EM forces are proportional to charge and charge can be positive or negative. Gravitational forces are proportional to mass and mass can only be positive. The lowest order of EM radiation is dipole. The lowest order of gravitational radiation is quadrupole. The force between two charges of the same sign is repulsive. The force between two masses of the same sign is attractive. In a fixed gravitational field all test objects accelerate at the same rate regardless of their mass. In a fixed EM field different test objects with different charge accelerate at different rates. Gravitation respects the equivalence principle. EM does not respect the equivalence principle. All of this is to say that it is not a matter of strength. They have different characteristics, regardless of strength. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/531140', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/253781/']} | jdg_78040 |
Subsets and Splits