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 | 25250098 |
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 creating a leaflet map component, here is an example on plunker http://plnkr.co/edit/LkghwOcby49XESdGb782?p=preview here is the code leaflet.jsx /** @jsx React.DOM *//*jshint indent: 2, node: true, nomen: true, browser: true*//*global React */'use strict';module.exports = React.createClass({ getInitialState: function () { return { map: {} }; }, componentDidMount: function() { var map = L.map('map').setView([51.505, -0.09], 13); L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', { attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' }).addTo(map); this.setState({map: map}); }, modifyMap: function (method, options) { this.setState({ map : this.state.map[method](options.latLong, options.zoom, options.zoom_options) }); }, render: function () { return ( /* jshint ignore:start */ <div id="map"></div> /* jshint ignore:end */ ); }}); map.html <!DOCTYPE html><!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--><!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--><!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--><!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Leafy</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width"> <!-- Place favicon.ico and apple-touch-icon.png in the root directory --> <!-- build:css(.tmp) styles/main.css --> <style> #map { height: 200px; } </style> <link rel="stylesheet" href="//cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"> <!-- endbuild --> </head> <body> <!--[if lt IE 9]> <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p> <![endif]--> <div class="container"> <div id="leaflet"></div> </div> <!-- build:js scripts/vendor.js --> <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/react/0.11.0/react-with-addons.min.js"></script> <script src="//cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script> <!-- endbuild --> <!-- build:js scripts/main.js --> <script src="leaflet.jsx"></script> <!-- endbuild --> </body></html> I would like to try and call the modifyMap method directly from the browser console or from any script on the page. I have tried to use statics but I am unable to find the Object which contains the modifyMap method. Is there an easy way to find this method or is there a better way of doing this with Reactjs? I also know that this is possible if the React class was created on this page instead of using module.exports in a separate file, I am hoping there is another way! Please help!
Now provide the response and nothing else.
| If you want to call methods on the component instance , you need to make it available at some point during the component's lifecycle. For example, if you have only one such map on the page, you could do something like this: componentDidMount: function() { // ... this.setState({map: map}); window.map = this;} Now, you can access the component from the global map variable: Standard disclaimer: while this can be useful from time to time, especially when debugging, if you find yourself doing this very often, you should revisit your use of React—namely, you should generally pass properties into components, which the component would then use to update itself. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25250098', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1354978/']} | jdg_379441 |
stackexchange | llm_judgeable_groundtruth_similarity | 603813 |
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:
In a cave we are currently exploring, there is a temporary siphon that sometimes blocks our way. I was thinking about monitoring it (pressure sensor or other level sensor at the siphon, transmitter via mobile phone outside the cave.) The problem is that there is more than half a kilometer between the entrance and the siphon (including some narrow passages,) so I was wondering if it is possible to transmit information over such a long distance (let's say 1km) with a SINGLE wire (ie no "ground" wire, but both ends can connect to earth.) The requirements: a single wire between the siphon and the mobile phone emitter (ie no ground wire, but each side can be connected to the soil ("earth")) distance : 1km transmission in single direction (from cave to outside) very low bandwidth needed (I'm fine with one bit per minute) using a thin wire would be best (lower cost and weight). ideally not consuming too much power (both sides will be battery powered, I need to transmit 8bits once per hour) one micro-controller on each side (+ sensor or 4G module) + the necessary electronics for transmission only safe voltages/currents (ie no injury if insulation is damaged and someone touches the wire) Do you know if something like that is feasible?If so, do you know where to start looking about information on how to build such a transmission (I have no idea how it might be called, so it's difficult to search for it.)
Now provide the response and nothing else.
| Why a single wire? Why not a twisted pair? With a twisted pair (think "phone line") you can definitely get kilometer distance reliably and you can send power down the line as well, so that you only have to deal with batteries at the entrance to the cave. Splicing is easy with Scotchloks , which is an advantage over fiber. 300bps (and probably at least 9600bps) possible easily using 1970s technology (except "microcontroller"). Phone wires have been around for well over a hundred years. As noted in a comment, you can often find military or other surplus telephone wire extremely cheap. Not high enough quality for modern networks, but more than adequate for voice or low-speed data. If the goal is to monitor a single open or close status then you may be able to avoid a complex system by literally opening /closing a switch on a pair of wires. If you can go do that with a passive device - float switch, bimetal thermostat etc. then you don't even need power at the far end. Changing batteries at the entrance is easy. If you miss a week or two due to weather or other reasons and can't change a remote battery then the system becomes useless. | {} | {'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/603813', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/301878/']} | jdg_379442 |
stackexchange | llm_judgeable_groundtruth_similarity | 1501717 |
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:
Imagine a real-valued semilog function $\DeclareMathOperator{\sog}{sog}\sog$ with the property that $$\sog(\sog(x)) = \log(x)$$ for all real $x>0$. My questions: Does such a function exist? How do I compute it?
Now provide the response and nothing else.
| EDIT: I got my copy of Hellmuth Kneser (1950) from the Göttingen digital repository, click to download just the article itself (rather than the whole journal issue) LINK HELLMUTH KNESER 1950 Reele analytische or straight to DIRECT TO PDF . If anyone tries and has trouble with the link(s), I have now made a nice pdf that is small enough for email, I sent it to myself and gmail says 2MB, no trouble. I put the journal cover, contents page, then a third page after the article itself. There are two issues, both of which are non-problems for the logarithm. If you are considering a function on the reals that is also real valued, as long as there are no fixpoints, we can expect to produce real analytic half-iterates, in an open set around the relevant portion of the real axis. The open set may vary in width. To be specific, the open set cannot be expected to include complex fixpoints of the function. It will generally turn out that fractional iterates will not extend to the entire complex plane, even when the original function is entire and single valued. If you have a fixpoint on the real line, where the derivative of the function is negative, it is easy to see that the half iterate cannot stay real valued. For example, a half iterate of $-x$ is $ix,$ because $i(ix) = -x.$ In the presence of fixpoints with derivative larger than $1$ or strictly between $0$ and $1,$ we get to solve a Schöder equation. With $x^2$ at $1$ we arrive at $x^{\sqrt 2},$ because $$ \left( x^{\sqrt 2} \right)^{\sqrt 2} = x^2 $$ for positive $x.$ As soon as we try to include $0,$ we are stuck with $|x|^{\sqrt 2},$ which is $C^1$ but not $C^2$ at the origin. So, fixpoints are a problem. Finally, the hardest bit is when the fixpoint has derivative $1.$ I spent quite a bit of time finding a half-iterate for $\sin x.$ It works, the result is in between the sine wave and a sawtooth curve (of line segments) that is tangent to the sine curve at multiples of $\pi.$ And, for $0 < x < \pi,$ it is real analytic. I wrote to Jean Ecalle, it turns out that the function really is $C^\infty$ when we expand to include $x=0,$ therefore $C^\infty$ on the entire real line. Let's see, amplitude a little larger than $\sin x$ itself, not as large as the sawtooth; $\pi/2 \approx 1.570796,$ and we get $f_{1/2} (1.570796) \approx 1.140179.$ The (substantial) work is summarized at https://mathoverflow.net/questions/45608/formal-power-series-convergence/46765#46765 As commented, Helmuth Kneser constructed a real analytic half-iterate for $e^x.$ At about the same time I did $\sin x,$ I also did $e^x-1,$ which has a fixpoint with derivative $1$ at $x=0.$ Once again, real analytic for $x > 0,$ also for $x < 0,$ but just $C^\infty$ on the whole real line. Having trouble posting the picture, partly because it is a jpeg instead of a pdf. Anyway, the outcome is that $\log x$ works, but $\log (1+x)$ is more difficult. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1501717', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/10237/']} | jdg_379443 |
stackexchange | llm_judgeable_groundtruth_similarity | 663829 |
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:
If I have a Hamiltonian $H$ , the corresponding time-evolution operator is $e^{-iHt}$ . If one defines the evolution operator in imaginary time, one uses $e^{-H\tau}$ , where $\tau = it$ . It is commonly said that $e^{-H\tau}$ is non-unitary (see, for example, paragraph one of this arXiv post , or this StackExchange post ). But, if $\tau = it$ , shouldn't it follow that $e^{-H\tau} = e^{-iHt}$ ? The only explanation for why $e^{-H\tau}$ is non-unitary that I can think of is that really we are putting $\text{Im}(\tau)$ into the exponent instead of $\tau$ . But if that is the case, then why do we do that, and why isn't it written explicitly as $e^{-H\text{Im}(\tau)}$ ?
Now provide the response and nothing else.
| If $H$ is hermitian then $U=e^{-itH}$ is unitary if and only if $t$ is real. Making a change of variables $t=i\tau$ won't change that. The point is that when you do a Wick rotation to imaginary time you are not making a simple change of variables - a change of variables after all can't actually affect the physics. The basic place where an imaginary time quantity arises is the thermal density matrix $$ \rho = \frac{e^{-\beta H}}{Z}$$ with $\beta=1/(k_BT)$ the inverse temperature, which to have physical meaning must be real. This is the same thing as $U$ for an imaginary time $t=-i\beta$ . This should be enough to convince you that in the vast majority of cases when talking about imaginary time one really does consider the time to be imaginary, and not purely real as needed for $U$ to be unitary. In the context often encountered in QFT courses one is interested in time-dependent quantities, here the Wick rotation is less physical and more of a mathematical trick - you decide that the observables $O(t)$ asked for are hard to compute along the real line and instead compute them along the imaginary axis $O(it)$ and hope that the resulting formulas are analytically continuable to the entire complex plane. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/663829', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/230943/']} | jdg_379444 |
stackexchange | llm_judgeable_groundtruth_similarity | 10075572 |
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 can never seem to be able to create MySQL tables with columns of the type TEXT. Here's my MySQL: CREATE TABLE factions(id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), name VARCHAR(16) NOT NULL, desc TEXT NOT NULL, admins TEXT NOT NULL, mods TEXT, members TEXT, land TEXT, enemies TEXT, allies TEXT) When it's run, I get this: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'desc text NOT NULL, admins text NOT NULL, mods text, members text, land text, en' at line 1 I can't figure out what's wrong! I'm using Java if it makes any difference.
Now provide the response and nothing else.
| desc is a reserved word and shouldn't be used as a name of a column. You can use desc as a name of a column, but if you do, you must always wrap it in back-ticks. CREATE TABLE factions( id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), name VARCHAR(16) NOT NULL, `desc` TEXT NOT NULL, admins TEXT NOT NULL, mods TEXT, members TEXT, land TEXT, enemies TEXT, allies TEXT); The above is tested and works, but since you'll always have to wrap it in back-ticks (in every INSERT , UPDATE and DELETE ) you may want to change the name, or just get in the habit of wrapping all fields in back-ticks, which has other advantages. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10075572', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/720889/']} | jdg_379445 |
stackexchange | llm_judgeable_groundtruth_similarity | 558392 |
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:
This seems like a very common voltage.I remember older batteries used more round numbers like 1.5V or 3V or 9V. 3.7V seems very arbitrary but seems to be everywhere.
Now provide the response and nothing else.
| The voltage is dependent on the materials used in the cell chemistry and cannot be chosen per se. 3.7V is typical for Lithium chemistries. Similarly, 1.2V is typical for nickel-cadmium (NiCd), 1.2V for nickel-metal hydride (NiMh), 1.5V for alkaline batteries, and 2V for lead-acid. Notice that 3V and 9V are multiples of 1.5V. 3V and 9V are not customized values simply because they are round figures. They have been chosen as such since they are batteries constructed from stacks of alkaline cells. The same is true for 6V and 12V lead-acid batteries made from stacks of 2V cells. So, why are there so many lithium batteries today? They are rechargeable, have no memory, and have superior qualities with respect to energy, power density, power volume, and weight compared to the other forms of batteries mentioned above. NOTE: Memory is a behavior that some battery chemistries display wherein their capacities decrease every time you recharge them if you are not properly maintaining them or discharging them to near-empty before recharging them. Think of it like letting the old gas at the bottom of your gas tank congeal and solidify and then filling it up again. You get less gas into and out of it every time. | {} | {'log_upvote_score': 7, 'links': ['https://electronics.stackexchange.com/questions/558392', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/282047/']} | jdg_379446 |
stackexchange | llm_judgeable_groundtruth_similarity | 1032489 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Bots, how do they work? Do they tell the video game a key was pressed or the mouse was clicked? If not is there a way to have your program tell another program a key was pressed? I would like to make a program to beat some game. So any resources or examples are appreciated. Update: So one way is to emulate keystrokes, so what are some methods to do this (in any language)?
Now provide the response and nothing else.
| I've written a bunch of bots at one time or another (from Pogo games to Yohoho Puzzle Pirates). For windows, you're usually going to either be sending Win32 events to simulate mouse movements, or spoof the actually low-level messages sent between windows when the mouse is actually clicked. A lot of it really depends on how the program reacts (by accepting the message with the coordinates, or, in Java's case, immediately reading the mouse coordinates). The "automation" part usually involves reading the screen and writing heuristics or algorithms for determining the state, but can also be as nice as packet sniffing (a lot of information there in poor poker implementations) or as hacky as reading memory locations directly. Pretty big "field", and poorly documented as it's pretty profitable and not hard to get into. Sending Input C/C++ (in Windows) For keys, try CodeProject: http://www.codeproject.com/KB/cpp/sendkeys_cpp_Article.aspx And messages: http://www.codeproject.com/KB/threads/sendmsg.aspx Your best bet is to learn to send messages using the Win32 API, then use something like Spy++ or its derivatives to "reverse engineer" how KeyPresses and mouse movements are sent to the window. Java Java has an amazingly portable Robot class that is able to: Read Pixels from the screen. Control the mouse. Send keys. I'd give that a shot if you're looking for quick and easy. Basic Logic This is described elsewhere on the internet in depth, but most bots follow a simple state-machine program flow. You read the screen (or packets, or memory), find out what "state" you're in based on your readings and past data, do calculations, and send the result back out to the program. Reading the screen can be difficult, but can be made easier if you consider that a lot of times, there are a few "lucky" pixels relative to the window that will give you an idea of what state the program is in. The process of finding these pixels can be automated. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1032489', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/340/']} | jdg_379447 |
stackexchange | llm_judgeable_groundtruth_similarity | 114505 |
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:
In an attempt to actually grok sine, I came across the $y''= -y$ definition. This is incredibly cool, but it leads me to a whole new series of questions. Sine seems pretty prevalent everywhere in life (springs, sound, circles...) and I have to wonder, what's so special about the second derivative in this scenario? In other words, why does nature / math seem to care more about the scenario where $y'' = -y$ instead of, say, $y' = -y$ or $y''' = y$? Why is acceleration equal to negative the magnitude such a recurring theme in math and nature, while velocity equal to negative the magnitude ($y'=-y$) or jerk equal to negative the magnitude ($y'''=-y$) are seemingly unimportant? In other words, what makes sine so special? Note that this question also sort of applies to $e$, which satisfies $y'' = y$. (Edit: Yes, I understand that $e$ and $\sin$ are closely related. I'm not looking for a relationship between $e$ and $\sin$. Rather, I'm wondering why these functions in particular, which both arise from a relationship between a function and its own second derivative, are so prevalent. For example, do functions satisfying $y'''=-y$ also recur frequently, and I just haven't noticed them? Or is the second derivative in some way 'important'?)
Now provide the response and nothing else.
| This answer is perhaps more suited to physics.SE, but anyways. I can see why you're wondering about the "specialness" of y'' = -y (or more generally -ky). Let me try to give an explanation of why it shows up all over the place. Imagine a ball sitting at the bottom of a round well (looking like a U), its equation of motion is $y = 0$, its height is constant and not changing (let's say it is 0). Imagine you disturb this ball very slightly, you raise it to a very small height $\epsilon$ along the wall of the well. There's a force that will act on it to return it to 0. This force is a function of $\epsilon$, $F(\epsilon)$. We can expand $F(\epsilon) = a_0 + a_1 \epsilon + a_2 \epsilon^2 + ...$ Noting that F(0) = 0, we get $a_0 = 0$. Since $\epsilon$ is small, $\epsilon^2$ and all higher powers are just very small.. So we will ignore them. So we get $F(\epsilon) \approx - k \epsilon$ (the negative sign is there because the function pulls the ball down). We can conclude that $F(y) = -k y$, around the equilibrium. We know that the force is proportional to accleration (at low speeds). Therefore, $m y'' = -k y$ and thus $y'' = -c y$. This means that any small motion around a stable equilibrium is approximately a sinusoid. Now a circular motion is just two oscillations (one on each axis). This is all just a consequence of the fact that our universe seems to favor equations of the second degree, since the force is proportional to the acceleration (not to the velocity and not to the change of acceleration). Why is this the case? One can trace that to the action (Hamiltonian) of the physical system or even to the conservation laws (which follow from the invariants, for example, that the physics won't change if we shift everything up or down, or if we try the experiment at a later time). Still these are just features of our universe. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/114505', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8267/']} | jdg_379448 |
stackexchange | llm_judgeable_groundtruth_similarity | 26560726 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
import mathx = int(input("Enter a value for x: "))y = int(input("Enter a value for y: "))if y == 1 or y == x: print(1)if y > x: print(0) else: a = math.factorial(x) b = math.factorial(y) div = a // (b*(x-y)) print(div) This binomial coefficient program works but when I input two of the same number which is supposed to equal to 1 or when y is greater than x it is supposed to equal to 0.
Now provide the response and nothing else.
| This question is old but as it comes up high on search results I will point out that scipy has two functions for computing the binomial coefficients: scipy.special.binom() scipy.special.comb() import scipy.special# the two give the same results scipy.special.binom(10, 5)# 252.0scipy.special.comb(10, 5)# 252.0scipy.special.binom(300, 150)# 9.375970277281882e+88scipy.special.comb(300, 150)# 9.375970277281882e+88# ...but with `exact == True`scipy.special.comb(10, 5, exact=True)# 252scipy.special.comb(300, 150, exact=True)# 393759702772827452793193754439064084879232655700081358920472352712975170021839591675861424 Note that scipy.special.comb(exact=True) uses Python integers, and therefore it can handle arbitrarily large results! Speed-wise, the three versions give somewhat different results: num = 300%timeit [[scipy.special.binom(n, k) for k in range(n + 1)] for n in range(num)]# 52.9 ms ± 107 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)%timeit [[scipy.special.comb(n, k) for k in range(n + 1)] for n in range(num)]# 183 ms ± 814 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)each)%timeit [[scipy.special.comb(n, k, exact=True) for k in range(n + 1)] for n in range(num)]# 180 ms ± 649 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) (and for n = 300 , the binomial coefficients are too large to be represented correctly using float64 numbers, as shown above). | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/26560726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3396351/']} | jdg_379449 |
stackexchange | llm_judgeable_groundtruth_similarity | 2133856 |
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 a simple double integral: $$\int\int(x+y)dxdy$$ Now, change the variables according to the following scheme: $$x=u+v$$$$y=u-v$$ The jacobian is then:$$|\frac{\partial (x,y)}{\partial (u,v)}|=1$$ Substitute u and v into the integral, solving the integral and substituting y and x back in their place equals: $$(\frac{x-y}{2})(\frac{x+y}{2})^2$$ Which is obviously not the same as the result from directly integrating: $yx(\frac{x+y}{2})$ So my question is, can this technique not be used for solving double integrals, and is there perhaps any way to make the technique work (unless I have made a mistake somewhere).
Now provide the response and nothing else.
| Let's calculate first the whole value of $I$ over the rectangle $\mathcal D=[a,X]\times[b,Y]$ , we integrate over $y$ first. $\displaystyle I(\mathcal D)=\int_a^X\int_b^Y(x+y)dxdy$ $\displaystyle =\int_a^X\bigg[xy+\frac{y^2}{2}\bigg]_b^Ydx=\int_a^Xx(Y-b)+\frac{Y^2-b^2}{2}dx$ $\displaystyle =\bigg[\frac{x^2}{2}(Y-b)+\frac{Y^2-b^2}{2}x\bigg]_a^X=\frac{X^2-a^2}{2}(Y-b)+\frac{Y^2-b^2}{2}(X-a)$ $\displaystyle =\frac{XY}{2}(X+Y)-\frac{b}{2}X^2-\frac{a}{2}Y^2-\frac{b^2}{2}X-\frac{a^2}{2}Y+\frac{ab}{2}(a+b)$ This is all symmetrical in $a,b,X,Y$ , and obviously the result will be the same if we integrate over $x$ first. So we can see that the primitive obtained without specifying any domain of integration is in fact $$F(X,Y)=\frac{XY}{2}(X+Y)=I(\mathcal D_0)$$ where $\mathcal D_0=[0,X]\times[0,Y]$ for $a,b=0$ . Your change of variables is the following: $\begin{pmatrix} x\\ y\\ \end{pmatrix}=\begin{pmatrix} u+v\\ u-v\\ \end{pmatrix}=\begin{pmatrix}1 & 1\\ 1 & -1\\ \end{pmatrix}\begin{pmatrix} u\\ v\\ \end{pmatrix}$ and jacobian $|J|=|-1-1|=2$ In regards to the previous explanation, when you calculate $\displaystyle G(U,V)=\iint_{\mathcal W_0} 2u\,|J|\ dudv=\bigg[2u^2v\bigg]_{\mathcal W_0}=2U^2V$ you implicitly do it over the domain $\mathcal W_0=[0,U]\times[0,V]$ . Before studying your change of variables, let's have a look at a simple rotation by angle $\theta=-45°$ . $\begin{pmatrix} u\\ v\\ \end{pmatrix}=\begin{pmatrix}\cos(\theta) & -\sin(\theta)\\ \sin(\theta) & \cos(\theta)\\ \end{pmatrix}\begin{pmatrix} x\\ y\\ \end{pmatrix}=\begin{pmatrix}\frac{1}{\sqrt 2} & \frac{1}{\sqrt 2}\\ -\frac{1}{\sqrt 2} & \frac{1}{\sqrt 2}\\ \end{pmatrix}\begin{pmatrix} x\\ y\\ \end{pmatrix}=\frac{1}{\sqrt 2}\begin{pmatrix} y+x\\ y-x\\ \end{pmatrix}$ Now if you change the frame $(\vec x,\vec y)$ to the rotated frame $(\vec u,\vec v)$ then the domain $\mathcal D_0$ will simply transform into the rotated rectangle $\mathcal E_0$ of same length and width. Thus $\mathcal E_0=[0,X]\times[0,Y]$ in the new frame $(\vec u,\vec v)$ . Where the rotation differs from integral change of variables, is that the plane $(x+y)$ is transported to the plane $(u+v)$ by the rotation. Which obviously leads to the same value of the integral : $\displaystyle \iint_{\mathcal D_0}(x+y)dxdy=\iint_{\mathcal E_0}(u+v)dudv$ So finally what is wrong will all this ? Your change of variable is pretty close to the rotation case we have seen, in that case the rectangular domain $\mathcal D_0$ was transformed to another rectangular domain $\mathcal E_0$ but the inners of the integral were unchanged [ $(x+y)dxdy\to (u+v)dudv$ ]. We have seen also that the primitives $F(X,Y)$ and $G(U,V)$ without specifying the domain were equivalent to calculating them over the respective domains $\mathcal D_0$ and $\mathcal W_0$ . The catch in that, is that the theorem for the change of variables, ensures that $F(X,Y)=G(U,V)$ only if $\mathcal D_0$ is transformed into $\mathcal W_0$ by this change of variables. The issue is that $\mathcal D_0=[0,X]\times[0,Y]$ does not changes to any $\mathcal W_0=[0,U]\times[0,V]$ (and certainly not to $[0,\frac{X+Y}{2}]\times[0,\frac{X-Y}{2}]$ either) So let's have a look at the shape, $\mathcal D_0$ transforms into (obviously this will be some kind of rotated rectangle with change of orientation). $\begin{cases}(x,y)=(0,0)\to(u,v)=(0,0)\\(x,y)=(X,0)\to(u,v)=(\frac{X}{2},\frac{X}{2})\\(x,y)=(0,Y)\to(u,v)=(\frac{Y}{2},-\frac{Y}{2})\\(x,y)=(X,Y)\to(u,v)=(\frac{X+Y}{2},\frac{X-Y}{2})\\\end{cases}$ We can see (as expected), that it is not an $[0,U]\times[0,V]$ for any $U,V$ . Since the integral is symmetric in $x,y$ we do not lose generality in assuming $0\le Y\le X$ (else invert the role of $x$ and $y$ ), so we can have a drawing to support the study. As you can see the blue rectangle $\mathcal D_0$ is transformed into the pink rectangle $\mathcal R$ , but it is not supported by horizontal and vertical axis any more. Yet, let now split along the dash lines: $\mathcal R$ can be decomposed into $3$ compliant domains $\begin{cases}u\in[0,\frac{Y}{2}] & v\in[-u,u]\\\\u\in[\frac{Y}{2},\frac{X}{2}] & v\in[u-Y,u]\\\\u\in[\frac{X}{2},\frac{X+Y}{2}] & v\in[u-Y,X-u]\\\end{cases}$ $\displaystyle I_1=\int_0^\frac{Y}{2}\int_{-u}^u2u\ dudv=\int_0^\frac{Y}{2}4u^2du=\bigg[\frac{4}{3}u^3\bigg]_0^\frac{Y}{2}=\frac{Y^3}{6}$ $\displaystyle I_2=\int_\frac{Y}{2}^\frac{X}{2}\int_{u-Y}^u2u\ dudv=\int_\frac{Y}{2}^\frac{X}{2}2uYdu=\bigg[u^2Y\bigg]_\frac{Y}{2}^\frac{X}{2}=\frac{X^2Y}{4}-\frac{Y^3}{4}$ $\displaystyle I_3=\int_\frac{X}{2}^\frac{X+Y}{2}\int_{u-Y}^{X-u}2u\ dudv=\int_\frac{X}{2}^\frac{X+Y}{2}2u(X+Y-2u)du=\bigg[u^2(X+Y)-\frac{4}{3}u^3\bigg]_\frac{X}{2}^\frac{X+Y}{2}=\frac{Y^3}{12}+\frac{XY^2}{4}$ $\begin{align}\displaystyle \iint_{\mathcal R}2u\,|J|\ dudv=2\times(I_1+I_2+I_3)&=2\times\left(Y^3\left(\frac{1}{6}-\frac{1}{4}+\frac{1}{12}\right)+\frac{X^2Y}{4}+\frac{XY^2}{4}\right)\\&=\frac{XY}{2}(X+Y)\end{align}$ Finally we have $$\iint_{\mathcal R}2u\,|J|\ dudv = \iint_{\mathcal D_0}(x+y)\ dxdy$$ It is important thus to understand that a change of variable, is not simply a change of frame that transport $(\vec x,\vec y)$ to $(\vec u,\vec v)$ but an operation in which the domain of integration matters and is affected by the transformation. Specifically when you write a primitive as a n-dimensional integral without bounds, then it implicitly refers to the integral over the cuboid domain $\prod\limits_i [0,X_i]$ and you cannot assume it will simply transport to another cuboid domain $\prod\limits_i [0,U_i]$ by performing the variables change $(x_i)_i\to(u_i)_i$ . This is indeed this mistake that you are doing when calculating a primitive in $(u_i)_i$ variables by the integral without bounds. When calculating over the properly transformed domain $\mathcal D_0\to\mathcal R$ , we have seen in our particular example, that we were able to find the same result. Remark: The reason we do not have this issue in dimension $1$ , is because an interval is always transformed into another interval by a continuous bijective change of variable. While in dimension $2$ a rectangle is not necessarily another rectangle with sides parallel to axis of coordinates... | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2133856', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/258406/']} | jdg_379450 |
stackexchange | llm_judgeable_groundtruth_similarity | 296991 |
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I accidentally down-voted this question. By the time I realized I had done it, it was past the 5 minute grace period and now I cannot take that vote back. From reading on Meta, I know that the vote lock is intended to prevent "gaming" and "griefing". These do not apply to my intentions here. I would like to edit the post so that I can change my vote, but the post is already pretty good. Under these circumstances, is a trivial edit acceptable so that I can change my vote?
Now provide the response and nothing else.
| As your reputation is below the 2K Free Edit threshold, your well intended "dummy" edit would get placed into the Review Queue and then you'd have to wait for approval. There is a good chance it gets rejected at that point for a clearly Minor Edit - even if you acknowledge this in the description! Sort of the opposite of Robo-Reviewers: reviewers may believe it's just a deliberate hoax to gain Two Points Of Reputation ! Without the longer back story, there is indeed not much to show your intentions. In the worst case, reviewers may decide you are wasting their Review Quotum and reject just for that. And if the edit got approved you'd gain 2 reputation points for, to be perfectly honest, No Good Reason Whatsoever. Scan the post and its comments critically. Is there absolutely nothing else to improve? Add, remove, or change tags? (... For instance, it is missing a programming language. And I have no idea why the OP thought of point-of-sale .) If all else fails, post a comment, briefly explain the situation and ask the OP to make a minor change. That way you can change your vote without gaining reputation. If we must declare a Policy for this, it could end up as "it's only one vote, better forget about it"... | {} | {'log_upvote_score': 6, 'links': ['https://meta.stackoverflow.com/questions/296991', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/1467396/']} | jdg_379451 |
stackexchange | llm_judgeable_groundtruth_similarity | 14401008 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
From Miguel de Icaza : We use a library profile that is better suited for mobile devices, so we removed features that are not necessary (like the entire System.Configuration stack, just like Silverlight does). After years of .NET development, I'm accustomed to storing configuration settings in web.config and app.config files. When using Mono for Android, where should I put my configuration settings? If it matters, I'd like to store different configuration settings for different build configurations as well.
Now provide the response and nothing else.
| I would probably recommend using shared preferences and compilation symbols to manage different configurations. Below is an example of how you can use a preferences file to add or change keys based on the compilation symbols. Additionally, you could create a separate preferences file that is only available for a particular configuration. Because these keys are not available on all configurations, make sure to always perform checks for them before using. var prefs = this.GetSharedPreferences("Config File Name", FileCreationMode.Private);var editor = prefs.Edit();#if MonoReleaseeditor.PutString("MyKey", "My Release Value");editor.PutString("ReleaseKey", "My Release Value");#elseeditor.PutString("MyKey", "My Debug Value");editor.PutString("DebugKey", "My Debug Value");#endifeditor.PutString("CommonKey", "Common Value");editor.Commit(); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14401008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/109941/']} | jdg_379452 |
stackexchange | llm_judgeable_groundtruth_similarity | 2989531 |
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 do you show that every group homomorphism from $(\mathbb{Q}, +)$ to $(\mathbb{Q}, \times)$ is the trivial map? I am trying to use proof by contradiction by assuming there is an element $\frac{a}{b}$ such that some homomorphism $\phi$ has $\phi(\frac{a}{b}) = \frac{c}{d} \ne 1$ . But I cannot seem to deduce any contradictions from here. Maybe using direct proof is a better approach? Any help is appreciated.
Now provide the response and nothing else.
| Hint: For any $r\in \mathbb Q$ and any $n\in \mathbb Z$ , $$ \phi(r/n)^n = \phi(n * r/n) = \phi(r),$$ that is $\phi(r)$ has rational $n$ -th root for any $n$ . Now, it is left to show $1$ is the only such element in $(\mathbb Q, \times)$ , which, honestly, is not that trivial to me. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2989531', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/524764/']} | jdg_379453 |
stackexchange | llm_judgeable_groundtruth_similarity | 4243577 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Which is better or more convenient to use: <script type="text/javascript">...</script> or <script>...</script>
Now provide the response and nothing else.
| Do you need a type attribute at all? If you're using HTML5, no. Otherwise, yes. HTML 4.01 and XHTML 1.0 specifies the type attribute as required while HTML5 has it as optional, defaulting to text/javascript . HTML5 is now widely implemented, so if you use the HTML5 doctype, <script>...</script> is valid and a good choice. As to what should go in the type attribute, the MIME type application/javascript registered in 2006 is intended to replace text/javascript and is supported by current versions of all the major browsers (including Internet Explorer 9). A quote from the relevant RFC : This document thus defines text/javascript and text/ecmascript but marks them as "obsolete". Use of experimental and unregistered media types, as listed in part above, is discouraged. The media types, * application/javascript * application/ecmascript which are also defined in this document, are intended for common use and should be used instead. However, IE up to and including version 8 doesn't execute script inside a <script> element with a type attribute of either application/javascript or application/ecmascript , so if you need to support old IE, you're stuck with text/javascript . | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4243577', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/136141/']} | jdg_379454 |
stackexchange | llm_judgeable_groundtruth_similarity | 63330028 |
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 just build and deployed a flutter web app. The problem I encountered is that it doesn't scroll when I press arrow keys, also there is no scroll bar. (Only 2 figure gesture scrolling is possible) I'm using SingleChildScrollView() with the column as its child. Is there a way to implement them? Or just one of them?
Now provide the response and nothing else.
| The code from Karan works, but when the app is in Debug Mode , instead of using the event.logicalKey.debugName == "Arrow Up" , we could use event.logicalKey == LogicalKeyboardKey.arrowUp which works in both the debug and release mode. class _MyKeyboardScrollingPageState extends State<MyKeyboardScrollingPage> { final ScrollController _controller = ScrollController(); final FocusNode _focusNode = FocusNode(); void _handleKeyEvent(RawKeyEvent event) { var offset = _controller.offset; if (event.logicalKey == LogicalKeyboardKey.arrowUp) { setState(() { if (kReleaseMode) { _controller.animateTo(offset - 200, duration: Duration(milliseconds: 30), curve: Curves.ease); } else { _controller.animateTo(offset - 200, duration: Duration(milliseconds: 30), curve: Curves.ease); } }); } else if (event.logicalKey == LogicalKeyboardKey.arrowDown) { setState(() { if (kReleaseMode) { _controller.animateTo(offset + 200, duration: Duration(milliseconds: 30), curve: Curves.ease); } else { _controller.animateTo(offset + 200, duration: Duration(milliseconds: 30), curve: Curves.ease); } }); } } @override void dispose() { _focusNode.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( body: RawKeyboardListener( autoFocus = true, focusNode = _focusNode, onKey: _handleKeyEvent, child: SingleChildScrollView( controller: _controller, child: SomeAwesomeWidget(), ), ), ); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63330028', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13592012/']} | jdg_379455 |
stackexchange | llm_judgeable_groundtruth_similarity | 97202 |
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:
Which of the following compound has minimum C-H bond length? ethane ethene 1,2-dibromoethene 1,2-dibromoethane How can we know the comparison of $\ce{C-H}$ bond length (not $\ce{C-C}$)? Also, there is not any reagent given, so that we would do dehydrohalogenation reaction at it. How to compare it simply?
Now provide the response and nothing else.
| One way to compare $\ce{C-H}$ bond lengths is to compare their stretching frequencies using IR spectroscopy. However, since ethane and ethylene are gases at ambient conditions, we are going to have some difficulties in accuracy. Yet, it is worth comparing. Since we are comparing $\ce{C-H}$ bond in each case, we can suggest that the stronger the stretching frequency of $\ce{C-H}$ bond is, the shorter the bond should be. 1,2-Dibromoethane is a liquid at room temperature and $\pu{760 torr}$ with boiling point in the range of $\pu{131-132 ^\circ C}$. 1,2-Dibromoethene is from Aldrich is a mixture of cis - and trans -isomers, which boils at $\pu{110 ^\circ C}$ under $\pu{754 torr}$ pressure. IR spectra of both are extracted from NIST.gov webbook and illustrated as follows: 1,2-Dibromoethene: Range of $\ce{C-H}$ stretching is around $\pu{3150-3050 cm^{-1}}$ (Maximum $\ce{C-H}$ stretching is around $\pu{3100 cm^{-1}}$): 1,2-Dibromoethane: Range of $\ce{C-H}$ stretching is around $\pu{3010-2950 cm^{-1}}$ (Maximum $\ce{C-H}$ stretching is around $\pu{3000 cm^{-1}}$): Accordingly, we can easily suggest that $\ce{C-H}$ bond in 1,2-dibromoethane is longer than that in 1,2-dibromoethene. However, this is hardly a surprise since we are comparing a $\mathrm{sp^3-s}$ bond versus a $\mathrm{sp^2-s}$ bond. Nonetheless, this is a good exercise because it confirm the validity of the test, in a way. Yet, the $\ce{C-H}$ stretching at around $\pu{3000 cm^{-1}}$ is undoubtedly suggested that $\ce{C-H}$ bond in 1,2-dibromoethane is shorter than a $\ce{C-H}$ bond in a regular alkane. Now, let's see two good liquid alkane and alkene examples to represent gasious ethane and ethene, respectively. 2-Methylpent-1-ene (a terminal alkene) is a liquid at room temperature and $\pu{760 torr}$ with boiling point of $\pu{62 ^\circ C}$. n-Pentane (the shortest n-alkene at ambient condition) is a liquid at room temperature and $\pu{760 torr}$ with its boiling point around the range of $\pu{35-36 ^\circ C}$. 2-Methylpent-1-ene: Range of $\ce{C-H}$ stretching is around $\pu{3100-2800 cm^{-1}}$ (Maximum $\ce{C-H}$ stretching is around $\pu{3075 cm^{-1}}$): 2-Methylpent-1-ene: Range of $\ce{C-H}$ stretching is around $\pu{2990-2800 cm^{-1}}$ (Maximum $\ce{C-H}$ stretching is around $\pu{2900 cm^{-1}}$): Thus, we can confidently suggest that the $\ce{C-H}$ bond lengths of given compounds are in following order: ethane > 1,2-dibromoethane >ethene > 1,2-dibromoethene | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/97202', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/46621/']} | jdg_379456 |
stackexchange | llm_judgeable_groundtruth_similarity | 517695 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Had a coworker ask me this, and in my brain befuddled state I didn't have an answer: Why is it that you can do: string ham = "ham " + 4; But not: string ham = 4; If there's an implicit cast/operation for string conversion when you are concatenating , why not the same when assigning it as a string? (Without doing some operator overloading, of course)
Now provide the response and nothing else.
| When concatenating the compiler turns the statement "ham" + 4 into a call to String.Concat , which takes two object parameters, so the value 4 is boxed and then ToString is called on that. For the assignment there is no implicit conversion from int to string , and thus you cannot assign 4 to a string without explicitly converting it. In other words the two assignments are handled very differently by the compiler, despite the fact that they look very similar in C#. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/517695', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2108310/']} | jdg_379457 |
stackexchange | llm_judgeable_groundtruth_similarity | 3336333 |
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:
Show that \begin{eqnarray*}I=\int_0^1 \int_0^1 \frac{dx \,dy}{\sqrt{1-x^2y^2}} = \frac{\pi}{2} \ln 2.\end{eqnarray*} My try ... from this question here we have \begin{eqnarray*}\int_0^1 \frac{ \sin^{-1}(x)}{x} \,dx = \frac{\pi}{2} \ln 2 .\end{eqnarray*} And from this question here we have \begin{eqnarray*}\int_0^1 \ln \left( \frac{1+ax}{1-ax} \right) \frac{dx}{x\sqrt{1-x^2}}=\pi\sin^{-1} a,\qquad |a|\leq 1. \end{eqnarray*} It is easy to show \begin{eqnarray*}\int_0^1 \frac{dy}{1+yz}=\frac{1}{z} \ln(1+z). \end{eqnarray*} So we have (with a little tad of algebra) \begin{eqnarray*}\frac{\pi}{2} \ln 2 &=& \int_0^1 \frac{ \sin^{-1}(x)}{x}\, dx \\ &=& \frac{1}{\pi} \int_0^1 \int_0^1 \ln \left( \frac{1+xt}{1-xt} \right) \frac{dt}{xt\sqrt{1-t^2}} x\, dx \\ &=& \frac{2}{\pi} \int_0^1 \int_0^1 \int_0^1 \frac{dx \,dy\, dt}{(1-x^2y^2t^2)\sqrt{1-t^2} } \\ \end{eqnarray*} This suggests we should consider the integral (sub $t=\sin(\theta)$ ) \begin{eqnarray*}\frac{2}{\pi} \int_0^1 \frac{ dt}{(1-x^2y^2t^2)\sqrt{1-t^2} } \\ = \int_0^{\pi/2} \frac{d \theta }{1- x^2 y^2 \sin^2(\theta)}. \end{eqnarray*} Now it is well known (Geometrically expand, integrate term by term & sum the familiar plum) that \begin{eqnarray*}\frac{2}{\pi} \int_0^{\pi/2} \frac{d \theta }{1- \alpha \sin^2(\theta)}=\frac{2}{\pi} \frac{1}{\sqrt{1-\alpha}} \end{eqnarray*} and using this we have \begin{eqnarray*}\frac{\pi}{2} \ln 2 =\int_0^1 \int_0^1 \frac{dx\, dy}{\sqrt{1-x^2y^2}} .\end{eqnarray*} The above double integral reminds of \begin{eqnarray*}\sum_{n=0}^{\infty} \frac{1}{(2n+1)^2}=\int_0^1 \int_0^1 \frac{dx\, dy}{1-x^2y^2} = \frac{\pi^2}{8}\end{eqnarray*} which can be evaluated using the substitution $x= \frac{\sin u}{\cos v}$ , $y= \frac{\sin v}{\cos u}$ . My solution above used some pretty heavy machinery to establish the result. So my question is: is there an easier method ?
Now provide the response and nothing else.
| $$\int_0^1 \int_0^1 \frac{dxdy}{\sqrt{1-x^2y^2}}\overset{xy=t}=\int_0^1 \frac{1}{y}\int_0^y \frac{1}{\sqrt{1-t^2}}dtdy=\int_0^1 \frac{\arcsin y}{y}dy$$ $$\overset{IBP}=-\int_0^1 \frac{\ln y}{\sqrt{1-y^2}}dy\overset{y=\sin x}=-\int_0^\frac{\pi}{2}\ln(\sin x)dx=\frac{\pi}{2}\ln 2$$ See here for the above integral. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3336333', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/404247/']} | jdg_379458 |
stackexchange | llm_judgeable_groundtruth_similarity | 37877895 |
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 Denmark we have an odd grading system that goes as follows. [-3,00,02,4,7,10,12]Our assignment is to take a vector with different decimal numbers, and round it to the nearest valid grade. Here is our code so far. import numpy as npdef roundGrade(grades): if (-5<grades<-1.5): gradesRounded = -3 elif (-1.5<=grades<1.5): gradesRounded = 00 elif (1.5<=grades<3): gradesRounded = 2 elif (3<=grades<5.5): gradesRounded = 4 elif (5.5<=grades<8.5): gradesRounded = 7 elif (8.5<=grades<11): gradesRounded = 10 elif (11<=grades<15): gradesRounded = 12 return gradesRoundedprint(roundGrade(np.array[-2.1,6.3,8.9,9])) Our console doesn't seem to like this and retuns:TypeError: builtin_function_or_method' object is not subscriptable All help is appreciated, and if you have a smarter method you are welcome to put us in our place.
Now provide the response and nothing else.
| You are getting that error because when you print, you are using incorrect syntax: print(roundGrade(np.array[-2.1,6.3,8.9,9])) needs to be print(roundGrade(np.array([-2.1,6.3,8.9,9]))) Notice the extra parentheses: np.array(<whatever>) However, this won't work, since your function expects a single number. Fortunately, numpy provides a function which can fix that for you: In [15]: roundGrade = np.vectorize(roundGrade)In [16]: roundGrade(np.array([-2.1,6.3,8.9,9]))Out[16]: array([-3, 7, 10, 10]) http://docs.scipy.org/doc/numpy-1.10.1/reference/generated/numpy.vectorize.html | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37877895', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6478411/']} | jdg_379459 |
stackexchange | llm_judgeable_groundtruth_similarity | 2676160 |
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 $r < 57$, let $C$ denote a circle centered at ($57$, $r$) with radius $r$. $C$ is tangent to a parabola, $y=x^2+r$, from the outside in the first quadrant. Find the value of $r$. I am not sure how to approach the above problem. I started with implicit differentiation of the general circle formula. $r^2 = (x-57)^2+(y - r)^2$ $D(r^2) = D\left((x-57)^2+( y - r)\right)$ $0 = 2x - 114 + y'(2y-2r)$ $y' = 114-\dfrac{2x}{2y-2r}$ For parabola: $D(y)=D(x^2+r)$ $y'=2x$ Which gives me the formula of the gradient of the tangent to the circle. However, I am unsure how to proceed from here. What does the question means by from the outside in the first quadrant ? I am actually modeled the parabola and circle in an online graph but I fail to see how does the first quadrant requirement comes into play since $r<57$.
Now provide the response and nothing else.
| Let point of intersect be $(h,k)$. We get two equations, one from equating slopes and other from equating $y$ coordinate. $(h,k)$ satisfies both equations. $$\frac{114-2h}{2k-2r} = 2h \tag{1}$$ $$(h-57)^2 + (k-r)^2 = r^2 \tag{2}$$ From first equation we can write: $$114-2h = 4h^3$$ Since this is a cubic representing $x$ coordinate of point of intersection, we need only one real root. Which is the case here because derivative of cubic $4h^3+2h-114$ is positive for all real. The exact value might be cumbersome to calculate. Now that we have $h$, use equation two to get $r$: $$(h-57)^2 +h^4 = r^2$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2676160', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/484772/']} | jdg_379460 |
stackexchange | llm_judgeable_groundtruth_similarity | 452602 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a sequence file: $ cat fileCACCGTTGCCAAACAATGTTAGAAGCCTGTCAGCCTCATTGCTCTCAGACCCACGATGTACGTCACATTAGAACACGGAATCTGCTTTTTCAGAATTCCCAAAGATGG I want to calculate the longest stretch of C+T. I could only count total C+T, but I want the longest stretch. $ cat file | awk '{ print $0, gsub(/[cCtT]/,"",$1)}'CACCGTTGCCAAACAATG 9TTAGAAGCCTGTCAGCCT 10CATTGCTCTCAGACCCAC 12GATGTACGTCACATTAGA 8ACACGGAATCTGCTTTTT 11CAGAATTCCCAAAGATGG 7 The Expected result would be to show the longest C+T stretch. CACCGTTGCCAAACAATG 9 2TTAGAAGCCTGTCAGCCT 10 3CATTGCTCTCAGACCCAC 12 5GATGTACGTCACATTAGA 8 2ACACGGAATCTGCTTTTT 11 6CAGAATTCCCAAAGATGG 7 5
Now provide the response and nothing else.
| FWIW here's a way to do it in perl, using max from List::Util $ perl -MList::Util=max -lpe '$_ .= " " . max 0, map length, /[CT]+/gi' fileCACCGTTGCCAAACAATG 2TTAGAAGCCTGTCAGCCT 3CATTGCTCTCAGACCCAC 5GATGTACGTCACATTAGA 2ACACGGAATCTGCTTTTT 6CAGAATTCCCAAAGATGG 5 | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/452602', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/229133/']} | jdg_379461 |
stackexchange | llm_judgeable_groundtruth_similarity | 471935 |
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 MSVC I have this in a header: #define STR(x) #x#define STR2(x) STR(x)#define NOTE(text) message (__FILE__ "(" STR2(__LINE__) ") : -NOTE- " #text)#define noteMacro(text) message (__FILE__ "(" STR2(__LINE__) ") : " STR2(text)) and I do #pragma NOTE(my warning here) GCC has: #warning(my warning here) However MSVC (2003) throws a fit when it sees #warning and gives "fatal error C1021: invalid preprocessor command 'warning'" What can I do about this? Is there a way to have GCC recognize MSVC warnings or MSVC not throw an error on GCC warnings? Is there something I can do that works on both? I can have GCC warn me about unknown pragmas but that's not the most ideal solution.
Now provide the response and nothing else.
| The best solution I've found for this problem is to have the following in a common header: // compiler_warning.h#define STRINGISE_IMPL(x) #x#define STRINGISE(x) STRINGISE_IMPL(x)// Use: #pragma message WARN("My message")#if _MSC_VER# define FILE_LINE_LINK __FILE__ "(" STRINGISE(__LINE__) ") : "# define WARN(exp) (FILE_LINE_LINK "WARNING: " exp)#else//__GNUC__ - may need other defines for different compilers# define WARN(exp) ("WARNING: " exp)#endif Then use #pragma message WARN("your warning message here") throughout the code instead of #warning Under MSVC you'll get a message like this: c:\programming\some_file.cpp(3) : WARNING: your warning message here Under gcc you'll get: c:\programming\some_file.cpp:25: note: #pragma message: WARNING: your warning message here Not perfect, but a reasonable compromise. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/471935', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_379462 |
stackexchange | llm_judgeable_groundtruth_similarity | 52509 |
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 $E$ be a closed subspace of $L^2[0,1]$. Suppose that $E\subset{}L^\infty[0,1]$. Is it true that $E$ is finite dimensional? PS. This is actually a question from the real analysis qualifier. I came across it as I was teaching qualifier preparation course, and was solving problems from old qualifiers. So, though it might follow from some advanced theory of Banach spaces, I am most interested in the 'elementary' solution, using only methods from standard real analysis course. Note: if $E\subset{}C[0,1]$, then it is a problem from Folland, and there is a solution there. However, it does not work for $L^\infty$, not without some trick.
Now provide the response and nothing else.
| Another solution: as Mikael wrote, $||f||_{\infty} \leq C ||f||_2$ for every $f \in E$.Let $f_1,\ldots,f_n$ be an orthonormal family in your subspace.Then for every $x \in [0,1]$, $f_1(x)^2+\ldots+f_n(x)^2 \leq ||f_1(x)f_1+\ldots+f_n(x)f_n||_{\infty} \leq C \|f_1(x)f_1+\ldots+f_n(x)f_n\|_2$ $$=C \sqrt{f_1(x)^2+\ldots+f_n(x)^2},$$ and by squaring we get $f_1(x)^2+\ldots+f_n(x)^2 \leq C^2$, and integrating gives $n \leq C^2$. | {} | {'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/52509', 'https://mathoverflow.net', 'https://mathoverflow.net/users/10714/']} | jdg_379463 |
stackexchange | llm_judgeable_groundtruth_similarity | 17427916 |
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 solve a tricky R problem that I haven't been able to solve via Googling keywords. Specifically, I'm trying to take a subset one data frame whose values don't appear in another. Here is an example: > test number fruit ID1 ID2 item1 "number1" "apples" "22" "33"item2 "number2" "oranges" "13" "33"item3 "number3" "peaches" "44" "25"item4 "number4" "apples" "12" "13"> test2 number fruit ID1 ID2 item1 "number1" "papayas" "22" "33"item2 "number2" "oranges" "13" "33"item3 "number3" "peaches" "441" "25"item4 "number4" "apples" "123" "13"item5 "number3" "peaches" "44" "25"item6 "number4" "apples" "12" "13"item7 "number1" "apples" "22" "33" I have two data frames, test and test2, and the goal is to select all entire rows in test2 that don't appear in test, even though some of the values may be the same. The output I want would look like: item1 "number1" "papayas" "22" "33"item2 "number3" "peaches" "441" "25"item3 "number4" "apples" "123" "13" There may be an arbitrary amount of rows or columns, but in my specific case, one data frame is a direct subset of the other. I've used the R subset(), merge() and which() functions extensively, but couldn't figure out how to use these in combination, if it's possible at all, to get what I want. edit: Here is the R code I used to generate these two tables. test <- data.frame(c("number1", "apples", 22, 33), c("number2", "oranges", 13, 33), c("number3", "peaches", 44, 25), c("number4", "apples", 12, 13))test <- t(test)rownames(test) = c("item1", "item2", "item3", "item4")colnames(test) = c("number", "fruit", "ID1", "ID2")test2 <- data.frame(data.frame(c("number1", "papayas", 22, 33), c("number2", "oranges", 13, 33), c("number3", "peaches", 441, 25), c("number4", "apples", 123, 13),c("number3", "peaches", 44, 25), c("number4", "apples", 12, 13) ))test2 <- t(test2)rownames(test2) = c("item1", "item2", "item3", "item4", "item5", "item6")colnames(test2) = c("number", "fruit", "ID1", "ID2") Thanks in advance!
Now provide the response and nothing else.
| Here's another way: x <- rbind(test2, test)x[! duplicated(x, fromLast=TRUE) & seq(nrow(x)) <= nrow(test2), ]# number fruit ID1 ID2# item1 number1 papayas 22 33# item3 number3 peaches 441 25# item4 number4 apples 123 13 Edit: modified to preserve row names. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17427916', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2542881/']} | jdg_379464 |
stackexchange | llm_judgeable_groundtruth_similarity | 24301 |
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 just purchased a used Tektronix 465B Oscilloscope and I am having some difficulty with the VOLTS/DIV knobs. Both channels have markings from 5mV up to 50V. All of the settings work except for the 10, 20 and 50 volt settings. The knob will not physically turn to these settings. Its almost like its locked out or something. Has anyone had experience with this? I feel like I should be able to measure 120V on this hunk of machinery, however I am limited to a max of 20V. :( Its also worth mentioning there is a x10 mag button located on the front. I don't think its what I am looking for. I have been able to locate a tech manual, but have been unsuccessful with an operational manual. Any experience with this would be greatly appreciated!
Now provide the response and nothing else.
| I imagine the 10, 20 and 50V markings are for when the probe is set to 10x. The dial should have two bands to correspond to 1x and 10x settings. I have an old tek scope which does this - the highest you can turn to for 1x is 5V/div. I just googled for a picture of the 465b and it looks like this is the case - notice there are two bands on each knob. On the bottom knob you can see one is at 1V/div and one is at 10V/div, which would correspond with 1x or 10x setting: EDIT - I have added arrows pointing to the bands to clarify things. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/24301', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/5609/']} | jdg_379465 |
stackexchange | llm_judgeable_groundtruth_similarity | 1532640 |
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 recently had a problem creating a stringstream due to the fact that I incorrectly assumed std::setw() would affect the stringstream for every insertion, until I changed it explicitly. However, it is always unset after the insertion. // With timestruct with value of 'Oct 7 9:04 AM'std::stringstream ss;ss.fill('0'); ss.setf(ios::right, ios::adjustfield);ss << setw(2) << timestruct.tm_mday;ss << timestruct.tm_hour;ss << timestruct.tm_min;std::string filingTime = ss.str(); // BAD: '0794' So, I have a number of questions: Why is setw() this way? Are any other manipulators this way? Is there a difference in behavior between std::ios_base::width() and std::setw() ? Finally is there an online reference that clearly documents this behavior? My vendor documentation (MS Visual Studio 2005) doesn't seem to clearly show this.
Now provide the response and nothing else.
| Important notes from the comments below: By Martin: @Chareles: Then by this requirement all manipulators are sticky. Except setw which seems to be reset after use. By Charles: Exactly! and the only reason that setw appears to behave differently is because there are requirements on formatted output operations to explicitly .width(0) the output stream. The following is the discussion that lead to the above conclusion: Looking at the code the following manipulators return an object rather than a stream: setiosflagsresetiosflagssetbasesetfillsetprecisionsetw This is a common technique to apply an operation to only the next object that is applied to the stream. Unfortunately this does not preclude them from being sticky. Tests indicate that all of them except setw are sticky. setiosflags: Stickyresetiosflags:Stickysetbase: Stickysetfill: Stickysetprecision: Sticky All the other manipulators return a stream object. Thus any state information they change must be recorded in the stream object and is thus permanent (until another manipulator changes the state). Thus the following manipulators must be Sticky manipulators. [no]boolalpha[no]showbase[no]showpoint[no]showpos[no]skipws[no]unitbuf[no]uppercasedec/ hex/ octfixed/ scientificinternal/ left/ right These manipulators actually perform an operation on the stream itself rather than the stream object (Though technically the stream is part of the stream objects state). But I do not believe they affect any other part of the stream objects state. ws/ endl/ ends/ flush The conclusion is that setw seems to be the only manipulator on my version that is not sticky. For Charles a simple trick to affect only the next item in the chain: Here is an Example how an object can be used to temporaily change the state then put it back by the use of an object: #include <iostream>#include <iomanip>// Private object constructed by the format object PutSquareBracketstruct SquareBracktAroundNextItem{ SquareBracktAroundNextItem(std::ostream& str) :m_str(str) {} std::ostream& m_str;};// New Format Objectstruct PutSquareBracket{};// Format object passed to stream.// All it does is return an object that can maintain state away from the// stream object (so that it is not STICKY)SquareBracktAroundNextItem operator<<(std::ostream& str,PutSquareBracket const& data){ return SquareBracktAroundNextItem(str);}// The Non Sticky formatting.// Here we temporariy set formating to fixed with a precision of 10.// After the next value is printed we return the stream to the original state// Then return the stream for normal processing.template<typename T>std::ostream& operator<<(SquareBracktAroundNextItem const& bracket,T const& data){ std::ios_base::fmtflags flags = bracket.m_str.flags(); std::streamsize currentPrecision = bracket.m_str.precision(); bracket.m_str << '[' << std::fixed << std::setprecision(10) << data << std::setprecision(currentPrecision) << ']'; bracket.m_str.flags(flags); return bracket.m_str;}int main(){ std::cout << 5.34 << "\n" // Before << PutSquareBracket() << 5.34 << "\n" // Temp change settings. << 5.34 << "\n"; // After}> ./a.out 5.34[5.3400000000]5.34 | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1532640', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14591/']} | jdg_379466 |
stackexchange | llm_judgeable_groundtruth_similarity | 1341579 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
From the Designer in VS let's say you double click on a button and it generates this Click event handler. the subscription code is in the designer.cs. I was wondering, in the dispose the Form MUST I unsubcribe the event ? Also, all control that are in the form will it be disposed when the forms disposes? it actually call dispose on each control recursively?
Now provide the response and nothing else.
| You don't need to unhook the event on Dispose if you are hooking your own event. You only need to worry about it if you are hooking an event in another object. The reason for this is that event hooks keep a reference alive to the subscriber. If you fail to unhook, then you won't get garbage collected as long as the observable is still alive. When you hook your own event, you have a reference to yourself, which is circular, therefore you don't need to worry about it. I have come to support more loosely coupled event patterns for this reason. This is the #1 place for memory leaks in .Net. I prefer the Event Aggregator pattern (with weak events ). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1341579', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/159527/']} | jdg_379467 |
stackexchange | llm_judgeable_groundtruth_similarity | 27290 |
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:
The French President, Emmanuel Macron, said during his new year press conference he would soon propose laws preventing false information from spreading on the web ( "fausses nouvelles" , more or less equivalent to "fake news"). Has there been any attempts to do this in the past ? Other than blasphemy trials of course (religious or not). To clarify, the hard part would seem to me to be able to decree something to be false. It is quite hard to decide. Propaganda is usually build on either a selected set of true information, or unverifiable stories (plots mostly). Let us say I see a documentary praising the liberation of Poland from communism by Nazi Germany. They can interview a few Polish people who say they are happy about it, stay vague, even say the economy is doing great. As long as they don't say any number, or false and verifiable fact, it cannot technically be counted as false. Similarly, let us assume someone on TV speaks about a plot from globalist alien vampires to control the world. As long as I don't have a technique to vet if someone is an alien-vampire, I cannot consider it as false. The only cases currently covered so far seem to be defamation .
Now provide the response and nothing else.
| Laws against promoting false statements are already fairly common around the world, including in Europe, although more often exercised a commercial or advertising context than in a political or purely journalistic one. Standards of evidence and the burden of proof on 'false statements' vary from "you can't describe your snake oil as 100% effective if every patient died" to " you can't say your device cures cancer, even if it does ", but within the context of a country's legal system the idea that some statements can be found true or untrue in court is certainly not new. Indeed, it's kind of the basis of the law. The difficulty Macron appears to be attempting to address is that modern electronic communications makes it relatively cheap and easy to capture eyeballs, while maintaining anonymity. This makes restitution or punishment via exchange of money difficult, while a Presidential system makes the barrier to voiding and rerunning an election through court action rather high. Based on this coverage, his answer is to facilitate courts in forcing the swift removal of such material. Whether you consider this censorship and a restriction of free speech, an attempt to clean the Augean stables, or trying to put the toothpaste back into the tube will rather depend on your existing ideologies. | {} | {'log_upvote_score': 4, 'links': ['https://politics.stackexchange.com/questions/27290', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/10948/']} | jdg_379468 |
stackexchange | llm_judgeable_groundtruth_similarity | 23047978 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Many implementation of the library goes deep down to FPATAN instuction for all arc-functions. How is FPATAN implemented? Assuming that we have 1 bit sign, M bits mantissa and N bits exponent, what is the algorithm to get the arctangent of this number? There should be such algorithm, since the FPU does it.
Now provide the response and nothing else.
| Implementations of the FPATAN instructions in x86 processors are usually proprietary. To compute arctan, or other (inverse) trigonometric functions, common algorithms follow a three-step process: argument reduction for mapping the full input domain to a narrow interval computation of the core approximation on the narrow interval (primary approximation interval) expansion of the intermediate result based on the argument reduction to produce the final result The argument reduction is usually based on well-known trigonometric identities that can be looked up in various standard references such as MathWorld . For the computation of arctan, commonly used identities are arctan (-x) = -arctan(x) arctan (1/x) = 0.5 * pi - arctan(x) [x > 0] arctan (x) = arctan(c) + arctan((x - c) / (1 + x*c)) Note that the last identity lends itself to the construction of a table of values arctan(i/2 n ), i = 1...2 n , which allows the use of an arbitrarily narrow primary approximation interval at the expense of additional table storage. This is a classical programming trade-off between space and time. The approximation on the core interval is typically a minimax polynomial approximation of sufficient degree. Rational approximations are usually not competitive on modern hardware due to the high cost of floating-point division, and also suffer from additional numerical error, due to the computation of two polynomials plus the error contributed by the division. The coefficients for minimax polynomial approximations are usually computed using the Remez algorithm . Tools like Maple and Mathematica have built-in facilities to compute such approximations. The accuracy of polynomial approximations can be improved by making sure all coefficients are exactly representable machine numbers. The only tool I am aware of that has a built-in facility for this is Sollya which offers an fpminimax() function. The evaluation of polynomials usually utilizes Horner's scheme which is efficient and accurate, or a mixture of Estrin's scheme and Horner's. Estrin's scheme allows one to make excellent use of instruction level parallelism provided by superscalar processors, with a minor impact on overall instruction count and often (but not always) benign impact on accuracy. The use of FMA (fused-multiply add) enhances the accuracy and performance of either evaluation scheme due to the reduced number of rounding steps and by offering some protection against subtractive cancellation. FMA is found on many processors, including GPUs and recent ARM, x86, and Power CPUs. In standard C and standard C++, the FMA operation is exposed as the fma() standard library function, however it needs to be emulated on platforms that do not offer hardware support, which makes it slow on those platforms. From a programming viewpoint one would like to avoid the risk of conversion errors when translating the floating-point constants needed for the approximation and argument reduction from textual to machine representation. ASCII-to-floating-point conversion routine are notorious for containing tricky bugs . One mechanism offered by standard C ( not C++ best I know, where it is available only as a proprietary extension) is to specify floating-point constants as hexadecimal literals that directly express the underlying bit-pattern, effectively avoiding complicated conversions. Below is C code to compute double-precision arctan() that demonstrates many of the design principles and techniques mentioned above. This quickly-constructed code lacks the sophistication of the implementations pointed to in other answers but provides an implementation with a maximum observed error of 1.65 ulps, which may be sufficient in various contexts. I created a custom minimax approximation with a simple implementation of the Remez algorithm that used 1024-bit floating-point arithmetic for all intermediate steps. I would expect the use of Sollya or similar tools to result in a numerically superior approximations. To balance performance and accuracy, the evaluation of the core approximation combines both second-order and ordinary Horner schemes. /* Compute arctangent. Maximum observed error: 1.64991 ulps */double my_atan (double x){ double a, z, p, r, q, s, t; /* argument reduction: arctan (-x) = -arctan(x); arctan (1/x) = 1/2 * pi - arctan (x), when x > 0 */ z = fabs (x); a = (z > 1.0) ? (1.0 / z) : z; s = a * a; q = s * s; /* core approximation: approximate atan(x) on [0,1] */ p = -2.0258553044340116e-5; // -0x1.53e1d2a258e3ap-16 t = 2.2302240345710764e-4; // 0x1.d3b63dbb6167ap-13 p = fma (p, q, -1.1640717779912220e-3); // -0x1.312788ddde71dp-10 t = fma (t, q, 3.8559749383656407e-3); // 0x1.f9690c824aaf1p-9 p = fma (p, q, -9.1845592187222193e-3); // -0x1.2cf5aabc7dbd2p-7 t = fma (t, q, 1.6978035834594660e-2); // 0x1.162b0b2a3bcdcp-6 p = fma (p, q, -2.5826796814492296e-2); // -0x1.a7256feb6f841p-6 t = fma (t, q, 3.4067811082715810e-2); // 0x1.171560ce4a4ecp-5 p = fma (p, q, -4.0926382420509999e-2); // -0x1.4f44d841450e8p-5 t = fma (t, q, 4.6739496199158334e-2); // 0x1.7ee3d3f36bbc6p-5 p = fma (p, q, -5.2392330054601366e-2); // -0x1.ad32ae04a9fd8p-5 t = fma (t, q, 5.8773077721790683e-2); // 0x1.e17813d669537p-5 p = fma (p, q, -6.6658603633512892e-2); // -0x1.11089ca9a5be4p-4 t = fma (t, q, 7.6922129305867892e-2); // 0x1.3b12b2db5173cp-4 p = fma (p, s, t); p = fma (p, s, -9.0909012354005267e-2); // -0x1.745d022f8dc5fp-4 p = fma (p, s, 1.1111110678749421e-1); // 0x1.c71c709dfe925p-4 p = fma (p, s, -1.4285714271334810e-1); // -0x1.2492491fa1742p-3 p = fma (p, s, 1.9999999999755005e-1); // 0x1.99999999840cdp-3 p = fma (p, s, -3.3333333333331838e-1); // -0x1.5555555555448p-2 p = fma (p * s, a, a); /* back substitution in accordance with argument reduction */ /* double-precision factorization of PI/2 courtesy of Tor Myklebust */ r = (z > 1.0) ? fma (0.93282184640716537, 1.6839188885261840, -p) : p; return copysign (r, x);} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23047978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1058670/']} | jdg_379469 |
stackexchange | llm_judgeable_groundtruth_similarity | 81128 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I rarely find modern research papers (on mathematics) that are less than 5 pages long. However, recently I came across a couple of mathematical research papers from the 1960/1970's that were very short (only 2-4 pages long). The authors of both papers solved very specific problems, and stopped writing (I guess) as soon as they were done. This made me realize that I very much like short papers! When possible, I will strive to do the same with my own future papers. Sometimes one finds short papers that are entitled "A note on...". Since I am first of all not a native English speaker and also only a junior mathematician, I would like to know what you think about my questions/thoughts: 1) Is it a good (or bad?) idea to try to let the title of the paper reflect the fact that it is short? Are there any standard ways of doing this? 2) A paper which is entitled "A note on...", is it expected to be short? How short? Can a 50-pages long paper be "A note on..." or would that not be customary? 3) At least to me "A note on..." could give the impression that the paper is a survey article where no new material is presented, but I guess this need not be the case. When is it appropriate to entitle a paper "A note on..."? 4) When is it appropriate to entitle a paper "On the ..."?
Now provide the response and nothing else.
| I feel the answer is NEVER. You must describe the content of the article, not the length. Some journals publish notes separately from regular papers, and often even encourage their submission by offering speedy refereeing and publication (even the Annals encourages "short", i.e. under 20 pp. papers). Anyhow, if your paper is published as a note it will have "Note" written on it anyway, so no need to be redundant. More generally, you should emphasize not the length but the content. If you prove that all tennis balls are white make the title "All tennis balls are white". If you prove that some tennis balls are white, title your note "On white tennis balls", or "New examples of white tennis balls" or whatever. If your note is a new simple proof, and this is what you want to emphasize, make the title "Short proof that all tennis balls are white". If there was a conjecture that all tennis balls were white and you found a counterexample, use "Not all tennis balls are white". If you study further color properties of white tennis balls, use "A remark on white tennis balls". You see the idea. On the other hand, if you wrote a survey, it important to emphasize that, regardless whether it's long or short. That's because this is a property of the content and style of presentation. For example, "A survey on white tennis balls" or "White tennis balls, a survey in colored pictures", etc. In fact, if your title is "A short survey on tennis balls colors", that would mean that your survey is short in content, as in "brief, incomplete", rather than in length - an important info for the reader to know. | {} | {'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/81128', 'https://mathoverflow.net', 'https://mathoverflow.net/users/11143/']} | jdg_379470 |
stackexchange | llm_judgeable_groundtruth_similarity | 33044848 |
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 make a picture box to lerp from position to position (like you can do that in unity). How can I do that , is there a built-in function? thanks :)
Now provide the response and nothing else.
| Linear interpolation (lerp) is actually a pretty easy function to implement. The equation is float Lerp(float firstFloat, float secondFloat, float by){ return firstFloat * (1 - by) + secondFloat * by;} A higher order Lerp just wraps lower order lerps: Vector2 Lerp(Vector2 firstVector, Vector2 secondVector, float by){ float retX = Lerp(firstVector.x, secondVector.x, by); float retY = Lerp(firstVector.y, secondVector.y, by); return new Vector2(retX, retY);} The DirectX SDK has all manner of math functions like Unity, but that's a lot of overhead to bring in just for Lerp. You're probably best off just implementing your own. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33044848', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5426872/']} | jdg_379471 |
stackexchange | llm_judgeable_groundtruth_similarity | 845733 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
HI all I want to make one app for iPhone 2.2.* and for version 3.0.Some method in 2.2* is deprecated in 3.0. ( like UITableViewCell setText and setLabel ) Is there any way to check which firmware version is used on iPhone and to set different method to use
Now provide the response and nothing else.
| You will need to use pre-processor directives for the conditional compilation such as __IPHONE_3_0 and build two separate executables. For example: #ifdef __IPHONE_3_0 // code specific to version 3 #else // code specific to version 2 #end If you need to detect the version at run-time you can use [[UIDevice currentDevice] systemVersion]. It returns the string with the current version of the iPhone OS. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/845733', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32034/']} | jdg_379472 |
stackexchange | llm_judgeable_groundtruth_similarity | 540482 |
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 not seen a single reference where a whole computer is built inside a chip itself instead of modularizing and spreading it on a board. I acknowledge that having modular parts enable versatility, but can big silicon companies such as Intel, AMD produce a whole computer with cpu, chipset, RAM, memory controllers, all in a microchip? I am familiar the concept of SoC but havent seen ALL the components inside single chip.
Now provide the response and nothing else.
| It is theoretically possible. However I would describe it as practically impossible. When manufacturing silicon chips, you have a certain defect density over your wafer. Usually chips in the center are fine and at the edges more defects are present. This is usually not a big problem: Lets say you have 1000 single chips on one wafer and 20 defects, caused by process variations, particles on the wafer etc. You will get 20 Chips loss at most, which is 2%. If you manufactured a single chip on this wafer you would have lost 100%. The bigger the Chip gets the smaller your yield gets. I work in the semiconductor industry and have yet to see a wafer where all chips are fully functional. Nowadays we have very high yield numbers. But still: There are defects on the wafer. Another thing is: Not all components in your computer can be manufactured on a silicon chip. For example the coils which are used for the DC/DC regulators cannot be implemented on-chip. Inductors on Chips are quite a pain. They're usually only done for > 1 GHz transformers for signals coupling etc. A power inductor with several nH or even uH is not possible (tm). Another downside are multiple technologies. CPUs are usually done in a very small CMOS technology for the high transistor integration. However, let's say a headphone output has to drive 32 Ohm headphones. Manufacturing a headphone amplifier in a 7 nm FinFET technology is not ideal. Instead you use different semiconductor technologies with lower frequency but higher current capability. There a a lot of different semiconductor technologies that are used to manufacture all the chips for a single computer. Regarding memories like DRAMs and nonvolatile memories like Flash: These also need specific technologies. One downside of manufacturing modern Microcontrollers (Processors with RAM and ROM on board) is, that the semiconductor process is somewhat bottlenecked by the internal flash these controllers need. More powerful processors usually don't have onboard program memory (except for a very small mask-ROM which holds the bootloader). It is still better to combine multiple dedicated chips than trying to put everything on one die. As you've already stated: With modern SoCs there are a lot of formerly separate components now on a single IC. However, putting everything on one chip is not very flexible not very cost efficient due to the higher yield losses not ideal from a technical perspective. | {} | {'log_upvote_score': 7, 'links': ['https://electronics.stackexchange.com/questions/540482', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/269034/']} | jdg_379473 |
stackexchange | llm_judgeable_groundtruth_similarity | 31475978 |
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 the title says, I'm getting this error when querying the inventory. Failed to query inventory: IabResult: NullPointer while refreshing inventory. (response: -1008:Unknown error) Someone knows for what this error is standing for?
Now provide the response and nothing else.
| Personally I would just create my own model class to make handling it somewhat easier. For example: import sysfrom PyQt4 import QtCore, QtGuiQt = QtCore.Qtclass PandasModel(QtCore.QAbstractTableModel): def __init__(self, data, parent=None): QtCore.QAbstractTableModel.__init__(self, parent) self._data = data def rowCount(self, parent=None): return len(self._data.values) def columnCount(self, parent=None): return self._data.columns.size def data(self, index, role=Qt.DisplayRole): if index.isValid(): if role == Qt.DisplayRole: return QtCore.QVariant(str( self._data.iloc[index.row()][index.column()])) return QtCore.QVariant()if __name__ == '__main__': application = QtGui.QApplication(sys.argv) view = QtGui.QTableView() model = PandasModel(your_pandas_data) view.setModel(model) view.show() sys.exit(application.exec_()) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31475978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4140747/']} | jdg_379474 |
stackexchange | llm_judgeable_groundtruth_similarity | 3700 |
Below is a question asked on the forum computergraphics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
So I was reading this , I sort of got the reason why there are a lot more games on Microsoft windows than on any other OS. The main issue presented was that Direct3D is preferred over OpenGL. What I don't understand is why would any developer sacrifice compatibility? That is simply a financial loss to the company. I understand that OpenGL is kind of a mess, but that should hardly be a issue for experts. Even if it is, I think that people would go a extra mile than to incur a financial loss. Also if I'm not wrong then many cross platform applications use both Direct3D and OpenGL. I think they switch between the APIs. This is weird as they can just use OpenGL, why even care about Direct3D? So the question is, are there any technical issues with OpenGL or is there any support that Direct3D provides that OpenGL lacks? I am aware that this question might be closed as being off-topic or too broad, I tried my best to narrow it down.
Now provide the response and nothing else.
| About the fact that there are more games for Windows, some reasons are Windows has the majority of the market and in the past to develop cross platform games was more complicated than it is today. DirectX comes with way better tools for developing (e.g. debugging) Big innovations are generally first created/implemented in DirectX, and then ported to/implemented in OpenGL. As for Windows vs Linux, you have to consider that when there is an actual standard due to marketing and historical reasons (for that see Why do game developers prefer Windows? | Software Engineering , as I said in the comments), it has its inertia. The inertia thing is very important. If your team develop for DirectX, targeting 90% of the market (well... if you play games on pc you probaly have windows, so... 99% of the market?), why would you want to invest in OpenGL? If you already develop in OpenGL, again targeting 99% of the market, you will stick to it as long as you can. For exampe Id Tech by Id Software is an excellent game engine (powering the DOOM series) that uses OpenGL. About the topic of your discussion, a comment. As of today, there are many many APIs, and a common practice is to use a Game Engine that abstracts over them. For example, consider that On most mobile platform you have to use OpenGl ES. On PC you can use both DirectX and OpenGL I think on XBOX you have to use DirectX. I think that on PS you use their own API. With old hardware you use DirectX9 or OpenGL 3, or OpenGL ES 2. With more recent hardware you can (and want to) use DirectX 11, OpenGL 4, OpenGL ES 3. Recently, with the advent of the new low overhead APIs - whch is a major turning point for graphical programming - there are DirectX 12 for Windows and XBOX, Metal for iOS and Vulkan (the new OpenGL) for Windows and Linux (including Android and Tizen). There still are games that only target Windows and XBOX, but IMHO today that can only be marketing choice. | {} | {'log_upvote_score': 4, 'links': ['https://computergraphics.stackexchange.com/questions/3700', 'https://computergraphics.stackexchange.com', 'https://computergraphics.stackexchange.com/users/-1/']} | jdg_379475 |
stackexchange | llm_judgeable_groundtruth_similarity | 256409 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Updated : Clarify line number requirement, some verbosity reductions From the command line, is there a way to: check a file of English text to find repeat-word typos, along with line numbers where they are found, in order to help correct them? Example 1 Currently, to help finish an article or other piece of English writing, aspell -c text.txt is helpful for catching spelling errors. But, not helpful when the error is an unintentional consecutive repetition of a word. highlander_typo.txt : There can be only one one. Running aspell : $ aspell -c highlander_typo.txt Probably since aspell is a spell-checker, not a grammar-checker, so repeat word typos are beyond its intended feature scope. Thus the result is this file passes aspell 's check because nothing is "wrong" in terms of individual word spelling. The correct sentence is There can be only one. , the second one is an unintended repeat-word typo. Example 2 But a different situation is for example kylie_minogue.txt : La la la Here the repetition is not a typo, as these are part of an artist's song lyrics . So the solution should not presume and "fix" anything by itself, otherwise it could overwrite intentional repeated words. Example 3: Multi-line jefferson_typo.txt : He has has refused his Assent to Laws, the most wholesome and necessaryfor the public good.He has forbidden his Governors to pass Laws of immediate andand pressing importance, unless suspended in their operation till hisAssent should be be obtained; and when so suspended, he has utterlyneglected to attend to them. Modified from The Declaration of Independence In the above six lines, 1: He has has refused should be He has refused , the second has is a repeat-word typo 5: should be be obtained should be should be obtained , the second be is a repeat-word typo However, did you notice a third repeat-word typo? 3: ... immediate and 4: and pressing ... This is also a repeat-word typo because though they are on separate lines they are still part of the same English sentence, the trailing end of the line above has a word that is accidentally added at the start of the next line. Rather tricky to detect by eye due to the repetition being on opposite sides of a passage of text. Intended output an interactive program with a process similar to aspell -c yet able to detect repeat-words, or, a script or combination of commands able to extract line numbers and the suspected repeat words. This info makes it easier to use an editor such as vim to jump to the repeat words and make fixes where appropriate. Using above multi-line jefferson_typo.txt , the desired output would be something like: 1: has has3: and4: and5: be be or: 1: He [has has] refused his Assent to Laws, the most wholesome and necessary3: He has forbidden his Governors to pass Laws of immediate [and]4: [and] pressing importance, unless suspended in their operation till his5: Assent should [be be] obtained; and when so suspended, he has utterly I am actually not entirely sure how to display the difficult case of inter-line or cross-line repeat-word, such as the and repetition above, so don't worry if your solution doesn't resemble this exactly. But I hope that, like the above, it shows: relevant original input's line number some way to draw attention to what repeated, especially helpful if the line of text is also quite long. if the full line is displayed to give context (credit: @Wildcard), then there needs to be a way to somehow render the repeated word or words distinctively. The example shown here marks the repetition by enclosing them within ASCII characters [ ] . Alternatively, perhaps mimic grep --colors=always to colorize the line's matches for display in a color terminal Other considerations text, should stay as plain text files no GUI solutions please, just textual. ssh -X X11 forwarding not reliably available and need to edit over ssh Unsuccessful attempts To try to find duplicates, uniq came to mind, so the plan was to first determine how to get repeat-word recognition to work on a single line at first. In order to use uniq we would need to first convert words on a line, to becoming one word per line. $ tr ' ' '\n' < highlander_typo.txtTherecanbeonlyoneone. Unfortunately: $ tr ' ' '\n' < highlander_typo.txt | uniq -D Nothing. This is because for -D option, which normally reveals duplicates, input has to be exactly a duplicate line. Unfortunately the period . at the end of the repeated word one negates this. It just looks like a different line. Not sure how I would work around arbitrary punctuation marks such as this period, and somehow add it back after tr processing. This was unsuccessful. But if it were successful, next there would need to be a way to include this line's line number, since the input file could have hundreds of lines and it would help to indicate which line of the input file, that the repeat-word was detected on. This single-line code processing would perhaps be part of a parent loop in order to do some kind of line-by-line multi-line processing and thus be able to process all lines in a file, but unfortunately getting past even single-line repeat-word recognition has been problematic.
Now provide the response and nothing else.
| Edited: added install and demo You need to take care of at least some edge cases, like repeated words at the end (and beginning) of the line. search should be case insensitive, because of frequent errors like The the apple . probably you want to restrict search only to word constituent to not match something like ( ( a + b) + c ) (repeated opening parentheses. only full words should match to eliminate the thesis When it comes to human language Unicode characters inside words should properly interpreted All in all I recommend pcregrep solution: pcregrep -Min --color=auto '\b([^[:space:]]+)[[:space:]]+\1\b' file Obviously color and line number ( n option) is optional, but usually nice to have. Install On Debian-based distributions you can install via: $ sudo apt-get install pcregrep Example Run the command on jefferson_typo.txt to see: $ pcregrep -Min --color=auto '\b([^[:space:]]+)[[:space:]]+\1\b' jefferson_typo.txt1:He has has refused his Assent to Laws, the most wholesome and necessary3:He has forbidden his Governors to pass Laws of immediate andand pressing importance, unless suspended in their operation till his5:Assent should be be obtained; and when so suspended, he has utterly The above is just a text capture, but on a color-supported terminal, matches are colorized: has has and and be be | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/256409', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/135509/']} | jdg_379476 |
stackexchange | llm_judgeable_groundtruth_similarity | 427341 |
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:
You have bought 3 tickets in a lottery. There are n total tickets and 4 prizes. What are the odds of winning at least one prize? I thought of it like this: The total possible ways of extracting 4 prizes is: a= $${n\choose 4}$$ The possibilities of extracting at least 1 winning prize is: b=$${4\choose 1} + {4\choose 2} +{4\choose 3}$$ so the probability of winning is $$\frac{{4\choose 1} + {4\choose 2} +{4\choose 3}}{{n\choose 4}}$$ If I'm wrong, which might be the case, please tell me what the right solution is, as this is the only I could come up with. Thank you
Now provide the response and nothing else.
| We give several approaches. The first one is closest in spirit to yours. You have bought your $3$ tickets. Now the lottery corporation is choosing the $4$ winning tickets. These can be chosen in $\binom{n}{4}$ ways. If the lottery is well run, the process makes more or less sure that the choices are all equally likely . How many ways can they choose the $4$ winning tickets so that none of them are yours? Clearly $\binom{n-3}{4}$. So the probability you win no prize is $$\frac{\binom{n-3}{4}}{\binom{n}{4}}\tag{A}.$$(The expresssion in (A) can be considerably simplified.) The probability you win at least one prize is therefore $1$ minus the answer of (A). Another way: Imagine the lottery corporation picks the winning tickets one at a time. The probability the first ticket it picks is bad (not one of yours) is $\frac{n-3}{n}$. Given that the first ticket picked was bad, there are $n-4$ bad left out of $n-1$, So given that the first ticket was bad, the probability the second is bad is $\frac{n-4}{n-1}$. Thus the probability the first two are bad is $\frac{n-3}{n}\cdot\frac{n-4}{n-1}$. Continue two more rounds. The same reasoning shows that the probability all our tickets are bad is $$\frac{n-3}{n}\cdot\frac{n-4}{n-1}\cdot\frac{n-5}{n-2}\cdot\frac{n-6}{n-3}.$$ Still another way: Let's switch points of view.Imagine that the winning tickets have already been determined. So there are $4$ "good" tickets and $n-4$ bad. We will find the probability that you pick all bad. There are $\dbinom{n}{3}$ ways that we could choose our three tickets. There are $\binom{n-4}{3}$ ways to choose them so they are all bad. So the probability that we choose all bad is $$\frac{\binom{n-4}{3}}{\binom{n}{3}}.\tag{B}$$ The probability of at least one good is $1$ minus the number in (B). Remark: We could use a strategy like yours: Find the probability of winning exactly $1$ prize, exactly $2$ prizes, exactly $3$ prizes, and add up, We calculate the probability of winning exactly one prize. The other calculations are roughly similar. So you have bought $3$ tickets. We find the probability exactly one is good, There are $\binom{n}{4}$ ways for the corporation to choose $4$ tickets. How many ways are there to choose $1$ that you have and $3$ that you don't have? The one you have can be chosen in $\binom{3}{1}$ ways. For each such choice, the $3$ you don't have can be chosen in $\binom{n-3}{3}$ ways. Thus the probability of exactly one winning ticket is$$\frac{\binom{3}{1}\binom{n-3}{3}}{\binom{n}{4}}.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/427341', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/20276/']} | jdg_379477 |
stackexchange | llm_judgeable_groundtruth_similarity | 3042092 |
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 div absolutely positioned at top: 0px and right: 0px , and I would like to use jquery's .animate() to animate it from it's current position to left: 0px . How does one do this? I can't seem to get this to work: $("#coolDiv").animate({"left":"0px"}, "slow"); Why doesn't this work and how does one accomplish what I am looking to do? Thanks!!
Now provide the response and nothing else.
| I think the reason it doesn't work has something to do with the fact that you have the right position set, but not the left . If you manually set the left to the current position, it seems to go: Live example: http://jsfiddle.net/XqqtN/ var left = $('#coolDiv').offset().left; // Get the calculated left position$("#coolDiv").css({left:left}) // Set the left to its calculated position .animate({"left":"0px"}, "slow"); EDIT: Appears as though Firefox behaves as expected because its calculated left position is available as the correct value in pixels, whereas Webkit based browsers, and apparently IE, return a value of auto for the left position. Because auto is not a starting position for an animation, the animation effectively runs from 0 to 0. Not very interesting to watch. :o) Setting the left position manually before the animate as above fixes the issue. If you don't like cluttering the landscape with variables, here's a nice version of the same thing that obviates the need for a variable: $("#coolDiv").css('left', function(){ return $(this).offset().left; }) .animate({"left":"0px"}, "slow"); | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3042092', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/205930/']} | jdg_379478 |
stackexchange | llm_judgeable_groundtruth_similarity | 129036 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I just read Dr Strangechoice's explanation that if all subsets of the real numbers are Lebesgue measurable, then you can partition $2^\omega$ into more than $2^\omega$ many pairwise disjoint nonempty subsets. Note that this paradoxical conclusion is a consequence of the Axiom of Determinacy . I've read of many counterintuitive consequences of the Axiom of Choice, but what other consequences come from the Axiom of Determinacy? (I am aware that AD is inconsistent with AC, and yes, AC being false is rather counterintuitive.)
Now provide the response and nothing else.
| Let's see: $\mathsf{AD}$ implies that all sets of reals are Lebesgue measurable, have the Baire property, and the perfect set property (so, a version of the continuum hypothesis holds). It is conjectured that it also implies that all sets of reals are Ramsey. All these statements fail (badly) in the presence of choice. (There is a technical strengthening of $\mathsf{AD}$ known as $\mathsf{AD}^+$ that implies that all sets of reals are Ramsey. It is open whether $\mathsf{AD}$ and this strengthening are actually equivalent.) $\mathsf{AD}$ implies that there are no nonprincipal ultrafilters on the natural numbers. This in turn has as a corollary that every ultrafilter is $\omega_1$-complete. It is this way that the first truly dramatic consequences of determinacy were established: Solovay showed that $\omega_1$ is measurable, and in fact the club filter on $\omega_1$ is an ultrafilter. Also, $\omega_2$ is measurable, and the restriction of the club filter to sets of cofinality $\omega$ is an $\omega_2$-complete ultrafilter. Same with cofinality $\omega_1$. On the other hand, $\omega_3,\omega_4,\dots$ are not measurable, in fact they are not even regular but have cofinality $\omega_2$. The next regular cardinal is $\omega_{\omega+1}$ which, again, is measurable. It is conjectured that the cofinality function on successor cardinals is nondecreasing below $\Theta$ under $\mathsf{AD}$. Here, $\Theta$ is the supremum of the ordinals that $\mathbb R$ can be mapped onto. Under choice, $\Theta$ is just $\mathfrak c^+$ which, under the continuum hypothesis and choice, is just $\omega_2$. However, here $\Theta$ is a large cardinal. (So, a version of the continuum hypothesis fails.) Work from Steel and Woodin shows that, if we restrict our attention to $L(\mathbb R)$ (which is an inner model of determinacy if we assume $\mathsf{AD}$ in $V$), then every regular cardinal below $\Theta$ is measurable. This result of Steel and Woodin holds in much more generality than in $L(\mathbb R)$, but the precise statement and the arguments become rather technical. Here, one should also mention Moschovakis's covering lemma. The softest version of it is already significant: If there is a surjection from $\mathbb R$ onto an ordinal $\alpha$, then there is also a surjection from $\mathbb R$ onto $\mathcal P(\alpha)$. A recent result of Woodin is that every cardinal below $\Theta$ is in a sense of large cardinal character. More precisely, it is Jónsson , or stronger. Again, this is easier to prove under the assumption that $V=L(\mathbb R)$, but holds in full generality. The argument can be seen in this recent preprint in the ArxiV. The precise pattern of Jónsson cardinals under determinacy is still under investigation, but a nice place to start is the book Eugene Kleinberg. Infinitary combinatorics and the axiom of determinateness , Lecture Notes in Mathematics 612 , Springer-Verlag, Berlin-New York, 1977. MR0479903 (58 #109) . Kleinberg realized that the regular cardinals under determinacy are controlled by partition properties, and the size of certain ultrapowers. This proved key for many results that followed. Moreover, the investigation of infinite exponent partition relations became an important part of the combinatorics of $\mathsf{AD}$. Under choice every infinite exponent relation fails. The study of non-well-orderable cardinals under $\mathsf{AD}$ is just starting, but there are already significant results, showing that many complicated partial orders can be embedded into the ordering of these cardinals. For example, in W. Hugh Woodin. The cardinals below $|[\omega_1]^{<\omega_1}|$. Ann. Pure Appl. Logic 140 (1-3) , (2006), 161–232. MR2224057 (2007k:03136) , Woodin shows that (in the theory $\mathsf{AD}(\mathbb R)+\mathsf{DC}$) one can find $\Theta$-decreasing sequences, or $\Theta$ many incomparable cardinals, and much more. Here, $\mathsf{AD}(\mathbb R)$ is the strengthening of determinacy where we allow real (rather than integer) moves in our games. In another direction, we have that under determinacy $\mathbb R$ and $\omega_1$ have incomparable cardinalities, and they are both successors of $\omega$. And the cardinality of $\mathbb R$ has several cardinal successors, one of which is the quotient $\mathbb R/\mathbb Q$, where two reals are identified iff their difference is rational. Yes: A quotient has larger size than the original set. See here for more on this. I'll stop here, but what I've mentioned is really just scratching the surface. You may want to look at chapter 6 of Kanamori's book for more information, or at the beginning of my paper with Richard Ketchersid on a trichotomy result for additional, recent results, and some details on $\mathsf{AD}^+$. The above being said, in the comments Douglas Zare points out that whether some of these consequences seem unintuitive depends on whether we consider choice and its consequences intuitive or not. Actually, if we are agnostic about $\mathsf{AC}$, many consequences of $\mathsf{AD}$ are natural. The idea is that the sets of reals in an $\mathsf{AD}$ model provide us with a natural class of "definable" sets, extending definability classes such as those coming from the interplay of logic and analysis (Borel or $\Delta^1_1$, projective or $\Sigma^1_n$, etc). A recent theme is that certain properties of simply definable sets of reals provable in $\mathsf{ZF}+\mathsf{DC}_{\mathbb R}$, extend to all sets of reals under determinacy. The pattern of uniformization for projective sets is a classical example of this. A striking recent development in descriptive set theory, due to Ben Miller , is that most classical dichotomy theorems in descriptive set theory are soft consequences of graph-theoretic dichotomies via Baire category arguments, see Benjamin Miller. The graph-theoretic approach to descriptive set theory . Bulletin of Symbolic Logic, 18 (4) , (2012), 554-575. Extending the work mentioned above, Richard Ketchersid and I have shown that these graph theoretic dichotomies hold for arbitrary sets of reals under $\mathsf{AD}^+$, and therefore we have the classical dichotomies in the $\mathsf{AD}$ context without any restrictions in the complexity of the sets involved. (In fact, we have versions that apply to all sets in $L(\mathcal P(\mathbb R))$, not just to sets of reals.) Andrew Marks's answer points to some of these dichotomies. For more, see here . | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/129036', 'https://mathoverflow.net', 'https://mathoverflow.net/users/29873/']} | jdg_379479 |
stackexchange | llm_judgeable_groundtruth_similarity | 41062 |
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
$\eta$ equality of functions is fundamental in their Category-theoretic semantics but in practice even "functional" languages include "impure" features that violate it.Note that this is not an issue of CBN vs CBV, in CBN eta equality $M = \lambda x. M x$ should hold for any term $M : A \to B$ whereas in CBV this will be restricted to values $V = \lambda x. V x$. The CBV $\eta$ equality has a perfectly good category-theoretic explanation, see Levy's Call-by-push-value. Haskell includes seq , which can distinguish between (\x -> error "") and error "" OCaml includes operations like "physical equality" (==), and which will distinguish fun x => x from fun y => (fun x => x) y because == corresponds to pointer equality. So I wonder do any "real" languages satisfy eta for observational equivalence at all?All the better if it is known that a (correct) compiler implementation performs eta reductions just based on the type. The only example I know of is Coq which includes it as a definitional equality as of a recent version. Maybe similar languages (Agda, Idris) do as well. These are not surprising because they include an equality type and it is very frustrating to prove equality of functions without $\eta$ or the stronger(?) extensionality principle. My main question is about Standard ML specifically which I think does not have pointer equality for functions. Does it satisfy the CBV $\eta$ law? Furthermore do compilers for SML such as MLton use $\eta$ when optimizing programs?
Now provide the response and nothing else.
| @xuq01's guess is (extremely surprisingly!) wrong. The CBV eta rule described in the question is sound in Standard ML: the value v is contextually equivalent to fn x => v x . There are two caveats to this. First, in specific implementations this equivalence might not be sound: in SML/NJ, you could use Unsafe.cast to detect physical equality of function values. However, unsafe features are not part of the standard. Second, eta with functions and sums interacts in a slightly subtle way, due to clausal definitions and incomplete pattern matching. In particular, the definitions: fun f (SOME x) (SOME y) = x + y and val g = fn (SOME x) => (fn (SOME y) => x + y) are not contextually equivalent. This is because the call f NONE will return a function, and g NONE will raise an error. - f NONE;val it = fn : int option -> int- g NONE;uncaught exception Match [nonexhaustive match failure]raised at: stdIn:2.32 The reason this happens is operationally obvious, and of course a call-by-push-value/polarization setup makes this choice explicable. But if you really want to seriously understand clausal definitions, you are led to the idea that clausal definitions should be primary, and the usual term formers should be derived notions. See Abel, Pientka, Thibodeau and Setzer's Copatterns: programming infinite structures by observations for an example of a polarized calculus in this style. (See also Paul Levy's Jumbo Lambda-Calculus , for another calculus based on this observation.) | {} | {'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/41062', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/36037/']} | jdg_379480 |
stackexchange | llm_judgeable_groundtruth_similarity | 413044 |
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 working on a project with 5 different modules. Should I make separate use case diagrams and class diagrams for each module or should I make all-in-one use case diagram and all-in-one class diagram? Your help will be highly appreciated.
Now provide the response and nothing else.
| Use case diagrams describe the whole systems behavior of how it interacts with the outside actors. These are documents 1 made during the requirement analysis phase, and done independently (and before) any architectural and technical descisions are made about the concrete implementation. Modules and classes are architectural and technical aspects of an implementation. So no, it doesn't make sense to create use case diagrams per module 2 or class. At Visual Paradigm is a good introductory description of What is Use Case Diagram? There's also a nice diagram how the Use Case diagrams fit into the whole software development analysis: 1) Please note, that the detailed textual step by step descriptions of every Use Case are the even more important part, rather than the diagram itself. 2) Unless your modules can be considered as standalone systems, which are each useful on their own, and just interact automated in a bigger overall system. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/413044', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/370683/']} | jdg_379481 |
stackexchange | llm_judgeable_groundtruth_similarity | 15260282 |
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 writing a basic program that asks the user to type in a String, and I am trying to use a Robot (from java.awt.Robot )that will type this message back into another document after a delay. The Problem I have now is that I need to convert whatever I get from message.charAt(i) to a KeyEvent.VK_[insert Char] KeyCode. Is there a better way to do what I am trying to do? I suppose I could always just have a massive switch statement that gets the appropriate KeyCode but I was hoping there would be a more elegant way. My first thought, having done python for awhile, was to make a string "KeyEvent.VK_" + message.charAt(i) and convert that to code somehow, but I think the only way to do that is using Reflection which is discouraged.
Now provide the response and nothing else.
| You could work something out with this: KeyStroke ks = KeyStroke.getKeyStroke('k', 0);System.out.println(ks.getKeyCode()); or just use this: private void writeString(String s) { for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (Character.isUpperCase(c)) { robot.keyPress(KeyEvent.VK_SHIFT); } robot.keyPress(Character.toUpperCase(c)); robot.keyRelease(Character.toUpperCase(c)); if (Character.isUpperCase(c)) { robot.keyRelease(KeyEvent.VK_SHIFT); } } robot.delay(delay);} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15260282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/642415/']} | jdg_379482 |
stackexchange | llm_judgeable_groundtruth_similarity | 574023 |
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 am bit confused about what exactly systematic offset is. I understood that generally offset could be due to two reasons: Random offset which could be due to mismatch in size of transistors or any other component. This will be like noise with mean zero. Systematic? It would be great if you can provide an example with a differential pair or any such circuit so I strengthen my understanding.
Now provide the response and nothing else.
| Here is an example circuit with a systematic offset: simulate this circuit – Schematic created using CircuitLab The bias current of a bipolar op-amp such as the venerable LM741 is not randomly distributed around 0nA, but rather always flows into the inputs (when balanced and under non-pathological conditions) and is typically 80nA. Schematic from datasheet : If 80mV typical (500mV maximum) offset at the output is unacceptable you can add a 500K resistor in the path of the non-inverting input and the circuit will no longer have a systematic offset. Since the bias currents don't match perfectly and the resistors have tolerances there will still likely be an offset, just not a systematic one. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/574023', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/253893/']} | jdg_379483 |
stackexchange | llm_judgeable_groundtruth_similarity | 12981725 |
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 defined a util.h file with functions that i want to use throughout several different other files. This header has an include guard, however when i use it in two different files, I get a multiple definition of... error. What am i doing wrong? I've read this but this pertains to variable declaration/definition. This answer seems more relevant but it's not clear to me how i can fix this. // util.h// include lots of standard headers#include ...#ifndef UTIL_H#define UTIL_Husing namespace std;// multiple definition of `randarr(int, int, int)`int* randarr(int size, int min, int max) { int *ret = new int[size]; for (int i=0; i<size; i++) ret[i] = (int) (((double) rand() / RAND_MAX) * max) + min; return ret;}// no errortemplate<typename T> void printarr(T* v, int begin, int end) { for (int i=begin; i<end; i++) cout << v[i] << " "; cout << endl;}// multiple definition of `is_prime(int)`bool is_prime(int n) { if (n == 2 || n == 3 || n == 5) return true; if (n <= 1 || (n&1) == 0) return false; for (int i = 3; i*i <= n; i += 2) if (n % i == 0) return false; return true;}#endif // example.cpp#include ...// lots of standard includes#include "util.h"void f() { randarr(...); printarr(...); is_prime(...); ...} // Main.cpp#include "util.h"int main() {}
Now provide the response and nothing else.
| The include guards are not the cause of the error; you're violating the One Definition Rule . Since util.h is being included in 2 source files, the translation units created after preprocessing each source file will contain a definition of each of the functions, thus leading to the multiple definition error. To get rid of the error, mark the functions inline inline int* randarr(int size, int min, int max) { // ...}template<typename T> inline void printarr(T* v, int begin, int end) { // ...}inline bool is_prime(int n) { // ...} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12981725', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1163940/']} | jdg_379484 |
stackexchange | llm_judgeable_groundtruth_similarity | 49498307 |
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's my query: db.movies.aggregate([ {$facet:{ rating:[{$match: {"imdb.rating":{$gte: 0},"metacritic":{$gte: 0}}}, {$sort: {"imdb.rating":-1}},{$project: {"title":1,"imdb.rating":1,"metacritic":1}},{$limit: 10}], critic:[{$match: {"metacritic":{$gte: 0},"imdb.rating":{$gte: 0}}}, {$sort: {"metacritic": -1}},{$project: {"title":1,"imdb.rating":1,"metacritic":1}},{$limit: 10}], intersection:[{$project: {common: {$setIntersection: ["$rating","$critic"]}}}] }}]) And my sample data set is: {"_id" : ObjectId("573a13cef29313caabd8709c"),"title" : "Justin Bieber: Never Say Never","year" : 2011,"runtime" : 105,"released" : ISODate("2011-02-11T00:00:00.000Z"),"cast" : [ "Justin Bieber", "Boys II Men", "Miley Cyrus", "Sean Kingston"],"metacritic" : 52,"poster" : "http://ia.media-imdb.com/images/M/MV5BMTY0NDQzMjIzOF5BMl5BanBnXkFtZTcwNDk2NzczNA@@._V1_SX300.jpg","plot" : "Follows Justin Bieber with some footage of performances from his 2010 concert tour.","fullplot" : "The camera follows Justin Bieber (1994- ) during the ten days leading up to his August, 2010, sold-out show at Madison Square Garden. Footage of these ten days of concerts, rehearsals, and down time with boyhood friends, his mom, and his entourage is inter-cut with home movies, old photos, and interviews showing a musical prodigy who loves to perform, comes to the attention of an Atlanta agent via YouTube, impresses Usher, and rockets to international stardom soon after his 15th birthday. His manager emphasizes the importance of social media and of Justin's work ethic and personality in making him a star; the camera emphasizes Bieber's look. His mom and grandparents shine.","awards" : "2 wins & 6 nominations.","lastupdated" : "2015-08-23 00:33:04.327000000","type" : "movie","languages" : [ "English"],"directors" : [ "Jon M. Chu"],"imdb" : { "rating" : 1.6, "votes" : 73548, "id" : 1702443},"countries" : [ "USA"],"rated" : "G","genres" : [ "Documentary", "Music"],"tomatoes" : { "website" : "http://www.JustinBieberNeverSayNever.com", "viewer" : { "rating" : 3.5, "numReviews" : 61961, "meter" : 65 }, "dvd" : ISODate("2011-05-13T00:00:00.000Z"), "rotten" : 37, "boxOffice" : "$73.0M", "consensus" : "As a tour documentary, it's rather uninspired -- but as a 3D glimpse of a building pop culture phenomenon, Never Say Never is undeniably entertaining.", "critic" : { "rating" : 5.8, "numReviews" : 102, "meter" : 64 }, "production" : "Paramount Pictures", "lastUpdated" : ISODate("2015-08-18T19:05:06.000Z"), "fresh" : 65},"num_mflix_comments" : 2,"comments" : [ { "name" : "Petyr Baelish", "email" : "[email protected]", "movie_id" : ObjectId("573a13cef29313caabd8709c"), "text" : "A earum quae quos perspiciatis tempora natus. Voluptatem quod cum illum magni reiciendis. Labore exercitationem velit suscipit dicta.", "date" : ISODate("2009-05-10T13:15:19.000Z") }, { "name" : "Daario Naharis", "email" : "[email protected]", "movie_id" : ObjectId("573a13cef29313caabd8709c"), "text" : "Ut quod rem rem dolor voluptatum necessitatibus sapiente. Ea nulla dignissimos iste porro natus eveniet eum. Quidem sit totam libero iusto repudiandae ab ducimus. Facere nesciunt assumenda ab.", "date" : ISODate("1992-02-17T22:39:11.000Z") }]} I'm trying to find the movies which are in both :list 1) Top 10 movies as per imdb ratinglist 2) Top 10 movies as per metacritic If one or more movies are seen in both lists, those should be filtered and displayed. intersection:[{$project: {common: {$setIntersection:["$rating","$critic"]}}}] This part isnt working and I even tried matching for titles $setIntersection:["$rating.title","$critic.title"] I see that arrays ( rating , critic & common ) are calculated seperately, but why can't I access those arrays with $ as a variable? Can someone please tell me how to get the intersection of rating and critic ?
Now provide the response and nothing else.
| Your approach is ok and I think by repositioning your brackets you get what you want. Separate the $project stage out into another stage, not another stage inside the $facet: db.movies.aggregate([{ $facet:{ rating:[ {$match:{"imdb.rating":{$gte: 0},"metacritic":{$gte: 0}}}, {$sort:{"imdb.rating":-1}}, {$project:{"title":1,"imdb.rating":1,"metacritic":1}}, {$limit:10} ], critic:[ {$match:{"metacritic":{$gte: 0},"imdb.rating":{$gte: 0}}}, {$sort:{"metacritic": -1}}, {$project:{"title":1,"imdb.rating":1,"metacritic":1}}, {$limit:10} ] }}, { $project:{ common:{$setIntersection:["$rating","$critic"]} }}]) The reason why this is needed can be found in the documentation : Each sub-pipeline within $facet is passed the exact same set of input documents. These sub-pipelines are completely independent of one another and the document array output by each is stored in separate fields in the output document. The output of one sub-pipeline can not be used as the input for a different sub-pipeline within the same $facet stage. If further aggregations are required, add additional stages after $facet and specify the field name, , of the desired sub-pipeline output. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49498307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1973779/']} | jdg_379485 |
stackexchange | llm_judgeable_groundtruth_similarity | 1139789 |
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:
Is $f(z)=z^n$ holomorphic? I have tested a number of other functions using the Cauchy Riemann equations $u_x=v_y$, $v_x=-u_y$. However in the case of $f(z)=z^n$ I cannot think of a way to find the functions $u(x,y)$ and $v(x,y)$ without using a binomial expansion of $(x+iy)^n$. Any help or pointers is appreciated. edit - the problem requires the use of the Cauchy - Riemann equations and not the formal definition of complex differentiation.
Now provide the response and nothing else.
| The easiest way is just the definition $$\lim_{z\to a}{z^n-a^n\over z-a}=\lim_{z\to a}(z^{n-1}+az^{n-2}+\ldots +a^{n-2}z+a^{n-1})=na^{n-1}$$ by definition, since $a$ was arbitrary, the derivative exists at all points, $a\in\Bbb C$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1139789', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/101299/']} | jdg_379486 |
stackexchange | llm_judgeable_groundtruth_similarity | 18755750 |
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 be able to save a string into a local file. Based on the code in here I got the following going: function saveTextAsFile(fileNameToSaveAs, textToWrite) {var textFileAsBlob = new Blob([textToWrite], { type: 'text/plain'});var downloadLink = document.createElement("a");downloadLink.download = fileNameToSaveAs;downloadLink.innerHTML = "Download File";if (true) { //window.webkitURL !== null) { // Chrome allows the link to be clicked // without actually adding it to the DOM. downloadLink.href = window.URL.createObjectURL(textFileAsBlob);} else { // Firefox requires the link to be added to the DOM // before it can be clicked. downloadLink.href = window.URL.createObjectURL(textFileAsBlob); downloadLink.onclick = destroyClickedElement; downloadLink.style.display = "none"; document.body.appendChild(downloadLink);}downloadLink.click();} This works fine for Chrome and Firefox, but not for Internet Explorer 10 as downloadLink.click(); gives: SCRIPT5: Access is denied. Is there any explanation/solution to this ? thanks!
Now provide the response and nothing else.
| Thx to mstubna, here is a solution for Chrome, FF, and IE>9: function saveTextAsFile(fileNameToSaveAs, textToWrite) { /* Saves a text string as a blob file*/ var ie = navigator.userAgent.match(/MSIE\s([\d.]+)/), ie11 = navigator.userAgent.match(/Trident\/7.0/) && navigator.userAgent.match(/rv:11/), ieEDGE = navigator.userAgent.match(/Edge/g), ieVer=(ie ? ie[1] : (ie11 ? 11 : (ieEDGE ? 12 : -1))); if (ie && ieVer<10) { console.log("No blobs on IE ver<10"); return; } var textFileAsBlob = new Blob([textToWrite], { type: 'text/plain' }); if (ieVer>-1) { window.navigator.msSaveBlob(textFileAsBlob, fileNameToSaveAs); } else { var downloadLink = document.createElement("a"); downloadLink.download = fileNameToSaveAs; downloadLink.href = window.URL.createObjectURL(textFileAsBlob); downloadLink.onclick = function(e) { document.body.removeChild(e.target); }; downloadLink.style.display = "none"; document.body.appendChild(downloadLink); downloadLink.click(); }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18755750', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/460084/']} | jdg_379487 |
stackexchange | llm_judgeable_groundtruth_similarity | 644917 |
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 know you can change the frame size in the .emacs file with set-frame-width or (add-to-list 'default-frame-alist '(width . 80)) but how can I change the width after Emacs has started up (aside from dragging the edge of the frame)?
Now provide the response and nothing else.
| Well, go to the *scratch* buffer and use set-frame-width . (set-frame-width (selected-frame) 100) ;; ^J to execute. set-frame-width isn't interactive, so you can't run it with M-x but you could trivially write a set-frame-width-interactive, something like (defun set-frame-width-interactive (arg) (interactive "p") (set-frame-width (selected-frame) arg)) Now C-u 8 0 M-x set-frame-width-interactive will set the width to 80. Is this what you're trying to do? | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/644917', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/680/']} | jdg_379488 |
stackexchange | llm_judgeable_groundtruth_similarity | 205738 |
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:
Is the net angular momentum vector of our solar system pointing in roughly the same direction as the Milky Way galaxy's net angular momentum vector? If yes or no, is that common for most stars in the galaxy?
Now provide the response and nothing else.
| There is no alignment between the Sun or the Solar System's net angular momentum and the "spin axis" of the Galaxy. Think for a moment about whether the line of the ecliptic (which marks the "equatorial line" of the Solar System) and the Milky Way (which roughly marks the plane of the Galaxy) are lined up? If this were so, then you would always see the planets (Jupiter, Mars, etc.) projected against the Milky Way. In fact, the spin axes of the Solar System and Galaxy are inclined at an angle of 63 degrees with respect to each other (see cartoon below - note, the Solar System is not drawn to scale compared with the Galaxy!). We do not know much about the alignments of other solar systems. Both the Doppler shift discovery method and the transit discovery method have a rotational ambiguity about the plane of the exoplanets' orbits. In other words, if we were to observe a transiting planet, we know that the inclination is close to 90 degrees to the line of sight, but we could rotate the system around our line of sight by any angle, and would see the same observational signatures. The general assumption is that there is no relationship between the angular momentum directions of stars (and their planetary systems) and the Galaxy. Turbulence in molecular clouds on relatively small scales compared with the dimensions of the Milky way randomises the angular momentum vectors of collapsing prestellar cores. A possible alignment mechanism could come about through the threading of giant molecular clouds by the Galactic magnetic field. If we knew what fraction of stars had close-in, potentially transiting planets, we could use the numbers of detected transiting exoplanets in the Kepler field to say whether that number was consistent with random orientations or not. Alternatively, if we had another Kepler field pointing in a different Galactic direction, but with similar sensitivity to the original Kepler field, then the relative numbers of detected transiting planets in the two fields might tell us of any non-random orientations. For example, if orbital planes were all aligned with the Galactic plane, then no transits would be seen for any star viewed out of the Galactic plane. (I think this extreme possibility can already be ruled out.) | {} | {'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/205738', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/74534/']} | jdg_379489 |
stackexchange | llm_judgeable_groundtruth_similarity | 45112506 |
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 keep getting the following error when attempting to install readxl or haven in R (both dependencies of tidyverse ) post-compilation, when the installer runs the loading test: ** testing if installed package can be loadedError in dyn.load(file, DLLpath = DLLpath, ...) : unable to load shared object '<my_lib_Path>/readxl/libs/readxl.so': <my_lib_path>/readxl/libs/readxl.so: undefined symbol: libiconvError loading failed I have libiconv.so in a local lib path (not for R packages) that is included in LD_LIBRARY_PATH and I've verified in my R session that Sys.getenv("LD_LIBRARY_PATH") has that directory.Why can't R's dynamic library loader find this shared object? Is there a different R-specific environment variable I need to define to have the dynamic library loader in R search my local lib path? Please note that this is not an issue with an R library path, but instead for a non-R dependency that an R package has. If I were compiling and linking C++ code, gcc would use ld , and hence LD_LIBRARY_PATH to track down dynamic dependencies. R doesn't appear to respect this rather common approach, and I can't seem to find any documentation on how to manage these more fine-grained dependency issues. Additional Details !> sessionInfo() R version 3.3.3 (2017-03-06) Platform: x86_64-pc-linux-gnu (64-bit) Running under: CentOS Linux 7 (Core) locale: [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C [3] LC_TIME=en_US.UTF-8 LC_COLLATE=en_US.UTF-8 [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8 [7] LC_PAPER=en_US.UTF-8 LC_NAME=C [9] LC_ADDRESS=C LC_TELEPHONE=C [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C attached base packages: [1] stats graphics grDevices utils datasets methods base > I had previously compiled libiconv because it was a dependency for something else (don't recall what now - likely not an R package given current problems). I tried reinstalling it, but made no difference. Edit I have also tried manually loading the library prior to installation: > dyn.load(".local/lib/libiconv.so")> is.loaded("libiconv")[1] TRUE> install.packages("tidyverse") but it fails just as above.
Now provide the response and nothing else.
| Normally, the iconv method is picked up from glibc , which is linked to during build of the R packages in question. For whatever reason, however, iconv is getting resolved to libiconv in this case, but it is not linked by the R packages during build. Original Workaround One can make the linking to libiconv explicit by adding the following line to the haven/src/Makevars source file PKG_LIBS=-liconv which then let's you install from source R CMD INSTALL haven . However, editing packages feels hacky, plus this is something that will need to be done every upgrade, which sounds like a hassle. Cleaner Workaround Another option is to use withr::with_makevars , which allows one to temporarily control Makevars content. With this technique, one can install directly from the repo: withr::with_makevars(c(PKG_LIBS="-liconv"), install.packages("haven"), assignment="+=") Credit : @knb suggested that I inspect the readxl.so with ldd and this turned out to be super useful because it showed that the shared object wasn't even trying to link to libiconv . Knowing that, I realized I could manually add the reference via the -liconv flag. Thanks @knb! Additional Info On the package side of things, relevant details about connecting libraries to R packages can be found in the guide for building libraries . On the system configuration side, the R-admin guide has some useful sections. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45112506', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/570918/']} | jdg_379490 |
stackexchange | llm_judgeable_groundtruth_similarity | 30602861 |
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 a simple singleton: class Singleton{ Singleton(); virtual ~Singleton(); Singleton * Singleton::getInstance() { static Singleton * instance; if (!instance) { instance = new Singleton(); }; return instance; };} When main code calls Singleton::getInstance()->someMethod() for the first time, isn't the class instantiated twice? Will be there memory leak? I am asking because Visual Leak Detector detects memory leak on the line with new Singleton() .
Now provide the response and nothing else.
| When main code calls Singleton::getInstance()->someMethod() for the first time, isn't the class instantiated twice? No. Calling a static member of Singleton does not instantiate Singleton , so the only instance of Singleton to exist here is the one you create with new . And you only create it once, because once instance points to it, you never call new again. One problem you have here, however, is that you failed to make getInstance a static member function. I assume this is a typo/oversight since, otherwise, your program would not even compile. In fact, the declaration is ill-formed even as a non-static member. Furthermore, the constructor should be private to enforce the notion that only getInstance may instantiate the type. Will be there memory leak? Yes, and this is what Leak Detector is reporting. However, it's minimal: the problem is that there is nothing to delete that singleton instance right before your program shuts down. Frankly I wouldn't worry about it. This may be one of those rare times that a leak is acceptable, mostly because more than a "leak" it's just a one-time failure to de-allocate on process shutdown. However, if you get rid of the pointer entirely then you can avoid both problems at the same time, since one of the last things your program does will be to destroy objects of static storage duration: #include <iostream>class Singleton{public: ~Singleton() { std::cout << "destruction!\n"; } static Singleton& getInstance() { static Singleton instance; return instance; } void foo() { std::cout << "foo!\n"; }private: Singleton() { std::cout << "construction!\n"; }};int main(){ Singleton::getInstance().foo();}// Output:// construction!// foo!// destruction! ( live demo ) No need even for a pointer! This has the added benefit that the entire function becomes inherently thread-safe, at least as of C++11. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30602861', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1555823/']} | jdg_379491 |
stackexchange | llm_judgeable_groundtruth_similarity | 48061430 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
On HTML page, When user click / press F5 button page refresh but before refresh I want to execute one function or a simple alert. User can click on refresh button, press F5 or Ctrl + R. using Angular 2/4
Now provide the response and nothing else.
| The refresh of the page should trigger the event handler bound to window:beforeunload . This stackblitz shows how to implement it for the "Home" component, using HostListener . You can test the page refresh by executing it in full page mode . import { Component, HostListener } from '@angular/core';@Component({ ...})export class HomeViewComponent { @HostListener("window:beforeunload", ["$event"]) unloadHandler(event: Event) { console.log("Processing beforeunload..."); // Do more processing... event.returnValue = false; } ...} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48061430', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5836859/']} | jdg_379492 |
stackexchange | llm_judgeable_groundtruth_similarity | 18350424 |
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 question might be trivial, but I am looking for some best options. I have build a page that have a grid and an other editor kind of panel which have some drop downs , textboxes etc., When I select I row in a grid, the details will populate on the controls exists in the panel.also in panel based on the value of dropdown, the controls may be hidden or visible. I want to do all these operations without asp.net post backs. May be by using ajax, can somebody give me start up how to achieve this in asp.net 4.5.
Now provide the response and nothing else.
| A call to module.provider("test", ...); is really a call to module.config(function($provide) { $provide.provider("test", ...);}); (See my wiki article on dependency injection for more details.) And since config blocks run in the order they were declared, you just need to move the declaration of your provider to above the point where it's used. You'll often see it written something like this: angular.module('myApp', []) .provider ("test", function () { var prefix; this.setPrefix = function(p) { prefix = p; } this.$get = function () { return { log: function(msg) { console.log (prefix + msg); } } } }) .config(function (testProvider) { testProvider.setPrefix("works: "); }) .controller ("myCtrl", function($scope, test) { $scope.$watch ('myModel', function (newval) { test.log(newval); }) }); An example: http://plnkr.co/edit/AxTnGv?p=preview If you really want to keep the concerns separate, you can create a new module and set up a dependency: angular.module('logging', []) .provider ("test", function () { var prefix; this.setPrefix = function(p) { prefix = p; } this.$get = function () { return { log: function(msg) { console.log (prefix + msg); } } } })angular.module('myApp', ['logging']) .config(function (testProvider) { testProvider.setPrefix("works: "); }) .controller ("myCtrl", function($scope, test) { $scope.$watch ('myModel', function (newval) { test.log(newval); }) }); Example: http://plnkr.co/edit/PWtDFG?p=preview | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18350424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2306913/']} | jdg_379493 |
stackexchange | llm_judgeable_groundtruth_similarity | 11476088 |
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 having a problem understanding why this part of my code is causing a memory leak: for($i=0; $i<count($values); $i++){ $values[$i] = addslashes($values[$i]);} To put the code in context, i have a previously built array called values, which has all the values to be inserted into a database. all the fields are strings so i need to escape all of them and for this application addslashes or mysql_real_escape_string are a good choice imo. Now the strange thing is that as soon as i added the part shown above, i get a message like this: PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 24 bytes) I understood that this generated a memory leak but i don't know why. Digging in, i commented out the only line in the for loop, leaving the for statement just for curiosity, and the leak is gone. Any ideas what could this possibly mean? PS: The strings are all UTF8 encoded, could that be a problem? EDIT: The array contains something like this : Array ( [dossier] => 002A [permis] => [adresse] => 18, rue Bellevue [ville] => Ste-Anne-des-Lacs (Québec) [province] => [code_postal] => J0R 1B0 [numero_centrale] => N/A [routes] => De la Gare, droite chemin Avila jusqu'au bout et droite chemin Ste-Anne-des-lacs sur 1,8 km et droite sur Bellevue.)
Now provide the response and nothing else.
| Your array has string keys, but you are checking/assigning numeric keys. As @nickb notes, each time you add a numeric key, count($values) increases by one, so you have an infinite loop. Hence the memory exhaustion. Check with a debugger, or better yet, switch to a foreach loop or one of the array_* functions ( array_walk() , array_map() , etc. depending on what you are trying to do). @Jeremy correctly points out that you should not be using addslashes() to escape your strings. Look at mysqli_real_escape_string() (as he suggests), or better yet, consider using PDO if you can. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11476088', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1015808/']} | jdg_379494 |
stackexchange | llm_judgeable_groundtruth_similarity | 22100206 |
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 cant seem to find a decent example that shows how can I consume an AWS Kinesis stream via Python. Can someone please provide me with some examples I could look into? Best
Now provide the response and nothing else.
| you should use boto.kinesis: from boto import kinesis After you created a stream: step 1: connect to aws kinesis: auth = {"aws_access_key_id":"id", "aws_secret_access_key":"key"}connection = kinesis.connect_to_region('us-east-1',**auth) step 2: get the stream info (like how many shards, if it is active ..) tries = 0while tries < 10: tries += 1 time.sleep(1) try: response = connection.describe_stream('stream_name') if response['StreamDescription']['StreamStatus'] == 'ACTIVE': break except : logger.error('error while trying to describe kinesis stream : %s')else: raise TimeoutError('Stream is still not active, aborting...') step 3 : get all shard ids, and for each shared id get the shard iterator: shard_ids = []stream_name = None if response and 'StreamDescription' in response: stream_name = response['StreamDescription']['StreamName'] for shard_id in response['StreamDescription']['Shards']: shard_id = shard_id['ShardId'] shard_iterator = connection.get_shard_iterator(stream_name, shard_id, shard_iterator_type) shard_ids.append({'shard_id' : shard_id ,'shard_iterator' : shard_iterator['ShardIterator'] }) step 4 : read the data for each shard limit is the limit of records that you want to receive. (you can receive up to 10 MB)shard_iterator is the shared from previous step. tries = 0result = []while tries < 100: tries += 1 response = connection.get_records(shard_iterator = shard_iterator , limit = limit) shard_iterator = response['NextShardIterator'] if len(response['Records'])> 0: for res in response['Records']: result.append(res['Data']) return result , shard_iterator in your next call to get_records, you should use the shard_iterator that you received with the result of the previous get_records. note : in one call to get_records, (limit = None) you can receive empty records.if calling to get_records with a limit, you will get the records that are in the same partition key (when you put data in to stream, you have to use partition key : connection.put_record(stream_name, data, partition_key) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22100206', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1208792/']} | jdg_379495 |
stackexchange | llm_judgeable_groundtruth_similarity | 69358 |
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:
As a condensed matter physicist, I take it for granted that a Fermi surface is stable . But it is stable with respect to what? For instance, Cooper pairing is known as an instability of the Fermi surface. I'm simply wondering what makes the Fermi surface stable? Possible way of thinking: Is it a topological property of the Fermi gas (only of the free one ?, only robust against disorder?)? What is the modern, mathematical definition of the Fermi surface (shame on me, I don't even know this, and all my old textbooks are really sloppy about that, I feel)? What can destroy the Fermi surface, and what does destroy mean? Any idea / reference / suggestion to improve the question is welcome. Addenda / Other possible way to discuss the problem: After writing this question, I noted this answer by wsc , where (s)he presents a paper by M. Oshikawa (2000), Topological Approach to Luttinger’s Theorem and the Fermi Surface of a Kondo Lattice PRL 84 , 3370–3373 (2000) (available freely on arXiv ), and a paper by J. Luttinger & J. Ward Ground-State Energy of a Many-Fermion System. II. Phys. Rev. 118 , 1417–1427 (1960) . An other interesting reference to start with is a paper by J. Luttinger, Fermi Surface and Some Simple Equilibrium Properties of a System of Interacting Fermions , Phys. Rev. 119 , 1153–1163 (1960) , where he shows (eq.33) that the volume of the Fermi surface is conserved under interaction, using analytic properties of the Green function including the self-energy as long as the total number of particles is conserved. I'm not sure if it's sufficient to proof the stability of the Fermi surface (but what does stability means exactly, I'm now confused :-p ) Is there absolutely no modern (topological ?) version of this proof ?
Now provide the response and nothing else.
| There are answers in the note by Polchinski linked by Matt, and an article by Shankar in Review of Modern Physics: Renormalization-group approach to interacting fermions . Just to flesh out was it meant by "stability" and "Fermi surface". The Fermi-liquid can be thought of as a phase characterized by several properties: arbitrarily long-lived, gapless electron-like excitations, preservation of various symmetries, the presence of the discontinuity that characterizes the Fermi surface, and in the end by a certain analytic structure of the correlators as elucidated by Landau. We know that the free electron gas is in this phase, in a trivial way. If we start adding interaction what happens? In the usual sense, we want to know if this phase is stable - that is: if we add an arbitrarily small interaction of some kind will we change the phase at zero temperature? Note that because of the Fermi surface there are an infinite number of different interactions. As the articles show the "normal" interactions do not change the phase. However the "pairing" interactions change the phase at zero temperature, even when they are arbitrarily small. This you know from BCS theory already - the superconductor is the ground state for all attractive interaction, regardless how weak (although the transition temperature goes to zero rapidly with interaction strength). A couple more points: the Fermi surface can be unstable to large values of interactions such as the Pomeranchuk instability (unless I'm getting the names confused), or because of particular geometric structures like nesting Fermi surfaces. This is somewhat different from the question of: "is the Fermi liquid generally stable?" You ask about disorder: This is a technical topic which I'm not expert in, but my understanding is that the appropriately defined disordered Fermi-liquid is stable in 3-dimensions (i.e. it takes a finite amount of disorder to turn it to an insulator). See for example this paper by Basko, Aleiner and Altshuler. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/69358', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/16689/']} | jdg_379496 |
stackexchange | llm_judgeable_groundtruth_similarity | 12358228 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I'm having some problems wrapping my head around the best idiomatic way to deal with some complex html cases flexibly using Mustache.php The first is a pre-selected select dropdown, e.g. <select> <option value=''></option> <option value='bob'>Bob Williams</option> <option value='james' selected>James Smith</option></select> I have a way that I deal with this, but my way seems really inflexible: take an array in php, reformat it into multi-dimensional arrays with 3 elements; value, display, selected (boolean) pass it to the template where option, value, and selected are output in a loop Is there an awesome approach for making preselected select dropdowns using partials or anonymous functions or methods or some other feature of mustache.php that I'm missing? Edit: Pared down this question into separate parts to try to maximize clarity.
Now provide the response and nothing else.
| The idiomatic way to do this in Mustache would be to create a View (or ViewModel) rather than passing in a hash of data: <?phpclass Dropdown{ public $name; public $value; private $options; public function __construct($name, array $options, $value) { $this->name = $name; $this->options = $options; $this->value = $value; } public function options() { $value = $this->value; return array_map(function($k, $v) use ($value) { return array( 'value' => $k, 'display' => $v, 'selected' => ($value === $k), ) }, array_keys($this->options), $this->options); }} Then you could combine this with a dropdown partial... <select name="{{ name }}"> {{# options }} <option value="{{ value }}"{{# selected }} selected{{/ selected }}> {{ display }} </option> {{/ options }}</select> Which you can use in your template like this: {{# state }} <label for="{{ name }}">State</label> {{> dropdown }}{{/ state }}{{# country }} <label for="{{ name }}">Country</label> {{> dropdown }}{{/ country }} And render it: <?php$data = array( 'state' => new Dropdown('state', $someListOfStates, 'CA'), 'country' => new Dropdown('country', $someListOfCountries, 'USA'),);$template->render($data); ... But you can do even better than that :) With this: <?phpclass StateDropdown extends Dropdown{ static $states = array(...); public function __construct($value, $name = 'state') { parent::__construct($name, self::$states, $value); }} And this: <?phpclass CountryDropdown extends Dropdown{ static $countries = array(...); public function __construct($value, $name = 'country') { parent::__construct($name, self::$countries, $value); }} And one of these: <?phpclass Address{ public $street; public $city; public $state; public $zip; public $country; public function __construct($street, $city, $state, $zip, $country, $name = 'address') { $this->street = $street; $this->city = $city; $this->state = new StateDropdown($state, sprintf('%s[state]', $name)); $this->zip = $zip; $this->country = new CountryDropdown($country, sprintf('%s[country]', $name)); }} Throw in a new address partial: <label for="{{ name }}[street]">Street</label><input type="text" name="{{ name }}[street]" value="{{ street }}"><label for="{{ name }}[city]">City</label><input type="text" name="{{ name }}[city]" value="{{ city }}">{{# state }} <label for="{{ name }}">State</label> {{> dropdown }}{{/ state }}<label for="{{ name }}[zip]">Postal code</label><input type="text" name="{{ name }}[zip]" value="{{ zip }}">{{# country }} <label for="{{ name }}">Country</label> {{> dropdown }}{{/ country }} Update your main template: <h2>Shipping Address</h2>{{# shippingAddress }} {{> address }}{{/ shippingAddress }}<h2>Billing Address</h2>{{# billingAddress }} {{> address }}{{/ billingAddress }} And go! <?php$data = array( 'shippingAddress' => new Address($shipStreet, $shipCity, $shipState, $shipZip, $shipCountry, 'shipping'), 'billingAddress' => new Address($billStreet, $billCity, $billState, $billZip, $billCountry, 'billing'),};$template->render($data); Now you have modular, reusable, easily testable, extensible bits of code and partials to go with 'em. Note that the classes we created are "Views" or "ViewModels". They're not your domain model objects... They don't care about persistence, or validation, all they care about is preparing values for your templates. If you're using Models as well, that makes it even easier, because things like our Address class can wrap your address model, and grab the values it needs directly off the model rather than requiring you to pass a bunch of things to the constructor. The Zen of Mustache If you take this approach to its logical conclusion, you end up with one top-level View or ViewModel class per action/template pair in your app — the View could internally delegate to sub-Views and partials, like we did with the Dropdowns from our Address View, but you'd have one first-class View or ViewModel responsible for rendering each action. Meaning (in an MVC/MVVM world), your Controller action would do whatever "action" was required of it, then create the View or ViewModel class responsible for populating your template, hand it a couple of domain Model objects, and call render on the template. The Controller wouldn't prepare any data, because that's the responsibility of the View layer. It would simply hand it a couple of model objects. Now all your logic for "rendering" is neatly encapsulated in the View layer, all your markup is neatly encapsulated in your template file, your Model is free from ugly formatting business, and your Controller is nice and light like it should be :) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12358228', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/69993/']} | jdg_379497 |
stackexchange | llm_judgeable_groundtruth_similarity | 81541 |
Below is a question asked on the forum datascience.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Here is the code for the Prediction of multiple images from the folder. But getting the same label(class) for all the images.I'm not able to find out why every image shows the same label. # import the necessary packagesfrom tensorflow.keras.models import load_modelimport argparseimport pickleimport cv2from tensorflow.keras.preprocessing.image import img_to_arrayfrom tensorflow.keras.applications.imagenet_utils import decode_predictionsimport numpy as npimport logging, osimport sys from keras.preprocessing import imageimport tensorflow as tfimport mathimport operatorfrom pathlib import Path# disable the warningslogging.disable(logging.WARNING)os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"image_path = "test_image_folder"images = [] # load all images into a listfor img in os.listdir(image_path): img = os.path.join(image_path, img) img = image.load_img(img, target_size=(64,64)) img = image.img_to_array(img) img = np.expand_dims(img, axis=0) # normalize the image processed_image = np.array(img, dtype="float") / 255.0 images.append(processed_image) images = np.vstack(images)# relative paths to the model and labelsmodel_path = os.path.join("Output", 'VGG_model.h5')label_file_path = os.path.join("Output", 'labels')# load the model and the label encodermodel = load_model(model_path)lb = pickle.loads(open(label_file_path, "rb").read())# make a prediction on the imageimages_data = []filenames = []for filename in os.listdir(image_path): pred_result = model.predict(images) images_data.append(pred_result) filenames.append(filename)#sorts attributes according to confidence score (how probable attribute exists)top_k = []pred = [] for i in range(len(images_data)): rank = images_data[i][0].argsort()[-len(images_data[i][0]):][::-1] top_k.append(rank) top = top_k[i][:15] print(filenames[i]) for node_id in top: human_string = label_file_path[node_id] score = images_data[i][0][node_id] print('%s (score = %.5f)' % (human_string, score))
Now provide the response and nothing else.
| You are looping on a folder to predict each image - for filename in os.listdir(image_path): pred_result = model.predict(images) images_data.append(pred_result) filenames.append(filename) But the argument of the predict function is not changing. Its a stacked value defined above as - images = np.vstack(images) This same prediction is being appended into images_data Assuming your prediction is not failing, it means every prediction is the prediction on all the images stacked in the images_data. So, for every iteration for i in range(len(images_data)): This images_data[i][0] is returning you the 1st prediction only. Changing to for i in range(len(images_data[0])): and images_data[i] should work | {} | {'log_upvote_score': 4, 'links': ['https://datascience.stackexchange.com/questions/81541', 'https://datascience.stackexchange.com', 'https://datascience.stackexchange.com/users/104143/']} | jdg_379498 |
stackexchange | llm_judgeable_groundtruth_similarity | 33655731 |
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 installed the Tensorflow bindings with python successfully. But when I try to import Tensorflow, I get the follwoing error. ImportError: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.17' not found (required by /usr/local/lib/python2.7/dist-packages/tensorflow/python/_pywrap_tensorflow.so) I have tried to update GLIBC_2.15 to 2.17, but no luck.
Now provide the response and nothing else.
| I had the same problem, so googling I made these steps: $ sudo pip install --upgrade virtualenv$ virtualenv --system-site-packages ~/tensorflow$ cd ~/tensorflow$ source bin/activate$ pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.5.0-cp27-none-linux_x86_64.whl$ cd /tmp$ wget http://launchpadlibrarian.net/137699828/libc6_2.17-0ubuntu5_amd64.deb$ wget http://launchpadlibrarian.net/137699829/libc6-dev_2.17-0ubuntu5_amd64.deb$ mkdir libc6_2.17$ cd libc6_2.17$ ar p ../libc6_2.17-0ubuntu5_amd64.deb data.tar.gz | tar zx$ ar p ../libc6-dev_2.17-0ubuntu5_amd64.deb data.tar.gz | tar zx$ cd -$ LD_LIBRARY_PATH=/tmp/libc6_2.17/lib/x86_64-linux-gnu/ /tmp/libc6_2.17/lib/x86_64-linux-gnu/ld-2.17.so bin/python local/lib/python2.7/site-packages/tensorflow/models/image/mnist/convolutional.py And to exit: $ deactivate That works for me. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33655731', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5551505/']} | jdg_379499 |
stackexchange | llm_judgeable_groundtruth_similarity | 49466033 |
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 image with bounding box in it, and I want to resize the image. img = cv2.imread("img.jpg",3)x_ = img.shape[0]y_ = img.shape[1]img = cv2.resize(img,(416,416)); Now I want to calculate the scale factor: x_scale = ( 416 / x_)y_scale = ( 416 / y_ ) And draw an image, this is the code for the original bounding box: ( 128, 25, 447, 375 ) = ( xmin,ymin,xmax,ymax)x = int(np.round(128*x_scale))y = int(np.round(25*y_scale))xmax= int(np.round (447*(x_scale)))ymax= int(np.round(375*y_scale)) However using this I get: While the original is: I don't see any flag in this logic, what's wrong? Whole code: imageToPredict = cv2.imread("img.jpg",3)print(imageToPredict.shape)x_ = imageToPredict.shape[0]y_ = imageToPredict.shape[1]x_scale = 416/x_y_scale = 416/y_print(x_scale,y_scale)img = cv2.resize(imageToPredict,(416,416));img = np.array(img);x = int(np.round(128*x_scale))y = int(np.round(25*y_scale))xmax= int(np.round (447*(x_scale)))ymax= int(np.round(375*y_scale))Box.drawBox([[1,0, x,y,xmax,ymax]],img) and drawbox def drawBox(boxes, image): for i in range (0, len(boxes)): cv2.rectangle(image,(boxes[i][2],boxes[i][3]),(boxes[i][4],boxes[i][5]),(0,0,120),3) cv2.imshow("img",image) cv2.waitKey(0) cv2.destroyAllWindows() The image and the data for the bounding box are loaded separately. I am drawing the bounding box inside the image. The image does not contain the box itself.
Now provide the response and nothing else.
| I believe there are two issues: You should swap x_ and y_ because shape[0] is actually y-dimension and shape[1] is the x-dimension You should use the same coordinates on the original and scaled image. On your original image the rectangle is (160, 35) - (555, 470) rather than (128,25) - (447,375) that you use in the code. If I use the following code: import cv2import numpy as npdef drawBox(boxes, image): for i in range(0, len(boxes)): # changed color and width to make it visible cv2.rectangle(image, (boxes[i][2], boxes[i][3]), (boxes[i][4], boxes[i][5]), (255, 0, 0), 1) cv2.imshow("img", image) cv2.waitKey(0) cv2.destroyAllWindows()def cvTest(): # imageToPredict = cv2.imread("img.jpg", 3) imageToPredict = cv2.imread("49466033\\img.png ", 3) print(imageToPredict.shape) # Note: flipped comparing to your original code! # x_ = imageToPredict.shape[0] # y_ = imageToPredict.shape[1] y_ = imageToPredict.shape[0] x_ = imageToPredict.shape[1] targetSize = 416 x_scale = targetSize / x_ y_scale = targetSize / y_ print(x_scale, y_scale) img = cv2.resize(imageToPredict, (targetSize, targetSize)); print(img.shape) img = np.array(img); # original frame as named values (origLeft, origTop, origRight, origBottom) = (160, 35, 555, 470) x = int(np.round(origLeft * x_scale)) y = int(np.round(origTop * y_scale)) xmax = int(np.round(origRight * x_scale)) ymax = int(np.round(origBottom * y_scale)) # Box.drawBox([[1, 0, x, y, xmax, ymax]], img) drawBox([[1, 0, x, y, xmax, ymax]], img)cvTest() and use your "original" image as "49466033\img.png", I get the following image And as you can see my thinner blue line lies exactly inside your original red line and it stays there whatever targetSize you chose (so the scaling actually works correctly). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49466033', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8184563/']} | jdg_379500 |
stackexchange | llm_judgeable_groundtruth_similarity | 3316991 |
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:
It is easy to prove that $\sin(a) < \tan(a)$ when $0 < a < \pi/2$ , but how can I prove that $\sin(a) < a < \tan(a)$ when $0 < a < \pi/2?$
Now provide the response and nothing else.
| For $0 \le a \lt \frac{\pi}{2}$ , define $$f(a) = a - \sin(a) \tag{1}\label{eq1}$$ $$g(a) = \tan(a) - a \tag{2}\label{eq2}$$ From \eqref{eq1}, note $f(0) = 0$ . For $a \gt 0$ , $f'(a) = 1 - \cos(a) \gt 0$ so $f(a) \gt 0$ , giving $$\sin(a) \lt a \tag{3}\label{eq3}$$ From \eqref{eq2}, $g(0) = 0$ . For $a \gt 0$ , $g'(a) = \frac{\cos(a)}{\cos(a)} + \frac{\sin^2(a)}{\cos^2(a)} - 1 = \frac{\sin^2(a)}{\cos^2(a)} \gt 0$ so $g(a) \gt 0$ , giving $$a \lt \tan(a) \tag{4}\label{eq4}$$ Putting \eqref{eq3} and \eqref{eq4} together gives $$\sin(a) \lt a \lt \tan(a) \tag{5}\label{eq5}$$ for $0 \lt a \lt \frac{\pi}{2}$ . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3316991', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/634546/']} | jdg_379501 |
stackexchange | llm_judgeable_groundtruth_similarity | 31357745 |
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 having some trouble querying a document by values matching inside the document after population by mongoose. My schemas are something like this: var EmailSchema = new mongoose.Schema({ type: String});var UserSchema = new mongoose.Schema({ name: String, email: [{type:Schema.Types.ObjectId, ref:'Email'}]}); I would like to have all users which have a email with the type = "Gmail" for example. The following query returns empty results: Users.find({'email.type':'Gmail').populate('email').exec( function(err, users) { res.json(users); }); I have had to resort to filtering the results in JS like this: users = users.filter(function(user) { for (var index = 0; index < user.email.length; index++) { var email = user.email[index]; if(email.type === "Gmail") { return true; } } return false; }); Is there any way to query something like this straight from mongoose?
Now provide the response and nothing else.
| @Jason Cust explained it pretty well already - in this situation often the best solution is to alter the schema to prevent querying Users by properties of documents stored in separate collection. Here's the best solution I can think of that will not force you to do that, though (because you said in the comment that you can't). Users.find().populate({ path: 'email', match: { type: 'Gmail' }}).exec(function(err, users) { users = users.filter(function(user) { return user.email; // return only users with email matching 'type: "Gmail"' query });}); What we're doing here is populating only email s matching additional query ( match option in .populate() call) - otherwise email field in Users documents will be set to null . All that's left is .filter on returned users array, like in your original question - only with much simpler, very generic check. As you can see - either the email is there or it isn't. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31357745', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/977431/']} | jdg_379502 |
stackexchange | llm_judgeable_groundtruth_similarity | 328581 |
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:
In the American Roulette wheel, the winning odds of betting colours(black/red) is 47.36%. Consider this method, if the minimum single bet is \$10 and if I were to bet \$10 and double my next bet of what my previous bet is $10 if I happen to lose my previous bet for a total of 3 times going forward making the total bet count of 4, will this be a profitable play in the long run. Like this way: Initial bet: \$10, if I win I put \$10 again for the next bet. If I lost I put double the amount of my previous bet for my next bet, which is \$10 making it \$20. If I win this bet of \$20, I go back to betting \$10, but if I lost I will double this amount for my next bet making it \$40. I'm going to do this for a total of 3 consecutive times in the event of a lost, so it's 10 + 20 + 40 + 80 = \$150. So if each single bet gives me 47.36%, 0.4736 * 4 = 1.8944 * 100 =189.4% meaning if I were to do this doubling for 3 consecutive times for a total of 4 bet counts, each single bet technically gives me 189% chance of winning. Am I right, is this the correct way of calculating it? I was also thinking about the application of this same method to the dozen bets. For a dozen bet, the winning odds is 31.57%, but the payout is 2 to 1 vs. only 1 to 1 for colour bets. If the same method is applied to betting, which of the two types of bets will be more profitable in the long run?
Now provide the response and nothing else.
| The error in your calculation is that the chance of winning at least once in four tries is $1-(\frac {20}{38})^4 \approx 0.9233$. You can't keep adding the $\frac {18}{38}$s-the fact that the sum exceeds $1$ should tip you off. This is because you might win more than one-the events are not mutually exclusive. Your expected win from one series is then $10 \cdot 0.9233 + (-150) \cdot 0.0767=9.233-11.51=-2.28$ The important truth is that no series of losing bets can be winning. You can have a high probability of profit, as here, but the expectation will be negative. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/328581', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/48585/']} | jdg_379503 |
stackexchange | llm_judgeable_groundtruth_similarity | 17848521 |
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 any counter-indication to doing this ? Or is the behavior well specified? #pragma omp parallel forfor(auto x : stl_container){ ...} Because it seems that OpenMP specification is only valid for c++98 but I guess there might be more incompatibilities due to C++11 threads, which are not used here. I wanted to be sure, still.
Now provide the response and nothing else.
| The OpenMP 4.0 specification was finalised and published several days ago here . It still mandates that parallel loops should be in the canonical form (§2.6, p.51): for ( init-expr ; test-expr ; incr-expr ) structured-block The standard allows for containers that provide random-access iterators to be used in all of the expressions, e.g.: #pragma omp parallel forfor (it = v.begin(); it < v.end(); it++){ ...} If you still insist on using the C++11 syntactic sugar, and if it takes a (comparatively) lot of time to process each element of stl_container , then you could use the single-producer tasking pattern: #pragma omp parallel{ #pragma omp single { for (auto x : stl_container) { #pragma omp task { // Do something with x, e.g. compute(x); } } }} Tasking induces certain overhead so it would make no sense to use this pattern if compute(x); takes very little time to complete. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17848521', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1495627/']} | jdg_379504 |
stackexchange | llm_judgeable_groundtruth_similarity | 32299 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Can I 100% rely on $_SERVER[] to be a safe source of data that I do not need to sanitized like I do $_GET[] and $_POST[] ?
Now provide the response and nothing else.
| This is taken from one of my questions on Stack Overflow: Which $_SERVER variables are safe? Server controlled These variables are set by the server environment and depend entirely on the server configuration. 'GATEWAY_INTERFACE' 'SERVER_ADDR' 'SERVER_SOFTWARE' 'DOCUMENT_ROOT' 'SERVER_ADMIN' 'SERVER_SIGNATURE' Partly server controlled These variables depend on the specific request the client sent, but can only take a limited number of valid values, since all invalid values should be rejected by the web server and not cause the invocation of the script to begin with. Hence they can be considered reliable . 'HTTPS' 'REQUEST_TIME' 'REMOTE_ADDR' * 'REMOTE_HOST' * 'REMOTE_PORT' * 'SERVER_PROTOCOL' 'HTTP_HOST' † 'SERVER_NAME' † 'SCRIPT_FILENAME' 'SERVER_PORT' 'SCRIPT_NAME' * The REMOTE_ values are guaranteed to be the valid address of the client, as verified by a TCP/IP handshake. This is the address where any response will be sent to. REMOTE_HOST relies on reverse DNS lookups though and may hence be spoofed by DNS attacks against your server (in which case you have bigger problems anyway). This value may be a proxy, which is a simple reality of the TCP/IP protocol and nothing you can do anything about. † If your web server responds to any request regardless of HOST header, this should be considered unsafe as well. See How safe is $_SERVER[“HTTP_HOST”]? . Also see http://shiflett.org/blog/2006/mar/server-name-versus-http-host . Entirely arbitrary user controlled values These values are not checked at all and do not depend on any server configuration, they are entirely arbitrary information sent by the client. 'argv' , 'argc' (only applicable to CLI invocation, not usually a concern for web servers) 'REQUEST_METHOD' ‡ 'QUERY_STRING' 'HTTP_ACCEPT' 'HTTP_ACCEPT_CHARSET' 'HTTP_ACCEPT_ENCODING' 'HTTP_ACCEPT_LANGUAGE' 'HTTP_CONNECTION' 'HTTP_REFERER' 'HTTP_USER_AGENT' 'AUTH_TYPE' § 'PHP_AUTH_DIGEST' § 'PHP_AUTH_USER' § 'PHP_AUTH_PW' § 'PATH_INFO' 'ORIG_PATH_INFO' 'REQUEST_URI' (may contain tainted data) 'PHP_SELF' (may contain tainted data i.e. /index.php/evilstring) 'PATH_TRANSLATED' any other 'HTTP_' value ‡ May be considered reliable as long as the web server allows only certain request methods. § May be considered reliable if authentication is handled entirely by the web server. The superglobal $_SERVER also includes several environment variables. Whether these are "safe" or not depend on how (and where) they are defined. They can range from completely server controlled to completely user controlled. | {} | {'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/32299', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/21768/']} | jdg_379505 |
stackexchange | llm_judgeable_groundtruth_similarity | 33004708 |
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: sudo pip install ipython I get the following error OSError: [Errno: 1] Operation not permitted: '/System/Library/Frameworks/Python.framework/Versions/2.7/share' The last command executed tries to create the directory given above. Also, the following command fails to install iPython without providing any errors. sudo pip install --user python (I am on Mac OS X El Capitan in case other folks on this OS see the same issue.)
Now provide the response and nothing else.
| Instructions telling people to use sudo pip install are inherently wrong. If there is any tutorial out there which says you should use sudo pip then please file a bug against this package. The author is dis-educating the Python community, as time has proven sudo pip to be a broken practice. OSX El Capitan introduced mechanisms to prevent damaging the operating system files . /System/Library/Frameworks/Python.framework/Versions/2.7/share is one of the protected locations. A normal user has no reason to put or write any files there . This is because the operating system itself relies on these files and sudo pip , with all force given from the above, would unconditionally overwrite them. Usually bad things would not happen, but the chances are there. Apple wants to protect their OS users from accidentally bricking their installation. Instead, you need to install a Python package, like IPython, locally to the home folder of your user . The easiest way is to create a virtual environment , activate it , and then run pip in the virtual environment. Example: cd ~ # Go to home directoryvirtualenv my-venvsource my-venv/bin/activatepip install IPython More info Official Python package installation tutorial . How to create virtual environments . Alternatively, one should be able to use pip install --user . But again, sudo is not needed and you need to manually set up PATH environment variable. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/33004708', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3984840/']} | jdg_379506 |
stackexchange | llm_judgeable_groundtruth_similarity | 205167 |
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:
Let's say that I have a non-stationary time series and that the series can be transformed to a stationary series using a first difference. If I want to forecast this series using ARIMA then what is the difference between forecasting using the original non-stationary series and the forecasting using the now stationary differenced series? That is, can I expect the forecast for the stationary series to be more accurate than the forecast for non-stationary series? I am aware that one advantage of forecasting with the stationary series will have the advantage of also producing forecast intervals (which are dependent upon the assumption of a stationary series).
Now provide the response and nothing else.
| [W]hat is the difference between forecasting using the original non-stationary series and the forecasting using the now stationary differenced series? (Here I deliberately left out the qualification that the series can be transformed to a stationary series using first differencing and that the OP is interested in forecasting using ARIMA in particular.) The problem with nonstationary data is that for most of the time series models, the model assumptions are violated when nonstationary data is used. This leads to the estimators no longer having the nice properties such as asymptotic normality and sometimes even consistency. So if you apply a model that requires a stationary series to a nonstationary series, you will likely get poor estimates of the model parameters and hence poor forecasts. (Now let me add the qualification back.) For an integrated series $x_t$ that can be made stationary using first differencing, $\Delta x_t$, and that can be approximated by an ARIMA model reasonably well, there are three ways to go: Force stationarity and estimate an ARIMA($p,0,q$) model for the original series $x_t$. Force, or allow for, first differencing so that you end up with ARIMA($p,1,q$) model for the original data $x_t$. Difference the series manually and then apply ARIMA($p,0,q$) model for the differenced series $\Delta x_t$. Option 1. is the only one that is clearly asking for trouble as it forces stationarity in presence of nonstationary data. Options 2. and 3. are essentially the same, the difference being in whether you difference $x_t$ manually outside the model or as an initial step within the model. [C]an I expect the forecast for the stationary series to be more accurate than the forecast for non-stationary series? If you have in mind an integrated series $x_t$ and its first-differenced stationary version $\Delta x_t$, you will have greater accuracy when forecasting $\Delta x_t$, but does that matter? It could be misleading to think that you can get more accurate forecasts by focusing on $\Delta x_t$ rather than $x_t$. It is perhaps the most natural to think about gains in accuracy when the underlying process of interest is kept the same, e.g. a gain in accuracy due to using a better approximation to the same process. Meanwhile, if you change the underlying object (go from $x_t$ to $\Delta x_t$), the gain is not really a gain, in the following sense. It is a bit like shooting at a target from 100m and from 10m. You will be more accurate from 10m, but isn't that obvious and irrelevant? If you have in mind two unrelated series $x_{1,t}$ and $\Delta x_{2,t}$ where the first one is integrated while the second one is stationary, you may expect that in the long run you will have greater forecast accuracy for $\Delta x_{2,t}$. In the short run this might not hold if the variance of $\Delta x_{1,t}$ (the increments of the first process) is small compared to the variance of $\Delta x_{2,t}$. I am aware that one advantage of forecasting with the stationary series will have the advantage of also producing forecast intervals (which are dependent upon the assumption of a stationary series). Actually, you can get forecast intervals regardless of whether the series is integrated or stationary. If you model an integrated time series using its first differences, you obtain the forecast intervals and cumulatively add them when forming the forecast interval for the integrated series. That is why forecast intervals for an integrated series expand linearly while those of a stationary series expand slower than linearly (illustrations can be found in time series textbooks). | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/205167', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/105630/']} | jdg_379507 |
stackexchange | llm_judgeable_groundtruth_similarity | 15570542 |
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 know how to get the speed of a vehicle using your phone while seated in the vehicle using gps. I have read that the accelerometer is not very accurate. Another thing is; will GPS be accessible while seated in a vehicle. Won't it have the same effect as while you are in a building? Here is some code I have tried but I have used the NETWORK PROVIDER instead.I will appreciate the help. Thanks... package com.example.speedtest;import android.app.Activity;import android.content.Context;import android.location.Location;import android.location.LocationListener;import android.location.LocationManager;import android.os.Bundle;import android.widget.Toast;public class MainActivity extends Activity { LocationManager locManager; LocationListener li; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); locManager=(LocationManager)getSystemService(Context.LOCATION_SERVICE); li=new speed(); locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, li); } class speed implements LocationListener{ @Override public void onLocationChanged(Location loc) { Float thespeed=loc.getSpeed(); Toast.makeText(MainActivity.this,String.valueOf(thespeed), Toast.LENGTH_LONG).show(); } @Override public void onProviderDisabled(String arg0) {} @Override public void onProviderEnabled(String arg0) {} @Override public void onStatusChanged(String arg0, int arg1, Bundle arg2) {} }}
Now provide the response and nothing else.
| GPS works fine in a vehicle. The NETWORK_PROVIDER setting might not be accurate enough to get a reliable speed, and the locations from the NETWORK_PROVIDER may not even contain a speed. You can check that with location.hasSpeed() ( location.getSpeed() will always return 0). If you find that location.getSpeed() isn't accurate enough, or it is unstable (i.e. fluctuates drastically) then you can calculate speed yourself by taking the average distance between a few GPS locations and divide by the time elapsed. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15570542', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1550867/']} | jdg_379508 |
stackexchange | llm_judgeable_groundtruth_similarity | 23407515 |
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 recommended way to manage the connection to AmazonS3 when working with AWS? Typical Amazon S3 code(taken from Amazon official sample) looks usually like this? AmazonS3 s3 = new AmazonS3Client(...);...s3.putObject(new PutObjectRequest(bucketName, project.getName() + "/" + imageFile.getName(), imageFile)); Following are the questions: Is this a good idea to maintain a single AmazonS3Client used by everyone in the code or is it better to create one on every call? Is there a concept of connection pool like when working with MySQL for example? Are questions like disconnection(MySQL analogy: MySQL was restarted) relevant such that the AmazonS3Client would become invalid and require re-creation? What would be the right way to handle a disconnection if so? Does anyone know what features are provided by the spring integration with aws at: https://github.com/spring-projects/spring-integration-extensions/tree/master/spring-integration-aws Thx.
Now provide the response and nothing else.
| I'll repeat the questions to be clear: Is this a good idea to maintain a single AmazonS3Client used by everyone in the code or is it better to create one on every call? All client classes in the Java SDK are thread safe, so usually it is a better idea to re-use a single client than instantiating new ones. Or a few, if you are operating concurrently on multiple regions or credentials. Is there a concept of connection pool like when working with MySQL for example? Yes, there is connection management in the client, specially if you use the TransferManager class instead of the AmazonS3Client directly. see: http://docs.aws.amazon.com/AWSJavaSDK/latest/javadoc/com/amazonaws/services/s3/transfer/TransferManager.html Are questions like disconnection(MySQL analogy: MySQL was restarted) relevant such that the AmazonS3Client would become invalid and require re-creation? What would be the right way to handle a disconnection if so? By default, the client does retries with exponential backoff for recoverable errors.If it really fails/disconnects, you need to handle the exception as appropriate for your app. see: http://docs.aws.amazon.com/general/latest/gr/api-retries.html Does anyone kwow what fearures are provided by the spring integration with aws at: https://github.com/spring-projects/spring-integration-extensions/tree/master/spring-integration-aws It provide declarative instantiation, injection and utility classes for easier integration into Spring projects, in a similar way there are helpers for JDBC, JMS, etc... For more AWS SDK tips and tricks, see: http://aws.amazon.com/articles/3604?_encoding=UTF8&jiveRedirect=1 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23407515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1190830/']} | jdg_379509 |
stackexchange | llm_judgeable_groundtruth_similarity | 59156895 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Python 3.8 error ImportError: cannot import name 'mydb' from partially initialized module 'connection' (most likely due to a circular import) (C:\Users\Mark04\Documents\Python tutorial\databasing\connection.py) When I tried to execute child module select.py import bcrypt;from connection import mydb That has an imported module connection.py import mysql.connectormydb = "Success"; I don't know what is the problem. The error doesn't appear when I remove import mysql.connector from my module connection.py, but it does not solve my problem. > python -m select
Now provide the response and nothing else.
| To answer the above question, we need to understand the problem of circular dependency. To understand the circular dependency, I want to layout a simple example, in front of you. I think every app needs to have the few basic blocks as follows: +----------------+-------------------------------------------------------------------------------------------+| Filename | Description |+----------------+-------------------------------------------------------------------------------------------+| app.py | Creates the app and starts the server. || models.py | Define what the entity will look like (e.g, UserModel has username, email, password etc.) || controllers.py | Fetches Data from database, generates HTML and sends the response to the user browser. |+----------------+-------------------------------------------------------------------------------------------+ Our simple example will also have three files project/ - app.py ( Creates and starts the server) - models.py ( Class to model a user) - controllers.py ( We will fetch data from database, and return html to user.) The contents of the app.py file will look as follows: # =============# app.py# =============# Define the applicationapp = Flask()# Define the Databasedb = SQLAlchemy(app)# Register the Controllerfrom .controllers import auth_controllerapp.register_blueprint(auth_controller) The contents of the models.py file will look as follows: # =============# models.py# =============from .app import db# We will not focus on implementationclass User(db.Model): pass The contents of the controllers.py file will look as follows: # =============# controllers.py# =============from flask import Blueprintfrom .models import User# Create the auth appauth = Blueprint('auth', __name__)# Define the [email protected]('/login')def login(): return "I will fetch some data and allow the user to login" I think now, I have laid out a diagram of our app, now let's proceed to understanding how the app will work. The app starts from app.py app variable inside the app.py file gets created in memory. db variable inside the app.py gets created in memory. Now, to import auth from controllers.py file we switch to ```controllers.py`` file We import Blueprint from flask. To import User , we switch to models.py file. Now, inside models.py file we import db (We are able to import it because it was created in step 3) And program continues so on and so on.... The most important import step in the above sequence is step 7 , becuase it will cause the problem of circular dependency in our app, in just a moment. Now we will try to change the app.py file to introduce the problem of circular dependency. Now, as a developer, we might think that all our imports should be at the top of the file, doesn't it make your code cleaner. Yes, of course! it does make the code cleaner. # ============================# Refactored app.py file# ============================from .controllers import auth_controller# ......# Rest of the file is same, we only shifted this import at the top Now, we have a problem of circular dependency in our app. Let me show you, how? Our app starts from app.py file First, we need to import auth_controller from controllers.py file Let's visit the controllers.py file, and process it. From flask we import Blueprint Let's switch to models.py file to import User Inside models.py file, we import db from app (But db does not exist yet.) Now, I think you got the point, The problem if just saw, was an example of circular dependency. The same problem is causing the ImportError in your case. The solution would be to inspect the import statements and put them at the right place. Sometimes, we use code formatter, and it refactors all the import statements at the top. This might be causing the problem for you. I hope the this may answer your question! | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/59156895', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11349966/']} | jdg_379510 |
stackexchange | llm_judgeable_groundtruth_similarity | 146654 |
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've been reading an article discussing single-supply op-amp design . Regarding Sallen-Key low-pass filter circuits, the author states that: A few filter topologies, such as the Sallen-Key low pass (see section 1), require a resistive divider to DC bias the input. Addition of this network negates the requirement of a Virtual Ground. By virtual ground, the author is referring to ICs such as the TLE2426 virtual ground chip. Can someone explain why Sallen-Key requires a resistor divider? Why won't biasing the AC-coupled signal (i.e. put a capacitor in series with the input) to Vcc/2 (provided by e.g. a TLE2426) work?
Now provide the response and nothing else.
| Let's look at a Sallen-Key low-pass filter: One thing you will notice: the filter does not introduce any additional DC path to ground. C2 is connected to "ground", but since there is no DC path to it, it doesn't actually matter where it's connected, as long as it's a fixed voltage. We could just as well connect it to \$V_{CC}\$, or any other power rail. It doesn't matter, except for power-on transients. How about a high-pass filter? Here, we have a path to ground through R2, but R2 is 10kΩ. The point of a virtual ground IC is to provide a low impedance virtual ground, but here we need a 10kΩ ground. We don't need an IC for that, we just need a voltage divider made of two 20kΩ resistors. Sure, you could use a virtual ground IC and follow it with a 10kΩ resistor, but what's the point? A pair of 20kΩ resistors is a lot simpler. Look at the Sallen-Key topology in general: In this topology, there is always some impedance (\$Z_4\$) between the filter and ground. Since the point of a virtual ground IC is to make a low impedance ground, but we would never need that, the Sallen-Key "negates the requirement of a Virtual Ground". In other words, it isn't that you couldn't use a virtual ground IC: it's that you'd never need to use one. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/146654', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/62701/']} | jdg_379511 |
stackexchange | llm_judgeable_groundtruth_similarity | 3794649 |
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 the Qt world, what is the difference of events and signal/slots? Does one replace the other? Are events an abstraction of signal/slots?
Now provide the response and nothing else.
| In Qt, signals and events are both implementations of the Observer pattern . They are used in different situations because they have different strengths and weaknesses. First of all let's define what we mean by 'Qt event' exactly: a virtual function in a Qt class, which you're expected to reimplement in a base class of yours if you want to handle the event. It's related to the Template Method pattern . Note how I used the word " handle ". Indeed, here's a basic difference between the intent of signals and events: You " handle " events You " get notified of " signal emissions The difference is that when you "handle" the event, you take on the responsibility to "respond" with a behavior that is useful outside the class. For example, consider an app that has a button with a number on it. The app needs to let the user focus the button and change the number by pressing the "up" and "down" keyboard keys. Otherwise the button should function like a normal QPushButton (it can be clicked, etc). In Qt this is done by creating your own little reusable "component" (subclass of QPushButton ), which reimplements QWidget::keyPressEvent . Pseudocode: class NumericButton extends QPushButton private void addToNumber(int value): // ... reimplement base.keyPressEvent(QKeyEvent event): if(event.key == up) this.addToNumber(1) else if(event.key == down) this.addToNumber(-1) else base.keyPressEvent(event) See? This code presents a new abstraction: a widget that acts like a button, but with some extra functionality. We added this functionality very conveniently: Since we reimplemented a virtual, our implementation automatically became encapsulated in our class. If Qt's designers had made keyPressEvent a signal, we would need to decide whether to inherit QPushButton or just externally connect to the signal. But that would be stupid, since in Qt you're always expected to inherit when writing a widget with a custom behavior (for good reason - reusability/modularity). So by making keyPressEvent an event, they convey their intent that keyPressEvent is just a basic building block of functionality. If it were a signal, it'd look like a user-facing thing, when it's not intended to be. Since the base-class-implementation of the function is available, we easily implement the Chain-of-responsibility pattern by handling our special cases (up&down keys) and leaving the rest to the base class. You can see this would be nearly impossible if keyPressEvent were a signal. The design of Qt is well thought out - they made us fall into the pit of success by making it easy to do the right thing and hard to do the wrong thing (by making keyPressEvent an event). On the other hand, consider the simplest usage of QPushButton - just instantiating it and getting notified when it's clicked : button = new QPushButton(this)connect(button, SIGNAL(clicked()), SLOT(sayHello()) This is clearly meant to be done by the user of the class: if we had to subclass QPushButton every time we want some button to notify us of a click, that would require a lot of subclasses for no good reason! A widget that always shows a "Hello world" messagebox when clicked is useful only in a single case - so it's totally not reusable. Again, we have no choice but to do the right thing - by connecting to it externally. we may want to connect several slots to clicked() - or connect several signals to sayHello() . With signals there is no fuss. With subclassing you would have to sit down and ponder some class diagrams until you decide on an appropriate design. Note that one of the places QPushButton emits clicked() is in its mousePressEvent() implementation. That doesn't mean clicked() and mousePressEvent() are interchangable - just that they're related. So signals and events have different purposes (but are related in that both let you "subscribe" to a notification of something happening). | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3794649', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/156623/']} | jdg_379512 |
stackexchange | llm_judgeable_groundtruth_similarity | 11641983 |
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 JSON RFC, section 2.5 , says in part: To escape an extended character that is not in the Basic MultilingualPlane, the character is represented as a twelve-character sequence,encoding the UTF-16 surrogate pair. So, for example, a stringcontaining only the G clef character (U+1D11E) may be represented as"\uD834\uDD1E". Assume I have a valid reason to encode JSON as UTF-16BE (which is allowed). When doing so, is it still necessary to escape characters that are not in the Basic Multilingual Plane? E.g., instead of this: 00 5C 00 75 00 44 00 38 00 33 00 34 00 5C 00 75 00 44 00 44 00 31 00 45 \ u D 8 3 4 \ u D D 1 E which is the 24-byte UTF-16BE byte sequence for \uD834\uDD1E , is it legal to do this: D8 34 DD 1E i.e., use the 4-byte UTF-16BE values directly? Similarly, if I were to encode the same JSON string as UTF-32BE, could I simply use the code-point value directly: 00 01 D1 1E ?
Now provide the response and nothing else.
| As far as I can tell, yes, you can write the UTF-16 values directly. Support: the RFC paragraph you quoted explains how to escape arbitrary Unicode if you have decided to escape it . However, earlier in that same section, the RFC says All Unicode characters may be placed within the quotation marks except for the characters that must be escaped : quotation mark, reverse solidus, and the control characters (U+0000 through U+001F). Any character may be escaped. If the character is in the Basic Multilingual Plane (U+0000 through U+FFFF), then it may be represented as a six-character sequence... (Emphasis added.) To me, this says that only " , \ and control characters must be escaped, and that any other Unicode characters may be placed as-is directly into the JSON text (in whatever UTF form you are using). It also says to me that even if you're encoding as UTF-8, you don't need to use the \uXXXX form for any Unicode character other than " , \ , and control characters. (As an aside, this does make me wonder whether the \uXXXX form is actually useful for anything other than control characters. As the other poster said, it probably comes down to what your JSON parser actually supports.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11641983', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/99089/']} | jdg_379513 |
stackexchange | llm_judgeable_groundtruth_similarity | 31999317 |
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 find the second smallest element in an array of n elements using only n + ceil(lg n) - 2 comparisons. The hint in CLRS says to find the smallest element. This takes n - 1 comparisons so I'm left with ceil(lg n) - 1 comparisons to find the second smallest, once I know the largest. Any ideas? Thanks, bclayman
Now provide the response and nothing else.
| Let's say we've got a list a 1 ...a n with n being a power of 2. First pair the elements up, let's say a 1 with a 2 , a 3 with a 4 and so on, and compare them with each other. This gives you n/2 comparisons. Advance all the winners to the next round, which only has n/2 elements now, and repeat the same process. This requires n/4 more comparisons. Repeat the above until you've only got 1 element left, the ultimate winner. To get there you had to do n/2 + n/4 + ... + 1 = n-1 comparisons. That's great but which one could be the second smallest? Well, it has to be one of the elements your winner had beaten along the way to the top. There are lg n such losers, so you need to compare them amongst each other to find the smallest (requiring a further lg n - 1 comparisons). And the smallest of the losers is the second smallest overall. It's easy to prove why the above method always finds the second smallest: since it's smaller than every element but the ultimate winner, it would win every round apart from the one against the champion. If n isn't a power of 2, the process is almost exactly the same, except the list of losers will be as long as it would be for the next exact power of 2 which is why you end up with ceil(lg n) . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31999317', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1316501/']} | jdg_379514 |
stackexchange | llm_judgeable_groundtruth_similarity | 366457 |
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 column A with the following frequency distribution for all the values in that column A Value Frequency3 2924 715 476 627 228 129 22 I have another column B , similarly, these are the frequency distribution for all the values in that column B Value Frequency3 2744 715 466 627 228 129 22 Please note that the frequencies for value 3 in Column A is 292 and frequency for value 3 in column B is 274. My goal is to find out if the frequencies for value 3 in column A is statistically different than frequency in column B for value 3.I am guessing I cannot use Chi-Square test ? So what test should I use to test whether the frequencies for value 3 in these two columns A, B are similar or different ?
Now provide the response and nothing else.
| If you are mainly interested in the proportion of outcomes taking Value 3,then it seems best to compare that proportion in A, which is $292/528 = 0.553,$with that proportion in B, which is $274/509 = 0.538.$ The difference seemsquite small. A formal test (here done in Minitab) shows that this differenceis not significant at the 5% level (P-value $0.635 > 0.05).$ Also noticethat a 95% confidence interval for the population difference covers $0$ (nodifference). Test and CI for Two Proportions Sample X N Sample p1 292 528 0.5530302 274 509 0.538310Difference = p (1) - p (2)Estimate for difference: 0.014719995% CI for difference: (-0.0458945, 0.0753343)Test for difference = 0 (vs ≠ 0): Z = 0.48 P-Value = 0.634 This test uses a normal approximation of the difference betweentwo binomial proportions, which should be very accurate for your sample sizesabove 500. Notes: [a] You could also do a chi-squared test of the null hypothesis that theproportions of outcomes with Values 3 through 9 are 'homongeneous' for A and B.(Computations are the same as for a test of 'independence' between Values (3through 9) and Types (A and B). That test also does not give a significant result. Pearson Chi-Square = 0.235, DF = 6, P-Value = 1.000 [b] I do not see how it would be appropriate to use a t test to answer this question. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/366457', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/64064/']} | jdg_379515 |
stackexchange | llm_judgeable_groundtruth_similarity | 2778889 |
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 the following code. #include <stdio.h>#include <vector>#include <iostream>struct XYZ { int X,Y,Z; };std::vector<XYZ> A;int rec(int idx){ int i = A.size(); A.push_back(XYZ()); if (idx >= 5) return i; A[i].X = rec(idx+1); return i;}int main(){ A.clear(); rec(0); puts("FINISH!");} I couldn't figure out the reason why the code gives a segmentation fault on Linux (IDE used: Code::Blocks ) whereas on Windows (IDE used: Visual C++ ) it doesn't. When I used Valgrind just to check what actually the problem was, I got this output . I got Invalid write of size 4 at four different places. Then why didn't the code crash when I used Visual C++? Am I missing something?
Now provide the response and nothing else.
| The recursive call to rec() might modify the vector while you're assigning a value to it. What happens if you replace A[i].X = rec(idx+1); with int tmp = rec(idx+1);A[i].X = tmp; ? Also, just to summarize the useful comments: the operand evaluation order of a = operation is unspecified and since the vector wasn't preallocated, several resizes can occur during a recursive call to rec() , thus invalidating any iterator to values in the vector. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2778889', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/165520/']} | jdg_379516 |
stackexchange | llm_judgeable_groundtruth_similarity | 338702 |
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 is it possible to call a client side javascript method after a specific update panel has been loaded? Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler) does not work for me because this will fire after ANY update panel finishes loading, and I can find no client side way to find which is the one ScriptManager.GetCurrent(Page).AsyncPostBackSourceElementID AsyncPostBackSourceElementID does not work for me as this is a server side object, and i want Client Side The ClientSide .Net framework must know which UpdatePanel it is updating in order to update the correct content. Surely there is a way to hook into this event? Any help would be appreciated.
Now provide the response and nothing else.
| Thanks - both good answers. I went with the client side script "pageloaded" in the end. That is a fairly buried method that google did not reveal to me. For those who are interested, this code works with FireBug to give a good demo of the PageLoaded method working to find the updated panels: <script type="text/javascript"> $(document).ready(function() { panelsLoaded = 1; Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(PageLoaded) }); function PageLoaded(sender, args) { console.log("I have occured " + panelsLoaded++ + " times!"); var panelsCreated = args.get_panelsCreated(); for (var i = 0; i < panelsCreated.length; i++) { console.log("Panels Updating: " + panelsCreated[i].id); } var panelsUpdated = args.get_panelsUpdated(); for (var i = 0; i < panelsUpdated.length; i++) { console.log("Panels Updating: " + panelsUpdated[i].id); } } </script> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/338702', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_379517 |
stackexchange | llm_judgeable_groundtruth_similarity | 160387 |
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 new to the functional programming concepts in C#, but I have some experience with higher order functions via Haskell, Scala, Python and Ruby. I'm currently going through an old .NET 2.0 codebase with a LOT of duplication in it. Most of it is simple "copy/paste" with a few variables changed. I'm trying to condense as much of this as possible. A chunk of code within a routine I'm working on now goes a bit like this, for example: if (PostProcess.UsesFirstPass){ w.WriteLine(V1 + " = 0" + " !! SET FOO"); w.WriteLine(V2 + " = 0" + " !! SET BAR"); w.WriteLine(V3 + " = 0" + " !! SET BAZ"); if (PostProcess.IsSpecial){ w.WriteLine(V3 + " = 20" + " !! INCREASE BAZ"); } w.WriteLine(V4 + " = 0" + " !! SET QUUX");}if (PostProcess.UsesSecondPass){ w.WriteLine(V5 + " = 0" + " !! SET FOO"); w.WriteLine(V6 + " = 0" + " !! SET BAR"); w.WriteLine(V7 + " = 0" + " !! SET BAZ"); if (PostProcess.IsSpecial){ w.WriteLine(V7 + " = 20" + " !! INCREASE BAZ"); } w.WriteLine(V8 + " = 0" + " !! SET QUUX");}if (PostProcess.UsesFinalPass){ w.WriteLine(V9 + " = 0" + " !! SET FOO"); w.WriteLine(V10 + " = 0" + " !! SET BAR"); w.WriteLine(V11 + " = 0" + " !! SET BAZ"); if (PostProcess.IsSpecial){ w.WriteLine(V11 + " = 20" + " !! INCREASE BAZ"); } w.WriteLine(V12 + " = 0" + " !! SET QUUX");} Where any of the "V"s you see in there is a string variable defined earlier. It's part of a fairly large method. I could write another method called, say, WriteVariables() and pass in the required info and call it three times, but it only ever applies to this section of method. I think this would be a place where writing an anonymous inner function would make sense. I did it to test it out, and it seems to work fine. Now I have a single delegate that looks something like: private delegate void WriteCutVars(string V1, string V2, string V3, string V4, CuttingParameters cutParam);// snip //WriteCutVars WriteVars = (Va, Vb, Vc, Vd) => { w.WriteLine(Va + " = 0" + " !! SET FOO"); w.WriteLine(Vb + " = 0" + " !! SET BAR"); w.WriteLine(Vc + " = 0" + " !! SET BAZ"); if (PostProcess.IsSpecial){ w.WriteLine(Vc + " = 20" + " !! INCREASE BAZ"); } w.WriteLine(Vd + " = 0" + " !! SET QUUX");}if (Process.UsesFirstPass) WriteVars(V1, V2, V3, V4);if (Process.UsesSecondPass) WriteVars(V5, V6, V7, V8);if (Process.UsesFinalPass) WriteVars(V9, V10, V11, V12); My main questions: Is this a proper use of inner functions? Is this acceptable when I'm the only CS graduate on a team ofmostly mechanical engineers?
Now provide the response and nothing else.
| Your implementation seems reasonable to me. However, if most of the other people developing the software have limited advanced programming experience you might want to use a regular function instead of an anonymous one since it will be more obvious what's going on. When you're the senior developer and the rest of your team is at a significantly lower skill level; making sure they understand how your code works and can easily modify it if needed is an important consideration. Since your team mostly consists of non-programmers this is a larger consideration, since for programming techniques they probably congregate closer to the Use What I Know end of the scale than the Learn New Things Everyday end. Breaking the repeated logic out and removing the copy/pasting should be simple to explain the benefits of. More advanced techniques like anonymous functions or linq would be a harder sell since they don't give major and obvious functional/maintenance improvements. The hardware engineers I've worked with in the past mostly only learned C in college since it was the language of choice for the micro-controllers in the gadgets they were building. With only a handful of classes their skills were concentrated on practical basic programming only, and not anything advanced. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/160387', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/53697/']} | jdg_379518 |
stackexchange | llm_judgeable_groundtruth_similarity | 3044622 |
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:
There is a lot of material showing that a positive definite matrix $A$ has a unique positive definite square root, $B$ such that $B^2=A$ . During a self study session, I needed to use this fact for a proof sketch, but I was confused about whether $B$ is the only square root of $A$ and it happens to be positive definite or is the uniqueness only valid for the positive definiteness; such that one can come up with a matrix $C$ , not positive definite and $C^2=A$ . I am confused about which is the correct one.
Now provide the response and nothing else.
| Parameterize this integral by adding a second parameter, $t$ : $$I(t):= \int_{-\infty}^\infty \frac{e^{-(x^2+a^2)t}}{x^2+a^2}dx$$ Differentiating with respect to $t$ , we have $$I'(t)=-\int_{-\infty}^\infty e^{-(x^2+a^2)t}dx=-\sqrt{\frac{\pi}{t}} e^{-a^2 t}$$ This shows us that $$\begin{align}I(t)&=I(0)-\int_0^t \sqrt{\frac{\pi}{x}}e^{-a^2 x}dx\\&=\frac{\pi}{a}-2\int_0^{\sqrt{t}} \sqrt{\pi}e^{-a^2 x^2}dx\\&=\frac{\pi}{a}-\frac{\pi \text{erf}(a\sqrt{t})}{a}\\&=\frac{\pi \text{erfc}(a\sqrt{t})}{a}\\\end{align}$$ Which gives us the desired value of your integral: $$\int_{-\infty}^\infty \frac{e^{-x^2}}{x^2+a^2}dx=\frac{\pi e^{a^2}\text{erfc}(a)}{a}$$ Delicious! | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3044622', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/65147/']} | jdg_379519 |
stackexchange | llm_judgeable_groundtruth_similarity | 410597 |
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 know that $\zeta(n) = \displaystyle\sum_{k=1}^\infty \frac{1}{k^n}$ (Where $\zeta(n)$ is the Riemann zeta function ) But the reciprocal of $\zeta(n)$ for $n$ a positive integer is equal to the probability that $n$ numbers chossen at random are relatively prime. But why? Can you give a proof?
Now provide the response and nothing else.
| Here is a very rough sketch of the idea : We have the following : $$\zeta(n) = \sum_{k \ge 1} \frac 1{k^n} = \sum_{k \ge 1} \prod_{p^{k_p} || k} \frac 1{(p^n)^{k_p} } = \prod_{p} \sum_{k \ge 0} \left( \frac 1{p^n} \right)^k = \prod_{p} \frac 1{1-\frac 1{p^n}}.$$(You need to work out the details for all the convergence issues and these are treated in pretty much all good elementary number theory books.) Now if we choose $k_1, \dots, k_n$ integers independently and uniformly over the interval $[1,x]$, one roughly expects that $p | k_i$ with probability $1/p$. The fact that $(k_1,\dots,k_n) = 1$ means that there is no prime which divides all those integers at once. $p$ divides $k_1, \dots, k_n$ with probability $1/p^n$ assuming independence, hence the probability we are looking for is roughly$$\prod_{p \le x} \left( 1 - \frac 1{p^n} \right) \underset{x \to \infty}{\longrightarrow} \prod_p \left( 1 - \frac 1{p^n} \right) = \frac 1{\zeta(n)}.$$You probably need to understand better what happens when $p$ is relatively large compared to $x$ to work out the error terms, but the basic ideas are all here. Hope that helps, | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/410597', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/80245/']} | jdg_379520 |
stackexchange | llm_judgeable_groundtruth_similarity | 14482 |
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:
Has anyone attempted time series prediction using support vector regression? I understand support vector machines and partially understand support vector regression, but I don't understand how they can be used to model time series, especially multivariate time series. I've tried to read a few papers, but they are too high level. Can anyone explain in lay terms how they would work, especially in relation to multivariate time series? EDIT:To elaborate a bit, let me try to explain with a stock price example. Say we have stock prices for N days. Then, for each day we could construct a feature vector, which, in a simple case, could be be the previous day's price and the current day's price. The response for each feature vector would be the next day's price. Thus, given yesterday's price and today's price the objective would be to predict the next days price. What I don't understand is, say we have six months training data, how would you give greater emphasis to the more recent feature vectors?
Now provide the response and nothing else.
| In the context of support vector regression, the fact that your data is a time series is mainly relevant from a methodological standpoint -- for example, you can't do a k-fold cross validation, and you need to take precautions when running backtests/simulations. Basically, support vector regression is a discriminative regression technique much like any other discriminative regression technique. You give it a set of input vectors and associated responses, and it fits a model to try and predict the response given a new input vector. Kernel SVR, on the other hand, applies one of many transformations to your data set prior to the learning step. This allows it to pick up nonlinear trends in the data set, unlike e.g. linear regression. A good kernel to start with would probably be the Gaussian RBF -- it will have a hyperparameter you can tune, so try out a couple values. And then when you get a feeling for what's going on you can try out other kernels. With a time series, an import step is determining what your "feature vector" ${\bf x}$ will be; each $x_i$ is called a "feature" and can be calculated from present or past data, and each $y_i$, the response, will be the future change over some time period of whatever you're trying to predict. Take a stock for example. You have prices over time. Maybe your features are a.) the 200MA-30MA spread and b.) 20-day volatility, so you calculate each ${\bf x_t}$ at each point in time, along with $y_t$, the (say) following week's return on that stock. Thus, your SVR learns how to predict the following week's return based on the present MA spread and 20-day vol. (This strategy won't work, so don't get too excited ;)). If the papers you read were too difficult, you probably don't want to try to implement an SVM yourself, as it can be complicated. IIRC there is a "kernlab" package for R that has a Kernel SVM implementation with a number of kernels included, so that would provide a quick way to get up and running. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/14482', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/5887/']} | jdg_379521 |
stackexchange | llm_judgeable_groundtruth_similarity | 35406707 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Do events (DOM events or system events) have a 1:1 relationship with actions? i.e. should a single click event trigger only one action? For example, let's say we have a page which displays a table of 10 rows and 2 columns. Each row has a Product field and an Amount field. The Amount field has a range input with a range of [0, 10]. The user can set the Amount of each Product individually. The user is also given 2 options, through the use of 2 buttons. Pressing the second button will disable all but the first product in the table (effectively setting their Amount to 0 and the user can no longer interact with them to set their Amount). Let's call this Option B Pressing the first button enables all Products after the first (by default setting their Amount to 1 for each of them) and the user can once again interact with them, to set their amounts individually. Let's call this Option A . Option A selected: | PRODUCT | AMOUNT | |------------------|-----------| | Product A | - 4 + | | Product B | - 0 + | | Product C | - 4 + | ```````````````````````````````` _________| Option A| OPTION B `````````Option B selected: | PRODUCT | AMOUNT | |------------------|-----------| | Product A | - 4 + | | Product B | Disabled | (Amount == 0) | Product C | Disabled | (Amount == 0) ```````````````````````````````` _________OPTION A | OPTION B| `````````Option A selected again: | PRODUCT | AMOUNT | |------------------|-----------| | Product A | - 4 + | | Product B | - 1 + | | Product C | - 1 + | ```````````````````````````````` _________| Option A| OPTION B ````````` The state of this 'app' is described by this simple object state = { option : <String>, products : [ { name : <String>, amount : <Integer> }, ... ]} We also have these 4 simple action creators: function setOption(option) { return { type : 'SET_OPTION', option : option};}function incAmount(productName) { return { type : 'INCREMENT_AMOUNT', product : productName }} function decAmount(productName) { return { type : 'DECREMENT_AMOUNT', product : productName }}function setAmount(productName, amount) { return { type : 'SET_AMOUNT', payload : { product : productName, amount : amount } }} For the sake of simplicity, we have only one reducer. In this example, selecting Option B should have the following effects on the state : Change option to B Set the amount of every product after the first to 0 Selecting Option A should have the following effects on the state, respectively : Change option to A Set the amount of every product after the first to 1 Incrementing the amount of Product A should have the following effects on the state : Increment the amount of Product A by 1 What would be the proper way to implement these changes? a) Have the onClick handler of the option buttons do the following: Fire a store.dispatch(setOption(option)) For each product after the first one fire a store.dispatch(setAmount(productName, amount)) ( amount = 1 for option A, 0 for option B) b) Have the onClick handler of the option buttons do the following: Fire a store.dispatch(setOption(option)) And have the reducer change the option as well as the amount of every product after the first one to the specified amount ( amount = 1 for option A, 0 for option B) If we go with a) each case in the switch (action) {} statement of the reducer deals with just one aspect of the state, but we have to fire more than one action from one click event If we go with b) we fire only one action from the click event but the case for SET_OPTION in the reducer not only changes the option but also the amount of products.
Now provide the response and nothing else.
| There is no general answer to this question so we have to evaluate on a case by case basis. When using Redux, you should strive to keep a balance between keeping reducers simple and keeping the action log meaningful. It is best when you can read the action log and it makes sense why things happened. This is the “predictability” aspect that Redux brings. When you dispatch a single action, and different parts of the state change in response, it is easy to tell why they change later. If you debug a problem, you are not overwhelmed by the amount of actions, and every mutation can be traced to something a user did. By constrast, when you dispatch multiple actions in response to a single user interaction, it is harder to tell why they were dispatched. They clutter the action log, and if there is a mistake in how they were dispatched, the log won’t uncover the underlying reasons. A good rule of thumb is that you never want to dispatch in a loop. This is highly inefficient and, as noted above, obscures the true nature of why the change happened. In your particular example I would recommend firing a single action. However this does not mean that firing a single action is always the way to go. Like everything, it is a tradeoff. There are valid cases when it is more convenient to fire several actions in response to a single user interaction. For example, if your app lets users tag products, it can be more convenient to separate CREATE_TAG and ADD_TAG_TO_PRODUCT actions because while in this scenario they happen at the same time, they may also happen separately, and it can be easier to write reducers that handle them as different actions. As long as you don’t abuse this pattern and don’t do something like this in a loop, you should be fine. Keep action log as close to the history of user interactions as you can. However if it makes reducers tricky to implement consider splitting some actions in several, if a UI update can be thought of two separate operations that just happen to be together. Don’t fall into either of the extremes. Prefer reducer clarity to a perfect log, but also prefer not dispatching in a loop to reducer clarity. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/35406707', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4651083/']} | jdg_379522 |
stackexchange | llm_judgeable_groundtruth_similarity | 2934269 |
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 read docs about positioning controls on the map( TOP , TOP_LEFT , etc), but Is there any way to make custom position? For example: left: 20px; top: 200px ;I just want to have in top_left corner my logo and zoom control right under logo. And how to remove pan control in navigation controls? I want to have only zoom control in default style(not minimized).Thank you.
Now provide the response and nothing else.
| Although the question is rather old, with almost 3k views it still seems to draw interest - So, here is my solution: Wrap the controls! First we have to find the container-element, where Google puts the control. This depends on which controls we want to use on the map. Google doesn't use unique ids for those containers. But all the controls have the class "gmnoprint" in common. So just counting the elements with "gmnoprint" does the job. Say we only want to use the "ZoomControlStyle.SMALL"-control. It's always the last element with "gmnoprint". Now, we can simply style the element - Right? No. As soon as you zoom or resize the map, Google resets the styling of the controls. Bad luck, but: We can wrap a container around the controls and style this container! Using jQuery, this is a really simple task: $('div.gmnoprint').last().parent().wrap('<div id="newPos" />'); We only have to make sure, the control is fully loaded by the time we try to wrap it. It's not totally bulletproof I guess, but using the MapsEventListener "tilesloaded" does a pretty good job: google.maps.event.addDomListener(map, 'tilesloaded', function(){ // We only want to wrap once! if($('#newPos').length==0){ $('div.gmnoprint').last().parent().wrap('<div id="newPos" />'); }}); Check out http://jsfiddle.net/jfPZH/ (not working, see Update Feb 2016 ) Of course if you don't like the initial flicker and want a more reliable version you can do all kinds of improvements like fadeIn etc: http://jsfiddle.net/vVLWg/ (not working, see Update Feb 2016 ) So, I hope some of you will find this useful - Have fun! Update: With this method you can position any other control (e.g. the controls of the Drawing Library ) as well. You just have to make sure to select the right container! This is a modified example: http://jsfiddle.net/jP65p/1/ (somehow still working) Update : As of Feb 2016 Google seems to have changed the positioning of the map controls. This does not break my solution. It just needs some adjustment. So here are the updated fiddles: Simple: http://jsfiddle.net/hbnrqqoz/ Fancy: http://jsfiddle.net/2Luk68w5/ | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2934269', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/353104/']} | jdg_379523 |
stackexchange | llm_judgeable_groundtruth_similarity | 2658932 |
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:
need a clue to solve $$\int ^{1}_{0}(\dfrac {1-x}{\ln x}\left( x^{2^{0}}+x^{2^{1}}+\ldots +x^{2 ^{n}}\right))dx$$the answer is -ln3. I have no idea to begin with.
Now provide the response and nothing else.
| In a triangle $A+B+C=\pi$, hence$$\cos(C)=\cos(\pi-(A+B))=-\cos(A+B)=\sin(A)\sin(B)-\cos(A)\cos(B)$$where $\cos(A)=\frac{3}{5}$ implies $\sin(A)=\frac{4}{5}$ and $\cos(B)=\frac{24}{25}$ implies $\sin(B)=\frac{7}{25}$. It follows that$$ \cos(C) = \frac{4\cdot 7-3\cdot 24 }{5\cdot 25}=\color{red}{-\frac{44}{125}}.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2658932', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/533395/']} | jdg_379524 |
stackexchange | llm_judgeable_groundtruth_similarity | 58882959 |
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 the following anonymous recursive function: $f = function($n) use (&$f) { return ($n == 1) ? 1 : $n * $f($n - 1);};echo $f(5); // 120 I try to rewrite to version 7.4, but there is an error, please tell me what I'm missing? $f = fn($n) => ($n == 1) ? 1 : $n * $f($n - 1);echo $f(5); Notice: Undefined variable: f Fatal error: Uncaught Error: Function name must be a string
Now provide the response and nothing else.
| Just like Barmar said, you can't use $f from the outside scope, because when the implicit binding takes place $f is still undefined. There is nothing stopping you from passing it later as a parameter. $f = fn($f, $n) => $n == 1 ? 1 : $n * $f($f, $n - 1);echo $f($f, 5); // 120 The way arrow functions work, is that during definition time they will use by-value binding of the outer scope's variables. As already mentioned, arrow functions use by-value variable binding. This is roughly equivalent to performing a use($x) for every variable $x used inside the arrow function. - https://wiki.php.net/rfc/arrow_functions_v2 The assignment of the closure to the variable $f happens after closure's definition and the variable $f is undefined prior to it. As far as I am aware, there isn't any mechanism to bind by reference while defining arrow functions. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58882959', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9908035/']} | jdg_379525 |
stackexchange | llm_judgeable_groundtruth_similarity | 255428 |
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 am looking at a file generated by another CAS. I'd like to convert it to Mathematica syntax. Only issue is how to convert exp(....) to Exp[....] . I am using StringReplace with pattern to do the replacement but it is not catching all possible cases. I am not good at regular expressions in Mathematica. Here are 5 simple input examples to test with ClearAll[z]str1 = "exp(x)^2";str2 = "exp((x+2))";str3 = "exp( (x+2) * exp(exp(x)+2) )";str4 = "(4*x)/exp((x-(2/5))/((3/(exp(x)+5))*4+(x-(2-x))*x))+4"str5="(20*x^4+(-30)*x^3+12*x^2+4*x)*exp(x)^2+(200*x^4+(-300)*x^3+300*x^2+(-236)*x)*exp(x)+(500*x^4+(-750)*x^3+1500*x^2+(-1400)*x+720)" These should become str1 = "Exp[x]^2";str2 = "Exp[(x+2)]";str3 = "Exp[ (x+2) * Exp[Exp[x]+2] ]";str4 = "(4*x)/Exp[(x-(2/5))/((3/(Exp[x]+5))*4+(x-(2-x))*x)]+4"str5 = "(20*x^4+(-30)*x^3+12*x^2+4*x)*Exp[x]^2+(200*x^4+(-300)*x^3+300*x^2+(-236)*x)*Exp[x]+(500*x^4+(-750)*x^3+1500*x^2+(-1400)*x+720)" This is what I tried among many other things StringReplace[str, "exp(" ~~ z__ ~~ ")" :> "Exp[" ~~ z ~~ "]"] Only the first and second worked.The third one, it did not change any of the internal ones. it failed on str4 and str5 also. Any suggestions how to do this conversion all in one command? Either using string patterns or regular expression in Mathematica. I am using version 12.3.1
Now provide the response and nothing else.
| Update: We can convert the strings to expressions without any string processing: ClearAll[sR0]sR0 = ToExpression[#, TraditionalForm] &;sR0 /@ {str1, str2, str3, str4, str5} // Column If you need to get strings as output wrap the expression with ToString[#, InputForm]& using the third argument of ToExpression : ClearAll[sR01]sR01 = ToExpression[#, TraditionalForm, ToString[#, InputForm] &] &;sR01 /@ {str1, str2, str3, str4, str5} {"E^(2*x)", "E^(2 + x)", "E^(E^(2 + E^x)*(2 + x))", "4 + (4*x)/E^((-2/5 + x)/(12/(5 + E^x) + x*(-2 + 2*x)))", "720 - 1400*x + 1500*x^2 - 750*x^3 + 500*x^4 + E^(2*x)*(4*x + 12*x^2 - 30*x^3 + 20*x^4) + E^x*(-236*x + 300*x^2 - 300*x^3 + 200*x^4)"} Original answer: ClearAll[sR]sR = StringReplace[#, "exp(" ~~ Shortest[z__] ~~ ")" /; Equal @@ (StringCount[z, #] & /@ {"(", ")"}) :> "Exp[" <> sR @ z <> "]"] &;sR /@ {str1, str2, str3, str4, str5} {"Exp[x]^2", "Exp[(x+2)]", "Exp[ (x+2) * Exp[Exp[x]+2] ]", "(4*x)/Exp[(x-(2/5))/((3/(Exp[x]+5))*4+(x-(2-x))*x)]+4", "(20*x^4+(-30)*x^3+12*x^2+4*x)*Exp[x]^2+(200*x^4+(-300)*x^3+300*x^2+ (-236)*x)*Exp[x]+(500*x^4+(-750)*x^3+1500*x^2+(-1400)*x+720)"} You can also use FixedPoint as follows: ClearAll[sR2]sR2 = FixedPoint[StringReplace[ "exp(" ~~ Shortest[z__] ~~ ")" /; Equal @@ (StringCount[z, #] & /@ {"(", ")"}) :> "Exp[" <> z <> "]"], #] &;sR2 /@ {str1, str2, str3, str4, str5} == sR /@ {str1, str2, str3, str4, str5} True | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/255428', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/70/']} | jdg_379526 |
stackexchange | llm_judgeable_groundtruth_similarity | 97030 |
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:
I read on Wikipedia and in many books that when $\ce{K2Cr2O7}$ is reduced, it forms $\ce{Cr^3+}$ and a change is noticed from orange color to green. I want to know in what exact complex/salt/compound $\ce{Cr^3+}$ exists that it shows green color. I know $\ce{[CrCl3].3H2O}$ shows green color but in many of these reactions, there is no $\ce{Cl-}$ ion, so I guess that is not formed. Also, $\ce{Cr^3+}$ can exist as $\ce{[Cr(H2O)6]^3+}$ but since it is violet in color, that possibility is also ruled out. So basically, how does the solution becomes green in color?
Now provide the response and nothing else.
| The dichromate ($\ce{Cr2O7^2-}$) ions are strong oxidizing agents at low pH. During the redox process, each chromium atom in the dichromate ions (oxidation state = +6) gains three electrons and get its oxidation state reduced to +3. In redox reactions in aqueous acid solution, the aquated $\ce{Cr^3+}$ ion is produced according to following half-reaction ( Electrochemical Series ):$$\ce{Cr2O7^2- + 14H3O+ + 6e- <=> 2Cr^3+ + 21H2O} \space \space \space \pu{E^0 = 1.36 V}$$ Assume that the $\ce{Cr^3+}$ ion in aqueous solutions is in its simplest ion form: the hexaaquachromium(III) or $\ce{[Cr(H2O)6]^3+}$. This ion is violet-blue-grey in color. However, when $\ce{Cr^3+}$ ion is formed during a reaction in aquous acid solution, it is often appeared in green color. Thus, we always describe the green color due to $\ce{Cr^3+ (aq)}$, implying it as the hexaaquachromium(III) ion ($\ce{[Cr(H2O)6]^3+}$), but that's actually not the case. What's really happening in the solution is that one or more of the water molecules in each of $\ce{[Cr(H2O)6]^3+}$ ions get replaced by other negative ions in the solution, typically by $\ce{SO4^2-}$ (if the acid used is $\ce{H2SO4}$) or $\ce{Cl-}$ (if the acid is $\ce{HCl}$). For example, if one of the water molecules is replaced by a $\ce{SO4^2-}$ ion, $\ce{[Cr(H2O)6]^3+}$ becomes $\ce{[Cr(H2O)5SO4]+}$, which is green (notice also the change in the charge on the ion). You can check this by yourself: warm freshly prepared aqueous chromium(III) sulphate hexahydrate solution, which would change its color of purple-blue or violet ($\ce{[Cr(H2O)6]^3+}$) to green ($\ce{[Cr(H2O)5SO4]+}$) due to the ligand exchange discussed above [ Chem Guide ]. In $\ce{CrCl3.6H2O}$, on the other hands, the green color of the solid itself or its aqueous solution is due to the $\ce{[Cr(H2O)4Cl2]+}$ ion. Hence, actually more proper way of writing the formula is $\ce{CrCl2(H2O)4Cl.2H2O}$. In contrast to previous case, the green $\ce{CrCl2(H2O)4Cl.2H2O}$ solution would slowly becomes violet in color by standing at room temperature overnight, by slow ligand exchange with solvent (water)[Chem Guide]. Interesting fact: Chromium was discovered by Louis Nicholas Vauquelin in 1797 who named his new element after the Greek word chroma — which means color. Late Additions: Although $\ce{Cr^3+}$ ions complexes with most ligands to give green color, it gives vivid line of colors with other ligands (note it names after chroma !). Some interesting examples are illustrated in the picture below: Also see: Chromium(III) nitrate: Blue-violet crystals (anhydrous), and purple crystals (nonahydrate), according to Wikipedia (see the picture below). | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/97030', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/60468/']} | jdg_379527 |
stackexchange | llm_judgeable_groundtruth_similarity | 26814427 |
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 "status" collection like this strcture - { _id: ObjectId("545a0b63b03dbcd1238b4567"), status: 1004, comment: "Rem dolor ipsam placeat omnis non. Aspernatur nobis qui nisi similique.", created_at: ISODate("2014-11-05T11:34:59.804Z")},{ _id: ObjectId("545a0b66b03dbcd1238b4568"), status: 1001, comment: "Sint et eos vero ipsa voluptatem harum. Hic unde voluptatibus et blanditiis quod modi.", created_at: ISODate("2014-11-05T11:35:02.814Z")}........ I need to get result grouped by 15 minutes interval from that collection.
Now provide the response and nothing else.
| There are a couple of ways to do this. The first is with Date Aggregation Operators , which allow you to dissect the "date" values in documents. Specifically for "grouping" as the primary intent: db.collection.aggregate([ { "$group": { "_id": { "year": { "$year": "$created_at" }, "dayOfYear": { "$dayOfYear": "$created_at" }, "hour": { "$hour": "$created_at" }, "interval": { "$subtract": [ { "$minute": "$created_at" }, { "$mod": [{ "$minute": "$created_at"}, 15] } ] } }}, "count": { "$sum": 1 } }}]) The second way is by using a little trick of when a date object is subtracted (or other direct math operation) from another date object, then the result is a numeric value representing the epoch timestamp milliseconds between the two objects. So just using the epoch date you get the epoch milliseconds representation. Then use date math for the interval: db.collection.aggregate([ { "$group": { "_id": { "$subtract": [ { "$subtract": [ "$created_at", new Date("1970-01-01") ] }, { "$mod": [ { "$subtract": [ "$created_at", new Date("1970-01-01") ] }, 1000 * 60 * 15 ]} ] }, "count": { "$sum": 1 } }}]) So it depends on what kind of output format you want for the grouping interval. Both basically represent the same thing and have sufficient data to re-construct as a "date" object in your code. You can put anything else you want in the "grouping operator" portion after the grouping _id . I'm just using the basic "count" example in lieu of any real statement from yourself as to what you really want to do. MongoDB 4.x and Upwards There were some additions to Date Aggregation Operators since the original writing, but from MongoDB 4.0 there will be actual "real casting of types" as opposed to the basic math tricks done here with BSON Date conversion. For instance we can use $toLong and $toDate as new helpers here: db.collection.aggregate([ { "$group": { "_id": { "$toDate": { "$subtract": [ { "$toLong": "$created_at" }, { "$mod": [ { "$toLong": "$created_at" }, 1000 * 60 * 15 ] } ] } }, "count": { "$sum": 1 } }}]) That's a bit shorter and does not require defining an external BSON Date for the "epoch" value as a constant in defining the pipeline so it's pretty consistent for all language implementations. Those are just two of the "helper" methods for type conversion which all tie back to the $convert method, which is a "longer" form of the implementation allowing for custom handling on null or error in conversion. It's even possible with such casting to get the Date information from the ObjectId of the primary key, as this would be a reliable source of "creation" date: db.collection.aggregate([ { "$group": { "_id": { "$toDate": { "$subtract": [ { "$toLong": { "$toDate": "$_id" } }, { "$mod": [ { "$toLong": { "$toDate": "$_id" } }, 1000 * 60 * 15 ] } ] } }, "count": { "$sum": 1 } }}]) So "casting types" with this sort of conversion can be pretty powerful tool. Warning - ObjectId values are limited to precision to the second only for the internal time value that makes up part of their data allowing the $toDate conversion. The actual inserted "time" is most probably dependent on the driver in use. Where precision is required, it's still recommended to use a discrete BSON Date field instead of relying on ObjectId values. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/26814427', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1808517/']} | jdg_379528 |
stackexchange | llm_judgeable_groundtruth_similarity | 14911038 |
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 little confused with roles. If I have in my page a navigation that is enclosed in a nav element and specify a role="navigation" . <nav role="navigation"> ...</nav> Isn't it already semantically explicit that the nav section is navigation? Or if I have some other navigation sections on my page, and specify role for only one of them, this section becomes the most important on a page? And those without role="navigation" just boring navigations?
Now provide the response and nothing else.
| It is true that most modern browsers/technologies recognise the HTML5 <nav> element as navigation and give it the same attention. But explicitly setting the role="navigation" attribute just makes sure that a lot more technologies can pick it up. For example screen-readers and other technologies for users with disabilities are very rarely fully standards compliant (especially if they have to work all the way back to IE6 or lower!) so adding the role attributes explicitly always ensures that you cover all your bases for the most users possible. Also (and this is just a guess) some of the lesser known search engines may not fully recognise HTML5 yet, so adding these roles should help with the sites crawl-ability. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14911038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2008650/']} | jdg_379529 |
stackexchange | llm_judgeable_groundtruth_similarity | 15997966 |
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 order to deal with different versions of a content-type i am trying to use the accept-parameters of the "Accept*" headers ( RFC 2616 ). Accept: application/vnd.mycompany.mytype;version=2 , application/vnd.mycompany.mytype;version=1;q=0.1 The problem is that Jax-RS annotations do not support Accept-parameters... @GET@Produces("application/vnd.test;version=1")public Response test1() { return Response.ok("Version 1", "application/vnd.test").build();}@GET@Produces("application/vnd.test;version=2")public Response test2() { return Response.ok("Version 2", "application/vnd.test").build();} Results in a media type conflict exception: Producing media type conflict. The resource methods public javax.ws.rs.core.Response test.resources.TestResource.test2() and public javax.ws.rs.core.Response test.resources.TestResource.test1() can produce the same media type Maybe, this exception only related to my JAX-RS framework (Jersey), but i'm afraid this is due to the JSR311 which is not explicit about accept-parameters. By now, i'm using content-types which holds the version within their names, but i found this solution pretty uggly. @GET@Produces("application/vnd.test-v1")public Response test() { return Response.ok("Version 1", "application/vnd.test-v1").build();} Do you have any ideas about how to deal with accept-parameters ? EDIT I think i wasn't clear enough.I want to automatically route the request to specific methods.These methods are versioned and correspond to a specific version of the returned content-type.JAX-RS current implementation prevents me to use accept-parameters to route the request (to the corresponding method). greenkode suggest that i manage the version accept-parameter within a dispatching method (using @HeaderParam("Accept") ).This solution would end-up in re-writing the content negociation logic which is embeded in the framework (and described in JSR 311). What can i do to use both accept-parameter and content-negociation logic from JAX-RS ? Maybe a solution is to use another framework (I only worked with Jersey by Now). But i don't know which one.
Now provide the response and nothing else.
| The JAX-RS specification does not explicitly state anything about ignoring Accept header parameters. But the only parameter for which handling is definitely defined is quality (q). This is a possible area for improvement as it seems to have lead to ambiguity (or outright bugginess) in the Jersey implementation. The current version of Jersey (1.17) does not take Accept header parameters into consideration when matching incoming requests to resource methods, which is why you are getting the error: SEVERE: Producing media type conflict. The resource methods ... For the resource: @GET@Produces("application/vnd.test;version=1")public Response test1() { return Response.ok("Version 1", "application/vnd.test").build();}@GET@Produces("application/vnd.test;version=2")public Response test2() { return Response.ok("Version 2", "application/vnd.test").build();} It would appear that Jersey performs a 'uniqueness' check based on the Accept header 'type/subtype', totally omitting any parameters. This can be confirmed by testing with various pairs of headers on the 'matching' resource methods: Resource 1 Resource 2----------------------------------------text/html;q=0.4 text/html;q=0.8text/html text/html;q=0.2text/html text/html;qs=1.4text/html;qs=1.4 text/html;qs=1.8text/html;level=1 text/html;level=2text/html;foo=bleh text/html;bar=23 All fail with the same error. If the assumption were made that only the quality parameter is ever sent, then it would make sense to only match on 'type/subtype', because this kind of request is nonsensical: Accept: text/html;q=0.8, text/html;q=0.4, text/html Aka, quality parameters only make sense when you are dealing with a mix of possible content types. However, this sort of limited matching fails when non-quality parameters or additional parameters are being sent: Accept: text/html;version=4.0;q=0.8, text/html;version=3.2;q=0.4 So what are the possible solutions? Intercept the high level request based off 'type/subtype', then route to more appropriate method (you've indicated you do not want to do this) Modify your expected headers. For example 'application/vnd.mycompany.mytype+v2' and 'application/vnd.mycompany.mytype+v1'. No other changes would be required and you could keep on using Jersey Switch frameworks. RESTEasy happens to handle your scenario with ease. With RESTEasy, and resource: @Path("/content/version")public class ContentVersionResource { @GET @Produces("application/vnd.test;version=1") public Response test1() { return Response.ok("Version 1", "application/vnd.test").build(); } @GET @Produces("application/vnd.test;version=2") public Response test2() { return Response.ok("Version 2", "application/vnd.test").build(); }} A successful match is made with the following Accept header: Accept: application/vnd.test;version=1;q=0.3, application/vnd.test;version=2;q=0.5 Response: Version 2 And this: Accept: application/vnd.test;version=1;q=0.5, application/vnd.test;version=2;q=0.3 Response: Version 1 You can download and test with this sample project . Git, Maven and JBoss 7.x required | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15997966', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/226292/']} | jdg_379530 |
stackexchange | llm_judgeable_groundtruth_similarity | 161738 |
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 check if a given string is a valid URL address? My knowledge of regular expressions is basic and doesn't allow me to choose from the hundreds of regular expressions I've already seen on the web.
Now provide the response and nothing else.
| I wrote my URL (actually IRI, internationalized) pattern to comply with RFC 3987 ( http://www.faqs.org/rfcs/rfc3987.html ). These are in PCRE syntax. For absolute IRIs (internationalized): /^[a-z](?:[-a-z0-9\+\.])*:(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9\._~!\$&'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*)?|(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\/\?])*)?$/i To also allow relative IRIs: /^(?:[a-z](?:[-a-z0-9\+\.])*:(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9\._~!\$&'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*)?|(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\/\?])*)?|(?:\/\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:])*@)?(?:\[(?:(?:(?:[0-9a-f]{1,4}:){6}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|::(?:[0-9a-f]{1,4}:){5}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3})|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|v[0-9a-f]+\.[-a-z0-9\._~!\$&'\(\)\*\+,;=:]+)\]|(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?:\.(?:[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}|(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=])*)(?::[0-9]*)?(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|\/(?:(?:(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*)?|(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=@])+)(?:\/(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@]))*)*|(?!(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])))(?:\?(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}\/\?])*)?(?:\#(?:(?:%[0-9a-f][0-9a-f]|[-a-z0-9\._~\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}!\$&'\(\)\*\+,;=:@])|[\/\?])*)?)$/i How they were compiled (in PHP): <?php/* Regex convenience functions (character class, non-capturing group) */function cc($str, $suffix = '', $negate = false) { return '[' . ($negate ? '^' : '') . $str . ']' . $suffix;}function ncg($str, $suffix = '') { return '(?:' . $str . ')' . $suffix;}/* Preserved from RFC3986 */$ALPHA = 'a-z';$DIGIT = '0-9';$HEXDIG = $DIGIT . 'a-f';$sub_delims = '!\\$&\'\\(\\)\\*\\+,;=';$gen_delims = ':\\/\\?\\#\\[\\]@';$reserved = $gen_delims . $sub_delims;$unreserved = '-' . $ALPHA . $DIGIT . '\\._~';$pct_encoded = '%' . cc($HEXDIG) . cc($HEXDIG);$dec_octet = ncg(implode('|', array( cc($DIGIT), cc('1-9') . cc($DIGIT), '1' . cc($DIGIT) . cc($DIGIT), '2' . cc('0-4') . cc($DIGIT), '25' . cc('0-5'))));$IPv4address = $dec_octet . ncg('\\.' . $dec_octet, '{3}');$h16 = cc($HEXDIG, '{1,4}');$ls32 = ncg($h16 . ':' . $h16 . '|' . $IPv4address);$IPv6address = ncg(implode('|', array( ncg($h16 . ':', '{6}') . $ls32, '::' . ncg($h16 . ':', '{5}') . $ls32, ncg($h16, '?') . '::' . ncg($h16 . ':', '{4}') . $ls32, ncg($h16 . ':' . $h16, '?') . '::' . ncg($h16 . ':', '{3}') . $ls32, ncg(ncg($h16 . ':', '{0,2}') . $h16, '?') . '::' . ncg($h16 . ':', '{2}') . $ls32, ncg(ncg($h16 . ':', '{0,3}') . $h16, '?') . '::' . $h16 . ':' . $ls32, ncg(ncg($h16 . ':', '{0,4}') . $h16, '?') . '::' . $ls32, ncg(ncg($h16 . ':', '{0,5}') . $h16, '?') . '::' . $h16, ncg(ncg($h16 . ':', '{0,6}') . $h16, '?') . '::',)));$IPvFuture = 'v' . cc($HEXDIG, '+') . cc($unreserved . $sub_delims . ':', '+');$IP_literal = '\\[' . ncg(implode('|', array($IPv6address, $IPvFuture))) . '\\]';$port = cc($DIGIT, '*');$scheme = cc($ALPHA) . ncg(cc('-' . $ALPHA . $DIGIT . '\\+\\.'), '*');/* New or changed in RFC3987 */$iprivate = '\x{E000}-\x{F8FF}\x{F0000}-\x{FFFFD}\x{100000}-\x{10FFFD}';$ucschar = '\x{A0}-\x{D7FF}\x{F900}-\x{FDCF}\x{FDF0}-\x{FFEF}' . '\x{10000}-\x{1FFFD}\x{20000}-\x{2FFFD}\x{30000}-\x{3FFFD}' . '\x{40000}-\x{4FFFD}\x{50000}-\x{5FFFD}\x{60000}-\x{6FFFD}' . '\x{70000}-\x{7FFFD}\x{80000}-\x{8FFFD}\x{90000}-\x{9FFFD}' . '\x{A0000}-\x{AFFFD}\x{B0000}-\x{BFFFD}\x{C0000}-\x{CFFFD}' . '\x{D0000}-\x{DFFFD}\x{E1000}-\x{EFFFD}';$iunreserved = '-' . $ALPHA . $DIGIT . '\\._~' . $ucschar;$ipchar = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . ':@'));$ifragment = ncg($ipchar . '|' . cc('\\/\\?'), '*');$iquery = ncg($ipchar . '|' . cc($iprivate . '\\/\\?'), '*');$isegment_nz_nc = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . '@'), '+');$isegment_nz = ncg($ipchar, '+');$isegment = ncg($ipchar, '*');$ipath_empty = '(?!' . $ipchar . ')';$ipath_rootless = ncg($isegment_nz) . ncg('\\/' . $isegment, '*');$ipath_noscheme = ncg($isegment_nz_nc) . ncg('\\/' . $isegment, '*');$ipath_absolute = '\\/' . ncg($ipath_rootless, '?'); // Spec says isegment-nz *( "/" isegment )$ipath_abempty = ncg('\\/' . $isegment, '*');$ipath = ncg(implode('|', array( $ipath_abempty, $ipath_absolute, $ipath_noscheme, $ipath_rootless, $ipath_empty))) . ')';$ireg_name = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . '@'), '*');$ihost = ncg(implode('|', array($IP_literal, $IPv4address, $ireg_name)));$iuserinfo = ncg($pct_encoded . '|' . cc($iunreserved . $sub_delims . ':'), '*');$iauthority = ncg($iuserinfo . '@', '?') . $ihost . ncg(':' . $port, '?');$irelative_part = ncg(implode('|', array( '\\/\\/' . $iauthority . $ipath_abempty . '', '' . $ipath_absolute . '', '' . $ipath_noscheme . '', '' . $ipath_empty . '')));$irelative_ref = $irelative_part . ncg('\\?' . $iquery, '?') . ncg('\\#' . $ifragment, '?');$ihier_part = ncg(implode('|', array( '\\/\\/' . $iauthority . $ipath_abempty . '', '' . $ipath_absolute . '', '' . $ipath_rootless . '', '' . $ipath_empty . '')));$absolute_IRI = $scheme . ':' . $ihier_part . ncg('\\?' . $iquery, '?');$IRI = $scheme . ':' . $ihier_part . ncg('\\?' . $iquery, '?') . ncg('\\#' . $ifragment, '?');$IRI_reference = ncg($IRI . '|' . $irelative_ref); Edit 7 March 2011: Because of the way PHP handles backslashes in quoted strings, these are unusable by default. You'll need to double-escape backslashes except where the backslash has a special meaning in regex. You can do that this way: $escape_backslash = '/(?<!\\)\\(?![\[\]\\\^\$\.\|\*\+\(\)QEnrtaefvdwsDWSbAZzB1-9GX]|x\{[0-9a-f]{1,4}\}|\c[A-Z]|)/';$absolute_IRI = preg_replace($escape_backslash, '\\\\', $absolute_IRI);$IRI = preg_replace($escape_backslash, '\\\\', $IRI);$IRI_reference = preg_replace($escape_backslash, '\\\\', $IRI_reference); | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/161738', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1842864/']} | jdg_379531 |
stackexchange | llm_judgeable_groundtruth_similarity | 49637967 |
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 an app that lets users log routes (locations/GPS). To ensure locations are logged even when the screen is off, I have created a foreground service for the location logging. I store the locations in a Room Database which is injected into my service using Dagger2 . However, this service is killed by Android which is, of course, not good. I could subscribe to low memory warnings but that doesn't solve the underlying problem of my service getting killed after ~30 minutes on a modern high-end phone running Android 8.0 I have created a minimal project with only a "Hello world" activity and the service: https://github.com/RandomStuffAndCode/AndroidForegroundService The service is started in my Application class, and route logging is started through a Binder : // Application@Overridepublic void onCreate() { super.onCreate(); mComponent = DaggerAppComponent.builder() .appModule(new AppModule(this)) .build(); Intent startBackgroundIntent = new Intent(); startBackgroundIntent.setClass(this, LocationService.class); startService(startBackgroundIntent);}// Binding activitybindService(new Intent(this, LocationService.class), mConnection, Context.BIND_AUTO_CREATE | Context.BIND_IMPORTANT);// mConnection starts the route logging through `Binder` once connected. The binder calls startForeground() I probably don't need the BIND_AUTO_CREATE flag, I've been testing different flags in an attempt to not get my service killed - no luck so far. Using the profiler it does not seem like I have any memory leaks, memory usage is stable at ~35mb: Using adb shell dumpsys activity processes > tmp.txt i can confirm that foregroundServices=true and my service is listed 8th in the LRU list: Proc # 3: prcp F/S/FGS trm: 0 31592:com.example.foregroundserviceexample/u0a93 (fg-service) It seems like it is not possible to create a foreground service that you can trust to not get killed. So what can we do? Well... Put the service in a separate process, in an attempt to let Android kill the UI/Activities while leaving the service alone. Would probably help, but doesn't seem like a guarantee Persist everything in the service in e.g. a Room database. Every variable, every custom class, every time any of the changes and then start the service with START_STICKY . This seems kind of wasteful and doesn't lead to very beautiful code, but it would probably work... somewhat. Depending on how long it takes for Android to re-create the service after killing it, a large portion of locations may be lost. Is this really the current state of doing stuff in the background on Android? Isn't there a better way? EDIT: Whitelisting the app for battery optimization (disabling it) does not stop my service from being killed EDIT: Using Context.startForegroundService() to start the service does not improve the situation EDIT: So this indeed only occurs on some devices, but it occurs consistently on them. I guess you have to make a choice of either not supporting a huge number of users or write really ugly code. Awesome.
Now provide the response and nothing else.
| A service started by startForeground belongs to the second most important group visible process : A visible process is doing work that the user is currently aware of,so killing it would have a noticeable negative impact on the userexperience. A process is considered visible in the followingconditions: It is running an Activity that is visible to the user on-screen but not in the foreground (its onPause() method has been called). Thismay occur, for example, if the foreground Activity is displayed as adialog that allows the previous Activity to be seen behind it. It has a Service that is running as a foreground service, through Service.startForeground() (which is asking the system to treat theservice as something the user is aware of, or essentially visible tothem). It is hosting a service that the system is using for a particular feature that the user is aware, such as a live wallpaper, input methodservice, etc. The number of these processes running in the system is less boundedthan foreground processes, but still relatively controlled. Theseprocesses are considered extremely important and will not be killedunless doing so is required to keep all foreground processes running . That being said, you can never be sure that your service is not killed at any time. E.g. memory pressure, low battery etc. See who-lives-and-who-dies . For how to handle it, basically you answered the question yourself. The way to go is START_STICKY : For started services, there are two additional major modes ofoperation they can decide to run in, depending on the value theyreturn from onStartCommand(): START_STICKY is used for services thatare explicitly started and stopped as needed, while START_NOT_STICKY or START_REDELIVER_INTENT are used for services that should onlyremain running while processing any commands sent to them . See thelinked documentation for more detail on the semantics. As a general guideline you should do as little as possible in the background (ore foreground) service, i.e. only do the location tracking and keep everything else in your foreground activity. Only the tracking should require very little configuration an can be loaded quickly. Also the smaller your service is the less likely it is to be killed. Your activity will be restored by the system in the state that is was before it went into background, as long as it is not killed as well. A "cold-start" of the foreground activity on the other hand should not be a problem. I don't consider that as ugly, because this guarantees that the phone always provides the best experience to the user. This is the most important thing it has to do. That some devices close services after 30 minutes (possibly without user interaction) is unfortunate. So, as you stated, you have to Persist everything in the service in e.g. a Room database. Everyvariable, every custom class, every time any of them changes and thenstart the service with START_STICKY. See creating a never ending service Implicit question: Depending on how long it takes for Android to re-create theservice after killing it, a large portion of locations may be lost. This usually takes only a really short time. Especially because you can use the Fused Location Provider Api for the location updates, which is an independent system service and very unlikely to be killed. So it mainly depends on the time you need to recreate the service in onStartCommand . Also take note that from Android 8.0 onwards you need to use a forground service because of the background locationlimits . Edit:As recently covered in the news:Some manufacturers may give you a hard time to keep your service running. The site https://dontkillmyapp.com/ keeps track of the manufacturers and possible mitigations for your device. Oneplus is currently (29.01.19) one of the worst offenders. When releasing their 1+5 and 1+6 phones, OnePlus introduced one of themost severe background limits on the market to date, dwarfing eventhose performed by Xiaomi or Huawei. Not only did users need to enableextra settings to make their apps work properly, but those settingseven get reset with firmware update so that apps break again and usersare required to re-enable those settings on a regular basis. Solution for users Turn off System Settings > Apps > Gear Icon > Special Access > BatteryOptimization. sadly there is No known solution on the developer end | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49637967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1202032/']} | jdg_379532 |
stackexchange | llm_judgeable_groundtruth_similarity | 50705680 |
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 following Jenkinsfile : #!groovydef projectPath = "${projectPath}"def specPath = "${specPath}"int numberOfRetries = "${NUM_OF_RETRIES}".toInteger()def failure = truedef retryAmount = 0def start = System.currentTimeMillis()def getSpecName() { specPath.split("/")[-1].split(".")[0]}def getProjectPath() { projectPath.split("/")[-1]}def rmDocker() { def remove = sh script: "docker rm -f cypress_${getSpecName()}", returnStatus: true}stage("Cypress Setup") { node("Cypress") { rmDocker() }}stage("Cypress Run") { node("Cypress") { currentBuild.setDisplayName("${projectPath} - ${getSpecName()}") while (failure && retryAmount < numberOfRetries) { sh "docker pull dockreg.bluestembrands.com/cypresswithtests:latest" if (getSpecName().toLowerCase().contains("auth")) { exit_code = sh script:"docker run --name cypress_${getSpecName()} dockreg.bluestembrands.com/cypresswithtests:latest sh -c \"node SQLSite/request.js & cypress run -P ${projectPath} --spec ${specPath} --env RUN=${retryAmount} --config videoCompression=${videoCompression} --reporter /usr/local/lib/node_modules/mochawesome-cypress-bsb --reporter-options \"reportDir=mochawesome-reports/run${retryAmount}/, reportName=mochawesome\"\"", returnStatus: true } else { exit_code = sh script:"docker run --name cypress_${getSpecName()} dockreg.bluestembrands.com/cypresswithtests:latest sh -c \"cypress run -P ${projectPath} --spec ${specPath} --env RUN=${retryAmount} --config videoCompression=${videoCompression} --reporter /usr/local/lib/node_modules/mochawesome-cypress-bsb --reporter-options \"reportDir=mochawesome-reports/run${retryAmount}/, reportName=mochawesome\"\"", returnStatus: true } failure = exit_code != 0 try { println "/var/docker-mounts/nfs/qa/test-results/${getProjectPath()}-${getSpecName()}/" dir("/var/docker-mounts/nfs/qa/test-results/${getProjectPath()}-${getSpecName()}/") { sh "docker cp cypress_${getSpecName()}:/cypress/${projectPath}/mochawesome-reports /var/docker-mounts/nfs/qa/test-results/${getProjectPath()}-${getSpecName()}/${BUILD_ID}" } } catch (Exception e) { println e echo "Failed to copy Mochawesome tests" } rmDocker() retryAmount++ } } if (failure) { currentBuild.result = "FAILURE" }} It throws following exception when I try to run it: java.lang.StackOverflowError: Excessively nested closures/functions at WorkflowScript.getProjectPath(WorkflowScript:16) - look for unbounded recursion - call depth: 1025 at com.cloudbees.groovy.cps.impl.CpsFunction.invoke(CpsFunction.java:28) at com.cloudbees.groovy.cps.impl.CpsCallableInvocation.invoke(CpsCallableInvocation.java:40) at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:62) at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:109) at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixName(FunctionCallBlock.java:77) at sun.reflect.GeneratedMethodAccessor345.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:497) at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72) at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21) at com.cloudbees.groovy.cps.Next.step(Next.java:83) at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:174) at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:163) at org.codehaus.groovy.runtime.GroovyCategorySupport$ThreadCategoryInfo.use(GroovyCategorySupport.java:122) at org.codehaus.groovy.runtime.GroovyCategorySupport.use(GroovyCategorySupport.java:261) at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:163) at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$101(SandboxContinuable.java:34) at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.lambda$run0$0(SandboxContinuable.java:59) at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox.runInSandbox(GroovySandbox.java:108) at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:58) at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:174) at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:332) at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$200(CpsThreadGroup.java:83) at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:244) at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:232) at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:64) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:131) at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28) at jenkins.security.ImpersonatingExecutorService$1.run(ImpersonatingExecutorService.java:59) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) at java.util.concurrent.FutureTask.run(FutureTask.java:266) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) at java.lang.Thread.run(Thread.java:745) The variables are: NUM_OF_RETRIES: 3 specPath: bsb-haband-web/hab-shop/cypress/integration/Search/SearchNoResultsSpec.js VideoCompression: false projectPath: bsb-haband-web/hab-shop BRANCH_NAME: master I don't understand where the recursion call is happening as getProjectPath just does a standard split call. I have tried changing it to .tokenize() , but it still fails. It might be of note that more than one of these can run at the same times, however the error occurs even if run in isolation. Could you please help me understanding why this StackOverflowError happens?
Now provide the response and nothing else.
| Calling getProjectPath() method causes this exception. It happens, because if Groovy finds a getter method for a field foo like getFoo() it fallbacks to execute this method anytime it sees accessing foo value. What does it mean in your case? When you call the method def getProjectPath() { projectPath.split("/")[-1]} it runs into infinite recursion because this method is seen as: def getProjectPath() { getProjectPath().split("/")[-1]} so it never reaches .split("/")[-1] - that is why replacing it with tokenize() method didn't change a thing. Solution: rename getProjectPath() method or projectPath variable name. Groovy class properties A property is an externally visible feature of a class. Rather than just using a public field to represent such features (which provides a more limited abstraction and would restrict refactoring possibilities), the typical convention in Java is to follow JavaBean conventions, i.e. represent the property using a combination of a private backing field and getters/setters. Source: http://groovy-lang.org/objectorientation.html#properties This part of Groovy's documentation explains this behavior. It can be simplified to an example - a class like: class Person { String name} is compiled to something like this: class Person { private String name void setName(String name) { this.name = name } String getName() { return this.name }} The general rule of thumb when working with Groovy is that when you specify a field foo you implement getFoo() carefully (if you actually have to do it). Especially you avoid accessing field foo inside this method, because it runs into this infinite recursive call issue. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50705680', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9797099/']} | jdg_379533 |
stackexchange | llm_judgeable_groundtruth_similarity | 30981727 |
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 creating some APIs using apiary , so the language used is JSON. Let's assume I need to represent this resource: { "id" : 9, "name" : "test", "customer_id" : 12, "user_id" : 1, "store_id" : 3, "notes" : "Lorem ipsum example long text"} Is it correct to refer to other resources by their IDs ( 12 , 1 , 3 ), or I should specify the URL of these resources (i.e. /customers/12 , /users/1 , /stores/3 )? I am not using HATEOAS and I am a bit confused.
Now provide the response and nothing else.
| DO include absolute entity URIs in your responses (such as /customers/12 or even http://www.example.com/customers/12 ). DO NOT include just an entity's ID (such as 12 ) in a response, because that way you're forcing clients to put together resource URIs themselves. In order to do that, they would need to have prior knowledge of what URIs there are, and you're losing control over the URI space on the server side. (Having the client put together an URI is OK if the server instructs the client how, e.g. by sending a URI template along with the ID; but if it did that, it could just as well send the resulting URI.) See also: Article "REST APIs must be hypertext-driven" by Roy T. Fielding (the originator of REST). Take note especially of these two bullet points: "A REST API should be entered with no prior knowledge beyond the initial URI (bookmark)." "A REST API must not define fixed resource names or hierarchies (an obvious coupling of client and server). Servers must have the freedom to control their own namespace. Instead, allow servers to instruct clients on how to construct appropriate URIs[.]" HAL , which specifies a standard way to put links to related resources into your responses. JSON API — "a specification for building APIs in JSON" The above advice is not just for IDs of other resources (i.e. "foreign keys" such as your customer_id ); you'd also turn the resource's own id into a so-called "self link"; see the SO question "What is the importance of the self link in hypermedia APIs?" . Example: Your original resource could be re-designed as follows: { "type": "foobar", "id": "9", "links": { "self": "//example.com/foobars/9" }, "cashier": { "type": "user", "id": "1", "links": { "self": "//example.com/users/1" } }, "customer": { "type": "customer", "id": "12", "links": { "self": "//example.com/customers/12" } }, "name" : "test", "notes" : "Lorem ipsum example long text", "store": { "type": "store", "id": "3", "links": { "self": "//example.com/stores/3" } }} A few things to note: Each resource (the main object being transferred, but also sub-resources) has some self-descriptive meta-data attached to it, such as type , id , links . Sub-resources can include partial or complete data. As long as the self-link is there, the client knows where to get the complete resource. The type might seem somewhat redudant; often, you implicitly know what kind of object to expect. This property can help in validation, and also gives you the opportunity to distinguish between object type and role (e.g. cashier is-a user in the above example). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30981727', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4063626/']} | jdg_379534 |
stackexchange | llm_judgeable_groundtruth_similarity | 3302227 |
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:
Prove that $$\lim_{n\to \infty}\frac{(-1)^n(n+1)!}{n^{n+1}}=0$$ I noticed that it can be expressed in the form of $n+1$ terms product but I have no idea with the upper bound. I have trouble with how to operate $(-1)^n$
Now provide the response and nothing else.
| Let us ignore the $(-1)^n$ for the time being $$0<\dfrac{(n+1)!}{n^{n+1}}=\dfrac{n+1}n\cdot \prod_{r=2}^n\dfrac rn\cdot\dfrac1n<\dfrac{n+1}n\cdot\dfrac1n$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3302227', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/608383/']} | jdg_379535 |
stackexchange | llm_judgeable_groundtruth_similarity | 45544928 |
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 following this tutorial to use tensorflow serving using my object detection model. I am using tensorflow object detection for generating the model. I have created a frozen model using this exporter (the generated frozen model works using python script). The frozen graph directory has following contents ( nothing on variables directory) variables/ saved_model.pb Now when I try to serve the model using the following command, tensorflow_model_server --port=9000 --model_name=ssd --model_base_path=/serving/ssd_frozen/ It always shows me ... tensorflow_serving/model_servers/server_core.cc:421] (Re-)addingmodel: ssd 2017-08-07 10:22:43.892834: Wtensorflow_serving/sources/storage_path/file_system_storage_path_source.cc:262]No versions of servable ssd found under base path /serving/ssd_frozen/2017-08-07 10:22:44.892901: Wtensorflow_serving/sources/storage_path/file_system_storage_path_source.cc:262]No versions of servable ssd found under base path /serving/ssd_frozen/ ...
Now provide the response and nothing else.
| I had same problem, the reason is because object detection api does not assign version of your model when exporting your detection model. However, tensorflow serving requires you to assign a version number of your detection model, so that you could choose different versions of your models to serve. In your case, you should put your detection model(.pb file and variables folder) under folder:/serving/ssd_frozen/1/. In this way, you will assign your model to version 1, and tensorflow serving will automatically load this version since you only have one version. By default tensorflow serving will automatically serve the latest version(ie, the largest number of versions). Note, after you created 1/ folder, the model_base_path is still need to be set to --model_base_path=/serving/ssd_frozen/. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45544928', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5330223/']} | jdg_379536 |
stackexchange | llm_judgeable_groundtruth_similarity | 40247030 |
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 in my db Brand and Product with the next simple structure: | Brand | id PK | | Product | id PK | brand_id FK | and entities for that tables: @Entity@Table(name = "Brand")public class Brand { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "brand") private String brand; /* getters and setters */} @Entity@Table(name = "Product")public class Product { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "brand_id") private Brand brand; /* getters and setters */} As I use Spring-Data I have repository and service with implementation for Brand: @Repositorypublic interface BrandRepository extends JpaRepository<Brand, Long> { Brand findByBrand(String brand);} public interface BrandService { Brand findByBrand(String brand);} @Servicepublic class BrandServiceImpl implements BrandService { @Autowired private BrandRepository brandRepository; @Override public Brand findByBrand(String brand) { return brandRepository.findByBrand(brand); }} and for Product: @Repositorypublic interface ProductRepository extends JpaRepository<Product, Long> {} public interface ProductService { Product save(Product product);} @Servicepublic class ProductServiceImpl implements ProductService { @Autowired private ProductRepository productRepository; @Override public Product save(Product product) { return productRepository.save(product); }} The goal is to save Product object. Brand object should be saved automatically if it doesn't exist in db or should be set to Product otherwise: Brand brand = brandService.findByBrand(brandName);if (brand == null) { brand = new Brand(); brand.setBrand("Some name");}product.setBrand(brand);productService.save(product); It works fine if Brand object with specified brandName is not in my db. But if it is I get: PersistentObjectException: detached entity passed to persist for Brand. I can change cascade type to MERGE and it will work fine. But if I run the code with MERGE cascade type and Brand object with specified brandName is not in my db I get IllegalStateException:org.hibernate.TransientPropertyValueException:object references an unsaved transient instance - save the transient instance before flushing for Brand (that's really not surprised). What Cascade Type should be? Ot what I did wrong?
Now provide the response and nothing else.
| Short answer: There is no problem with your cascade annotation. You should not rely on automatic cascade and implement this logic by hand and inside your service layer. Long answer: You have two scenarios: Scenario 1 - CascadeType.ALL + existing brand = detached entitypassed to persist Scenario 2 - CascadeType.MERGE + new brand = savethe transient instance before flushin Scenario 1 happens because JPA is trying to persist BRAND after persist PRODUCT (CascadeType.ALL). Once BRAND already exists you got an error. Scenario 2 happend because JPA is not trying to persist BRAND (CascadeType.MERGE) and BRAND was not persisted before. It's hard to figure out a solution because there are so many abstraction layers. Spring data abstracts JPA that abstracts Hibernate that abstracts JDBC and so on. A possible solution would be use EntityManager.merge instead of EntityManager.persist so that CascadeType.MERGE could work. I belive you can do that re-implementing Spring Data save method. There is some reference about that here : Spring Data: Override save method Another solution would be the short answer. Example: @Overridepublic Product save(Product product, String brandName) { Brand brand = brandService.findByBrand(brandName); if (brand == null) { brand = brandService.save(brandName); } return productRepository.save(product);} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40247030', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7070820/']} | jdg_379537 |
stackexchange | llm_judgeable_groundtruth_similarity | 33891669 |
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 all I know, I have to write request in action create. How to use a promise in action for submitting a request? I am getting data in action. Then new state is created in reducer. Bind action and reducer in connect. But I don't know how to use promise for request. Action import $ from 'jquery';export const GET_BOOK = 'GET_BOOK';export default function getBook() { return { type: GET_BOOK, data: $.ajax({ method: "GET", url: "/api/data", dataType: "json" }).success(function(data){ return data; }) };} Reducer import {GET_BOOK} from '../actions/books';const booksReducer = (state = initialState, action) => { switch (action.type) { case GET_BOOK: return state; default: return state; }};export default booksReducer; Container How display data in container? import React, { Component, PropTypes } from 'react';import { connect } from 'react-redux';import getBook from '../actions/books';import Radium from 'radium';import {Link} from 'react-router';function mapStateToProps(state) { return { books: state.data.books, };}function mapDispatchToProps(dispatch) { return { getBooks: () => dispatch(getBook()), };}@Radium@connect(mapStateToProps, mapDispatchToProps)class booksPage extends Component { static propTypes = { getBooks: PropTypes.func.isRequired, books: PropTypes.array.isRequired, }; render() { const {books} = this.props; return ( <div> <Link to={`/authors`}><MUIButton style="flat">All Authors</MUIButton></Link> <ul> {books.map((book, index) => <li key={index}> <Link to={`/book/${book.name}`}><MUIButton style="flat"><div class="mui--text-black mui--text-display4"> "{book.name}"</div></MUIButton></Link> <Link to={`/author/${book.author}`}><MUIButton style="flat"><div class="mui--text-black mui--text-display4"> {book.author}</div></MUIButton></Link> </li> )} </ul> </div> ); }}export default booksPage;
Now provide the response and nothing else.
| Since you are already using redux you can apply redux-thunk middleware which allows you to define async actions. Installation & usage: Redux-thunk export function fetchBook(id) { return dispatch => { dispatch(setLoadingBookState()); // Show a loading spinner fetch(`/book/${id}`, (response) => { dispatch(doneFetchingBook()); // Hide loading spinner if(response.status == 200){ dispatch(setBook(response.json)); // Use a normal function to set the received state }else { dispatch(someError) } }) }}function setBook(data) { return { type: 'SET_BOOK', data: data };} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33891669', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5599188/']} | jdg_379538 |
stackexchange | llm_judgeable_groundtruth_similarity | 16413633 |
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 create a bar like this initially when progress is zero it will be a fade in color but and as progress goes on it will become bright on that part(This is best I can explain) main thing is i want bar to show all colors at the same time.
Now provide the response and nothing else.
| Clip your "on" drawable: over your "off" drawable: by using res/drawable/custom_progress_drawable.xml <layer-list xmlns:android="http://schemas.android.com/apk/res/android" > <!-- Background --> <item android:id="@android:id/background" android:drawable="@drawable/custom_progress_bar_off"/> <!-- Secondary progress - this is optional --> <item android:id="@android:id/secondaryProgress"> <clip android:drawable="@drawable/custom_progress_bar_secondary" /> </item> <!-- Progress --> <item android:id="@android:id/progress"> <clip android:drawable="@drawable/custom_progress_bar_on" /> </item></layer-list> From an Activity , use Drawable progressDrawable = ResourcesCompat.getDrawable(getResources(), R.drawable.custom_progress_drawable, getTheme());myProgressBar.setProgressDrawable(progressDrawable); or in xml, use android:progressDrawable="@drawable/custom_progress_drawable" And here's the result when using android:max="10" in xml: It's a little bit off, but you could use setMax() with something more like 10000 and do some offsetting calculations when calling setProgress() to make it cleaner. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16413633', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/540393/']} | jdg_379539 |
stackexchange | llm_judgeable_groundtruth_similarity | 13402094 |
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'm semi new to java and I am making a pong game. I want to do it completely by myself, but I've come to a problem. I have got 2 classes so far. My main one, and one which contains information about the ball. My main class is as follows: import java.awt.Canvas;import java.awt.Color;import java.awt.DisplayMode;import java.awt.Graphics;import java.awt.Graphics2D;import java.awt.image.BufferStrategy;import javax.swing.JFrame;public class Main extends Canvas implements Runnable{ private static final long serialVersionUID = 1L; public static int Width=800; public static int Height=600; public boolean Running=false; public Thread thread; public Ball ball; public int BallX = ball.BallLocationX; public int BallY = ball.BallLocationY; public static void main(String[] args){ Main game = new Main(); JFrame frame = new JFrame(); frame.setSize(Width, Height); frame.setTitle("Pong By Poo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); frame.setVisible(true); frame.setLocationRelativeTo(null); frame.add(game); game.start(); } public void start(){ if(Running==true){ return; } else { Running=true; thread = new Thread(this); thread.start(); } } public void run(){ while(Running==true){ Draw(); } } public void Draw(){ BufferStrategy bs = this.getBufferStrategy(); if(bs==null){ createBufferStrategy(2); }else{ Graphics g = bs.getDrawGraphics(); g.setColor(Color.BLACK); g.fillOval(BallX, BallY, 10, 10); } }} And my ball class is this: **import java.awt.Color;import java.awt.Graphics;import javax.swing.JPanel;public class Ball extends JPanel{ public int BallLocationX; public int BallLocationY; public boolean BallMovementY; //true makes the ball go up, false makes it go down public boolean BallMovementX; //True makes the ball go right, false makes it go left. public void paintComponent(Graphics g){ super.paintComponent(g); g.setColor(Color.BLACK); g.fillOval(BallLocationX, BallLocationY, 10, 10); } //moves the ball left to right public int YVelocity(){ if(BallMovementY==true){ BallLocationY++; } else{ BallLocationY--; } return BallLocationY; } //Moves the ball up and down public int XVelocity(){ if(BallMovementX==true){ BallLocationX++; } else{ BallLocationX--; } return BallLocationX; }}** Im trying to draw the ball on the screen inside my main class, useing the location of the ball which I get from the ball class.I know that (As of yet) The ball wont move, Ill figure that out later. My probmlem is that it wont draw the ball on screen, getting me this error: Exception in thread "main" java.lang.NullPointerException at Main.<init>(Main.java:20) at Main.main(Main.java:26) Thanks!
Now provide the response and nothing else.
| public Ball ball; // ball is not initializedpublic int BallX = ball.BallLocationX; // NPE herepublic int BallY = ball.BallLocationY; Here's the problem. In your instance variable declaration, your ball is still pointing to null and you have used it to access BallLocationX . It will throw a NPE . You should initialize your ball reference to point to an instance of Ball first: - public Ball ball = new Ball(); // Or whatever way you use to instantiate itpublic int BallX = ball.BallLocationX;public int BallY = ball.BallLocationY; An Advice : - I just noticed that, you have used public modifier for all your fields . You should not do that. As far as possible, try to have private modifier for your fields, and provide public accessors toaccess them. ( getters and setters ). Also, follow Java Naming Conventions. Variable names should start with lowercase alphabets/underscore/dollar symbol (Change BallX to ballX and BallLocationX to ballLocationX ) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13402094', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1827253/']} | jdg_379540 |
Subsets and Splits