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 | 79615 |
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:
Would the excess charge on a conductor move to surface until the electric field inside become zero if the Coulomb law was for example $\frac{1}{r^3}$? If yes, would the distribution $\sigma(x,y)$ be different from when it is $\frac{1}{r^2}$?
Now provide the response and nothing else.
| James Clerk Maxwell thought about this one and showed the following. Suppose we have two concentric conducting spheres and we charge one up to a potential $\Phi$ relative to some grounding plane. Then the voltage of the inner sphere relative to the same ground is: $$\Phi_{inner} = \Phi \,q\, \left(\frac{\rho}{2}\log\left(\frac{\rho+1}{\rho-1}\right)-\frac{1}{2}\log\left(\frac{4\,\rho^2}{\rho^2-1}\right)\right)\quad\quad\quad(1)$$ where $\rho = r_{outer} / r_{inner}$ is the ratio of the radiuses of the outer to inner spheres and $q$ is the deviation between the power of $r$ in the Coulomb law and 2 . Thus, the radial dependence in Coulomb's law is $r^{-(2\pm q)}$; if there is exactly inverse square dependence, then $q=0$. This fact has been used to test the Coulomb law to high precision, see: Plimpton, S. J.; Lawton, W. E., "A Very Accurate Test of Coulomb's Law of Force Between Charges", Physical Review, vol. 50 (1936), Issue 11, pp. 1066-1071 If the photon has a mass $m$, the Coulomb $1/r$ potential generalises to a Yukawa potential : $$\Phi = -\frac{q}{4\,\pi\,\epsilon_0} \frac{\exp\left(-\frac{m\,c}{\hbar}\,r\right)}{r}\quad\quad\quad(2)$$ and so the experiment described can be used to bound the photon mass. According to Wikipedia (see the "Experimental checks on photon mass" on the "Photon" page) , this bound is $10^{-14}\mathrm{eV}/c^2$, or about $1.6\times10^{-50}\mathrm{kg}$, i.e. about $10^{-20}$ electron masses. So now I'd like to show how to relate the Coulomb-Yukawa potential and the photon mass, and show how to interpret the experimental null result. A good review paper (at least it was clear to me) here is: Liang-Cheng Tu and Jun Luo, "Experimental tests of Coulomb’s Law and the photon rest mass", Metrologia 41 (2004) pp136–146 It is much easier, and equivalent, to talk about this kind of thing in terms of potentials rather than forces (assuming we have irrotational forces). Also, the following discussion in terms of photon mass is actually a much simpler framework to talk about straight deviations from the postulated $1/r$ Coulomb potential than Maxwell's (incidentally, the Maxwell expression (1) is derived in the review paper as well). Instead of talking about a deviation $q$ of the power $1/r^{1\pm q}$ in the Coulomb potential law from its postulated power as Maxwell does, we speak of a multiplicative error factor $f(r) \approx 1+\epsilon_1\,r\approx e^{\epsilon\,r}$ (the approximation holding for $r \ll 1/\epsilon$) so that we assume our actual potential law is $e^{\epsilon\,r}/r$ rather than $1/r$. The photon mass would make itself felt by changing the propagation equation for the electromagnetic potentials from the massless wave equation to the Maxwell-Proca equations (see the Wikipedia page for "Proca Action" ): $$\nabla^2 A_\mu - \frac{1}{c^2}\,\partial_t^2 A_\mu - \left(\frac{m\,c}{\hbar}\right)^2\,A_\mu = -\mu_0 J_\mu\quad\quad\quad(3)$$ where $J_\mu$ is the four-current source for the field. To understand that the scaling constant $m^2\,c^2/\hbar^2$ in the new term $m^2\,c^2\,A_\mu /\hbar^2$ has the interpretation of being a mass, we can: Make the observation that in freespace $\hbar^2 \nabla^2 - \hbar^2 \partial_t^2/c^2$ is the operator (quantum observable) equivalent to the squared length of the four-momentum $E^2 /c^2 - |\vec{p}|^2$, which is the proper (rest mass) term $m^2 c^2$; or Think of the solution to freespace version of (3) ($J_\mu = 0$) as a Fourier decomposition into plane waves: plane wave (wavenumber $k$), time harmonic (frequency $\omega$) solutions of (3) are defined by $$\omega = \pm \sqrt{k^2 +\frac{m^2\,c^2}{\hbar^2}}\,c\quad\quad\quad(4)$$ which is, of course $\omega = c\,|k|$ when the mass is nought, whence the group speed equals the phase speed equals $c$. But with nonzero $m$, the group speed for low frequencies $k \ll m\,c/\hbar$ is nought, and a wavepacket can stand roughly still for a time that is proportional to the $m$ term. So now we look at the static situation ($\partial_t = 0$) for the electrostatic charge so that (3) becomes $$\left(\nabla^2 - \left(\frac{m\,c}{\hbar}\right)^2\right)\,\Phi = \frac{\rho}{\epsilon_0}\quad\quad\quad(5)$$ and the Yukawa potential (2) is the relevant Green's function for this equation, i.e. the solution to $$\left(\nabla^2 - \left(\frac{m\,c}{\hbar}\right)^2\right)\,\Phi = \delta(\vec{r})\quad\quad\quad(6)$$ whence we can build up fields arising from general charge distributions $\rho$ by linear superposition: $$\Phi(\vec{r}) = -\frac{1}{4\,\pi\,\epsilon_0} \int_V \rho(\vec{r}^\prime)\frac{\exp\left(-\frac{m\,c}{\hbar}\,|\vec{r} -\vec{r}^\prime|\right)}{|\vec{r} -\vec{r}^\prime|}\,\mathrm{d}V^\prime\quad\quad\quad(7)$$ Note that the static field in freespace away from the charge for any distrubution of charges each having the Yukawa potential (2) still fulfills the freespace equation $$\left(\nabla^2 - \left(\frac{m\,c}{\hbar}\right)^2\right)\,\Phi = 0\quad\quad\quad(8)$$ by linear superposition: $\nabla^2$ is unaffected by either a shift in the origin or a rotation of the relevant co-ordinate system. Notice that we could not say the same thing if, say, we had $\Phi\propto 1/r^n$ for $n\neq 1$, because then the relevant differential equation would be: $$\nabla^2 \Phi -\frac{n\,(n-1)}{r^2} \Phi = 0\quad\quad\quad(9)$$ and the factor $n\,(n-1)/r^2$ most certainly changes its form in response to shifts in the origin. The Coulomb and Yukawa potentials are special insofar that they are the Green's function of constant co-efficient, linear partial differential equations. Now we look at a hollow conductor. The first thing to note here is that the uniqueness theorems for Laplace's equaton and the static Maxwell-Proca potential equation work in exactly the same way. If we know the potential on the boundary $\partial V$ of a volume $V$, then if there are no singlarities in $V$, we suppose there were two real valued solutions $\phi_1$ and $\phi_2$ with the same behaviour on $\partial V$ and we apply Gauss's divergence theorem to $\psi\,\nabla \phi$ where $\phi = \phi_1-\phi_2$ (noting $\phi$ on $\partial V$ is nought by assumption): $$0 = \oint_{\partial V} \phi\,\nabla\phi\cdot \hat{\vec{n}} \mathrm{d}S = \int_V\left( |\nabla \phi|^2 + \phi \nabla^2 \phi\right)\,\mathrm{d} V = \int_V \left(|\nabla \phi|^2 + \frac{m^2\,c^2}{\hbar^2}|\phi|^2\right)\,\mathrm{d} V\quad\quad\quad(10)$$ so that $\phi$ must be nought throughout $V$ since the integrand on the RHS is positive or nought, i.e. we have proven uniqueness given we can find a solution in the first place. For a perfect conductor, any charges inside will shift until there is no force tangential to the conductor's surface ($i.e.$ the charges move feely until tethered by the surface), for otherwise they could further re-arrange themselves (by moving along the surface). So the electric field is always orthogonal to a conductor's surface - this fact is independent of the form of the Coulomb law. So the inner surface of any hollow conductor is always an equipotential surface, independent of the form of the elctrostatic force law (as long as the force from a lone charge is radially directed towards or away from the charge). Now, in the case of the $\Phi = 1/r$ potential, if the potential on the hollow inside surface is $\Phi_0$, then a constant potential of $\Phi_0$ is a solution of Laplace's equation and, by the foregoing discussion, it is the only solution fulfilling our boundary conditions. So $\nabla \Phi = 0$ and there is no electric field inside the conductor. So now we do the same for the static Maxwell-Proca potential. We consider a hollow sphere of radius $R$ and we charge it up to a monstrous voltage $\Phi_0$. Then a nonsingular, axissymetric solution to (8) inside the hollow is: $$\Phi(r) = \Phi_0\,\frac{R_0\,\sinh\left(\frac{m\,c}{\hbar} r\right)}{r\,\sinh\left(\frac{m\,c}{\hbar} R_0\right)}\quad\quad\quad(11)$$ and, by the foregoing, this must be the only solution. Notice that, as an aside, the solutions to this problem are the Helmholtz equation solutions, to wit, spherical Bessel functions, but for imaginary wavenumbers, since the static Maxwell-Proca potential equation is the Helmholtz equation with an imaginary $k$. The electric field inside our sphere is: $$\vec{E}= R_0\,\Phi_0\,\frac{\sinh\left(\frac{m\,c}{\hbar} r\right) - \frac{m\,c\,r}{\hbar} \cosh\left(\frac{m\,c}{\hbar} r\right)}{r^3\,\sinh\left(\frac{m\,c}{\hbar} R_0\right)}\vec{r}\approx \frac{m^2 c^2\,\Phi_0}{3\,\hbar^2}\,\vec{r}\quad\quad\quad(12)$$ so suppose we charge a one metre radius sphere to a million volts and measure no electric field with a probe just inside the sphere, accurate to within, say, 100 volts per metre. Then the experiment has yielded an upper bound on the photon mass of: $$m < \sqrt{\frac{3\times 100\mathrm{V\,m^{-1}}}{10^6\mathrm{V}\times1\mathrm{m}}} \times \frac{\hbar}{c} = 6\times 10^{-45}\mathrm{kg}$$ Notice also that, by the uniqueness theorem we looked at above, the experimental result does not hinge on the sphere's being exactly spherical. We can numerically solve the Maxwell-Proca potential equation for distorted spheres and thus test the sensitivity of our experiment to such distortions. The above figures represent a very crude and easy experiment in a modern high voltage laboratory. As noted in Wikipedia, the actual photon mass bound acheived by this experiment is about six orders of magnitude smaller than this ($1.6\times10^{-50}\mathrm{kg}$), the photon mass bound achievable by any current method (observation of the galactic plasma) is about thirteen orders of magnitude smaller again ($10^{-63}\mathrm{kg}$) and lastly, as noted in the Liang-Cheng Tu and Jun Luo paper, for the present universe the maximum achievable accuracy for measuring the energy (mass) of something can be reckonned with the Heisenberg inequality $\Delta E \Delta t \geq \frac{\hbar}{2}$ with $\Delta t$ set to the age of the universe ($4\times10^{17}$ seconds), so the minumum achievable mass bound is $\hbar/(2\,c^2\,\Delta t)\approx 10^{-69}\mathrm{kg}$. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/79615', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/21108/']} | jdg_84341 |
stackexchange | llm_judgeable_groundtruth_similarity | 701325 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have read a passage in Wikipedia about the List of unsolved problems in physics and dimensionless physical constants: Dimensionless physical constants : At the present time, the values of various dimensionless physical constants cannot be calculated; they can be determined only by physical measurement .[4][5] What is the minimum number of dimensionless physical constants from which all other dimensionless physical constants can be derived? Are dimensional physical constants necessary at all? One of these fundamental physical constants is the Fine-Structure Constant . But why does Wikipedia say that these constants, such as the fine-structure constant, can be only measured and not theoretically calculated? The fine-structure constant $α$ as far as I know for the electromagnetic force for example can be theoretically calculated by this expression: $$\alpha=\frac{e^{2}}{4 \pi \varepsilon_{0} \hbar c} \approx \frac{1}{137.03599908}$$ So why then does Wikipedia say that it can only measured but not calculated? I don't understand the meaning of this above-quoted Wikipedia text?
Now provide the response and nothing else.
| In "natural units", we set $\hbar=c=\epsilon_0=1$ . In these units, the equation you wrote down becomes \begin{equation}\alpha = \frac{e^2}{4\pi}\end{equation} In this notation, it is perhaps more obvious that the equation you wrote down is not really a way to calculate $\alpha$ , since $\alpha$ depends on another dimensionless constant $e^2$ that we do not know how to calculate. In fact, you can read this equation as defining $e^2$ , given $\alpha$ . The dream of "calculating $\alpha$ from first principles" would be to have a formula where $\alpha$ was expressed purely in terms of mathematical constants like $2$ and $\pi$ . | {} | {'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/701325', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/183646/']} | jdg_84342 |
stackexchange | llm_judgeable_groundtruth_similarity | 15127989 |
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 new to perl and seeking the lowest value in an @array . Is there some constant that represents a very large integer number? I know I could sort the array and take the beginning, but that seems to be a lot of wasted CPU cycles. What is an elegant solution to my problem in Perl?
Now provide the response and nothing else.
| In the general case, you can use undef to signal a non-existent value; perl scalars aren't restricted to holding just integers. That would be written: my $min; # undef by defaultfor my $value (@array) { $min = $value if !defined $min or $value < $min;} But there are some simpler options here. For example, initialize $min to the first value in the array, then compare to the rest: my $min = $array[0];for my $i (1 .. $#array) { $min = $array[$i] if $array[$i] < $min;} Or just use a built-in function: use List::Util 'min';my $min = min @array; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15127989', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/365338/']} | jdg_84343 |
stackexchange | llm_judgeable_groundtruth_similarity | 10876015 |
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 some help to understand when I can expect my broadcast receiver will work when just registered in the manifest versus having to be registered from a running activity or service. So for example if I register a stand alone receiver with the following intent filter it works without having a service/activity reference to it: <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.blk_burn.standalonereceiver" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" /> <uses-permission android:name="android.permission.WAKE_LOCK"/> <application android:icon="@drawable/ic_launcher" android:label="@string/app_name" > <receiver android:name="TestReceiver"> <intent-filter> <action android:name="android.media.AUDIO_BECOMING_NOISY"/> </intent-filter> </receiver> </application></manifest> However if I replace android.media.AUDIO_BECOMING_NOISY with android.intent.action.HEADSET_PLUG the receiver is not triggered ( Android Documentation ) From what I found on this site you have to register this receiver from an activity or service that is already running for it to work ( Post ). Can anyone tell me why this does not work when just adjusting your intent filter in the manifest and why you need to have a service running in the background that references/registers the receiver? Is there a work around so that I can just register my receiver in my app's manifest using an intent filter with android.intent.action.HEADSET_PLUG ? How can do I identify which Broadcast actions from the android documentation need to have a service or activity register them versus just having the right filter in the manifest?
Now provide the response and nothing else.
| If your receiver is registered in the manifest, and your app is not running, a new process will be created to handle the broadcast. If you register it in code, it's tied to the life of the activity/service you registered it in. For some broadcasts, it doesn't really make sense to create a new app process if it doesn't exist, or there are some security, performance, etc. implications, and thus you can only register the receiver in code. As for the HEADSET_PLUG broadcast, it seems the idea is that your already running app can get this to do app-specific adjustments to UI, volume, etc. If your app is not running, you shouldn't really care about the headphones being unplugged. AFAIK, there is no single place this info is summarized for all broadcasts, but each Intent should have a comment in the JavaDoc about how to register and use it, but apparently it's lacking in places. You should be able to compile a list if you grep the Android source tree for Intent.FLAG_RECEIVER_REGISTERED_ONLY . | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/10876015', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1159192/']} | jdg_84344 |
stackexchange | llm_judgeable_groundtruth_similarity | 1354999 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My web application uses sessions to store information about the user once they've logged in, and to maintain that information as they travel from page to page within the app. In this specific application, I'm storing the user_id , first_name and last_name of the person. I'd like to offer a "Keep Me Logged In" option on log in that will put a cookie on the user's machine for two weeks, that will restart their session with the same details when they return to the app. What is the best approach for doing this? I don't want to store their user_id in the cookie, as it seems like that would make it easy for one user to try and forge the identity of another user.
Now provide the response and nothing else.
| OK, let me put this bluntly: if you're putting user data, or anything derived from user data into a cookie for this purpose, you're doing something wrong. There. I said it. Now we can move on to the actual answer. What's wrong with hashing user data, you ask? Well, it comes down to exposure surface and security through obscurity. Imagine for a second that you're an attacker. You see a cryptographic cookie set for the remember-me on your session. It's 32 characters wide. Gee. That may be an MD5... Let's also imagine for a second that they know the algorithm that you used. For example: md5(salt+username+ip+salt) Now, all an attacker needs to do is brute force the "salt" (which isn't really a salt, but more on that later), and he can now generate all the fake tokens he wants with any username for his IP address! But brute-forcing a salt is hard, right? Absolutely. But modern day GPUs are exceedingly good at it. And unless you use sufficient randomness in it (make it large enough), it's going to fall quickly, and with it the keys to your castle. In short, the only thing protecting you is the salt, which isn't really protecting you as much as you think. But Wait! All of that was predicated that the attacker knows the algorithm! If it's secret and confusing, then you're safe, right? WRONG . That line of thinking has a name: Security Through Obscurity , which should NEVER be relied upon. The Better Way The better way is to never let a user's information leave the server, except for the id. When the user logs in, generate a large (128 to 256 bit) random token. Add that to a database table which maps the token to the userid, and then send it to the client in the cookie. What if the attacker guesses the random token of another user? Well, let's do some math here. We're generating a 128 bit random token. That means that there are: possibilities = 2^128possibilities = 3.4 * 10^38 Now, to show how absurdly large that number is, let's imagine every server on the internet (let's say 50,000,000 today) trying to brute-force that number at a rate of 1,000,000,000 per second each. In reality your servers would melt under such load, but let's play this out. guesses_per_second = servers * guessesguesses_per_second = 50,000,000 * 1,000,000,000guesses_per_second = 50,000,000,000,000,000 So 50 quadrillion guesses per second. That's fast! Right? time_to_guess = possibilities / guesses_per_secondtime_to_guess = 3.4e38 / 50,000,000,000,000,000time_to_guess = 6,800,000,000,000,000,000,000 So 6.8 sextillion seconds... Let's try to bring that down to more friendly numbers. 215,626,585,489,599 years Or even better: 47917 times the age of the universe Yes, that's 47917 times the age of the universe... Basically, it's not going to be cracked. So to sum up: The better approach that I recommend is to store the cookie with three parts. function onLogin($user) { $token = GenerateRandomToken(); // generate a token, should be 128 - 256 bit storeTokenForUser($user, $token); $cookie = $user . ':' . $token; $mac = hash_hmac('sha256', $cookie, SECRET_KEY); $cookie .= ':' . $mac; setcookie('rememberme', $cookie);} Then, to validate: function rememberMe() { $cookie = isset($_COOKIE['rememberme']) ? $_COOKIE['rememberme'] : ''; if ($cookie) { list ($user, $token, $mac) = explode(':', $cookie); if (!hash_equals(hash_hmac('sha256', $user . ':' . $token, SECRET_KEY), $mac)) { return false; } $usertoken = fetchTokenByUserName($user); if (hash_equals($usertoken, $token)) { logUserIn($user); } }} Note: Do not use the token or combination of user and token to lookup a record in your database. Always be sure to fetch a record based on the user and use a timing-safe comparison function to compare the fetched token afterwards. More about timing attacks . Now, it's very important that the SECRET_KEY be a cryptographic secret (generated by something like /dev/urandom and/or derived from a high-entropy input). Also, GenerateRandomToken() needs to be a strong random source ( mt_rand() is not nearly strong enough. Use a library, such as RandomLib or random_compat , or mcrypt_create_iv() with DEV_URANDOM )... The hash_equals() is to prevent timing attacks .If you use a PHP version below PHP 5.6 the function hash_equals() is not supported. In this case you can replace hash_equals() with the timingSafeCompare function: /** * A timing safe equals comparison * * To prevent leaking length information, it is important * that user input is always used as the second parameter. * * @param string $safe The internal (safe) value to be checked * @param string $user The user submitted (unsafe) value * * @return boolean True if the two strings are identical. */function timingSafeCompare($safe, $user) { if (function_exists('hash_equals')) { return hash_equals($safe, $user); // PHP 5.6 } // Prevent issues if string length is 0 $safe .= chr(0); $user .= chr(0); // mbstring.func_overload can make strlen() return invalid numbers // when operating on raw binary strings; force an 8bit charset here: if (function_exists('mb_strlen')) { $safeLen = mb_strlen($safe, '8bit'); $userLen = mb_strlen($user, '8bit'); } else { $safeLen = strlen($safe); $userLen = strlen($user); } // Set the result to the difference between the lengths $result = $safeLen - $userLen; // Note that we ALWAYS iterate over the user-supplied length // This is to prevent leaking length information for ($i = 0; $i < $userLen; $i++) { // Using % here is a trick to prevent notices // It's safe, since if the lengths are different // $result is already non-0 $result |= (ord($safe[$i % $safeLen]) ^ ord($user[$i])); } // They are only identical strings if $result is exactly 0... return $result === 0;} | {} | {'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/1354999', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/55619/']} | jdg_84345 |
stackexchange | llm_judgeable_groundtruth_similarity | 30399534 |
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 question contains its own answer at the bottom. Use preallocated arrays. Following-up from this question years ago, is there a canonical "shift" function in numpy? I don't see anything from the documentation . Here's a simple version of what I'm looking for: def shift(xs, n): if n >= 0: return np.r_[np.full(n, np.nan), xs[:-n]] else: return np.r_[xs[-n:], np.full(-n, np.nan)] Using this is like: In [76]: xsOut[76]: array([ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9.])In [77]: shift(xs, 3)Out[77]: array([ nan, nan, nan, 0., 1., 2., 3., 4., 5., 6.])In [78]: shift(xs, -3)Out[78]: array([ 3., 4., 5., 6., 7., 8., 9., nan, nan, nan]) This question came from my attempt to write a fast rolling_product yesterday. I needed a way to "shift" a cumulative product and all I could think of was to replicate the logic in np.roll() . So np.concatenate() is much faster than np.r_[] . This version of the function performs a lot better: def shift(xs, n): if n >= 0: return np.concatenate((np.full(n, np.nan), xs[:-n])) else: return np.concatenate((xs[-n:], np.full(-n, np.nan))) An even faster version simply pre-allocates the array: def shift(xs, n): e = np.empty_like(xs) if n >= 0: e[:n] = np.nan e[n:] = xs[:-n] else: e[n:] = np.nan e[:n] = xs[-n:] return e The above proposal is the answer. Use preallocated arrays.
Now provide the response and nothing else.
| For those who want to just copy and paste the fastest implementation of shift, there is a benchmark and conclusion(see the end). In addition, I introduce fill_value parameter and fix some bugs. Benchmark import numpy as npimport timeit# enhanced from IronManMark20 versiondef shift1(arr, num, fill_value=np.nan): arr = np.roll(arr,num) if num < 0: arr[num:] = fill_value elif num > 0: arr[:num] = fill_value return arr# use np.roll and np.put by IronManMark20def shift2(arr,num): arr=np.roll(arr,num) if num<0: np.put(arr,range(len(arr)+num,len(arr)),np.nan) elif num > 0: np.put(arr,range(num),np.nan) return arr# use np.pad and slice by me.def shift3(arr, num, fill_value=np.nan): l = len(arr) if num < 0: arr = np.pad(arr, (0, abs(num)), mode='constant', constant_values=(fill_value,))[:-num] elif num > 0: arr = np.pad(arr, (num, 0), mode='constant', constant_values=(fill_value,))[:-num] return arr# use np.concatenate and np.full by chrisaycockdef shift4(arr, num, fill_value=np.nan): if num >= 0: return np.concatenate((np.full(num, fill_value), arr[:-num])) else: return np.concatenate((arr[-num:], np.full(-num, fill_value)))# preallocate empty array and assign slice by chrisaycockdef shift5(arr, num, fill_value=np.nan): result = np.empty_like(arr) if num > 0: result[:num] = fill_value result[num:] = arr[:-num] elif num < 0: result[num:] = fill_value result[:num] = arr[-num:] else: result[:] = arr return resultarr = np.arange(2000).astype(float)def benchmark_shift1(): shift1(arr, 3)def benchmark_shift2(): shift2(arr, 3)def benchmark_shift3(): shift3(arr, 3)def benchmark_shift4(): shift4(arr, 3)def benchmark_shift5(): shift5(arr, 3)benchmark_set = ['benchmark_shift1', 'benchmark_shift2', 'benchmark_shift3', 'benchmark_shift4', 'benchmark_shift5']for x in benchmark_set: number = 10000 t = timeit.timeit('%s()' % x, 'from __main__ import %s' % x, number=number) print '%s time: %f' % (x, t) benchmark result: benchmark_shift1 time: 0.265238benchmark_shift2 time: 0.285175benchmark_shift3 time: 0.473890benchmark_shift4 time: 0.099049benchmark_shift5 time: 0.052836 Conclusion shift5 is winner! It's OP's third solution. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/30399534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/478288/']} | jdg_84346 |
stackexchange | llm_judgeable_groundtruth_similarity | 41476 |
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:
Consider electromagnetism, an abelian gauge theory, with a massive photon. Is the massless limit equal to electromagnetism? What does it happen at the quantum level with the extra degree of freedom? And, what does it happen at the classical level? We ca not get an extra massless classical scalar field, do we?
Now provide the response and nothing else.
| There is a simple way to understand the massive electrodynamics Lagrangian and limit, which is the Stueckelberg (Affine Higgs) mechanism. This is matematically equivalent to DJBunk's answer, but it is slightly more intuitive physically. Consider an Abelian Higgs model, with a massless electrodynamic vector potential $A$ and a scalar field with a $\phi^4$ potential $$ S = \int |F|^2 + |D\phi|^2 + \lambda (\phi^2 - a)^2 $$ Then consider the limit that the charge e on $\phi$ goes to zero while the mass of the Higgs goes to infinity ($a\rightarrow\infty$), in such a way that the product $ea$ stays constant. In this limit, you can write the complex scalar as: $$ \phi = R e^{i\theta}$$ And the R excitations have a mass that goes as a, and goes to infinity, while the $\theta$ excitations are eaten by the A field and together make a gauge boson of mass ea. This is the massive electrodynamics model, and this limit shows why it is renormalizable--- you can take e to zero in a U(1) gauge theory, because there is no charge quantization. In this model, it is obvious what the massless limit of massive electromagnetism is: this is the limit that $e=0$ for the Higgs field. In this case, the Higgs is decoupled from the gauge field, and you just have a massless gauge field. The longitudinal degree of freedom just decouples. This is the clearest way to see why it must be so in my opinion. When the mass is small, the longitudinal degree of freedom, the one that comes from the infinitely heavy Higgs in this model, is almost decoupled, so that the limit is smooth. The theory can be analyzed by starting with the massless electromagnetism and adding the Higgs field as a perturbation (so long as you work in the effective potential formalism). | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/41476', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/1335/']} | jdg_84347 |
stackexchange | llm_judgeable_groundtruth_similarity | 114925 |
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:
In a log file, I need to print the Elapsed time, in the following format: "Process completed %s - Elapsed %s",<time now in HH:MM:SS format>,<difference from start date to end date in HH:MM:SS format> Example: Process completed 23:57:59 - Elapsed 103:22:59 How could I achieve this?
Now provide the response and nothing else.
| Ksh has a special parameter SECONDS which always contains the number of seconds since the epoch. Evaluating $SECONDS at the beginning and at the end of the job gives you the start and end times, and the difference is the elapsed time. Unix time doesn't take leap seconds into account: a day in Unix time is always exactly 86400 seconds. Therefore time-of-day arithmetic on Unix time is easy. start=$SECONDS…end=$SECONDSelapsed=$((end - start))printf 'Process completed %d:%02d:%02d - Elapsed %d:%02d:%02d\n' \ $((end / 3600)) $((end / 60 % 60)) $((end % 60)) \ $((elapsed / 3600)) $((elapsed / 60 % 60)) $((elapsed % 60)) | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/114925', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/6560/']} | jdg_84348 |
stackexchange | llm_judgeable_groundtruth_similarity | 212255 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Recently I read about Denial of Service attack on Amazon & PayPal. I am curious that how this is performed. These big companies must have huge servers, so DOS would require billions of bots to access it. So my questions are How DDOS attack performed at this level? How to know beforehand that this is attack is happening? How to prevent this (how to distinguish from bot vs user, apart from common captcha way that is done)
Now provide the response and nothing else.
| Fundamentally, such denial of service attacks involve sending the server more requests than it can handle. It can be a large number of bots sending simple requests (though it does not require billions to bring down a single server - a few thousand tops) or a handful of bots sending requests that are notoriously long to execute. The second attack type is the most vicious, because a single bot could conceivably bring down a server. For instance, MySQL's LIMIT N OFFSET M is notoriously slow when M becomes large, so a simple attack would be to request pages 200-300 out of 500 in quick succession, clogging all the MySQL worker threads. On an unprotected server, this can be done with firebug. The only solution is to identify costly operations and then either optimize the hell out of them, make them sequential (so that clogging that part of the site does not bring down the rest of the site), or detect IPs that ask for costly operations and refuse to perform that operation unless a certain wait interval is respected. The first attack type is harder to pull off, because you need many bots. On the other hand, it's also harder to stop from the server: if you have thousands of bots sending you data as fast as they can, your bandwidth will be eaten up by the flood and there's nothing the server can do about it (even if it flat out refuses 99% of those requests), so a router with flood prevention is a good bet if you think you might be a target. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/212255', 'https://serverfault.com', 'https://serverfault.com/users/63449/']} | jdg_84349 |
stackexchange | llm_judgeable_groundtruth_similarity | 3530539 |
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 was sitting in analysis yesterday and, naturally, we took the limit of some expression. It occurred to me that "taking the limit" of some expression abides the rules of a linear transformation $$\lim_{x \rightarrow k}\ c(f(x)+g(x)) = c \lim_{x \rightarrow k} f(x) + c\ \lim_{x \rightarrow k} g(x),$$ and (my group theory is virtually non existent) appears also to be a homomorphism: $$\lim_{x \rightarrow k} (fg)(x) = \lim_{x \rightarrow k} f(x)g(x), $$ etc. Anyway, my real question is, what mathematical construct is the limit?
Now provide the response and nothing else.
| In general, let $X, Y$ be topological spaces, and $x_0$ a non-isolated point of $X$ . Then strictly speaking, " $\lim_{x\to x_0} f(x) = L$ " is a relation between functions $f : X \to Y$ and points $L \in Y$ (the equality notation being misleading in general). Now, if $Y$ is a Hausdorff topological space, it happens that this relation is what is known as a partial function : for any $f : X \to Y$ , there is at most one $L \in Y$ such that $\lim_{x\to x_0} f(x) = L$ . Now, for any relation $R \subseteq (X \to Y) \times Y$ which is a partial function, we can define a corresponding function $\{ f \in (X \to Y) \mid \exists y \in Y, (f, y) \in R \} \to Y$ by sending $f$ satisfying this condition to the unique $y$ with $(f, y) \in R$ . Then that somewhat justifies the "equality" in the notation $\lim_{x\to x_0} f(x) = L$ , though you still need to keep in mind that it is a partial function where $\lim_{x\to x_0} f(x)$ is not defined for all $f$ . (This part relates to the answer by José Carlos Santos.) Building on top of this, in the special case of $Y = \mathbb{R}$ , we can put a ring structure on $X \to Y$ by pointwise addition, pointwise multiplication, etc. Then $\{ f : X \to \mathbb{R} \mid \exists L \in \mathbb{R}, \lim_{x\to x_0} f(x) = L \}$ turns out to be a subring of $X \to \mathbb{R}$ , and the induced function from this subring to $\mathbb{R}$ is a ring homomorphism. (More generally, this will work if $Y$ is a topological ring. Similarly, if $Y$ is a topological vector space, then the set of $f$ with a limit at $x_0$ is a linear subspace of $X \to Y$ and the limit gives a linear transformation; if $Y$ is a topological group, you get a subgroup of $X \to Y$ and a group homomorphism; and so on.) | {} | {'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/3530539', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/675015/']} | jdg_84350 |
stackexchange | llm_judgeable_groundtruth_similarity | 2324420 |
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 jquery 1.3.2, the following works: <select id="c"> <option value="325">Red</option> <option value="833">Purple</option></select>$('#c').val('Red'); And it changes the select to the option with RED as its label. In jQuery 1.4 this fails. How can I get the same result in 1.4? Was this a bug in the 1.3 version?
Now provide the response and nothing else.
| You would have to do it this way: $('option:contains("Red")', '#c')[0].selected = true EDIT @Tomalak If the labels arent mutually exclusivey you'd need to rewrite the selector: $.fn.labselect = function(str) { $('option', this).filter(function() { return $(this).text() == str; })[0].selected = true; return this;};// Use it like this$('#c').labselect('Red'); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2324420', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/260302/']} | jdg_84351 |
stackexchange | llm_judgeable_groundtruth_similarity | 22636122 |
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 jar file which is having some issue and I would like to debug it. I created the application on eclipse. During dev phase I have done debug but with the source code. I wanted to debug jar file to find out the reason of error i.e. it could be source code I have is different from jar file or some jar file issue.
Now provide the response and nothing else.
| Seems like you want to remote debug. The use this command to launch your jar: java -Xdebug -Xrunjdwp:transport=dt_socket,address=8001,server=y,suspend=y -jar [JAR NAME HERE] It should state something like : Listening for transport dt_socket at address : 8001 And in eclipse, create a "Remote Java Application" debug configuration. The configuration is the only thing that matters as long as you have your project of interest open. Add the project[s] of interest that you would like to debug onto your source lookup path and set the port number to the configured address from the java launch command. When you connect to your debug-enabled jar launch, your jar will halt execution and await debugger input upon hitting breakpoints. Just make sure you have the same version of the code in your jar and your eclipse. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22636122', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3459883/']} | jdg_84352 |
stackexchange | llm_judgeable_groundtruth_similarity | 38327049 |
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 new to Selenium and need to check if element is clickable in Selenium Java , since element.click() passes both on link and label . I tried using the following code, but it is not working: WebDriverWait wait = new WebDriverWait(Scenario1Test.driver, 10);if(wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]")))==null)
Now provide the response and nothing else.
| elementToBeClickable is used for checking an element is visible and enabled such that you can click it. ExpectedConditions.elementToBeClickable returns WebElement if expected condition is true otherwise it will throw TimeoutException , It never returns null . So if your using ExpectedConditions.elementToBeClickable to find an element which will always gives you the clickable element , so no need to check for null condition, you should try as below :- WebDriverWait wait = new WebDriverWait(Scenario1Test.driver, 10); WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]")));element.click(); As you are saying element.click() passes both on link and label that's doesn't mean element is not clickable, it means returned element clicked but may be there is no event performs on element by click action. Note :- I'm suggesting you always try first to find elements by id , name , className and other locator. if you faced some difficulty to find then use cssSelector and always give last priority to xpath locator because it is slower than other locator to locate an element. Hope it helps you..:) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38327049', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6578986/']} | jdg_84353 |
stackexchange | llm_judgeable_groundtruth_similarity | 1289664 |
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 key/value pairs mapped by hash (ID) in Dictionary<string, Dictionary<string, string>> called id2key_value. You can think of this as a way to represent database-like table with rows. I added some helper functions to ease the use of some basic datatypes by doing a cast, like public int GetInt(string id, string key){ int value = 0; bool success = int.TryParse(map[id][key], out value); if (success) return value; else throw new InvalidOperationException( "Trying to obtain a non-integer value with GetInt().");} Well, I thought I was being clever when I came up with an idea of a "cast-cache", which basically holds already parsed objects, so I could skip the parsing of the string for int, bool, DateTime, etc., and simply cast them to appropriate datatype from the cache. Like, public int GetInt(string id, string key){ if (cast_cache.ContainsKey(id) && cast_cache[id].ContainsKey(key)) return (int) cast_cache[id][key]; int value = 0; bool success = int.TryParse(map[id][key], out value); if (success) { this.AddToCache(id, key, value); return value; } else throw new InvalidOperationException( "Trying to obtain a non-integer value with GetInt().");} The "cast-cache" is simply Dictionary<string, Dictionary<string, object>> . So, I did some performance testing with 10000 ints added to the map. Then I did one million random retrieves, with and without "cast-caching". It took 495(ms) without caching and 490(ms) with caching. I also ran a test with DateTime, there the difference was more significant, but less than I expect (~750(ms) non-cached vs ~500(ms) cached). Not (obviously) understanding the principle of a cast, how costly this operation is and why the performance is so close to the one that "deserializes" from string?
Now provide the response and nothing else.
| Casting is much faster that most people seem to think since you are not touching the object itself (you are simply changing the reference that points to that object). One of the main reasons that you ought to avoid casting is that when you cast you are eschewing type-safety and introducing potential execution-time errors into your application. I would rarely consider casting to be a performance concern. As a side note I would make sure that you test both reference types and value types in your cache to make sure that you are not incurring a performance penalty due to the boxing and unboxing of any value types. The performance penalty of boxing comes from the fact that casting a value type to an object does involve more than changing a reference as the value type must be copied to the heap. Also the use of a boxed value type will unbox the reference type and subsequently copy those values from the heap to the stack again. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1289664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_84354 |
stackexchange | llm_judgeable_groundtruth_similarity | 45613310 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Currently I read a 3D texture with the function texture(...) like this: vec3 value = texture(texture_3D, coord).rgb What I want to do now is: vec3 value = texelFetch(texture_3D, coord, 0).xyz However, I do not know how to convert my coordinate so that it works with texelFetch. My texture is of size 256x256x256 And my current coordinate calculation is as follows: vec3 min_box = vec3(-0.5);vec3 max_box = vec3(0.5);vec3 coord = worldToVolume(world_pos, min_box, max_box)vec3 worldToVolume(world_pos, min_box, max_box) { return (world_pos - min_box) / (max_box - min_box)} Any ideas? If you need more information please ask and I will provide it.
Now provide the response and nothing else.
| Those two functions perform quite different tasks on quite different arguments. texture expects normalized floating point texture coordinates in [0,1] (i.e. 0 being left/bottom and 1 being right/top) and performs proper wrapping (so the coordinates don't necessarily have to be in [0,1]) and filtering (so you don't necessarily get the exact texel color) according to whatever sampling modes you set. texelFetch on the other hand expects integer texel indices in [0,width-1] (and respectively height/depth for y and z) and doesn't perform any kind of filtering or wrapping, accessing the exact texel value at the specified index in a specified mipmap level. So texelFetch(texture_3D, ivec3(coord * vec3(256.0), 0) should be equivalent to texture(texture_3D, coord) with filter modes GL_NEAREST and wrapping modes GL_CLAMP_TO_EDGE . However, also keep in mind possible rounding problems in case coord is exactly 1.0 or on texel boundaries, maybe texelFetch(texture_3D, ivec3(coord * vec3(255.0) + vec3(0.5), 0) might be advisable to be more secure in that regard. However, just changing it this way seems a rather useless aproach compared to simply keeping your current texture access with a GL_NEAREST filter. It is more useful if you already have integer texel coordinates and already know the texture size. Just emulating nearest filtering this way won't really buy you anything. It's basically two conceptually different approaches, one filters a texture with size-independent floating point coordinates and the other one accesses a 3D-array with integer indices. It depends on your surrounding code which approach is more appropriate for your use case. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45613310', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_84355 |
stackexchange | llm_judgeable_groundtruth_similarity | 6655 |
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:
Is there a simple way to translate programs written in a basic "While" language (such as Winskels Imp)? I know about Church numerals and booleans, and I can see how if and while statements can be translated as $$\mbox{if}~t_c~\mbox{then}~t_t~\mbox{else}~t_f\qquad\rightarrow\qquad(t_c t_t)t_f$$ and $$\mbox{while}~t_c~\mbox{do}~t_l \qquad\rightarrow\qquad \omega(\lambda r.(t_c (t_l; \omega r) I))$$ (with suitable definitions for $\omega$ and $I$). Assignment however puzzles me. One example translation of the following program x := foo;if x then t_1 else t_2 would be $$(\lambda x.(x t_1)t_2)~foo$$ But I can't seem to find a general rule for it. How would for instance this program translate: x := true;y := false;while x do x := y
Now provide the response and nothing else.
| Here is the toy language I am going to use. Note that locations are numbered. $$ A := n \quad | \quad x_k \quad | \quad A_1 + A_2 \quad | \quad ... \text{ (where $n,k ∈ \mathbb{N})$ } $$$$ B := A_1 = A_2 \quad | \quad ... $$ $$ C := \quad C_1 ; C_2 \quad |\quad x_k := A\quad | \quad skip \quad |\quad \mathop{if}~B~\mathop{then}~C_1~\mathop{else}~C_2 \quad | \quad ... $$ First, you have to encode states. What's a state ? It's map from your set $L$ of locations to your set $V$ of values. Here I choose to implement themby a function $σ : \mathbb{N} → \mathbb{N}$. We'll call $Σ$ the set of states. There are two common operation over states : $$\mathop{get} : Σ → L → V$$$$\mathop{get} = λs.λx.(s~x)$$ $$\mathop{set} : Σ → L → V → Σ$$$$\mathop{set} = λs.λx.λv.\left(λk.\mathop{equal}~k~x~v~(s~k)\right)$$where $equal$ is a λ-term representing equality between Church numerals. Then we have to encode arithmetical expressions as function from $Σ$ to $V$ $$⟦n⟧ = λs.\lceil n \rceil$$$$⟦x_k⟧ = λs.get~s~\lceil k \rceil$$$$⟦A_1 + A_2⟧ = λs.\mathop{plus}~(⟦A₁⟧~s)~(⟦A₂⟧~s)$$$$\vdots$$where $\mathop{plus}$ is a λ-term representing addition over Church numerals and $\lceil n \rceil$ is the $n$-th Church numeral. And boolean expressions as functions from $Σ$ to booleans: $$⟦A₁ = A₂⟧ = λs.\mathop{equal}~(⟦A₁⟧~s)~(⟦A₂⟧~s)$$$$\vdots$$ Finally you encode your commands as "state transformers" from $Σ$ to $Σ$. $$ ⟦skip⟧ = λs.s $$$$ ⟦x_k := A⟧ = λs.\mathop{set}~s~\lceil k \rceil~(⟦A⟧~s) $$$$ ⟦C₁;C₂⟧ = ⟦C_2⟧ ∘ ⟦C_1⟧ = λs.⟦C_2⟧~(⟦C_1⟧~s)$$$$ ⟦\mathop{if}~B~\mathop{then}~C_1~\mathop{else}~C_2⟧ = λs.⟦B⟧~s~(⟦C₁⟧~s)~(⟦C₂⟧~s) $$$$\vdots$$ Exercise 1: Prove the correctness of this compilation wrt to a standard operational semantics. Exercise 2: Check that everything works in a typed context (you will however need some kind of fixpoint operator to translate the while construction). | {} | {'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/6655', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/5137/']} | jdg_84356 |
stackexchange | llm_judgeable_groundtruth_similarity | 4403385 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using a UITableViewController, I have resized the height of the table view and moved it a little down. Now I'd like to add a UIImageView above that table view but the only thing that I can do is add that UIImageView as a subview of the UITtableView of the UITableViewController, so that UIImageView is not above the UITableView and the image scrolls with the table view. How can I accomplish what I'm trying ? Here is the code I've been using : UIImageView *tabImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"temp.png"]];[self.view addSubview:tabImageView]; Thanks!
Now provide the response and nothing else.
| I believe UITableViewController requires that its view be a UITableView . In the past, I've worked around this by changing my view controller from subclassing UITableViewController to subclassing UIViewController and implementing the UITableViewDataSource and UITableViewDelegate protocols. Then you can have your view be whatever you want, including shifting your UITableView down and adding a UIImageView . Not sure if this is still the case in 4.2, though. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4403385', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/472220/']} | jdg_84357 |
stackexchange | llm_judgeable_groundtruth_similarity | 2128505 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Could anyone explain the difference between filter and filter_by functions in SQLAlchemy?Which one should I be using?
Now provide the response and nothing else.
| filter_by is used for simple queries on the column names using regular kwargs, like db.users.filter_by(name='Joe') The same can be accomplished with filter , not using kwargs, but instead using the '==' equality operator, which has been overloaded on the db.users.name object: db.users.filter(db.users.name=='Joe') You can also write more powerful queries using filter , such as expressions like: db.users.filter(or_(db.users.name=='Ryan', db.users.country=='England')) | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/2128505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/257942/']} | jdg_84358 |
stackexchange | llm_judgeable_groundtruth_similarity | 94752 |
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:
Recently an experiment was performed in which myself and a partner filled a water balloon and threw it back and forth at each other without breaking it. We gradually increased the distance at which it was being thrown and at one point I ended up on the second floor of one of my high school buildings and when I threw it, my partner caught it. For the last part of my experiment I went up to the third floor of the building and threw it, my partner caught the water balloon (it burst in her hands) I am assuming that the balloon had so much force behind it that the impact caused it to burst. I know that momentum is measured using mass and velocity but I do not know how to calculate the momentum when it reaches my partner. I would say that there is no momentum because once the balloon is caught, it will not be moving. But apparently that is incorrect so I am assuming the momentum will need to be that of the split second right before it is caught. My final question: How do I calculate the momentum of the balloon when it reaches the hands of my partner?
Now provide the response and nothing else.
| For a spherically symmetric distribution of mass, the acceleration felt by a test particle at radius $r$ is $-G M /r^2$ (negative because pointing in toward the center), regardless of the radial distribution of mass. This is a key part of the question, make sure you are comfortable with it. It is a concept that is related to Gauss' law of electromagnetism, if you've encountered that. The total mass of the collapsing cloud is given by the initial uniform density times the volume, or $M = (4 \pi /3) r_0^3 \rho_0$ From Newton's second law, the equation of motion for a test particle at the edge of the cloud is then $$ \frac{d^2r}{dt^2} = - \frac{4 \pi G r_0^3 \rho_0}{3r^2}$$ Now for some chain rule trickery (this is a nice trick, so it's good to remember it for similar differential equations): $$ \frac{d}{dt} = \frac{dr}{dt} \frac{d}{dr}$$ Keeping in mind that $v \equiv \frac{dr}{dt}$, and using the chain rule subustitution just mentioned, the equation of motion is now $$ v \frac{dv}{dr} = - \frac{4 \pi G r_0^3 \rho_0}{3r^2}$$ The point of doing all this is that the differential equaiton is now more clearly separable. You can solve it by integrating as follows $$ \int v \, dv = - \frac{4 \pi G r_0^3 \rho_0}{3}\int\frac{dr}{r^2}$$ $$\frac{1}{2} v^2 = \frac{4 \pi G r_0^3 \rho_0}{3r} + C$$ (You also could have gotten to this point by relating gravitational potential energy to kinetic energy, and being careful about where you set the zero of the gravitational potential). When $r = r_0$, $v = 0$, so $C = - \frac{4 \pi G r_0^2 \rho_0}{3}$ and $$\frac{1}{2} v^2 = \frac{4 \pi G r_0^2 \rho_0}{3}\left(\frac{r_0}{r} - 1 \right)$$ $$ |v| = \sqrt{\frac{8 \pi G r_0^2 \rho_0}{3}\left(\frac{r_0}{r} - 1 \right)}$$ The total time can be found by integrating $$t_{\rm collapse} = \int dt = \int \frac{dr}{|v|} = \sqrt{\frac{3}{8 \pi G r_0^2 \rho_0}}\int_0^{r_0}{\frac{dr}{\sqrt{\left(\frac{r_0}{r} - 1 \right)}}}$$ This is going to be a tricky integral, so let's non-dimensionalize it. Make a change of variable $u \equiv r/r_0$. Then we have $$ t_{\rm collapse} = \sqrt{\frac{3}{8 \pi G \rho_0}}\int_0^{1}{\frac{du}{\sqrt{\frac{1}{u} - 1}}}$$ If you are really adept at trigonometric substitutions in integrals, here's your chance to shine. Otherwise, just use Wolfram Alpha or something similar to tell you that the integral evaulates to $\pi/2$. That gives, finally, $$ t_{\rm collapse} = \sqrt{\frac{3 \pi}{32 G \rho_0}}$$ | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/94752', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/37929/']} | jdg_84359 |
stackexchange | llm_judgeable_groundtruth_similarity | 808706 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Amazon has two types of "dedicated" infrastructure: dedicated instances, and dedicated hosts. They say : When you launch instances on a Dedicated Host, the instances run on a physical server that is dedicated for your use. While Dedicated instances also run on dedicated hardware , Dedicated Hosts provide further visibility and control by allowing you to place your instances on a specific, physical server . This enables you to deploy instances using configurations that help address corporate compliance and regulatory requirements. [Italics mine.] I find this unclear. It doesn't explain what the difference is between dedicated hardware and physical server. What is the actual physical difference between these two "dedicated offerings"?
Now provide the response and nothing else.
| Short version: Dedicated Instances - You pay for the instances, but they get placed on whatever dedicated hardware Amazon decides. Dedicated Host - You pay for the entire physical server and can, in effect, run instances on it as you please. Long version: In both cases, its hardware that only your instances will use. However with dedicated hosts you have even more control than you would with dedicated instances. For example: Requesting a m4.large dedicated instance could end with your instance on a server exactly the size of an m4.large, so it'd be an old machine from years ago. Next time you reboot that instance it could be rebalanced onto new hardware. Maybe you have two dedicated instances that hammer the heck out of the RAM (making something up), they could end up on two different pieces of hardware or the same hardware. On the flip side with a dedicated hardware, you pay for the hardware much in the same way you could pay for a leased server at a colo. You know exactly what the hardware is, you can run instances on it in the way you choose. You can leave overhead, or not. If you decide that instance X runs on your dedicated hardware, it will always run on that dedicated hardware in the way you've specified. | {} | {'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/808706', 'https://serverfault.com', 'https://serverfault.com/users/26447/']} | jdg_84360 |
stackexchange | llm_judgeable_groundtruth_similarity | 64909849 |
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 use in Python the package pydantic and the linker Flake8. I want to use constr from pydantic with a regular Experssion. Only certain Characters should be passed. (a-z, A-Z, 0-9 and _) The regular Experssion "^[a-zA-Z0-9_]*$" works, but flake8 shows me the following error: syntax error in forward annotation '^[a-zA-Z0-9_]*$' flake8(F722) class RedisSettings(BaseModel): keyInput: constr(regex="^[a-zA-Z0-9_]*$") = "" keyOutput: constr(regex="^[a-zA-Z0-9_]*$") = "" Can you help me to avoid the Error Message?
Now provide the response and nothing else.
| the error here comes from pyflakes which attempts to interpret type annotations as type annotations according to PEP 484 the annotations used by pydantic are incompatible with PEP 484 and result in that error. you can read more about this in this pyflakes issue I'd suggest either (1) finding a way to use pydantic which doesn't involve violating PEP 484 or (2) ignoring the errors from pyflakes using flake8's extend-ignore / # noqa: ... / per-file-ignores disclaimer: I am one of the pyflakes maintainers and I am the current flake8 maintainer | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/64909849', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/14548431/']} | jdg_84361 |
stackexchange | llm_judgeable_groundtruth_similarity | 11258 |
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 UK has 4 states: England, Wales, Scotland, and Northern Ireland.I always thought that they are closer connected than the states of the US, since they have the same laws (as far as I know; I am German, so I don't have an idea, actually). In contrast to that every US state can make its own laws (at least I think this is the case, because the topic of different laws between US states sometimes occurs in the German news regarding death penalty and gun control laws). Currently there is the European championship in football (soccer) taking place in which the teams of England, Scotland, and Wales are participating (Northern Ireland didn't qualify). Whenever there is the World Cup all 4 teams are participating or at least trying to qualify, too, but the US only has one national team. My question: Why is that? Why do the UK states seem closer related to each other to me even though they all have their own national football team? And what is the difference compared to the US? EDIT: I found the answer here: https://sports.stackexchange.com/questions/5752/why-great-britain-or-england-scotland-wales-ireland-in-different-sport
Now provide the response and nothing else.
| The United States of America (US) was originally linked by the Articles of Confederation . These linked the thirteen states more like the European Union is linked now--sovereigns who banded together in mutual support. In fact, the national government did not even have a taxing power. It was reliant on voluntary contributions for the revenues needed to pay for government operations and debt reduction. The US decided to replace the articles of confederation with the more modern constitution. However, it was a compromise between those who wanted a more powerful and unified government and those who wanted to maintain the sovereignty of the individual states. It provided a limited national government. The states each authorize and maintain their own governments. So the structure and political systems are set by the states themselves. The federal government originally had little ability to affect those legislatively. Much of the ability for the federal government to interfere in local politics derives from the mandate in the 14th amendment to protect the citizenship rights of the former slaves. Scotland in the United Kingdom (UK) had no separate parliament prior to 1999 (at least since Scotland and England unified in 1707). I believe this means that the Scottish government is authorized by the national government. And of course, this is relatively recent. A twenty-year old history book wouldn't have it. I don't know why Northern Ireland and Wales have their own teams in the UEFA Euro 2016 . Presumably this is a national pride thing. Also note that football is apparently the highest profile sport in the United Kingdom (and many other countries). In the United States, it doesn't make the top three even neglecting car racing and golf . Top athletes in the United States are much more likely to play American football, baseball, or basketball. In some areas, even hockey would be ahead of association football. It's not clear that any American states would be able to field their own competitive teams in association football. Separate teams by state could mean that players from less populated states would be out of luck. So the unified team may represent a weaker association football tradition rather than more strongly unified laws. It's also worth noting that the American states don't have the same history of resenting their inclusion in the country as does Scotland. England conquered Scotland and left the Scottish people there. The descendants of the native American tribes are only a small proportion of the overall population and aren't concentrated in any one state. TLDR : even though I agree that the UK is more legally unified than the US (although the UK is less unified than it used to be), there are still good reasons why the US doesn't have more than one national association football (soccer) team. | {} | {'log_upvote_score': 5, 'links': ['https://politics.stackexchange.com/questions/11258', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/8473/']} | jdg_84362 |
stackexchange | llm_judgeable_groundtruth_similarity | 37468 |
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 was hoping to incorporate an If function into a Plot option, as in Plot[Sin[t], {t, 0, 2 Pi}, Filling -> Axis, FillingStyle -> If[Sin[t] > 0, LightGreen, LightRed]] or Plot[Sin[t], {t, 0, 2 Pi}, PlotStyle -> If[Sin[t] > 0, Dashed, Thick]] to no avail. Is it possible to pass an If to the plot options? I know that I can manually accomplish the effect via Piecewise , but I have more complicated applications in mind where I would not want to manually precompute the interval(s) on which my piecewise defined function would need to be defined.
Now provide the response and nothing else.
| Here is yet another crack at this problem. ConditionalPlot[func_, condition_, varrange_, trueopts_, falseopts_] := Module[{plottrue, plotfalse}, plottrue = Plot[If[condition, func], varrange, trueopts]; plotfalse = Plot[If[Not[condition], func], varrange, falseopts]; Show[plottrue, plotfalse, PlotRange -> All]] The first argument is the function or list of functions you want to plot. The second argument is the condition you want to apply. The third argument is the variable and range to plot in the form {x,xmin,xmax} . The third and fourth arguments are the options you apply when the condition is true or false, respectively. For example, the plot you mentioned in your question can be had by ConditionalPlot[Sin[x], Sin[x] > 0, {x, 0, 2 Pi}, {Filling -> Axis, FillingStyle -> LightGreen, PlotStyle -> Dashed}, {Filling -> Axis, FillingStyle -> LightRed, PlotStyle -> Thick}] This is versitile, you can give it a compound condition like ConditionalPlot[Sin[x], Sin[x] > .7 || Sin[x] < -.7, {x, 0, 2 Pi}, {Filling -> Axis, FillingStyle -> LightGreen, PlotStyle -> Dashed}, {Filling -> Axis, FillingStyle -> LightRed, PlotStyle -> Thick}] You can give it multiple functions to plot ConditionalPlot[{Sin[x], Cos[x]}, Sin[x] > Cos[x], {x, 0, 4 Pi}, {PlotStyle -> {Red, Thick}, Axes -> False, Frame -> True, BaseStyle -> 14}, {PlotStyle -> {Black, Thick,Dashed}}] Note that any global options you want to apply to the image in general should go in the trueopts as it is given to Show first. | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/37468', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1629/']} | jdg_84363 |
stackexchange | llm_judgeable_groundtruth_similarity | 51362237 |
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 struggling a long time with this problem.I want the value of my selectListItem to use it in the controller to make the right API call. Thats my Code in razor: var selectList = new SelectList( new List<SelectListItem> {new SelectListItem {Text = "Borussia Dortmund", Value = "10303", Selected= false},new SelectListItem {Text = "FC Bayern München", Value = "10285", Selected= false},new SelectListItem {Text = "Bayer 04 Leverkusen", Value = "10281", Selected= false}, . . . }, "Value", "Text", 1); @Html.DropDownList("ddlChosenTeam", selectList, "Team wählen", new { @class = "css-class" })} If i try the following in my Controller, it don´t know the selectList: protected void SquadChosen_Click(object sender, EventArgs e) { int selectedSquad = selectList.SelectedValue; } I just want to pick the value like 10303 if "borussia Dortmund" is selected, please safe my time. Edit:I wrote some other Code that is maybe more what i need.my Controller now: public SelectList UserChosenSquad() { var ssl = new SelectList(new List<SelectListItem> { new SelectListItem {Text = "Borussia Dortmund", Value = "10303", Selected = false}, new SelectListItem {Text = "FC Bayern München", Value = "10285", Selected = false}, new SelectListItem {Text = "Bayer 04 Leverkusen", Value = "10281", Selected = false}, }, "Value", "Text"); return ssl; } The Model: public class ChosenSquad{ public string Text { get; set; } public string Value { get; set; } public bool Selected { get; set; }} now i struggle with the view @model ChosenSquad @{ @Html.DropDownListFor(model => model.Text, Model.SelectListItem, "Text", "-Team wählen-") Is this the right way ? I need to show the DropDownList and then the value like before, i first want to see my list and then perhaps get the value with an if method that looks for selected item, right!?
Now provide the response and nothing else.
| By default, Python buffers output to sys.stdout . There are a few options: 1. Call an explicit flush Refactor the original print statement to include a flush=True keyword, like: print("Hello? Anyone there?", flush=True) Note: This will cause the entire buffer to flush, not just the same print call. So if there are 'bare' print function calls elsewhere (i.e. without flush=True ) that weren't explicitly unbuffered, these will always be flushed too. You could achieve the same thing with: import syssys.stdout.flush() This option is useful if you want the most control of when the flushing will occur. 2. Unbuffer the entire app via the PYTHONUNBUFFERED env var Drop the following into the environment section of your docker-compose.yml file: PYTHONUNBUFFERED: 1 This will cause all output to stdout to be flushed immediately. 3. Run python with -u Like option #2 above, this will cause Python to run 'unbuffered' across the full execution lifetime of your app. Just run with python -u <entrypoint.py> - no need for the environment variable. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/51362237', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9945720/']} | jdg_84364 |
stackexchange | llm_judgeable_groundtruth_similarity | 24228 |
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'm working on a project to make my own super-bright bike taillight using an emergency flasher LED (something like this:) The LED package requires a 12V input, but from what I've read from other people who've done this before, it will still work with as little as about 8V. It also uses a 12V momentary charge to switch flash patterns. I'm planning to use 3 18650 lithium-ion batteries in series to power the light. Each battery is 3.7V, so I should get 11.1 V total, which will (supposedly) be sufficient. I'll put them in a 3-battery holder like this one: This should be easy enough to set up, but I'm wondering how I should go about charging the batteries. I haven't been able to find 18650 chargers specifically designed for 3 batteries. I've found them for 1, 2, and 4 batteries only. My (limited) understanding of lithium batteries is that all batteries that will be used in a single device should be charged together so that the cells can be balanced, and that if this isn't done, it poses a fire risk. I'd like to avoid having a fire erupt between my legs while barreling down a hill at 30 mph. Would it be safe to use three 1-battery 18650 chargers, if I charge them all for the same time? Do they actually need to be balanced at all, or am I misunderstanding something? If they do all need to be charged together for safety purposes, then is there any way for me wire it up to get 12V out of 2 or 4 batteries, which I would then be able to charge normally?
Now provide the response and nothing else.
| Read my just posted answer to this question . While not identical it covers aspects which will answer some of your questions. 3 x 18650 LiIons (or any 3 LiIons) will have a fully charged voltage of 3 x 4.2V = 12.6V and a fully discharged voltage of ABOUT 3 x 3 = 9V. How low low goes is up to you. Too low and battery dies. Read my answer above re balancing. It is not NECESSARY as long as you are CERTAIN that no cell is ever deep discharged AND if charging in series, as long as no cell is in constant voltage tail off mode while you are attempting to inject full constant current at 1C. 'Attempting to" period may be short. IF you charge this off the bike and if all 3 cells are isolated from the world (but connected to each other) then my answers above re charging one at a time apply. You can charge 3 at a time with 3 chargers ** as long as** all charger outputs are truly isolated. An easy way to get 12V is to use one of the many many available switch mode power supplies. You can get 1 or 2 or 3 cell LiIon to 12V capable supplies. An 18650 LiIon cell is has a capacity of about 2000 mAH x 3.6V nominal =~~ 7 Watt hours. IF your flasher worked at 1 Watt average and was anything like serious it would blow following motorists off the road. Depends on design. 1 Watt at 10% duty cycle = 10 Watts when one. 1 Watt at 1% duty cycle = 100 Watts when on. Properly collimated a 1 att red LED willl do a very very very very good job. So a single 18650 cell with inverter of say 7% efficient (low) will run for 7 Wh/1 Watt x 70% = 5 hours. Ample for most people. ADDED: OK, so some clarifying questions. 1) how can I be certain that no cell is ever "deep discharged"? No cell ever under 3 Volt. Monitor voltage and prevent this happening OR Never discharge beyond known capacity to ensure this is true. Murphy says you will fail if you take the 2nd choice. 2) if I'm using a COTS charger (and charging each cell separately), what do you mean by the charger outputs must be truly isolated? If I'm using a physically separate charger for each cell, If the cells are not connected in any way this is irrelevant. This is an issue only if the cells are connected as in a battery holder. Outputs are fully isolated from the charger input. If you operate 2 chargers from mains simultaneously you must get no sensible voltage readings when measuring from eg V+ out of one to V+ out of other. If you plav a resistor from V+ out of oneto Ground out of th eother no current flows. Well under 1 mA would be acceptable. I'd expect good isolation. What is to be avoided is having ground out hard connected to ground pin in. 3 truly isolated chargers will work happily on 3 cells in series if there is no closed current path apart from the cell interconnections. will it be safe if when they're done charging separately I put all three cells back into the same system together Yes. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/24228', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/7223/']} | jdg_84365 |
stackexchange | llm_judgeable_groundtruth_similarity | 35788911 |
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 setup a basic swagger API doc in a new asp .net CORE / MVC 6 project and receiving a 500 error from the swagger UI: 500 : http://localhost:4405/swagger/v1/swagger.json My startup class has the following code in it: using Swashbuckle.SwaggerGen;using Swashbuckle.SwaggerGen.XmlComments;using Swashbuckle.Application;....public void ConfigureServices(IServiceCollection services){ ... services.AddSwaggerGen(); services.ConfigureSwaggerDocument(options => { options.SingleApiVersion(new Info { Version = "v1", Title = "Blog Test Api", Description = "A test API for this blogpost" }); });} and then under Configure: public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory){.... app.UseSwaggerGen(); app.UseSwaggerUi();....} When i build and run the project, the UI will come up when i go to swagger/UI/index.html, but the 500 error above is displayed. When i go to the swagger/v1/swagger.json link, console gives the following 500 error: Failed to load resource: the server responded with a status of 500 (Internal Server Error) Is there any way i can figure out the root cause of the 500 or enable any additional debug in swagger to figure out why it's throwing this error? Based on some of the tutorials i've looked at, only what i have in startup is required for a base implementation. Please let me know if i can provide any additional information. EDIT: this is for rc1, and may not be relevant to the new netcore 1.0 currently out (6/29/2016)
Now provide the response and nothing else.
| Initially I got a 500 error too. Deep down in the stacktrace it said:System.NotSupportedException: Unbounded HTTP verbs for path 'api/hotels'. Are you missing an HttpMethodAttribute? It turned out I was missing a HttpGet attribute for one of my api methods: [Microsoft.AspNetCore.Mvc.HttpGet] also if you used a method with a parameter like this "Get(int id)"you will get the same error without an explanation so you need to add it into the decoration"[HttpGet("{id:int}")]" | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/35788911', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5944024/']} | jdg_84366 |
stackexchange | llm_judgeable_groundtruth_similarity | 11992153 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been attempting to get PHP working with IIS 7.5 and have hit a bit of a roadblock. Whenever I try to load the page I get the following error: "HTTP Error 500.0 - Internal Server ErrorC:\Program Files\PHP\php.exe - The FastCGI process exited unexpectedly" Module FastCgiModule Notification ExecuteRequestHandler Handler PHP_via_FastCGI Error Code 0x00000000 Requested URL *http://localhost:80/index.php Physical Path C:\inetpub\wwwroot\index.php Logon Method Anonymous Logon User Anonymous Failed Request Tracing Log Directory C:\inetpub\logs\FailedReqLogFiles I've modified the PHP.ini file as required for use with IIS, and have also switched it to verbose mode. There isn't any log fiel in C:\inetpub\logs\FailedReqLogs, and none related to this error in the other log files generated. I've tried the other fixes I've found here and elsewhere but nothing's been successful so far. In some detail these were:re-checking PHP.iniSetting up fastCGI to work with PHP in IIS (configuring it to load the php.exe)Trying WinCache as the execution method.
Now provide the response and nothing else.
| I had this problem when I upgraded PHP 5.4.14 to 5.5.3 (32-bit). To fix it I had to install the Visual C++ Redistributable for Visual Studio 2012 Update 3 I found out that I needed this DLL by running php --version from the console when my web pages no longer loaded after the upgrade. Which then revealed that I needed the MSVCR110.dll, that comes with the 32-bit VS redistributable update from MS. Since I have optional updates turned off in Window Update, I did not get it automatically. They also come in different flavors (32-bit, 64-bit, and ARM) 32-bit is what worked for me. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11992153', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1555042/']} | jdg_84367 |
stackexchange | llm_judgeable_groundtruth_similarity | 77852 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to define a particular folder to be cookieless in IIS7, instead of just the root?
Now provide the response and nothing else.
| This is more of an ASP.NET question than an IIS question. A regular folder cannot have session state "defined" (i.e. InProc, SessionState, SQLServer, cookieless). However, if you mark a folder as an application then you can disable session state for that application. Additionally, you can disable session state per file if you want. However, the element in web.config can be set at any level and it will completely disable session state for you. You can set it in web.config in the folders that you don't want it like so: <system.web> <pages enableSessionState="false" /></system.web> Or you can set it in the root for a number of folders, like so: <location path="images"> <system.web> <pages enableSessionState="false" /> </system.web></location><location path="css"> <system.web> <pages enableSessionState="false" /> </system.web></location> | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/77852', 'https://serverfault.com', 'https://serverfault.com/users/58/']} | jdg_84368 |
stackexchange | llm_judgeable_groundtruth_similarity | 2563632 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to merge 2 commits into 1, so I followed “squashing commits with rebase” from git ready . I ran git rebase --interactive HEAD~2 In the resulting editor, I change pick to squash and then save-quit, but the rebase fails with the error Cannot 'squash' without a previous commit Now that my work tree has reached this state, I’m having trouble recovering. The command git rebase --interactive HEAD~2 fails with: Interactive rebase already started and git rebase --continue fails with Cannot 'squash' without a previous commit
Now provide the response and nothing else.
| Summary The error message Cannot 'squash' without a previous commit means you likely attempted to “squash downward.” Git always squashes a newer commit into an older commit or “upward” as viewed on the interactive rebase todo list, that is into a commit on a previous line. Changing the command on your todo list’s very first line to squash will always produce this error as there is nothing for the first commit to squash into. The Fix First get back to where you started with $ git rebase --abort Say your history is $ git log --pretty=onelinea931ac7c808e2471b22b5bd20f0cad046b1c5d0d cb76d157d507e819d7511132bdb5a80dd421d854f bdf239176e1a2ffac927d8b496ea00d5488481db5 a That is, a was the first commit, then b, and finally c. After committing c we decide to squash b and c together: (Note: Running git log pipes its output into a pager, less by default on most platforms. To quit the pager and return to your command prompt, press the q key.) Running git rebase --interactive HEAD~2 gives you an editor with pick b76d157 bpick a931ac7 c# Rebase df23917..a931ac7 onto df23917## Commands:# p, pick = use commit# r, reword = use commit, but edit the commit message# e, edit = use commit, but stop for amending# s, squash = use commit, but meld into previous commit# f, fixup = like "squash", but discard this commit's log message## If you remove a line here THAT COMMIT WILL BE LOST.# However, if you remove everything, the rebase will be aborted.# (Notice that this todo list is in the reverse order as compared with the output of git log .) Changing b’s pick to squash will result in the error you saw, but if instead you squash c into b (newer commit into the older or “squashing upward”) by changing the todo list to pick b76d157 bsquash a931ac7 c and save-quitting your editor, you'll get another editor whose contents are # This is a combination of 2 commits.# The first commit's message is:b# This is the 2nd commit message:c When you save and quit, the contents of the edited file become commit message of the new combined commit: $ git log --pretty=oneline18fd73d3ce748f2a58d1b566c03dd9dafe0b6b4f b and cdf239176e1a2ffac927d8b496ea00d5488481db5 a Note About Rewriting History Interactive rebase rewrites history. Attempting to push to a remote that contains the old history will fail because it is not a fast-forward. If the branch you rebased is a topic or feature branch in which you are working by yourself , no big deal. Pushing to another repository will require the --force option, or alternatively you may be able, depending on the remote repository’s permissions, to first delete the old branch and then push the rebased version. Examples of those commands that will potentially destroy work is outside the scope of this answer. Rewriting already-published history on a branch in which you are working with other people without very good reason such as leaking a password or other sensitive details forces work onto your collaborators and is antisocial and will annoy other developers. The “Recovering From an Upstream Rebase” section in the git rebase documentation explains, with added emphasis. Rebasing (or any other form of rewriting) a branch that others have based work on is a bad idea: anyone downstream of it is forced to manually fix their history. This section explains how to do the fix from the downstream’s point of view. The real fix, however, would be to avoid rebasing the upstream in the first place. … | {} | {'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/2563632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/286802/']} | jdg_84369 |
stackexchange | llm_judgeable_groundtruth_similarity | 6551214 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose I have a table with 3 columns: id (PK, int) timestamp (datetime) title (text) I have the following records: 1, 2010-01-01 15:00:00, Some Title2, 2010-01-01 15:00:02, Some Title3, 2010-01-02 15:00:00, Some Title I need to do a GROUP BY records that are within 3 seconds of each other. For this table, rows 1 and 2 would be grouped together. There is a similar question here: Mysql DateTime group by 15 mins I also found this: http://www.artfulsoftware.com/infotree/queries.php#106 I don't know how to convert these methods into something that will work for seconds. The trouble with the method on the SO question is that it seems to me that it would only work for records falling within a bin of time that starts at a known point. For instance, if I were to get FLOOR() to work with seconds, at an interval of 5 seconds, a time of 15:00:04 would be grouped with 15:00:01, but not grouped with 15:00:06. Does this make sense? Please let me know if further clarification is needed. EDIT: For the set of numbers, {1, 2, 3, 4, 5, 6, 7, 50, 51, 60}, it seems it might be best to group them {1, 2, 3, 4, 5, 6, 7}, {50, 51}, {60}, so that each grouping row depends on if the row is within 3 seconds of the previous. I know this changes things a bit, I'm sorry for being wishywashy on this. I am trying to fuzzy-match logs from different servers. Server #1 may log an item, "Item #1", and Server #2 will log that same item, "Item #1", within a few seconds of server #1. I need to do some aggregate functions on both log lines. Unfortunately, I only have title to go on, due to the nature of the server software.
Now provide the response and nothing else.
| I'm using Tom H.'s excellent idea but doing it a little differently here: Instead of finding all the rows that are the beginnings of chains, we can find all times that are the beginnings of chains, then go back and ifnd the rows that match the times. Query #1 here should tell you which times are the beginnings of chains by finding which times do not have any times below them but within 3 seconds: SELECT DISTINCT TimestampFROM Table aLEFT JOIN Table bON (b.Timestamp >= a.TimeStamp - INTERVAL 3 SECONDS AND b.Timestamp < a.Timestamp)WHERE b.Timestamp IS NULL And then for each row, we can find the largest chain-starting timestamp that is less than our timestamp with Query #2: SELECT Table.id, MAX(StartOfChains.TimeStamp) AS ChainStartTimeFROM TableJOIN ([query #1]) StartofChainsON Table.Timestamp >= StartOfChains.TimeStampGROUP BY Table.id Once we have that, we can GROUP BY it as you wanted. SELECT COUNT(*) --or whateverFROM TableJOIN ([query #2]) GroupingQueryON Table.id = GroupingQuery.idGROUP BY GroupingQuery.ChainStartTime I'm not entirely sure this is distinct enough from Tom H's answer to be posted separately, but it sounded like you were having trouble with implementation, and I was thinking about it, so I thought I'd post again. Good luck! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6551214', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/362536/']} | jdg_84370 |
stackexchange | llm_judgeable_groundtruth_similarity | 51224420 |
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 issue: I have 2 tabs using Default Tabs Controller, like so: Widget build(BuildContext context) { return DefaultTabController( length: 2, child: Scaffold( drawer: Menu(), appBar: AppBar( title: Container( child: Text('Dashboard'), ), bottom: TabBar( tabs: <Widget>[ Container( padding: EdgeInsets.all(8.0), child: Text('Deals'), ), Container( padding: EdgeInsets.all(8.0), child: Text('Viewer'), ), ], ), ), body: TabBarView( children: <Widget>[ DealList(), ViewersPage(), ], ), ), ); }} The DealList() is a StatefulWidget which is built like this: Widget build(BuildContext context) { return FutureBuilder( future: this.loadDeals(), builder: (BuildContext context, AsyncSnapshot snapshot) { print('Has error: ${snapshot.hasError}'); print('Has data: ${snapshot.hasData}'); print('Snapshot data: ${snapshot.data}'); return snapshot.connectionState == ConnectionState.done ? RefreshIndicator( onRefresh: showSomething, child: ListView.builder( physics: const AlwaysScrollableScrollPhysics(), itemCount: snapshot.data['deals'].length, itemBuilder: (context, index) { final Map deal = snapshot.data['deals'][index]; print('A Deal: ${deal}'); return _getDealItem(deal, context); }, ), ) : Center( child: CircularProgressIndicator(), ); }, ); }} With the above, here's what happens whenever I switch back to the DealList() tab: It reloads. Is there a way to prevent re-run of the FutureBuilder when done once? (the plan is for user to use the RefreshIndicator to reload. So changing tabs should not trigger anything, unless explicitly done so by user.)
Now provide the response and nothing else.
| There are two issues here, the first: When the TabController switches tabs, it unloads the old widget tree to save memory. If you want to change this behavior, you need to mixin AutomaticKeepAliveClientMixin to your tab widget's state. class _DealListState extends State<DealList> with AutomaticKeepAliveClientMixin<DealList> { @override bool get wantKeepAlive => true; @override Widget build(BuildContext context) { super.build(context); // need to call super method. return /* ... */ }} The second issue is in your use of the FutureBuilder -If you provide a new Future to a FutureBuilder , it can't tell that the results would be the same as the last time, so it has to rebuild. (Remember that Flutter may call your build method up to once a frame). return FutureBuilder( future: this.loadDeals(), // Creates a new future on every build invocation. /* ... */); Instead, you want to assign the future to a member on your State class in initState, and then pass this value to the FutureBuilder . The ensures that the future is the same on subsequent rebuilds. If you want to force the State to reload the deals, you can always create a method which reassigns the _loadingDeals member and calls setState . Future<...> _loadingDeals;@overridevoid initState() { _loadingDeals = loadDeals(); // only create the future once. super.initState();}@overrideWidget build(BuildContext context) { super.build(context); // because we use the keep alive mixin. return new FutureBuilder(future: _loadingDeals, /* ... */);} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/51224420', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1757321/']} | jdg_84371 |
stackexchange | llm_judgeable_groundtruth_similarity | 21491488 |
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 string containing an integer (which has been read from a file). I'm trying to convert the string to an int using strconv.ParseInt() . ParseInt requires that I provide a bitsize (bit sizes 0, 8, 16, 32, and 64 correspond to int, int8, int16, int32, and int64). The integer read from the file is small (i.e. it should fit in a normal int). If I pass a bitsize of 0, however, I get a result of type int64 (presumably because I'm running on a 64-bit OS). Why is this happening? How do I just get a normal int? (If someone has a quick primer on when and why I should use the different int types, that would awesome!) Edit: I can convert the int64 to a normal int using int([i64_var]) . But I still don't understand why ParseInt() is giving me an int64 when I'm requesting a bitsize of 0.
Now provide the response and nothing else.
| func ParseInt(s string, base int, bitSize int) (i int64, err error) ParseInt always returns int64 . bitSize defines the range of values. If the value corresponding to s cannot be represented by a signed integer of the given size, err.Err = ErrRange. http://golang.org/pkg/strconv/#ParseInt type int int int is a signed integer type that is at least 32 bits in size. It is a distinct type, however, and not an alias for, say, int32. http://golang.org/pkg/builtin/#int So int could be bigger than 32 bit in the future or on some systems like int in C. I guess on some systems int64 might be faster than int32 because that system only works with 64-bit integers. Here is an example of an error when bitSize is 8: http://play.golang.org/p/_osjMqL6Nj package mainimport ( "fmt" "strconv")func main() { i, err := strconv.ParseInt("123456", 10, 8) fmt.Println(i, err)} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21491488', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1576908/']} | jdg_84372 |
stackexchange | llm_judgeable_groundtruth_similarity | 45731 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
The concept of a subobject classifier is of course standard and ubiquitous. But is there any nontrivial example of an unrestricted slice classifier? Specifically, what I mean by this is, is there any non-preorder category with pullbacks with a morphism m into an object X such that ALL other morphisms can be taken as a pullback of m along some morphism into X? And, if so, is it even possible to have furthermore that parallel morphisms from any object Y into X are equal just in case the pullbacks of m along them are isomorphic as objects of the slice category over Y? Naturally, if we demand further structure on the category (e.g., local cartesian closure), this becomes impossible by Cantor type arguments in its internal logic, but if we only demand pullbacks, can it be done?
Now provide the response and nothing else.
| It looks like such categories may be rather easy to construct. The following example should give the general idea: take the category of sets $V_\alpha$ of cardinality less than or equal to $\alpha$, for some infinite cardinal $\alpha$. The morphism classifier will be the set $C$ of cardinals up to and including $\alpha$, and the universal morphism should be $S \to C$ where the fiber over a cardinal $\beta$ is a set of cardinality $\beta$. Given any function $f: Y \to X$, the classifying morphism $\chi_f: X \to C$ takes $x$ to the cardinal number of $f^{-1}(x)$. Hopefully I haven't made any dumb mistakes... | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/45731', 'https://mathoverflow.net', 'https://mathoverflow.net/users/3902/']} | jdg_84373 |
stackexchange | llm_judgeable_groundtruth_similarity | 51891 |
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 think it follows the S N i mechanism and would not lead to Walden inversion.Hence, the product should be ( S )‐2‐bromobutane: But the answer says otherwise (the problem didn't indicate the presence of pyridine in the reaction mixture though).
Now provide the response and nothing else.
| Yes, the haloalkane product will have the inverse stereochemistry of the alcohol that it was produced form. $\ce{PBr3}$ does this by converting the $\ce{-OH}$ into a good leaving group and providing a nucleophile all in one. This is can be seen in the two step mechanism: $\hspace{2.4cm}$ When $\ce{Br-}$ ejects $\ce{PBr2OH}$ in an $\mathrm{S_N2}$ reaction, the stereochemistry is inverted: $\hspace{3.1cm}$ | {} | {'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/51891', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/30498/']} | jdg_84374 |
stackexchange | llm_judgeable_groundtruth_similarity | 40728785 |
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 updated to latest WebStorm and I'm now getting this error: Error:(52, 14) TS1219:Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option to remove this warning. But in my tsConfig experimentalDecorators are set to true: { "version": "1.5.0", "compilerOptions": { //..., "experimentalDecorators": true, // <======== HERE //..., }, "files": [ //... ], "exclude": [ "node_modules" ]}
Now provide the response and nothing else.
| WS2016.3 applies config settings to a file only if the file is included in 'files' or 'include' tsconfig.json section. [ More info about tsconfig.json ] So the config must include all project files (or if you have several parts of the app you can have several tsconfig.json files). Otherwise typescript service uses default typescript options for the file. Preferred solution Your tsconfig.json should be: { "version": "1.5.0", "compilerOptions": { "target": "es5", "module": "commonjs", "noImplicitAny": false, "removeComments": true, "noLib": false, "emitDecoratorMetadata": true, "experimentalDecorators": true, "sourceMap": true, "listFiles": true, "isolatedModules": false, "moduleResolution": "node", "suppressImplicitAnyIndexErrors": true }, "include": [ "typings/thera/thera.d.ts", "typings/browser.d.ts", "typings/main.d.ts", "typings/meteor.d.ts", "typings/meteor_server.d.ts", "your_app_directory/**/*" ], "exclude": [ "node_modules" ], "compileOnSave":false //not required but is suggested for meteor projects} Another solution You can specify default options in the TypeScript settings ( track changes option should be unchecked if you don't want auto compilation): Note: If you don't like the new behaviour you can disable the typescript service integration in "File | Settings | Languages & Frameworks | TypeScript" -> "Use TypeScript service". | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40728785', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4031815/']} | jdg_84375 |
stackexchange | llm_judgeable_groundtruth_similarity | 12683314 |
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 looking at some assembly that was generated by disassembling some C programs and I am confused by a single optimization that I see repeated frequently. When I have no optimizations on the GCC compiler uses the subl instruction for subtraction, but when I do have optimizations turned on ( -O3 to be precise) the compiler uses a leal instruction instead of subtraction, example below: without optimizations: 83 e8 01 subl $0x1, %eax with optimizations 8d 6f ff leal -0x1(%edi), %ebp Both of these instructions are 3 bytes long, so I am not seeing an optimization here. Could someone help me out and try to explain the compiler's choice ? Any help would be appreciated.
Now provide the response and nothing else.
| It's hard to tell without seeing the original C code that produces this. But if I had to guess, it's because the leal allows the subtraction to be done out-of-place without destroying the source register. This can save an extra register move. The first example: 83 e8 01 subl $0x1, %eax overwrites %eax thereby destroying the original value. The second example : 8d 6f ff leal -0x1(%edi), %ebp stores %edi - 1 into %ebp . %edi is preserved for future use. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12683314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/702638/']} | jdg_84376 |
stackexchange | llm_judgeable_groundtruth_similarity | 10439094 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following two files :- single.cpp :- #include <iostream>#include <stdlib.h>using namespace std;unsigned long a=0;class A { public: virtual int f() __attribute__ ((noinline)) { return a; } };class B : public A { public: virtual int f() __attribute__ ((noinline)) { return a; } void g() __attribute__ ((noinline)) { return; } }; int main() { cin>>a; A* obj; if (a>3) obj = new B(); else obj = new A(); unsigned long result=0; for (int i=0; i<65535; i++) { for (int j=0; j<65535; j++) { result+=obj->f(); } } cout<<result<<"\n"; } And multiple.cpp :- #include <iostream>#include <stdlib.h>using namespace std;unsigned long a=0;class A { public: virtual int f() __attribute__ ((noinline)) { return a; }};class dummy { public: virtual void g() __attribute__ ((noinline)) { return; }};class B : public A, public dummy { public: virtual int f() __attribute__ ((noinline)) { return a; } virtual void g() __attribute__ ((noinline)) { return; }};int main() { cin>>a; A* obj; if (a>3) obj = new B(); else obj = new A(); unsigned long result=0; for (int i=0; i<65535; i++) { for (int j=0; j<65535; j++) { result+=obj->f(); } } cout<<result<<"\n";} I am using gcc version 3.4.6 with flags -O2 And this is the timings results I get :- multiple :- real 0m8.635suser 0m8.608ssys 0m0.003s single :- real 0m10.072suser 0m10.045ssys 0m0.001s On the other hand, if in multiple.cpp I invert the order of class derivation thus :- class B : public dummy, public A { Then I get the following timings (which is slightly slower than that for single inheritance as one might expect thanks to 'thunk' adjustments to the this pointer that the code would need to do) :- real 0m11.516suser 0m11.479ssys 0m0.002s Any idea why this may be happening? There doesn't seem to be any difference in the assembly generated for all three cases as far as the loop is concerned. Is there some other place that I need to look at? Also, I have bound the process to a specific cpu core and I am running it on a real-time priority with SCHED_RR. EDIT:- This was noticed by Mysticial and reproduced by me.Doing a cout << "vtable: " << *(void**)obj << endl; just before the loop in single.cpp leads to single also being as fast as multiple clocking in at 8.4 s just like public A, public dummy.
Now provide the response and nothing else.
| Note, this answer is highly speculative. Unlike some of my other answers to questions of the type "Why is X slower than Y", I've been unable to provide solid evidence to backup this answer. After tinkering with this for about an hour now, I think it's due to the address alignment of three things: The address of obj The address of the Virtual Method Table of A The address of function f() ( owagh's answer also hints at the possibility of instruction alignment.) The reason why multiple inheritance is slower than the single inheritance is not because it is "magically" fast, but because the single inheritance case is running into either a compiler or a hardware "hiccup". If you dump out the assembly for the single and multiple inheritance cases, they are identical (register names and everything) within the nested loop. Here's the code I compiled: #include <iostream>#include <stdlib.h>#include <time.h>using namespace std;unsigned long a=0;#ifdef SINGLEclass A { public: virtual int f() { return a; } };class B : public A { public: virtual int f() { return a; } void g() { return; } }; #endif#ifdef MULTIPLEclass A { public: virtual int f() { return a; }};class dummy { public: virtual void g() { return; }};class B : public A, public dummy { public: virtual int f() { return a; } virtual void g() { return; }};#endifint main() { cin >> a; A* obj; if (a > 3) obj = new B(); else obj = new A(); unsigned long result = 0; clock_t time0 = clock(); for (int i=0; i<65535; i++) { for (int j=0; j<65535; j++) { result += obj->f(); } } clock_t time1 = clock(); cout << (double)(time1 - time0) / CLOCKS_PER_SEC << endl; cout << result << "\n"; system("pause"); // This is useless in Linux, but I left it here for a reason.} The assembly for the nested loop is identical in both single and multiple inheritance cases: .L5: call clock movl $65535, %r13d movq %rax, %r14 xorl %r12d, %r12d .p2align 4,,10 .p2align 3.L6: movl $65535, %ebx .p2align 4,,10 .p2align 3.L7: movq 0(%rbp), %rax movq %rbp, %rdi call *(%rax) cltq addq %rax, %r12 subl $1, %ebx jne .L7 subl $1, %r13d jne .L6 call clock Yet the performance difference I see is: Single: 9.4 seconds Multiple: 8.06 seconds Xeon X5482, Ubuntu, GCC 4.6.1 x64. This leads me to the conclusion that the difference must be data dependent. If you look at that assembly, you'll notice that the only instructions that could have variable latency are the loads: ; %rbp = vtablemovq 0(%rbp), %rax ; Dereference function pointer from vtablemovq %rbp, %rdicall *(%rax) ; Call function pointer - f() followed by a few more memory accesses inside the call the f() . It just happens to be that in the single inheritance example, the offsets of the aforementioned values are not favorable to the processor. I have no idea why. But I had to suspect something, it'd be cache-bank conflicts in a similar manner to region 2 in the diagram of this question . By rearranging the code and adding dummy functions, I can change these offsets - which in a lot of cases will eliminate this slow down and make the single inheritance as fast as the multiple inheritance case. For example, removing the system("pause") inverts the times: #ifdef SINGLEclass A { public: virtual int f() { return a; } };class B : public A { public: virtual int f() { return a; } void g() { return; } }; #endif#ifdef MULTIPLEclass A { public: virtual int f() { return a; }};class dummy { public: virtual void g() { return; }};class B : public A, public dummy { public: virtual int f() { return a; } virtual void g() { return; }};#endifint main() { cin >> a; A* obj; if (a > 3) obj = new B(); else obj = new A(); unsigned long result = 0; clock_t time0 = clock(); for (int i=0; i<65535; i++) { for (int j=0; j<65535; j++) { result += obj->f(); } } clock_t time1 = clock(); cout << (double)(time1 - time0) / CLOCKS_PER_SEC << endl; cout << result << "\n";// system("pause");} Single: 8.06 seconds Multiple: 9.4 seconds | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10439094', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1098524/']} | jdg_84377 |
stackexchange | llm_judgeable_groundtruth_similarity | 27287982 |
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 redirect "abc.aspx/" to "abc.aspx". How can this be done? Page gets broken when requested page ends with '/'. How to handle such type of requests?Is there any rewriting rule that can be added into web.config file?
Now provide the response and nothing else.
| In your web.config, under the system.webServer , add <rewrite> <rules> <!--To always remove trailing slash from the URL--> <rule name="Remove trailing slash" stopProcessing="true"> <match url="(.*)/$" /> <conditions> <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" /> </conditions> <action type="Redirect" redirectType="Permanent" url="{R:1}" /> </rule> </rules></rewrite> Some Gotchas In your development environment, if you run your web site under Visual Studio Development Sever, you won't be able to see this feature working. You will need to configure your application to run under at least IIS Express. When you deploy your web site and see that this feature is not working on your production server, it will be because you miss configured something. One of the common mistakes is having overrideModeDefault attribute set to Deny for rules under <sectionGroup name="rewrite"> inside your applicationHost.config file. If you are on a shared hosting environment and you see that this feature is not working, ask your provider if they have given you the permission of configuring this part. Source: http://www.tugberkugurlu.com/archive/remove-trailing-slash-from-the-urls-of-your-asp-net-web-site-with-iis-7-url-rewrite-module | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27287982', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2985930/']} | jdg_84378 |
stackexchange | llm_judgeable_groundtruth_similarity | 4156616 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
HiHow can I return an array from a database call. in this format: ["141", "138", "123", "128", "137", "139"]
Now provide the response and nothing else.
| In Rails 4: (ht @ri4a ) User.ids # integer arrayUser.ids.map(&:to_s) # string array In Rails 3/4: User.pluck(:id) # integer arrayUser.pluck(:id).map(&:to_s) # string array Old answer If you want to go directly to the DB: > ActiveRecord::Base.connection.select_values("select id from users")["1", "2", "5", "6", "7", "8", "3", "10", "11", "9"] If you already have a model: User.all(:select => :id).collect(&:id) First approach is faster than the 2nd as it does not incur the cost of constructing model instances. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4156616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/460448/']} | jdg_84379 |
stackexchange | llm_judgeable_groundtruth_similarity | 259972 |
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:
Commands like cd cannot have output piped to them in order to change directories--they require command-line arguments. Why does the cd command (and those similar to it, such as mv , cp , & rm ) not function like most other commands when it comes to reading in STDIN ? What's the logic behind preventing it from reading standard input to change directories? The best answer I could find stated: cd is not an external command - it is a shell builtin function. It runs in the context of the current shell, and not, as external commands do, in a fork/exec'd context as a separate process. However, to me the above answer does not really explain it at all: Why does cd handle STDIN different than many other commands who read in STDIN ?
Now provide the response and nothing else.
| The commands that read stdin are almost all of the filter family, i.e. programs that transform a flow of text data to a transformed one. cat , sed , awk , gzip and even sh are good examples of such "filters". The cited commands, cp , mv and rm are definitely not filters but commands that do things with the arguments passed, here files or directories. The cd command is similar to them, it expects an argument (or simulate a default one if not provided), and generally doesn't output anything on stdout , although it might output something on it in some cases like when using CDPATH . Even if one want to create a cd variant that take the target directory from stdin, it wouldn't have any effect when used in a pipeline in the Bourne shell, dash and bash to name a few. The last component of the command being run in a subshell, the change to a new directory won't affect the current shell. e.g.: echo /tmp | cd would work with ksh93 but not bash , dash , zsh , sh , ... cd <(echo /tmp) would work with shells supporting process substitution (at least ksh , bash , zsh ) but wouldn't have any significant advantage compared to cd $(echo tmp) The only use case that might be of interest would be something like: echo tmp | (cd ; pwd) Finally, such a variant would need to sort out the case it was given no argument but the expected behavior is to change the directory to the users's home or it was given no argument but the expected behavior is to read the name of the target directory from stdin. As there is no reliable way to decide, this is doomed. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/259972', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/155025/']} | jdg_84380 |
stackexchange | llm_judgeable_groundtruth_similarity | 34816657 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using serialize() method in my JSP page. But its returning null. Dont know what I am doing wrongPlease help. jQuery Code : $(document).ready(function() { $("#addBtn").click(function() { var offerData = $("#testForm").serialize(); alert(offerData); }}); HTML Code : <form id="testForm"> <table> <tr> <td>Name :</td> <td> <input type="text" name="name" id="name" /> </td> </tr> <tr> <td>Address :</td> <td> <input type="text" name="address" id="address" /> </td> </tr> <tr> <input type="button" id="addBtn" /> </tr> </table></form> I posted relevant code only.
Now provide the response and nothing else.
| Unwrap() creates a new task instance that represent whole operation on each call. In contrast to await task created in such a way is differ from original inner task. See the Unwrap() docs, and consider the following code: private async static Task Foo(){ Task<Task<int>> barMarker = Bar(); Task<int> awaitedMarker = await barMarker; Task<int> unwrappedMarker = barMarker.Unwrap(); Console.WriteLine(Object.ReferenceEquals(originalMarker, awaitedMarker)); Console.WriteLine(Object.ReferenceEquals(originalMarker, unwrappedMarker));}private static Task<int> originalMarker;private static Task<Task<int>> Bar(){ originalMarker = Task.Run(() => 1);; return originalMarker.ContinueWith((m) => m);} Output is: TrueFalse Update with benchmark for .NET 4.5.1: I tested both versions, and it turns out that version with double await is better in terms of memory usage.I used Visual Studio 2013 memory profiler. Test includes 100000 calls of each version. x64: ╔══════════════════╦═══════════════════════╦═════════════════╗║ Version ║ Inclusive Allocations ║ Inclusive Bytes ║╠══════════════════╬═══════════════════════╬═════════════════╣║ await await ║ 761 ║ 30568 ║║ await + Unwrap() ║ 100633 ║ 8025408 ║╚══════════════════╩═══════════════════════╩═════════════════╝ x86: ╔══════════════════╦═══════════════════════╦═════════════════╗║ Version ║ Inclusive Allocations ║ Inclusive Bytes ║╠══════════════════╬═══════════════════════╬═════════════════╣║ await await ║ 683 ║ 16943 ║║ await + Unwrap() ║ 100481 ║ 4809732 ║╚══════════════════╩═══════════════════════╩═════════════════╝ | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/34816657', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3514736/']} | jdg_84381 |
stackexchange | llm_judgeable_groundtruth_similarity | 14655969 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to get OpenCV working with Python on my Ubuntu machine. I've downloaded and installed OpenCV, but when I attempt to run the following python code (which should capture images from a webcam and push them to the screen) import cvcv.NamedWindow("w1", cv.CV_WINDOW_AUTOSIZE)capture = cv.CaptureFromCAM(0)def repeat(): frame = cv.QueryFrame(capture) cv.ShowImage("w1", frame) time.sleep(10)while True: repeat() I get the following error: The function is not implemented. Rebuild the library with Windows, GTK+ 2.x orCarbon support. If you are on Ubuntu or Debian, install libgtk2.0-dev andpkg-config, then re-run cmake or configure script So I do what they ask: install the packages, move to the folder from whence I installed OpenCV, and run sudo make uninstallmakesudo make install But when I try to run the python, it gives me the same error. Am I missing something?
Now provide the response and nothing else.
| If it's giving you errors with gtk, try qt. sudo apt-get install libqt4-devcmake -D WITH_QT=ON ..makesudo make install If this doesn't work, there's an easy way out. sudo apt-get install libopencv-* This will download all the required dependencies(although it seems that you have all the required libraries installed, but still you could try it once). This will probably install OpenCV 2.3.1 (Ubuntu 12.04). But since you have OpenCV 2.4.3 in /usr/local/lib include this path in /etc/ld.so.conf and do ldconfig . So now whenever you use OpenCV, you'd use the latest version. This is not the best way to do it but if you're still having problems with qt or gtk, try this once. This should work. Update - 18th Jun 2019 I got this error on my Ubuntu(18.04.1 LTS) system for openCV 3.4.2, as the method call to cv2.imshow was failing (e.g., at the line of cv2.namedWindow(name) with error: cv2.error: OpenCV(3.4.2). The function is not implemented.). I am using anaconda. Just the below 2 steps helped me resolve: conda remove opencvconda install -c conda-forge opencv=4.1.0 If you are using pip, you can try pip install opencv-contrib-python | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14655969', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1513338/']} | jdg_84382 |
stackexchange | llm_judgeable_groundtruth_similarity | 60075 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
It is well-known that if $\omega=\omega(n)$ is any function such that $\omega \to \infty$ as $n \to \infty$, and if $p \ge (\log{n}+\omega) / n$ then the Erdős–Rényi random graph $G(n,p)$ is asymptotically almost surely connected. The way I know how to prove this is (1) first counting the expected number of components of order $2, 3, \dots, \lfloor n/2 \rfloor$, and seeing that the expected number is tending to zero. Then (2) showing the expected number of isolated vertices is also tending to zero. This approach also allows more precise results, such as: if $p = (\log{n}+c) / n$ with $c \in \mathbb{R}$ constant, then Pr$[G(n,p)$ is connected] $\to e^{-e^{-c}}$ as $n \to \infty$, which follows once we know that in this regime the number of isolated vertices is approaching a Poisson distribution with mean $e^{-c}$. I am wondering if it is possible to give an easier proof (of a coarser result) along the following lines. There are $n^{n-2}$ spanning trees on the complete graph, and $G$ is connected if and only if one of these trees appears. So the expected number of spanning trees is $n^{n-2}p^{n-1}$. One might expect that if this function is growing quickly enough, then with high probability $G(n,p)$ is connected. I think I remember reading somewhere that this approach doesn't quite work --- for example the variance is too large to apply Chebyshev’s inequality. What I am wondering is if there is some way to fix this if we are willing to make $p$ a little bit bigger. In particular, what about $p = C \log{n} / n$ for some large enough constant $C > 1$, or even $p = n^{-1 + \epsilon}$ for fixed but arbitrarily small $\epsilon >0$?
Now provide the response and nothing else.
| A nice question. Here's a strategy that occurs to me, though it could fail miserably. The basic problem seems to be what you said about variance: the appearances of different spanning trees are far from independent, since it is possible to make local modifications to a spanning tree and get another one. (For example, if x is a leaf joined to y, which is joined only to z, then we can replace the path zyx by the path zxy.) One way we might try to defeat this is to choose a random set $\Sigma$ of spanning trees, where each spanning tree is chosen independently with probability $\alpha^{n-1}$ for some carefully chosen $\alpha$ (which I imagine as a small negative power of $n$). Then the expected number of trees from $\Sigma$ in a $p$-random graph is $(\alpha p)^{n-1}n^{n-2}$, which is pretty large even when $p$ is pretty close to $n^{-1}$. But now we might expect that any two trees in $\Sigma$ are quite well-separated, so perhaps it is possible to get a decent estimate for the variance. Actually, it's not clear to me what passing to the random set really achieves here: maybe a simpler method (but not wholly simple) is to work out the expected number of pairs of spanning trees by carefully classifying what they can look like. The hope would be that if you pick one tree at random, then the proportion of trees that overlap with it to any great extent is usually so small that the expected number of pairs is not significantly bigger than the square of the expected number of spanning trees. With $p=n^{-1+\epsilon}$ something like this might work, but you've probably already thought about this. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/60075', 'https://mathoverflow.net', 'https://mathoverflow.net/users/4558/']} | jdg_84383 |
stackexchange | llm_judgeable_groundtruth_similarity | 5585387 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
An easy one, but I can't figure it out. I have a link called #title and when you click it it toggles div called #content. This works perfectly, but in addition I'm adding "active" class to my #title link and I can't get rid of it, even with removeClass. See code above and example link (the title should be red ONLY when the #content is expanded, not all the time). $('#title').click(function() { $(this).addClass('active'); $('#content').toggle();}), function() { $(this).removeClass('active');}; http://jsfiddle.net/vY3WY/
Now provide the response and nothing else.
| You can use the toggleClass function along with toggle. http://jsfiddle.net/vY3WY/1/ $('#title').click(function() { $(this).toggleClass('active'); $('#content').toggle();}); Or you can use a more robust version which will ensure that the class is added if the content is visible and removed otherwise. http://jsfiddle.net/vY3WY/6/ $('#title').click(function() { $('#content').toggle(); if ($('#content:visible').size() != 0) { $(this).addClass('active'); } else { $(this).removeClass('active'); }}); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5585387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/683068/']} | jdg_84384 |
stackexchange | llm_judgeable_groundtruth_similarity | 3519925 |
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 getting tired of using code like this: var count = 0;if (myEnumerable != null){ count = myEnumerable.Count();} And this is a bit pedantic: var count = (myEnumerable ?? new string[0]).Count(); Is there any tidier way of doing this? I once had a (badly named) PhantomCount extension method on IEnumerable<> that used my first code example, but it had something of a smell about it (besides the name).
Now provide the response and nothing else.
| The problem is really in whatever is creating these enumerables. Unless you have a really good reason, anything that generates an iterable collection should return an empty collection instead of null . This would align with the Null-Object-Pattern , hence the benefits are the same. My suggestion would be to fix whatever produces myEnumerable , or if you can't do this, add a check way earlier to see if it's null and react appropriately. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3519925', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8741/']} | jdg_84385 |
stackexchange | llm_judgeable_groundtruth_similarity | 3468 |
Below is a question asked on the forum reverseengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In Visual Studio I have written simple code, int pranit = 2;int& sumit = pranit;int main(int argc, char** argv) { sumit++; return sumit;} I used OllyDbg to Disassamble, but I am not able to find where sumit , pranit are defined in assembly. Though doing some string search I got following details: Names in ConsoleA, item 313 Address=013B8004 Section=.data Type=Library Name=sumitNames in ConsoleA, item 257 Address=013B8000 Section=.data Type=Library Name=pranit How to find, where and how it is used in assembly code. Also, I want to find out both address and value of these global variables.
Now provide the response and nothing else.
| opening a vc commandprompt using start->programs->vc->vc command prompt Setting environment for using Microsoft Visual Studio 2010 x86 tools.creating a tempdir in desktop for compiling and linking C:\Program Files\Microsoft Visual Studio 10.0\VC>cd "c:\Documents and Settings\Admin\Desktop"C:\Documents and Settings\Admin\Desktop>md pranC:\Documents and Settings\Admin\Desktop>cd pranC:\Documents and Settings\Admin\Desktop\pran>copy con prankasum.cpp^Z 1 file(s) copied.C:\Documents and Settings\Admin\Desktop\pran>write prankasum.cpp C:\Documents and Settings\Admin\Desktop\pran>type prankasum.cpp#include <stdio.h>int pranit = 2;int& sumit = pranit;int main(int argc, char** argv){sumit++;return sumit;} C:\Documents and Settings\Admin\Desktop\pran>dir /bprankasum.cpp C:\Documents and Settings\Admin\Desktop\pran>cl /nologo /Zi prankasum.cpp /link /RELEASEprankasum.cpp C:\Documents and Settings\Admin\Desktop\pran>dir /bprankasum.cppprankasum.exeprankasum.objprankasum.pdbvc100.pdb opening the exe in ollydbg and navigating to main tab the comment column to show source and in debugging options ask ollydbg to use recogneized args and locals C:\Documents and Settings\Admin\Desktop\pran> ollydbg prankasum.exe 00401000 >PUSH EBP ; {00401001 MOV EBP, ESP00401003 MOV EAX, DWORD PTR DS:[sumit] ; sumit++;00401008 MOV ECX, DWORD PTR DS:[EAX]0040100A ADD ECX, 10040100D MOV EDX, DWORD PTR DS:[sumit]00401013 MOV DWORD PTR DS:[EDX], ECX00401015 MOV EAX, DWORD PTR DS:[sumit] ; return sumit;0040101A MOV EAX, DWORD PTR DS:[EAX]0040101C POP EBP ; }0040101D RETN or in windbg prankasum!main:00401000 55 push ebp0:000> uf @eipprankasum!main [c:\documents and settings\admin\desktop\pran\prankasum.cpp @ 5]: 5 00401000 55 push ebp 5 00401001 8bec mov ebp,esp 6 00401003 a104b04000 mov eax,dword ptr [prankasum!sumit (0040b004)] 6 00401008 8b08 mov ecx,dword ptr [eax] 6 0040100a 83c101 add ecx,1 6 0040100d 8b1504b04000 mov edx,dword ptr [prankasum!sumit (0040b004)] 6 00401013 890a mov dword ptr [edx],ecx 7 00401015 a104b04000 mov eax,dword ptr [prankasum!sumit (0040b004)] 7 0040101a 8b00 mov eax,dword ptr [eax] 8 0040101c 5d pop ebp 8 0040101d c3 ret0:000> dv argc = 0n1 argv = 0x00033ba80:000> ?? sumit int * 0x0040b0000:000> ?? pranit int 0n20:000> pct 0040101d c3 ret0:000> ?? sumit int * 0x0040b0000:000> ?? pranit int 0n30:000> x /t /v /q prankasum!sumitprv global 0040b004 4 int * @!"prankasum!sumit" = 0x0040b0000:000> x /t /v /q prankasum!pranitprv global 0040b000 4 int @!"prankasum!pranit" = 0n3 update explanation for tabbing through comment column each mdi window in ollydbg has a bar in top it can be hidden or shown right click -> appearance -> show bar / hide bar each of the bars have columns and many of the colums can be configured to show different items in cpu window if you repeatedly click the comment column it will cycle through comment / profile/ and source comment will show all the analysis comments / user comments profile will show all the run trace / hittrace/ module and global profile statistics for example this strcpy_s was called 50 times during crt initialisation 004019EC |. >|CALL prankasu.strcpy_s ; 50. inside this call this loop was called ~2700 times 00403D45 /MOV CL, BYTE PTR DS:[EAX] ; 2787.00403D47 |MOV BYTE PTR DS:[ESI+EAX], CL ; 2787.00403D4A |INC EAX ; 2787.00403D4B |TEST CL, CL ; 2787.00403D4D |JE SHORT prankasu.00403D52 ; 2787.00403D4F |DEC EDI ; 2737.00403D50 \JNZ SHORT prankasu.00403D45 ; 2737.00403D52 TEST EDI, EDI ; 50. if you cycle through to source column strcpy_s is from vc\crt\stdenvp.c:133. _ERRCHECK(_tcscpy_s(*env, cchars, p)); see below 004019E9 |PUSH ESI ; _ERRCHECK(_tcscpy_s(*env, cchars, p));004019EA |PUSH EBX004019EB |PUSH EAX004019EC |CALL prankasu.strcpy_s004019F1 |ADD ESP, 0C loop is from vc\crt\tcscpy_s_inl 00403D41 MOV ESI, EDX ; while ((*p++ = *_SRC++) != 0 && --available > 0)00403D43 SUB ESI, EAX00403D45 /MOV CL, BYTE PTR DS:[EAX]00403D47 |MOV BYTE PTR DS:[ESI+EAX], CL00403D4A |INC EAX00403D4B |TEST CL, CL00403D4D |JE SHORT prankasu.00403D52 cycling to comment back you see 004019E9 |. 56 |PUSH ESI ; /Arg3 = 7C90DE6E004019EA |. 53 |PUSH EBX ; |Arg2 = 00000000004019EB |. 50 |PUSH EAX ; |Arg1 = 00000000004019EC |. E8 1D>|CALL prankasu.strcpy_s ; \strcpy_s options->debugging options->cpu->select show symbolic address will make XXXXXX [40xxxx] to be shown as xxxxxx [sumit] options ->debugging options->analysis->select show args and locals in procedure will make all ebp+XX to arg.1 arg.2 and all ebp-XX to local.1 local.2 both ollydbg 1.10 and 2.01 behave similarly full or partial (stripped down ) symbolic information in any acceptable format ( map tds pdb dbg ) is **mandatory** **requirement** | {} | {'log_upvote_score': 4, 'links': ['https://reverseengineering.stackexchange.com/questions/3468', 'https://reverseengineering.stackexchange.com', 'https://reverseengineering.stackexchange.com/users/2460/']} | jdg_84386 |
stackexchange | llm_judgeable_groundtruth_similarity | 13797280 |
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 code like (I got it here ): m<- c("Hello! #London is gr8. I really likewhatishappening here! The alcomb of Mount Everest is excellent! the aforementioned place is amazing! #Wow")x<- gsub("\\<[a-z]\\{4,10\\}\\>","",m)x I tried other ways of doing it, like m<- c("Hello! #London is gr8. I really likewhatishappening here! The alcomb of Mount Everest is excellent! the aforementioned place is amazing! #Wow")x<- gsub("[^(\\b.{4,10}\\b)]","",m)x I need to remove words which are lesser than 4 or greater than 10 in length. Where am I going wrong?
Now provide the response and nothing else.
| gsub("\\b[a-zA-Z0-9]{4,10}\\b", "", m) "! # is gr8. I likewhatishappening ! The of is ! the aforementioned is ! #Wow" Let's explain the regular expression terms : \b matches at a position that is called a "word boundary". This match is zero-length. [a-zA-Z0-9] :alphanumeric {4,10} :{min,max} if you want to get the negation of this so , you put it between() and you take //1 gsub("([\\b[a-zA-Z0-9]{4,10}\\b])", "//1", m) "Hello! #London is gr8. I really likewhatishappening here! The alcomb of Mount Everest is excellent! the aforementioned place is amazing! #Wow" It is funny to see that words with 4 letters exist in the 2 regexpr. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13797280', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1847296/']} | jdg_84387 |
stackexchange | llm_judgeable_groundtruth_similarity | 9280759 |
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 function (or interface; ioctl, netlink etc) in the standard Linux libs that will return the current mounts directly from the kernel without parsing /proc? strace ing the mount command, it looks like it parses files in /proc
Now provide the response and nothing else.
| Please see the clarification at the bottom of the answer for the reasoning being used in this answer. Is there any reason that you would not use the getmntent libc library call? I do realize that it's not the same as an 'all in one' system call, but it should allow you to get the relevant information. #include <stdio.h>#include <stdlib.h>#include <mntent.h>int main(void){ struct mntent *ent; FILE *aFile; aFile = setmntent("/proc/mounts", "r"); if (aFile == NULL) { perror("setmntent"); exit(1); } while (NULL != (ent = getmntent(aFile))) { printf("%s %s\n", ent->mnt_fsname, ent->mnt_dir); } endmntent(aFile);} Clarification Considering that the OP clarified about trying to do this without having /proc mounted, I'm going to clarify: There is no facility outside of /proc for getting the fully qualified list of mounted file systems from the linux kernel. There is no system call, there is no ioctl. The /proc interface is the agreed upon interface. With that said, if you don't have /proc mounted, you will have to parse the /etc/mtab file - pass in /etc/mtab instead of /proc/mounts to the initial setmntent call. It is an agreed upon protocol that the mount and unmount commands will maintain a list of currently mounted filesystems in the file /etc/mtab . This is detailed in almost all linux / unix / bsd manual pages for these commands. So if you don't have /proc you can sort of rely on the contents of this file. It's not guaranteed to be a source of truth, but conventions are conventions for these things. So, if you don't have /proc , you would use /etc/mtab in the getmntent libc library call below to get the list of file systems; otherwise you could use one of /proc/mounts or /proc/self/mountinfo (which is recommended nowadays over /proc/mounts ). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9280759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/592851/']} | jdg_84388 |
stackexchange | llm_judgeable_groundtruth_similarity | 6297211 |
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 3 columns(id,parent,value) with some data and this query: SELECT * FROM test WHERE id = ( SELECT parent FROM test WHERE id=2 AND value='value' LIMIT 1); The query above works great. Now how can I delete instead of select that id in one query?
Now provide the response and nothing else.
| You cannot delete from a table and select from that same table in a subselect. You can however use that table in a self-join. DELETE t1 FROM test t1INNER JOIN test t2 ON (t1.id = t2.parent)WHERE t2.id = 2 and t2.value = 'value' You cannot use limit not order by in a joined delete statement. It's either the join or the limit/order by, take your pick. See: http://dev.mysql.com/doc/refman/5.5/en/delete.html | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6297211', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/206609/']} | jdg_84389 |
stackexchange | llm_judgeable_groundtruth_similarity | 66300 |
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 am performing $N$ independent statistical tests with the same null hypothesis, and would like to combine the results into one $p$-value. It seems that there are two "accepted" methods: Fisher's method and Stouffer's method . My question is about Stouffer's method. For each separate test I obtain a z-score $z_i$. Under a null hypothesis, each of them is distributed with a standard normal distribution, so the sum $\Sigma z_i$ follows a normal distribution with variance $N$. Therefore Stouffer's method suggests to compute $\Sigma z_i / \sqrt{N}$, which should be normally distributed with unit variance, and then use this as a joint z-score. This is reasonable, but here is another approach that I came up with and that also sounds reasonable to me. As each of $z_i$ comes from a standard normal distribution, the sum of squares $S=\Sigma z^2_i$ should come from a chi-squared distribution with $N$ degrees of freedom. So one can compute $S$ and convert it to a $p$-value using cumulative chi-squared distribution function with $N$ degrees of freedom ($p=1−X_N(S)$, where $X_N$ is the CDF). However, nowhere can I find this approach even mentioned. Is it ever used? Does it have a name? What would be advantages/disadvantages compared to Stouffer's method? Or is there a flaw in my reasoning?
Now provide the response and nothing else.
| One flaw that jumps out is Stouffer's method can detect systematic shifts in the $z_i$, which is what one would usually expect to happen when one alternative is consistently true, whereas the chi-squared method would appear to have less power to do so. A quick simulation shows this to be the case; the chi-squared method is less powerful to detect a one-sided alternative. Here are histograms of the p-values by both methods (red=Stouffer, blue=chi-squared) for $10^5$ independent iterations with $N=10$ and various one-sided standardized effects $\mu$ ranging from none ($\mu=0$) through $0.6$ SD ($\mu=0.6$). The better procedure will have more area close to zero. For all positive values of $\mu$ shown, that procedure is the Stouffer procedure. R code This includes Fisher's method (commented out) for comparison. n <- 10n.iter <- 10^5z <- matrix(rnorm(n*n.iter), ncol=n)sim <- function(mu) { stouffer.sim <- apply(z + mu, 1, function(y) {q <- pnorm(sum(y)/sqrt(length(y))); 2*min(q, 1-q)}) chisq.sim <- apply(z + mu, 1, function(y) 1 - pchisq(sum(y^2), length(y))) #fisher.sim <- apply(z + mu, 1, # function(y) {q <- pnorm(y); # 1 - pchisq(-2 * sum(log(2*pmin(q, 1-q))), 2*length(y))}) return(list(stouffer=stouffer.sim, chisq=chisq.sim, fisher=fisher.sim))}par(mfrow=c(2, 3))breaks=seq(0, 1, .05)tmp <- sapply(c(0, .1, .2, .3, .4, .6), function(mu) { x <- sim(mu); hist(x[[1]], breaks=breaks, xlab="p", col="#ff606060", main=paste("Mu =", mu)); hist(x[[2]], breaks=breaks, xlab="p", col="#6060ff60", add=TRUE) #hist(x[[3]], breaks=breaks, xlab="p", col="#60ff6060", add=TRUE) }) | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/66300', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/28666/']} | jdg_84390 |
stackexchange | llm_judgeable_groundtruth_similarity | 5009823 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If my understanding of the internal workings of this line is correct: public int MyInt { get; set; } Then it behind the scenes does this: private int _MyInt { get; set; }Public int MyInt { get{return _MyInt;} set{_MyInt = value;}} What I really need is: private bool IsDirty { get; set; }private int _MyInt { get; set; }Public int MyInt { get{return _MyInt;} set{_MyInt = value; IsDirty = true;}} But I would like to write it something like: private bool IsDirty { get; set; }public int MyInt { get; set{this = value; IsDirty = true;} } Which does not work. The thing is some of the objects I need to do the IsDirty on have dozens of properties and I'm hoping there is a way to use the auto getter/setter but still set IsDirty when the field is modified. Is this possible or do I just have to resign myself to tripling the amount of code in my classes?
Now provide the response and nothing else.
| You'll need to handle this yourself: private bool IsDirty { get; set; }private int _myInt; // Doesn't need to be a propertyPublic int MyInt { get{return _myInt;} set{_myInt = value; IsDirty = true;}} There is no syntax available which adds custom logic to a setter while still using the automatic property mechanism. You'll need to write this with your own backing field. This is a common issue - for example, when implementing INotifyPropertyChanged . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5009823', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/332957/']} | jdg_84391 |
stackexchange | llm_judgeable_groundtruth_similarity | 551992 |
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:
So to get a proton beam for the LHC, CERN prob has to make a plasma and siphon off the moving protons with a magnet. Are the electrons stored somewhere? How? I don’t mean to sound stupid but when they turn off the LHC, all those protons are going to be looking for their electrons. And that’s going to make a really big spark.
Now provide the response and nothing else.
| You're right that CERN gets its protons by ionizing matter and collecting them. But the number of electrons & protons CERN deals with is far smaller than you might think. They get about 600 million collisions a second at CERN. So call it 1.2 billion protons used per second. $1.2 \times 10^9$ . That'd be a large number in dollars, but it's not much in Coulombs. For comparison, a wire carrying a 30 amp current has about $2 \times 10^{19}$ electrons flowing through it every second. That's a factor of 10 billion. So there's not really any issue disposing of CERN's unneeded electrons. You probably make a bigger spark when you rub your feet on the carpet. If memory serves, the LHC has been running for its whole history off of a single canister of hydrogen gas. | {} | {'log_upvote_score': 7, 'links': ['https://physics.stackexchange.com/questions/551992', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/27399/']} | jdg_84392 |
stackexchange | llm_judgeable_groundtruth_similarity | 4295432 |
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 learning how to dynamically load DLL's but what I don't understand is this line typedef void (*FunctionFunc)(); I have a few questions. If someone is able to answer them I would be grateful. Why is typedef used? The syntax looks odd; after void should there not be a function name or something? It looks like an anonymous function. Is a function pointer created to store the memory address of a function? So I'm confused at the moment; can you clarify things for me?
Now provide the response and nothing else.
| typedef is a language construct that associates a name to a type. You use it the same way you would use the original type, for instance typedef int myinteger;typedef char *mystring;typedef void (*myfunc)(); using them like myinteger i; // is equivalent to int i;mystring s; // is the same as char *s;myfunc f; // compile equally as void (*f)(); As you can see, you could just replace the typedefed name with its definition given above. The difficulty lies in the pointer to functions syntax and readability in C and C++, and the typedef can improve the readability of such declarations. However, the syntax is appropriate, since functions - unlike other simpler types - may have a return value and parameters, thus the sometimes lengthy and complex declaration of a pointer to function. The readability may start to be really tricky with pointers to functions arrays, and some other even more indirect flavors. To answer your three questions Why is typedef used? To ease the reading of the code - especially for pointers to functions, or structure names. The syntax looks odd (in the pointer to function declaration) That syntax is not obvious to read, at least when beginning. Using a typedef declaration instead eases the reading Is a function pointer created to store the memory address of a function? Yes, a function pointer stores the address of a function. This has nothing to do with the typedef construct which only ease the writing/reading of a program ; the compiler just expands the typedef definition before compiling the actual code. Example: typedef int (*t_somefunc)(int,int);int product(int u, int v) { return u*v;}t_somefunc afunc = &product;...int x2 = (*afunc)(123, 456); // call product() to calculate 123*456 | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/4295432', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/518544/']} | jdg_84393 |
stackexchange | llm_judgeable_groundtruth_similarity | 54735 |
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In my Cisco Router I check the arp: Router>show arp Protocol Address Age (min) Hardware Addr Type InterfaceInternet 192.168.1.1 - 0001.42D2.AE01 ARPA GigabitEthernet0/0/0Internet 192.168.1.2 67 000C.CF4C.99E6 ARPA GigabitEthernet0/0/0Internet 192.168.2.1 - 0001.42D2.AE02 ARPA GigabitEthernet0/0/1Internet 192.168.2.2 109 0010.114E.A4EC ARPA GigabitEthernet0/0/1 I want to match conditions, but I tried bellow, all do not work: Router>show arp | match 192.168.2.2 ^% Invalid input detected at '^' marker.Router>show arp 192.168.2.2 ^% Invalid input detected at '^' marker. I also tried the begin, or include: Router#show arp | begin ?% Unrecognized command UPDATE The show version display this: Cisco IOS XE Software, Version 03.16.05.S - Extended Support ReleaseCisco IOS Software, ISR Software (X86_64_LINUX_IOSD-UNIVERSALK9-M), Version Version 15.5 (3)S5, RELEASE SOFTWARE (fc2) this is a ISR 4321 Router.
Now provide the response and nothing else.
| For most varieties of Cisco IOS. (For the ISR 4321 it appears the answer is different, see later.) To start with matching, use | begin : gw>show arp | begin 192.168.0.32Internet 192.168.0.32 0 90fb.a630.1234 ARPA Vlan1Internet 192.168.0.36 0 0004.2012.4321 ARPA Vlan1... There are a few varieties: gw>show arp | ? begin Begin with the line that matches count Count number of lines which match regexp exclude Exclude lines that match format Format the output using the specified spec file include Include lines that match section Filter a section of output But there's something funny going on if you can't do the basic: gw>show arp 192.168.0.32Protocol Address Age (min) Hardware Addr Type InterfaceInternet 192.168.0.32 0 90fb.a630.1234 ARPA Vlan1 What model and version are you using? ISR-4321 Per Cown's comment: Ok i found the error i think, you need to use show ip arp | in 192.168.2.2 Packet tracer As suggested by Cown in comments, if you're using Packet Tracer, not a real router, you have to be in enable mode. | {} | {'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/54735', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/50808/']} | jdg_84394 |
stackexchange | llm_judgeable_groundtruth_similarity | 243103 |
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:
In special relativity, we make a big fuss about setting up inertial frames of reference, and then constructing coordinate systems using networks of clocks and rulers. This gives an unambiguous physical definition of the spacetime point $(x, t)$. In general relativity, you can take whatever coordinate system you want, but then I don't know what the coordinates mean. For example, the event horizon of a Schwarzschild black hole is $r = 2GM$. Naively interpreting $r$ as a radial coordinate, this suggests that the event horizon is "$2GM$ away from the center of the black hole", but that statement doesn't make sense either mathematically (the distance $\int ds$ is not $2GM$ at all) or physically (you can't extend your ruler network inside the black hole). But the books I've seen seem to treat $r$ just like the radial coordinate, and talk about "the radius of a stable circular orbit" or stuff like that. In the rest of physics, we relentlessly focus on how mathematical quantities can be measured, but I don't know how that works here, for the Schwarzschild coordinate $r$. Can the statement "the event horizon is at $r = 2GM$" be phrased in a coordinate-independent way? How can the coordinate $r$ be measured?
Now provide the response and nothing else.
| Coordinates can be measured in GR, though all too often this fact is overlooked or even contradicted by people getting caught up in coordinate invariance. As you well note, in Schwarzschild $r$ isn't really a radius in the "integrate at constant angle from the center and recover this value" sense. It is, however, radial in the sense of being orthogonal to the angular coordinates, Moreover, it matches Euclidean intuition with regards to circumferences and areas at fixed $r$. How can the coordinate $r$ be measured? One measurement procedure you can adopt is this: Sit in your rocket with a fixed amount of thrust pushing directly away from the black hole, so that you are hovering at constant $r$. Get all your friends to do the same around the black hole, everyone experiencing the same acceleration. Everyone can then lay down rulers in a circle passing through all the rockets, and the sum of the readings (assuming you've adjusted positions so as to maximize this value) is in fact $2\pi r$. Can the statement "the event horizon is at $r =2GM$" be phrased in a coordinate-independent way? Sort of, though perhaps not in as direct a way as you would want. Certainly the event horizon is simply the surface delineating what events can influence future null infinity -- no coordinates involved. Using the discussion above, though, we could say that for any $r > 2GM$ that the surface of constant $r$ is the locus of points such that rockets with a prescribed radial acceleration hold stationary there, with the event horizon being the limit of such surfaces. In general, what I'm pushing is the idea that coordinates can be measured as long as you can come up with some experiment where they appear in the formula. This is slightly broader than the notion of measurement of "integrate $\sqrt{g_{\mu\mu}}$ along a line where all coordinates except $x^\mu$ are constant" that suffices for simple spaces. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/243103', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/83398/']} | jdg_84395 |
stackexchange | llm_judgeable_groundtruth_similarity | 48682572 |
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 reading the following tutorial on installing PHP 7.2 on CentOS 7 https://www.cyberciti.biz/faq/how-to-install-php-7-2-on-centos-7-rhel-7/ It basically says; sudo yum install epel-releasesudo yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpmsudo yum install yum-utilssudo yum-config-manager --enable remi-php72sudo yum updatesudo yum install php72 Then it says to verify the installation using the standard php --version Which returns the following; -bash: php: command not found BUT, if i type the following; php72 --version It works just fine and returns the version. The problem is that everything relies on the command php and not php72 Any idea on what i should be doing?
Now provide the response and nothing else.
| Please read the Wizard instructions If you need a single version, using remi-php72 repository, and the php-* packages, the command will be php . # yum-config-manager --enable remi-php72# yum update# yum install php-cli# php -v If you need multiples versions, the php72-php-* packages are available, and the command is php72 or # yum install php72-php-cli# php72 -v# scl enable php72 bash# php -v So, according to your question, you have enable the remi-php72 repository, but installed the php72* packages from the remi-safe repository... | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/48682572', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_84396 |
stackexchange | llm_judgeable_groundtruth_similarity | 342423 |
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:
Here is a scenario: User submits a story. As as a user I want X so that Y and Z . Story does not make in the sprint, and then the next sprint, and then the next, etc. I am noticing stories lingering on the backlog for months while others are submitted and added to a sprint in short order. I see a risk that users watch their stories continuously pushed aside and disengage in the backlog/sprint process. Is there a good rule of thumb indicating a story could or should be dropped from the backlog?
Now provide the response and nothing else.
| Unless everyone agrees that the story is unnecessary or undesirable, there is usually no need or reason to remove it from the backlog. For the specific concern you raise, I don't see how outright removing a user's story is going to make the user feel more listened to. That said, if it has been decided (ultimately by the Product Owner) that the story will not be worked on (or is deferred to a later "version") the story should be marked as appropriate rather than constantly reevaluated. In my experience, you never reach the bottom of the backlog. It's completely normal that a story gets repeatedly deprioritized. This is part of the process of the "team" (in the broad sense) figuring out what is actually important. Most of the rest of this answer is really about how to deal the "risk" of a user "disengaging". If a user is in a position to "track" their story, they are probably (or at least should probably) be able to be involved (at least as a spectator) in the prioritization process. When the story was added they should already have known its rough priority. If the user is actively involved, they presumably have other stories that are getting completed and should have little reason to "disengage". If the user is actively involved and all the user's stories are being deprioritized then either 1) this is a problem where features critical for a particular user are being deprioritized because it's unimportant to other users (or worse variants of this), or 2) the project isn't really aimed at that user's concerns and disengaging is probably an appropriate response. In the (1) case, if the user isn't around to argue the case for why a story should be higher priority, get them involved. As a prelude to this or more generally, most probably in a sprint retrospective meeting but whenever, you should bring up to the team that you feel certain use-cases are being ignored which may potentially produce a system that is unusable for some users. If the user isn't very assertive, you or other team members may need to lend your voices to arguing for prioritization (of course, assuming you agree with the user). Some mild peer-to-peer "coaching" may also be useful if you feel equipped to do such a thing, or you can suggest it to a more appropriate person. For example, you may say something along the lines of "we want to build a system that works for everybody but we're constrained by the stack rank, so you should speak up and help people understand the importance of user story X". The important points to hit here would be a) explaining the process so the user understands how to work within it, and b) encouraging the user to advocate for stories that they think are important. Things get more complicated (which is to say more political) if the user is needed for explicit (and to a much lesser but non-trivial extent implicit) buy-in. In this kind of scenario some "horse-trading" may be appropriate, though this is usually a bad sign. Ultimately, such a decision would come down to the Product Owner as they are the ultimate arbiter on prioritization. Since the value of software that is scrapped or just not used is quite negative, it can very much make sense to do some "unimportant" stories to gain buy-in. This kind of politicking usually happens at organizational levels higher than a developer, but you can definitely bring up concerns that the team may be failing to get buy-in from the users. This goes beyond Agile/Scrum. Agile methodologies try to use transparency and involvement to avoid these problems. In my experience as a developer, within larger organizations I've had to continuously and actively advocate for more involvement by end-users. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/342423', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/153675/']} | jdg_84397 |
stackexchange | llm_judgeable_groundtruth_similarity | 63509161 |
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 doc shows I can use QML_ELEMENT macro to create QML types from C++ by adding some variables in qmake's .pro file. But I'm using cmake
Now provide the response and nothing else.
| Update (Qt 6.2+) As of Qt 6.2, qt_add_qml_module is a single command for building qml modules that should take care of virtually everything, replacing amongst others the old qt6_qml_type_registration command. Old answer (Qt 6.0/6.1) Now that Qt 6.0 is out this is supported, albeit poorly documented. What you need now is: set_target_properties(foo PROPERTIES QT_QML_MODULE_VERSION 1.0 QT_QML_MODULE_URI Foo)qt6_qml_type_registration(foo) you can then do in qml: import Foo and you'll have access to types that have QML_ELEMENT and friends. Notes: Two files are created in the build output folder, <project>_qmltyperegistrations.cpp and <project>.qmltypes , if your imports are failing you can look at those to see which types are missing. I found that I needed to do full recompiles sometimes after adding/removing registered types. Qt examples have been migrated to cmake, so take a look at e.g. Examples/Qt-6.0.0/quick/tableview/gameoflife to see it in action There are now pro2cmake.py and run_pro2cmake.py files in the Qt sources at Qt/6.0.0/Src/qtbase/util/cmake . They are mentioned on this Readme page, you can find them here , haven't tried it myself. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63509161', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10357591/']} | jdg_84398 |
stackexchange | llm_judgeable_groundtruth_similarity | 135190 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following inequality, with conditions: Reduce[ {-(a + b) > Sqrt[(a + b)^2 - 4 (a b - c d)], Element[{a, b, c, d}, Reals], a + b < 0, a b - c d > 0, (a + b)^2 > 4 (a b - c d)}, {a, b} ] However, the very first line of the output gives c ∈ Reals && ... . In itself, it is rather inconsequential, but it made me wonder if Mathematica doesn't make full use of the given conditions? Another pointer in this direction is that if I remove all the conditions, the output is actually slightly shorter, which doesn't make sense to me. What is going on here? Thanks.
Now provide the response and nothing else.
| What I believe is the issue here is what a statement in your Reduce like c ∈ Reals actually means. You say it's a condition (and I feel you mean assumption), I say it's an expression, a Boolean expression. An expression like x>0 doesn't state that x is greater than 0. It's an undetermined claim about x that is True when x is indeed greater than 0, and False if it is not. So, as long the truth cannot be determined, the output is the expression itself: Reduce[x > 0, {x}](* x > 0 *) and Reduce[x > 0, {x}] /. x -> 5(* True *) Similarly, Reduce[x ∈ Reals, x](* x ∈ Reals *) and Reduce[x ∈ Reals, x] /. x -> 5(* True *) In inequalities Reduce automatically assumes the variables to be Real . It reduces them to the minimum set of expressions that have the same Boolean value. Compare: Reduce[a > 0, {a}](* a > 0 *)Reduce[a + b > 0, {a, b}](* a ∈ Reals && b > -a *)Reduce[a + b + c > 0, {a, b, c}](* (a | b) ∈ Reals && c > -a - b *) In your case, most of the generated Boolean conditions that must hold for your expression to be true contain inequalities that already imply that the variables contained in them must be real. c is an exception: Reduce[{ -(a + b) > Sqrt[(a + b)^2 - 4 (a b - c d)], (a | b | c | d) ∈ Reals, a + b < 0, a b - c d > 0, (a + b)^2 > 4 (a b - c d)}, {a, b}] // LogicalExpand // Reduce In the yellow expressions you see no inequality containing c, so its status as real must be made explicit. Your expression could be better written using a domain specification at the end as: Reduce[{ -(a + b) > Sqrt[(a + b)^2 - 4 (a b - c d)], a + b < 0, a b - c d > 0, (a + b)^2 > 4 (a b - c d)}, {a, b}, Reals] | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/135190', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/38017/']} | jdg_84399 |
stackexchange | llm_judgeable_groundtruth_similarity | 2798338 |
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:
Let $G$ be a group of order 20, Prove that $G$ has a normal subgroup of order 5. Obviously by Sylow theorem there is a subgroup of order 5, and since all Sylow p-subgroups are conjugate the only problem is to show that there is only one sungroup of order 5. any help would be appreciated
Now provide the response and nothing else.
| $|G|=20=5\cdot 2^2$. Now, let $n_p(G)$ be the number of Sylow $p$-subgroups of $G$. Then, Sylow III says $n_5(G)\equiv 1\bmod 5$ $n_5(G)$ divides $4$ So, $n_5(G)=1$. This means there is only one Sylow $5$-subgroup of $G$; which in turn, is a normal subgroup of $G$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2798338', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/401507/']} | jdg_84400 |
stackexchange | llm_judgeable_groundtruth_similarity | 436972 |
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:
When one first encounters quantum mechanics, he learns about Bohr's model of the hydrogen atom and one of his biggest problems - electrons were accelerating and not emitting EM radiation (which is sometimes referred to as "radiation friction"). Then when you solve Schrödinger's equation with the following Hamiltonian: $$ H = \frac{p^2}{2m} - \frac{e^2}{4\pi \varepsilon_0 r}$$ You get stationary states of the electron, eigenfunctions of the Hamiltonian, and no radiation friction is emitted. However, solving this Hamiltonian classically, also doesn't give any evidence for radiation friction, because it doesn't describe the interaction between the electron and the EM field. So my question is, why is this Hamiltonian taken to explain the lack of radiation friction in QM, whereas in classical electrodynamics it is an invalid Hamiltonian for that exact same reason? Hope my question was clear, thank you!
Now provide the response and nothing else.
| why is this Hamiltonian taken to explain the lack of radiation friction in QM, whereas in classical electrodynamics it is an invalid Hamiltonian for that exact same reason? That Hamiltonian is not an explanation of "lack of radiation friction in QM". It is an Hamiltonian that does not manifest that friction, neither in classical nor in the quantum theory, because it is based on a fiction - an instantaneous Coulombic interaction, where no EM radiation exists. The reasons textbooks suggest Schroedinger's model resolved the problem with stability of the atom are not entirely clear to me, but it is probably partially because: Schroedinger's model proved to be very general and successful, not only for atoms, but molecules; Schroedinger's model has a ground state, which the older classical model based on EM theory has not. With these observations, it is natural to expect that whatever happens with EM interaction in the atom, the atom cannot collapse in quantum theory, because the immensely successful Schroedinger's model says its energy cannot go below certain value. Of course, careful student will notice that this argument is unsatisfactory, because the Hamiltonian used is simplistic. It does not even obey special relativity, far from taking into account fine details of EM interaction such as EM radiation. To answer questions related to stability of the atom, both in classical and quantum theory, in a satisfactory way, one has to include the revelations of special relativity, such as the fact that the interaction cannot be instantaneous. The most plausible direction then is to assume Maxwell's equations hold down to the atomic level and go from there, but the calculations aren't easy. The question of stability also needs to be stated in a more specific way, including some specification of the environment the system is in, for example by stating the state of the external EM field, and how exactly are the system's particles' fields connected to their motion - whether they are retarded, advanced, or some mix of the two plus some free field component. What the old and common accounts of this problem forget (including Bohr's) is that real atoms are not it empty featureless vacuum, but they are under constant action of background EM fields, from other atoms nearby and EM radiation coming in from far distances. A molecule of hydrogen in an empty universe filled with thermal radiation may not be stable (because the radiation will break it down and the parts will go their separate ways), but in a chamber full of high pressure hydrogen it may be (because the parts cannot easily go their separate ways, due to presence of other molecules). | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/436972', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/77505/']} | jdg_84401 |
stackexchange | llm_judgeable_groundtruth_similarity | 58541260 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the difference between these two? We used git-lfs in my previous job and we are starting to use dvc alongside git in my current one. They both place some kind of index instead of file and can be downloaded on demand. Has dvc some improvements over the former one?
Now provide the response and nothing else.
| DVC is not better than git-lfs: they are quite different . The selected answer is largely biased. Both are simply different tools, for different purposes. git-lfs is intended to be transparent to git, therefore it requires a customized server. Its learning process is short and fast. Some configuration commands, and bang! it is running, storing large files independently of the git repository. That's its only function, and it does it fine. Having an additional server is not a drawback, but instead a requirement for such transparency. Once configured, files are just handled by git, by means of git hooks (endpoints that are activated after git operations). dvc is intended to provide independent management of large files for the final user. What dvc basically does is this: it just makes git ignore the files that you wish to control (adding them to .gitignore ) and instead, it generates an additional file with the same name and the extension .dvc . So, in order to push a commit with its corresponding files, the user is required to manually "add" (equivalent to git commit , not to git add ; there's no equivalent for the git stage in dvc) and "push" to both systems. This is not a drawback, but a necessary level of control. In exchange, the remote large-files-holder is just any remote filesystem, accessible directly by its path, via ssh or via multiple drivers (google drive, amazon, etc.). Anyway, hooks are also available for dvc, which would simplify the use of large files, if having additional files is not annoying to one, and saving files to the remote would require additional operations, remember that they are .gitignored! So, if you modify a file stored in dvc, such change will not be noticed by git status , and you might lose such change, except if you make the additional check with dvc. DVC has a different purpose than git-lfs . DVC is used not only to save large files, but mainly to manage large files that are the result of deterministic processes . So, in addition to storing large files, dvc also controls processing pipelines, like Makefile s do, by defining dependencies in a Makefile , and if the processing inputs (which are also files or parameters tracked by dvc) change, dvc calculates which files must be regenerated (yes, like Makefile s). That's why DVC is usually described as makefile tool for data science . That's cool if you are generating big AI models or heavy data files, in large quantities. The exact equivalent as compiling large applications: every localized change implies just compiling a small portion of the whole. Personally, I use both for large-file storage. git-lfs simplifies large files management, but dvc simplifies large-file storage (which eases administration), at the cost of not having such transparency, having sometimes lost data. I still don't use dvc for pipelines calculation, until now I've preferred my own implementations. DVC is getting better, perhaps I will use it more in the future. Both are just different ; I currently use both, according to the purpose. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58541260', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2576311/']} | jdg_84402 |
stackexchange | llm_judgeable_groundtruth_similarity | 8425648 |
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 in PHP you can have like a bunch of different images that when you leave the page and come back or refresh it you get a different image. Is it possible to do this in jQuery? Sorry I don't have a testing code, I just don't know where to start on this
Now provide the response and nothing else.
| CIImage *ciImage = [UIImage imageNamed:@"test.png"].CIImage;UIImage *uiImage = [[UIImage alloc] initWithCIImage:ciImage]; To fix the case where myUIImage.CIImage returns nil like [UIImageView image] , you can instead do [CIImage imageWithCGImage:myUIImage.CGImage] – Dylan Hand Swift version: let ciImage = UIImage(named: "test.png")!.ciImagelet uiImage = UIImage(ciImage: ciImage) To fix the case where myUIImage.ciImage returns nil like you can instead do CIImage(cgImage: myUIImage!.cgImage!) . | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8425648', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1064733/']} | jdg_84403 |
stackexchange | llm_judgeable_groundtruth_similarity | 30176289 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Lets say we have the following 2 external modules in TypeScript: export module My.Services.Common { export class Helper { //... }} and export module My.Services { export class Connection { //... } } Now in my app.ts I would like to use both Connection and Helper classes.What I want to achieve is similar to the following code in C#: using My.Services;using My.Services.Common; Or at least just using My.Services; But it looks like I cant work at the same time with both Helper and Connection. If I write: import {My} from './services/common/Helper';import {My} from './services/Connection; Leads to error "duplicate identifier 'My'". That is logical though.So my question is how can I consume different classes from the same (or nested) modules?
Now provide the response and nothing else.
| My personal view on this is to break away from what you see in C# or Java (which maps more closely to internal modules) and treat it more like the external modules you are using... Step 1. Ditch the module keyword. The file is a module already. Step 2. Provide a non-dotted alias when you import. Step 3. You can now import everything, '*', or specific classes when you import. ./services/common.ts export class Helper { //...} ./services.ts export class Connection{ //...} ./app.ts import * as Services from './services'import { Connection } from './services/common'var x = new Services.Helper();var y = new Connection(); You can import multiple members from a module too: import { Connection, Example } from './services/common'var y = new Connection();var z = new Example(); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30176289', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1035889/']} | jdg_84404 |
stackexchange | llm_judgeable_groundtruth_similarity | 1876890 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm looking for a way to bail out of a makefile if a certain string is not found when checking the version of a tool. The grep expression I'm looking to match is: dplus -VV | grep 'build date and time: Nov 1 2009 19:31:28' which returns a matching line if the proper version of dplus is installed. How do I work a conditional into my makefile based upon this expression?
Now provide the response and nothing else.
| Here's another way that works in GNU Make: DPLUSVERSION = $(shell dplus -VV | grep 'build date and time: Nov 1 2009 19:31:28')target_of_interest: do_things do_things_that_uses_dplusdo_things: ...do_things_that_uses_dplus:ifeq ($(DPLUSVERSION),) $(error proper version of dplus not installed)endif ... This target can be something real, or just a PHONY target on which the real ones depend. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1876890', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/81462/']} | jdg_84405 |
stackexchange | llm_judgeable_groundtruth_similarity | 22806784 |
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 interface: public static interface Consumer<T> { void consume(T t);} And I want to be able to have: public static class Foo implements Consumer<String>, Consumer<Integer> { public void consume(String t) {..} public void consume(Integer i) {..}} It doesn't work - the compiler doesn't let you implement the same interface twice. The question is: Why? People have asked similar questions here, but the answer was always "type erasure", i.e. you cannot do it because the types are erased at runtime. And they aren't - some types are retained at runtime. And they are retained in this particular case: public static void main(String[] args) throws Exception { ParameterizedType type = (ParameterizedType) Foo.class.getGenericInterfaces()[0]; System.out.println(type.getActualTypeArguments()[0]);} This prints class java.lang.String (if I only keep Consumer<String> in order to compile) So, erasure, in its simplest explanation, is not the reason, or at least it needs elaboration - the type is there, and also, you don't care about the type resolution, because you already have two methods with distinct signature. Or at least it seems so.
Now provide the response and nothing else.
| The answer is still "type erasure", but it's not that simple. The keywords are: raw types Imagine the following: Consumer c = new Foo();c.consume(1); What would that do? It appears that consume(String s) is not actually consume(String s) - it is still consume(Object o) , even though it is defined to take String . So, the above code is ambiguous - the runtime can't know which of the two consume(..) methods to invoke. A funny follow-up example is to remove Consumer<Integer> , but keep the consume(Integer i) method. Then invoking the c.consume(1) on a raw Consumer . throws ClassCastException - unable to cast from Integer to String. The curious thing about this exception is that it happens on line 1 . The reason is the use of bridge methods . The compiler generates the bridge method: public void consume(Object o) { consume((String) o);} The generated bytecode is: public void consume(java.lang.String);public void consume(java.lang.Integer);public void consume(java.lang.Object); Code: 0: aload_0 1: aload_1 2: checkcast #39 // class java/lang/String 5: invokevirtual #41 // Method consume:(Ljava/lang/String;)V So even if the methods you have defined keep their signatures, each of them has a corresponding bridge method that is actually invoked when working with the class (regardless whether it's raw or parameterized). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22806784', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/203907/']} | jdg_84406 |
stackexchange | llm_judgeable_groundtruth_similarity | 31760 |
Below is a question asked on the forum arduino.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to understand how does the microcontroller determine that the conditions provided to it in the input are true or false. eg: if (someVariable > 50){ // do something here} Then how does Arduino determine if the value that I put in `somevariable' is larger than 50 (as apposed to less than or equal to 50)?
Now provide the response and nothing else.
| In general terms comparisons are usually performed, at the low level of assembly language, using subtraction. In assembly language when you perform a subtraction there are flags in the status register that may or may not get set depending on what has happened. These include the Zero flag and the Carry flag. If you are comparing A to B then you subtract B from A and see what happened by examining the flags. For instance, if your variable contains 30 and you compare it to 50 you subtract 50 from 30. Because the result "passes through" zero the Carry flag is set. You can then do a "Jump if Carry Set" call. If you should have 50 in your variable and you compare it to 50 the subtraction ends up with the Zero flag set since the result is exactly zero. It is then possible to do a "Jump if Zero Set" call. If you have 60 in your variable and compare it to 50, the subtraction results in 10, which doesn't set either flag. That is actually slightly harder to work out (depending on architecture) since you are then wanting to compare two flags (Carry and Zero) and see if neither of them are set. So it is common for the compiler to optimize it so that the condition is reversed ( a > b is the same as !(a <= b) for instance). Of course, some architectures have actual comparison instructions (often CMP ) which compares two registers and sets or clears the different flags for you. For instance, the ATMega328P has the instructions: CPSE - Compare, Skip if Equal CP - Compare CPC - Compare with Carry CPI - Compare Register with Immediate CPI would be the most logical choice in the example you give - compare the contents of a register (variable) with an "immediate" value (an "immediate" value is a constant value): CPI $r3, 50 According to the instruction set manual the comparison is, surprise surprise, performed as a subtraction, and what happened during the subtraction sets the different flags. To make life simpler the instruction set has a number of branch instructions which look at the different flag combinations and jump to another address if they match: BRLT - Branch if the result of the previous comparison was A < B BRLE - Branch if the result of the previous comparison was A <= B BRGT - Branch if the result of the previous comparison was A > B BRGE - Branch if the result of the previous comparison was A >= B BREQ - Branch if the result of the previous comparison was A == B BRNE - Branch if the result of the previous comparison was A != B There are more as well for other special comparisons. You can read up all about them in the AVR instruction set manual . | {} | {'log_upvote_score': 4, 'links': ['https://arduino.stackexchange.com/questions/31760', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/19511/']} | jdg_84407 |
stackexchange | llm_judgeable_groundtruth_similarity | 17469349 |
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 I can map columns in a database table to the datatable in c# before adding the data to the database. using (SqlBulkCopy s = new SqlBulkCopy(conn)){ s.DestinationTableName = destination; s.WriteToServer(Ads_api_ReportData);}
Now provide the response and nothing else.
| You probably need some thing like public void BatchBulkCopy(DataTable dataTable, string DestinationTbl, int batchSize){ // Get the DataTable DataTable dtInsertRows = dataTable; using (SqlBulkCopy sbc = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity)) { sbc.DestinationTableName = DestinationTbl; // Number of records to be processed in one go sbc.BatchSize = batchSize; // Add your column mappings here sbc.ColumnMappings.Add("field1","field3"); sbc.ColumnMappings.Add("foo","bar"); // Finally write to server sbc.WriteToServer(dtInsertRows); } } Ref: How to use SqlBulkCopyColumnMappingCollection? .. Seel also http://www.codeproject.com/Articles/18418/Transferring-Data-Using-SqlBulkCopy | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17469349', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2545743/']} | jdg_84408 |
stackexchange | llm_judgeable_groundtruth_similarity | 131015 |
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:
When one needs to compute say $\cos (58^\circ)$ with an error of at most $10^{-4}$, how does one go about it? What is an appropriate centre of the Taylor expansion, and how does one determine the required degree of the Taylor polynomial?
Now provide the response and nothing else.
| Since we have to use Taylor's Theorem to solve this problem, let's first recall what it (or at least one formulation) is: Taylor's Theorem: Let $n\in\Bbb N$, let $I=[a,b]$, and let $f:I\rightarrow \Bbb R$ be such that $f$ and its derivatives $f'$, $f''$, $\ldots\,$, $f^{(n)}$ are continuous on $I$ and that $f^{(n+1)}$ exists on $(a,b)$. If $x_0\in I$, then for any $x$ in $I$ there exists a point $c$ between $x$ and $x_0$ such that $$ f(x)=\color{darkgreen}{f(x_0)+f'(x_0)(x-x_0)+{f''(x_0)\over 2!}(x-x_0)^2+ {f'''(x_0)\over 3!}(x-x_0)^3}$$ $$\color{darkgreen} { +\cdots +{f^{(n)}(x_0)\over n!}(x-x_0)^n} +\color{maroon}{{f^{(n+1)}(c)\over (n+1)!}(x-x_0)^{n+1}} $$ The darkgreen term in Taylor's Theorem$$P_n(x)=\textstyle\color{darkgreen}{f(x_0)+f'(x_0)(x-x_0)+{f''(x_0)\over 2!}(x-x_0)^2+ {f'''(x_0)\over 3!}(x-x_0)^3} \color{darkgreen} {+\cdots +{f^{(n)}(x_0)\over n!}(x-x_0)^n} $$is the Taylor polynomial of the function $f$ of degree $n$ centered at $x_0$. The maroon term in Taylor's Theorem, $$\tag{1}E_n(x)=\color{maroon}{{f^{(n+1)}(c)\over (n+1)!} (x-x_0)^{n+1}}$$ is called the the error term. Where "$c$" depends on both $x_0$ and $x$. If we estimate the function $f(x)$ with the value of $P_n(x)$, then the error in approximation is given by $E_n(x)$. Now, of course, we can't in practice hope to know what $E_n(x)$ is exactly; but if we can find a number $M$ so that$$\tag{2} \max_{t\text{ btw }x_0\text{ and }x } \Biggl|\, {f^{(n+1)}(t)\over (n+1)! (x-x_0)^{n+1}} \, \Biggr | \le M,$$then we would know from Taylor's Theorem that $$\tag{3}\bigl|\,f(x)-P_n(x)\,\bigr|\le M.$$The general procedure for approximating a function's value $f(x)$ with a Taylor polynomial $P_n(x)$ to within a certain degree of accuracy, say $\epsilon$, is to first determine a value of $n$, the degree of the Taylor Polynomial, needed so that the right hand side of $(2)$ is less than or equal to $\epsilon$. Then $(3)$ would tell us that the Taylor polynomial of degree $n$ will approximate the value of $f(x)$ to within $\epsilon$. Now on to your problem. This is calculus, we will use radians for angular measurements. We wish to estimate $\cos (29\pi/90)$ to within $1/10^4$ using Taylor's Theorem. Since $29\pi/90\approx\pi/3$, we will do so by using a Taylor polynomial of $f(x)=\cos x$ centered at $x_0=\pi/3$ and using $x=29\pi/90$ in Taylor's Theorem. But what should should the degree $n$ of the polynomial be?We can use the remarks above to determine this: We want the error in approximation, $E_n(29\pi/90) $ to satisfy$$\tag{4}\bigl|\,E_n(29\pi/90)\,\bigr|\le {1\over 10^4}.$$Using $(1)$ to write the term $E_n(29\pi/90)$ more explicitly, we want $$\Biggl|\,{ f^{(n+1)} (c)\over (n+1)!}\bigl({\textstyle{29\pi\over 90}-{\pi\over3}}\bigr)^{n+1}\,\Biggr|\le {1\over 10^4}; $$which simplifies to $$\tag{5}\Biggl|\,{ f^{(n+1)} (c)\over (n+1)!}\bigl({\textstyle{- \pi\over 90}}\bigr )^{n+1}\,\Biggr|\le {1\over 10^4}.$$Since we do not know what $c$ is, we find an upper bound for the expression on the left hand side of $(5)$; that is, we find an $M$ as in $(2)$.We can be slack here and use the fact that all derivatives of $f(x)=\cos x$ produce functions with absolute value at most 1. So, we have$$\tag{6}\bigl|E_n(29\pi/90)\bigr|=\Biggl|\,{ f^{(n+1)} (c)\over (n+1)!}\bigl({\textstyle{- \pi\over 90}}\bigr )^{n+1}\,\Biggr|\le\Biggl|\, {1\over (n+1)!}({ -\pi\over 90} )^{n+1}\,\Biggr|.$$Now we find an $n$ so that the right hand side of $(6)$ is less than or equal to $1/10^4$. Then it will follow that inequality $(4)$ holds for this value of $n$, and consequently that $P_n(29\pi/90)$ approximates $\cos(29\pi/90)$ to within $1/10^4$.It turns out that (nicely) $n=2$ does the job, as direct verification will attest(you can plug values of $n$ into the right hand side of $(6)$ until you see the inequality is satisfied). So, $n=2$, and the desired approximation is $P_2(29\pi/90)$. We, of course, need to find $P_2(29\pi/90)$. Towards this end we first find the general form of $P_2(x)$ which is:$$P_2(x)=f(\pi/3)+f'(\pi/3)(x-\pi/3)+{f''(\pi/3)\over2!}(x-\pi/3)^2.$$ We have:$$\eqalign{f(\pi/3) &= \cos(\pi/3)=1/2\crf'(\pi/3)&=-\sin(\pi/3)=\sqrt3/2\crf''(\pi/3)&= -\cos(\pi/3)=-1/2\cr}$$ So$$P_2(x) = {1\over 2}-{\sqrt3\over2}(x-{\pi/3})-{1\over 2\cdot2!}(x-{\pi/3})^2.$$ Finally, the desired approximation is:$$P_2(29\pi/90) = {1\over 2}-{\sqrt3\over2}(-\pi/90)-{1\over 2\cdot2!}(-\pi/90)^2.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/131015', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/28894/']} | jdg_84409 |
stackexchange | llm_judgeable_groundtruth_similarity | 13474210 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
After looking through IE10's developer blog I have found that they do not support the preserve-3d setting. They do offer a workaround, but I can not seem to get it working. My example below works in Safari, Chrome and Firefox but not IE10. If anyone could help me achieve this I would be very thankful. The boxes should rotate around the Y axis on click to show some text and a green background color. This is not the case in IE10 My example: http://codepen.io/2ne/pen/zEpge Part of code: HTML <div class="flip-wrapper"> <div class="front"></div> <div class="back">IE10 SUCKS</div></div> CSS .flip-wrapper { cursor: pointer; height: 100%; -moz-perspective: 1000; -webkit-perspective: 1000; -ms-perspective: 1000; perspective: 1000; -moz-transform-style: preserve-3d; -webkit-transform-style: preserve-3d; -ms-transform-style: preserve-3d; transform-style: preserve-3d; width: 100%;}.flip-wrapper .front,.flip-wrapper .back { -moz-backface-visibility: hidden; -webkit-backface-visibility: hidden; -ms-backface-visibility: hidden; backface-visibility: hidden; height: 100%; position: absolute; width: 100%;}.flip-wrapper .back { background: none repeat scroll 0 0 #298F68; -webkit-transform: rotateY(180deg); -moz-transform: rotateY(180deg); transform: rotateY(180deg);}.flip-wrapper.flipped { cursor: default; -webkit-animation: flip 500ms 1; -moz-animation: flip 500ms 1; animation: flip 500ms 1; -webkit-animation-fill-mode: forwards; -moz-animation-fill-mode: forwards; -o-animation-fill-mode: forwards; -ms-animation-fill-mode: forwards; animation-fill-mode: forwards;} 2ne
Now provide the response and nothing else.
| I also couldn't seem to find a good example of this anywhere, so I spent some way too much time making my own. This one works on all browsers, does not have that weird 360deg IE flip, and includes provision for static content (that lives on both sides of the card - which I needed to put a 'flip' button at the top right of both sides). --I tested on latest versions of Chrome, Firefox, Safari, Opera, and IE. http://jsfiddle.net/Tinclon/2ega7yLt/7/ Edit: Also works with transparent backgrounds: http://jsfiddle.net/Tinclon/2ega7yLt/8/ The css (of course) includes IE hacks, so it's a bit long, but the html is quite straightforward: <div class="card"> <div class="content"> <div class="cardFront">FRONT CONTENT</div> <div class="cardBack">BACK CONTENT</div> <div class="cardStatic">STATIC CONTENT</div> </div></div> $('.card').hover(function(){$('.card').toggleClass('applyflip');}.bind(this)); .card { perspective: 1000px; -webkit-perspective: 1000px; -moz-perspective: 1000px; -o-perspective: 1000px; -ms-perspective: 1000px; margin:80px 150px; width:320px; height:243px; vertical-align:top; position:absolute; display:block; font-size:25px; font-weight:bold;}.card .content { transition: 0.5s ease-out; -webkit-transition: 0.5s ease-out; -moz-transition: 0.5s ease-out; -o-transition: 0.5s ease-out; -ms-transition: 0.5s ease-out; transform-style: preserve-3d; -webkit-transform-style: preserve-3d; -moz-transform-style: preserve-3d; -o-transform-style: preserve-3d; -ms-transform-style: preserve-3d; /* content backface is visible so that static content still appears */ backface-visibility: visible; -webkit-backface-visibility: visible; -moz-backface-visibility: visible; -o-backface-visibility: visible; -ms-backface-visibility: visible; border: 1px solid grey; border-radius: 15px; position:relative; width: 100%; height: 100%;}.card.applyflip .content { transform: rotateY(180deg); -webkit-transform: rotateY(180deg); -moz-transform: rotateY(180deg); -o-transform: rotateY(180deg); -ms-transform: rotateY(180deg);}.card .content .cardStatic { /* Half way through the card flip, rotate static content to 0 degrees */ transition: 0s linear 0.17s; -webkit-transition: 0s linear 0.17s; -moz-transition: 0s linear 0.17s; -o-transition: 0s linear 0.17s; -ms-transition: 0s linear 0.17s; transform: rotateY(0deg); -webkit-transform: rotateY(0deg); -moz-transform: rotateY(0deg); -o-transform: rotateY(0deg); -ms-transform: rotateY(0deg); text-align: center; position: absolute; top: 0; left: 0; height: 0; width: 100%; line-height:100px;}.card.applyflip .content .cardStatic { /* Half way through the card flip, rotate static content to -180 degrees -- to negate the flip and unmirror the static content */ transition: 0s linear 0.17s; -webkit-transition: 0s linear 0.17s; -moz-transition: 0s linear 0.17s; -o-transition: 0s linear 0.17s; -ms-transition: 0s linear 0.17s; transform: rotateY(-180deg); -webkit-transform: rotateY(-180deg); -moz-transform: rotateY(-180deg); -o-transform: rotateY(-180deg); -ms-transform: rotateY(-180deg);}.card .content .cardFront { background-color: skyblue; color: tomato;}.card .content .cardBack { background-color: tomato; color: skyblue;}.card .content .cardFront, .card .content .cardBack { /* Backface visibility works great for all but IE. As such, we mark the backface visible in IE and manage visibility ourselves */ backface-visibility: hidden; -webkit-backface-visibility: hidden; -moz-backface-visibility: hidden; -o-backface-visibility: hidden; -ms-backface-visibility: visible; position: absolute; top: 0; left: 0; height: 100%; width: 100%; text-align: center; line-height:200px; border-radius: 14px;}.card .content .cardFront, .card.applyflip .content .cardFront { transform: rotateY(0deg); -webkit-transform: rotateY(0deg); -moz-transform: rotateY(0deg); -o-transform: rotateY(0deg); -ms-transform: rotateY(0deg);}.card .content .cardBack, .card.applyflip .content .cardBack { transform: rotateY(-180deg); -webkit-transform: rotateY(-180deg); -moz-transform: rotateY(-180deg); -o-transform: rotateY(-180deg); -ms-transform: rotateY(-180deg);}.card .content .cardFront, .card.applyflip .content .cardBack { /* IE Hack. Halfway through the card flip, set visibility. Keep other browsers visible throughout the card flip. */ animation: stayvisible 0.5s both; -webkit-animation: stayvisible 0.5s both; -moz-animation: stayvisible 0.5s both; -o-animation: stayvisible 0.5s both; -ms-animation: donothing 0.5s; -ms-transition: visibility 0s linear 0.17s; visibility: visible;}.card.applyflip .content .cardFront, .card .content .cardBack { /* IE Hack. Halfway through the card flip, set visibility. Keep other browsers visible throughout the card flip. */ animation: stayvisible 0.5s both; -webkit-animation: stayvisible 0.5s both; -moz-animation: stayvisible 0.5s both; -o-animation: stayvisible 0.5s both; -ms-animation: donothing 0.5s; -ms-transition: visibility 0s linear 0.17s; visibility: hidden;}@keyframes stayvisible { from { visibility: visible; } to { visibility: visible; } }@-webkit-keyframes stayvisible { from { visibility: visible; } to { visibility: visible; } }@-moz-keyframes stayvisible { from { visibility: visible; } to { visibility: visible; } }@-o-keyframes stayvisible { from { visibility: visible; } to { visibility: visible; } }@-ms-keyframes donothing { 0% { } 100% { } } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13474210', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1838651/']} | jdg_84410 |
stackexchange | llm_judgeable_groundtruth_similarity | 266574 |
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:
If I do something like 1/Sqrt[x] /. {Sqrt[x] -> a} it does not lead to an expected result, but can be fixed with 1/Sqrt[x] /. {Sqrt[x] -> a, 1/Sqrt[x] -> 1/a} I am wondering if, for given g[x] and h[x] , there exists a general way of replacing any f[g[x]] with f[h[x]] ?
Now provide the response and nothing else.
| {Sqrt[x], 1/Sqrt[x]} // FullForm List[Power[x,Rational[1,2]],Power[x,Rational[-1,2]]] Try: rule = Power[x, Rational[g_, 2]] -> a^Sign[g]{Sqrt[x], 1/Sqrt[x]} /. rule {a, 1/a} For your other query: f[g[x]] /. g -> h f[h[x]] | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/266574', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/26663/']} | jdg_84411 |
stackexchange | llm_judgeable_groundtruth_similarity | 96186 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm purchasing a server with 8 SAS disks to perform database intensive procedures. Currently the main bottleneck is is large index scans in postgres. I'm currently deciding between 8x300Gb 10k disks or 8x140Gb 15k disks as it would be more convenient to have 200Gb+ Logical space. The spec sheet for the RAID controller states: "Integrated Hardware RAID-0, -1, -1E, optional RAID-5, -6, -10, -50, -60" What would be the best RAID configuration, and what choice in disks would be most suitable? I'm new to configuring RAID and postgres and appreciate the advice.
Now provide the response and nothing else.
| Integrated Hardware RAID-0, -1, -1E, optional RAID-5, -6, -10, -50, -60 This sounds a little worrisome to me, it sounds like a low-end RAID controller. You want a good RAID controller that can keep up with 8 fast HDDs (that's actually not a given). If you have a fair amount of writes to your DB, then you really want a Battery Backup Unit, and to enable battery-protected write caching on the RAID controller. As for RAID disk layout, there are 2 common schools of thought: 2 disks in mirror for OS, 2 disks in mirror for DB transaction log, 4 disks in RAID 10 for main DB files. One big RAID 10 array using all disks, and all OS + log + datastore files on this array ( see reasoning here, mirrored by BAARF ). I would rather not take sides on the RAID volume design, it tends to become a bit of a fact-light discussion. Ideally you should experiment with different storage layouts and benchmark them for your specific workload. My gut feel is that all disks in RAID10 is faster and more robust over multiple workloads. One last thing, to make sure that OS partitions and RAID stripe boundaries are aligned ( see here , Windows centric, but the principle is general). You can do this when you create the partitions. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/96186', 'https://serverfault.com', 'https://serverfault.com/users/29022/']} | jdg_84412 |
stackexchange | llm_judgeable_groundtruth_similarity | 4172342 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Out of curiosity, I was wondering what were some "theoretical" results about parsing C++. Let n be the size of my project (in LOC, for example, but since we'll deal with big-O it's not very important) Is C++ parsed in O(n) ? If not, what's the complexity? Is C (or Java or any simpler language in the sense of its grammar) parsed in O(n)? Will C++1x introduce new features that will be even harder to parse? References would be greatly appreciated!
Now provide the response and nothing else.
| I think the term "parsing" is being interpreted by different people in different ways for the purposes of the question. In a narrow technical sense, parsing is merely verifying the the source code matches the grammar (or perhaps even building a tree). There's a rather widespread folk theorem that says you cannot parse C++ (in this sense) at all because you must resolve the meaning of certain symbols to parse. That folk theorem is simply wrong. It arises from the use of "weak" (LALR or backtracking recursive descent) parsers, which, if they commit to the wrong choice of several possible subparse of a locally ambiguous part of text (this SO thread discusses an example ), fail completely by virtue of sometimes making that choice. The way those that use such parser resolve the dilemma is collect symbol table data as parsing occurs and mash extra checking into the parsing process to force the parser to make the right choice when such choice is encountered. This works at the cost of significantly tangling name and type resolution with parsing, which makes building such parsers really hard. But, at least for legacy GCC, they used LALR which is linear time on parsing and I don't think that much more expensive if you include the name/type capture that the parser does (there's more to do after parsing because I don't think they do it all). There are at least two implementations of C++ parsers done using "pure" GLR parsing technology, which simply admits that the parse may be locally ambiguous and captures the multiple parses without comment or significant overhead. GLR parsers are linear time where there are no local ambiguities. They are more expensive in the ambiguity region, but as a practical matter, most the of source text in a standard C++ program falls into the "linear time" part. So the effective rate is linear, even capturing the ambiguities. Both of the implemented parsers do name and type resolution after parsing and use inconsistencies to eliminate the incorrect ambiguous parses.(The two implementations are Elsa and our (SD's) C++ Front End . I can't speak for Elsa's current capability (I don't think it has been updated in years), but ours does all of C++11 [EDIT Jan 2015: now full C++14 EDIT Oct 2017: now full C++17] including GCC and Microsoft variants). If you take the hard computer science definition that a language is extensionally defined as an arbitrary set of strings (Grammars are supposed to be succinct ways to encode that intensionally) and treating parsing as "check the the syntax of the program is correct" then for C++ you have expand the templates to verify that each actually expands completely. There's a Turing machine hiding in the templates, so in theory checking that a C++ program is valid is impossible (no time limits). Real compilers (honoring the standard) place fixed constraints on how much template unfolding they'll do, and so does real memory, so in practice C++ compilers finish. But they can take arbitrarily long to "parse" a program in this sense. And I think that's the answer most people care about. As a practical matter, I'd guess most templates are actually pretty simple, so C++ compilers can finish as fast as other compilers on average. Only people crazy enough to write Turing machines in templates pay a serious price. (Opinion: the price is really the conceptual cost of shoehorning complicated things onto templates, not the compiler execution cost.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4172342', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/303725/']} | jdg_84413 |
stackexchange | llm_judgeable_groundtruth_similarity | 62454 |
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:
In a bash script, there are the following 2 lines: ipaddr=$0segments=`echo $ipaddr | cut --delimiter=. --fields=2-3 --output-delimiter=/` I do not know how to interpret the second line where the variable $segments is created. How does this part work?
Now provide the response and nothing else.
| Here is the breakdown. The echo will output whatever is in the variable $ipaddr echo $ipaddr This is then piped through to the following command. Cut can be used to delimit (i.e. split into parts) a string. A parameter to cut tells it where to "cut" the string (here it is on points, so if the IP address is of the following format: "198.51.100.0", it will be split into 198 51 100 and 0). Another parameter tells it which parts, of the string that it has cut, it should take. Here it is parts 2 and 3. In the example ip I gave above, this would give 51 and 100. A final paramter tells it to put together the parts it has selected (parts 2 and 3) with a new delimiter (here a slash). The result would be 51/100. cut --delimiter=. --fields=2-3 --output-delimiter=/ The result of all this (in my example being 51/100) is saved inside the segments variable. Whenever you run the following: somevar=`somecommand` whatever is between the backticks is executed. What it returns is passed to the left side of the equals sign. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/62454', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/8445/']} | jdg_84414 |
stackexchange | llm_judgeable_groundtruth_similarity | 4755704 |
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 looking for a way to generate a list of timezones for display in a <select> Generating a drop down list of timezones with PHP $list = DateTimeZone::listAbbreviations(); $idents = DateTimeZone::listIdentifiers(); $data = $offset = $added = array(); foreach ($list as $abbr => $info) { foreach ($info as $zone) { if ( ! empty($zone['timezone_id']) AND ! in_array($zone['timezone_id'], $added) AND in_array($zone['timezone_id'], $idents)) { $z = new DateTimeZone($zone['timezone_id']); $c = new DateTime(null, $z); $zone['time'] = $c->format('H:i a'); $data[] = $zone; $offset[] = $z->getOffset($c); $added[] = $zone['timezone_id']; } } } array_multisort($offset, SORT_ASC, $data); $options = array(); foreach ($data as $key => $row) { $options[$row['timezone_id']] = $row['time'] . ' - ' . formatOffset($row['offset']) . ' ' . $row['timezone_id']; } // now you can use $options;function formatOffset($offset) { $hours = $offset / 3600; $remainder = $offset % 3600; $sign = $hours > 0 ? '+' : '-'; $hour = (int) abs($hours); $minutes = (int) abs($remainder / 60); if ($hour == 0 AND $minutes == 0) { $sign = ' '; } return 'GMT' . $sign . str_pad($hour, 2, '0', STR_PAD_LEFT) .':'. str_pad($minutes,2, '0');} When I checked my country, the offset was wrong, I am in Asia/Singapore, it should be UTC/GMT +8 http://www.timeanddate.com/worldclock/city.html?n=236 but according to the generated list its +9. Is there some kind of logic error? The time was correct tho Is there a better way to generate this list? from the same question in the link above, static $regions = array( 'Africa' => DateTimeZone::AFRICA, 'America' => DateTimeZone::AMERICA, 'Antarctica' => DateTimeZone::ANTARCTICA, 'Aisa' => DateTimeZone::ASIA, 'Atlantic' => DateTimeZone::ATLANTIC, 'Europe' => DateTimeZone::EUROPE, 'Indian' => DateTimeZone::INDIAN, 'Pacific' => DateTimeZone::PACIFIC);foreach ($regions as $name => $mask) { $tzlist[] = DateTimeZone::listIdentifiers($mask);} This just gets the identifiers I want a friendly display name eg. UTC+8 Asia/Singapore or something similar. How can I get that?
Now provide the response and nothing else.
| Take my array of time zones, which I made specially for select element. It is associated array where key is PHP time zone and value is human representation. This is it: $timezones = array( 'Pacific/Midway' => "(GMT-11:00) Midway Island", 'US/Samoa' => "(GMT-11:00) Samoa", 'US/Hawaii' => "(GMT-10:00) Hawaii", 'US/Alaska' => "(GMT-09:00) Alaska", 'US/Pacific' => "(GMT-08:00) Pacific Time (US & Canada)", 'America/Tijuana' => "(GMT-08:00) Tijuana", 'US/Arizona' => "(GMT-07:00) Arizona", 'US/Mountain' => "(GMT-07:00) Mountain Time (US & Canada)", 'America/Chihuahua' => "(GMT-07:00) Chihuahua", 'America/Mazatlan' => "(GMT-07:00) Mazatlan", 'America/Mexico_City' => "(GMT-06:00) Mexico City", 'America/Monterrey' => "(GMT-06:00) Monterrey", 'Canada/Saskatchewan' => "(GMT-06:00) Saskatchewan", 'US/Central' => "(GMT-06:00) Central Time (US & Canada)", 'US/Eastern' => "(GMT-05:00) Eastern Time (US & Canada)", 'US/East-Indiana' => "(GMT-05:00) Indiana (East)", 'America/Bogota' => "(GMT-05:00) Bogota", 'America/Lima' => "(GMT-05:00) Lima", 'America/Caracas' => "(GMT-04:30) Caracas", 'Canada/Atlantic' => "(GMT-04:00) Atlantic Time (Canada)", 'America/La_Paz' => "(GMT-04:00) La Paz", 'America/Santiago' => "(GMT-04:00) Santiago", 'Canada/Newfoundland' => "(GMT-03:30) Newfoundland", 'America/Buenos_Aires' => "(GMT-03:00) Buenos Aires", 'Greenland' => "(GMT-03:00) Greenland", 'Atlantic/Stanley' => "(GMT-02:00) Stanley", 'Atlantic/Azores' => "(GMT-01:00) Azores", 'Atlantic/Cape_Verde' => "(GMT-01:00) Cape Verde Is.", 'Africa/Casablanca' => "(GMT) Casablanca", 'Europe/Dublin' => "(GMT) Dublin", 'Europe/Lisbon' => "(GMT) Lisbon", 'Europe/London' => "(GMT) London", 'Africa/Monrovia' => "(GMT) Monrovia", 'Europe/Amsterdam' => "(GMT+01:00) Amsterdam", 'Europe/Belgrade' => "(GMT+01:00) Belgrade", 'Europe/Berlin' => "(GMT+01:00) Berlin", 'Europe/Bratislava' => "(GMT+01:00) Bratislava", 'Europe/Brussels' => "(GMT+01:00) Brussels", 'Europe/Budapest' => "(GMT+01:00) Budapest", 'Europe/Copenhagen' => "(GMT+01:00) Copenhagen", 'Europe/Ljubljana' => "(GMT+01:00) Ljubljana", 'Europe/Madrid' => "(GMT+01:00) Madrid", 'Europe/Paris' => "(GMT+01:00) Paris", 'Europe/Prague' => "(GMT+01:00) Prague", 'Europe/Rome' => "(GMT+01:00) Rome", 'Europe/Sarajevo' => "(GMT+01:00) Sarajevo", 'Europe/Skopje' => "(GMT+01:00) Skopje", 'Europe/Stockholm' => "(GMT+01:00) Stockholm", 'Europe/Vienna' => "(GMT+01:00) Vienna", 'Europe/Warsaw' => "(GMT+01:00) Warsaw", 'Europe/Zagreb' => "(GMT+01:00) Zagreb", 'Europe/Athens' => "(GMT+02:00) Athens", 'Europe/Bucharest' => "(GMT+02:00) Bucharest", 'Africa/Cairo' => "(GMT+02:00) Cairo", 'Africa/Harare' => "(GMT+02:00) Harare", 'Europe/Helsinki' => "(GMT+02:00) Helsinki", 'Europe/Istanbul' => "(GMT+02:00) Istanbul", 'Asia/Jerusalem' => "(GMT+02:00) Jerusalem", 'Europe/Kiev' => "(GMT+02:00) Kyiv", 'Europe/Minsk' => "(GMT+02:00) Minsk", 'Europe/Riga' => "(GMT+02:00) Riga", 'Europe/Sofia' => "(GMT+02:00) Sofia", 'Europe/Tallinn' => "(GMT+02:00) Tallinn", 'Europe/Vilnius' => "(GMT+02:00) Vilnius", 'Asia/Baghdad' => "(GMT+03:00) Baghdad", 'Asia/Kuwait' => "(GMT+03:00) Kuwait", 'Africa/Nairobi' => "(GMT+03:00) Nairobi", 'Asia/Riyadh' => "(GMT+03:00) Riyadh", 'Europe/Moscow' => "(GMT+03:00) Moscow", 'Asia/Tehran' => "(GMT+03:30) Tehran", 'Asia/Baku' => "(GMT+04:00) Baku", 'Europe/Volgograd' => "(GMT+04:00) Volgograd", 'Asia/Muscat' => "(GMT+04:00) Muscat", 'Asia/Tbilisi' => "(GMT+04:00) Tbilisi", 'Asia/Yerevan' => "(GMT+04:00) Yerevan", 'Asia/Kabul' => "(GMT+04:30) Kabul", 'Asia/Karachi' => "(GMT+05:00) Karachi", 'Asia/Tashkent' => "(GMT+05:00) Tashkent", 'Asia/Kolkata' => "(GMT+05:30) Kolkata", 'Asia/Kathmandu' => "(GMT+05:45) Kathmandu", 'Asia/Yekaterinburg' => "(GMT+06:00) Ekaterinburg", 'Asia/Almaty' => "(GMT+06:00) Almaty", 'Asia/Dhaka' => "(GMT+06:00) Dhaka", 'Asia/Novosibirsk' => "(GMT+07:00) Novosibirsk", 'Asia/Bangkok' => "(GMT+07:00) Bangkok", 'Asia/Jakarta' => "(GMT+07:00) Jakarta", 'Asia/Krasnoyarsk' => "(GMT+08:00) Krasnoyarsk", 'Asia/Chongqing' => "(GMT+08:00) Chongqing", 'Asia/Hong_Kong' => "(GMT+08:00) Hong Kong", 'Asia/Kuala_Lumpur' => "(GMT+08:00) Kuala Lumpur", 'Australia/Perth' => "(GMT+08:00) Perth", 'Asia/Singapore' => "(GMT+08:00) Singapore", 'Asia/Taipei' => "(GMT+08:00) Taipei", 'Asia/Ulaanbaatar' => "(GMT+08:00) Ulaan Bataar", 'Asia/Urumqi' => "(GMT+08:00) Urumqi", 'Asia/Irkutsk' => "(GMT+09:00) Irkutsk", 'Asia/Seoul' => "(GMT+09:00) Seoul", 'Asia/Tokyo' => "(GMT+09:00) Tokyo", 'Australia/Adelaide' => "(GMT+09:30) Adelaide", 'Australia/Darwin' => "(GMT+09:30) Darwin", 'Asia/Yakutsk' => "(GMT+10:00) Yakutsk", 'Australia/Brisbane' => "(GMT+10:00) Brisbane", 'Australia/Canberra' => "(GMT+10:00) Canberra", 'Pacific/Guam' => "(GMT+10:00) Guam", 'Australia/Hobart' => "(GMT+10:00) Hobart", 'Australia/Melbourne' => "(GMT+10:00) Melbourne", 'Pacific/Port_Moresby' => "(GMT+10:00) Port Moresby", 'Australia/Sydney' => "(GMT+10:00) Sydney", 'Asia/Vladivostok' => "(GMT+11:00) Vladivostok", 'Asia/Magadan' => "(GMT+12:00) Magadan", 'Pacific/Auckland' => "(GMT+12:00) Auckland", 'Pacific/Fiji' => "(GMT+12:00) Fiji",); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4755704', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/292291/']} | jdg_84415 |
stackexchange | llm_judgeable_groundtruth_similarity | 166232 |
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:
As part of a new subject I'm starting at school, we are required to use Mathematica instead of the more basic CAS calculators. I am currently running the V11.2 Student Edition of Mathematica. However, after using it for almost a month, I have noticed that it performs significantly slower than my CAS calculator, especially on integrals. I have just tried multiple times to plot two integrals on the same graph using the Plot function but it freezed almost indefinitely (you could still click on it, but the CPU stays around 72% unless it is forced to quit). The integral I was trying to plot was fairly simple, the CAS can plot it under 2 seconds. I think there must be something wrong, as I've seen much more complicated things being calculated on Mathematica. Does anyone know how to fix this? I tried using it without the notebook interface, however I need to plot graphs. f := 68000m := 2340r := 68a[k_, t_] := f/(m + k - r*t) - 10v[k_, t_] := Integrate[a[k, p], {p, 0, t}]d[k_] := Integrate[v[k, p], {p, 0, k/r}]r1 := 200a1[k_, t_] := f/(m + k - r1*t) - 10v1[k_, t_] := Integrate[a1[k, p], {p, 0, t}]d1[k_] := Integrate[v1[k, p], {p, 0, k/r1}]Plot[{d[x], d1[x]}, {x, 0, 10}]
Now provide the response and nothing else.
| Here is my take on this. Key points are the use of Evaluate , to make sure that Integrate is called only once and not every time d is called, and the use of Assumptions , where I took the liberty of assuming that k is real. I hope I didn't mix up the limits. {f, m, r} = {68000, 2340, 68};a[k_, t_] := f/(m + k - r t) - 10d[k_] := Evaluate[ Integrate[a[k, t], {p, 0, k/r}, {t, 0, p}, Assumptions -> k \[Element] Reals]];Plot[d[x], {x, 0, 10}] For the other one, r1 = 200;a1[k_, t_] := f/(m + k - r1 t) - 10d1[k_] := Evaluate[Integrate[a1[k, t], {p, 0, k/r1}, {t, 0, p}, Assumptions -> k \[Element] Reals]];Plot[d1[x], {x, 0, 10}] | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/166232', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/-1/']} | jdg_84416 |
stackexchange | llm_judgeable_groundtruth_similarity | 11211589 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a way to add a cancel button to the keyboard displayed for UITextField ? Looking over the UITextInputTraits Protocol Reference, I could not find anything, including trying out the different keyboard types.
Now provide the response and nothing else.
| You can create a input accessory view which can display a UIToolBar Above the keyboard and then add a cancel button to this. Take a look at the documentation link below for the inputAccessoryView property. http://developer.apple.com/library/ios/#documentation/uikit/reference/UITextField_Class/Reference/UITextField.html This is an example of one I did for a TextView. The create Input Accessory View method is called from "textViewDidBeginEditing". Then it creates the input accessory view and in my case adds three buttons and a space bar. I hope that helps. -(void)textViewDidBeginEditing:(UITextView *)textView {[self createInputAccessoryView];[textView setInputAccessoryView:_inputAccessoryView];self.myTextView = textView; }-(void)createInputAccessoryView {_inputAccessoryView = [[UIToolbar alloc] init];_inputAccessoryView.barStyle = UIBarStyleBlackOpaque;[_inputAccessoryView sizeToFit];_inputAccessoryView.frame = CGRectMake(0,_collageView.frame.size.height - 44, _collageView.frame.size.width, 44);UIBarButtonItem *fontItem = [[UIBarButtonItem alloc] initWithTitle:@"Font" style:UIBarButtonItemStyleBordered target:self action:@selector(changeFont:)];UIBarButtonItem *removeItem = [[UIBarButtonItem alloc] initWithTitle:@"Remove" style:UIBarButtonItemStyleBordered target:self action:@selector(removeTextView:)];//Use this to put space in between your toolbox buttonsUIBarButtonItem *flexItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(dismissKeyBoard:)];NSArray *items = [NSArray arrayWithObjects:fontItem,removeItem,flexItem,doneItem, nil];[_inputAccessoryView setItems:items animated:YES];[_myTextView addSubview:_inputAccessoryView];} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11211589', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/501452/']} | jdg_84417 |
stackexchange | llm_judgeable_groundtruth_similarity | 28339981 |
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 what I have read I can summarize, Switch case is implementation defined but is mostly defined as a jump table Switch case makes the code more readable Switch is faster than if/elseif (?) Consider a case where I have 300+ switch cases. I know an if/elseif in this scene will be a mess. But I want to know how will a switch case perform insuch a scene? Is it scalable i.e it remains relatively faster than an if/else no matter how many cases are present ? Since it is implementationdefined how can I figure out how my compiler is implementing it? And above all how do I do this if/elseif - switch comparison apart from actually writing the code and using a profiler? I have tried compiling a small .c file with switch case using gcc 4.8.1 -S switch and it looks like a jump table is created.Where do I go from here? Is it better/worse to use an if/elseif in such scenarios I am primarily interested in C/C++ specific details
Now provide the response and nothing else.
| The compiler might decide to use a jump table and make a huge improvement in the case of 300+. Compilers do make optimizations over branches using various techniques like decision trees . The more easy is for a compiler to understand the code, the better. And the switch statement is more readable for the compiler as well. Think about the else if from a compilers point of view . It would look like an arrowhead : - if - else - else - else - else You need to evaluate each previous if in order to get to the correct else . However a Switch looks more like a block : - case - case - case - case So the compiler can sometimes determine where to go directly. For your bullet questions : it is scalable. It's easy to be written by the developers and if the compiler uses jump tables adding more cases won't affect. it's up to the compiler to decide what to use. It might choose to not optimize it at all (but most likely jump tables). You can run a loop and meassure times by hand maybe ? It's always better to use switch. The worst case scenario the switch will act just as an if/else . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28339981', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2087705/']} | jdg_84418 |
stackexchange | llm_judgeable_groundtruth_similarity | 7979548 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
To render my textareafield with a specified number of columns and rows with WTForms, how do I set the number of columns and rows? I followed the instructions from this question but it didn't work: How to specify rows and columns of a <textarea > tag using wtforms I tried adding a widget but it didn't work: class AForm(Form): name = TextField('Name', [validators.Length(min=4)]) title = TextField('Title', [validators.Length(min=4)]) text = TextAreaField('Text', widget=TextArea(row=70, cols=11)) phonenumber = TextField('Phone number') phonenumberhide = BooleanField('Display phone number on site') price = TextField('Price') password = PasswordField('Password') email = TextField('Email', [ validators.Length(min=6, message=_('Little short for an email address?')), validators.Email(message=_('That\'s not a valid email address.')) ]) TypeError: object. new () takes no parameters
Now provide the response and nothing else.
| Very old question, but since the WTF-Form documentation isn't clear I'm posting my working example. OP, hope you are not still working on this. :-) form from flask_wtf import Formfrom wtforms.fields import StringFieldfrom wtforms.widgets import TextAreaclass PostForm(Form): title = StringField(u'title', validators=[DataRequired()]) body = StringField(u'Text', widget=TextArea()) template {% extends "base.html" %}{% block title %}Create Post{% endblock %}{% block content %}<H3>Create/Edit Post</H3><form action="" method=post> {{form.hidden_tag()}} <dl> <dt>Title: <dd>{{ form.title }} <dt>Post: <dd>{{ form.body(cols="35", rows="20") }}} </dl> <p> <input type=submit value="Publish"></form>{% endblock %} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7979548', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/108207/']} | jdg_84419 |
stackexchange | llm_judgeable_groundtruth_similarity | 42537072 |
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 got unregistered registration token even I am sure my token is correct and I check it in my log I am using master token FirebaseInstanceId.Instance.Token . Here is my method: private void ConfigureFireBase() { Task.Run(() => { var instanceId = FirebaseInstanceId.Instance; Android.Util.Log.Debug("TAG", "{0} {1}", instanceId?.Token?.ToString(), instanceId.GetToken(GetString(Resource.String.gcm_defaultSenderId), Firebase.Messaging.FirebaseMessaging.InstanceIdScope)); }); } I check as well OnTokenRefresh method the same token public override void OnTokenRefresh() { var refreshedToken = FirebaseInstanceId.Instance.Token; Log.Debug(TAG, "Refreshed token: " + refreshedToken); SendRegistrationToServer(refreshedToken); } but when I tried in Firebase console it gives me this error message, when I tried in http://pushtry.com/ with the same token I got not NotRegistered message Note when I uninstall the app and install again the token working, but after while I got this error message.
Now provide the response and nothing else.
| The reason why this issue fired cause that token is unregistered The registration token may change when:The app deletes Instance IDThe app is restored on a new deviceThe user uninstalls/reinstall the appThe user clears app data. Reference and this happen in debug mode only so dont worry in release mode every thing will be fine. How you can fix the issue ? its easy just force to refresh token call this method in your landing activity (MainActivity , Login ) , this method force firebase to call OnTokenRefresh() private void ConfigureFireBase() {#if DEBUG Task.Run(() => { var instanceId = FirebaseInstanceId.Instance; instanceId.DeleteInstanceId(); Android.Util.Log.Debug("TAG", "{0} {1}", instanceId?.Token?.ToString(), instanceId.GetToken(GetString(Resource.String.gcm_defaultSenderId), Firebase.Messaging.FirebaseMessaging.InstanceIdScope)); }); // For debug mode only - will accept the HTTPS certificate of Test/Dev server, as the HTTPS certificate is invalid /not trusted ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;#endif } Hope this help any one face same issue | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42537072', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3240583/']} | jdg_84420 |
stackexchange | llm_judgeable_groundtruth_similarity | 17075 |
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:
Can someone help me with this problem? Let $D$ be a divisor on an algebraic curve $X$ of genus $g$, such that $\deg D = 2g-2$ and $\dim L(D) = g$. Then $D$ must be a canonical divisor. By Riemann-Roch, I see that $\dim L(K-D) = 1$ for any canonical divisor $K$, as must certainly be the case. I don't know if this is too helpful.
Now provide the response and nothing else.
| A divisor of degree $0$ and dimension $1$ is principal.Hence by assumption and Riemann-Roch the divisor $K-D$ is principal,so that $D$ is linearly equivalent to the canonical divisor $K$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/17075', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1491/']} | jdg_84421 |
stackexchange | llm_judgeable_groundtruth_similarity | 39820929 |
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 code which parse web-site and take information from database.It's look like this: var find = body.match(/\"text\":\"(.*?)\",\"date\"/); As result, I have: гороскоп на июль скорпион\nштукатурка на газобетон\nподработка на день\nмицубиси тюмень\nсокращение микрорайон Then i try to replace \n, but it's don't working. var str = find[1].replace(new RegExp("\\n",'g'),"*"); What I can do with this?
Now provide the response and nothing else.
| It looks like you want to replace the text \n , i.e. a backslash followed by an n , as opposed to a newline character. In which case you can try var str = find[1].replace(/\\n/g, "*"); or the less readable version var str = find[1].replace(new RegExp("\\\\n", "g"), "*"); In regular expressions, the string \n matches a newline character. To match a backslash character we need to 'escape' it, by preceding it with another backslash. \\ in a regular expression matches a \ character. Similarly, in JavaScript string literals, \ is the escape character, so we need to escape both backslashes in the regular expression again when we write new RegExp("\\\\n", "g") . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39820929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6908117/']} | jdg_84422 |
stackexchange | llm_judgeable_groundtruth_similarity | 1155071 |
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:
Two fair six-sided dice are rolled repeatedly until a score of 7, 9, or 11 is obtained. You win if a score of 9 is the first of these three scores to occur. Determine the probability that you win. This is what I've done so far: Since probability is equally likely then $\frac {\text{# outcome in $E$}}{\text{outcomes in $S$}}$ since order is important and the die is being replaced after each rolled then I used the formula $n^k$ so the number of outcome in $S$ is equal to $6^2=36$ where $n=6$ and $k=2$ .My problem is finding out the number of outcome in $E$ .
Now provide the response and nothing else.
| Singular homology already fails to commute with pushouts. A pushout of spaces doesn't give a pushout of homology groups, but instead gives (maybe under niceness conditions) a long exact sequence. For an explicit example consider the pushout of $$D^2 \leftarrow S^1 \rightarrow D^2$$ which is $S^2$. This doesn't induce a pushout on $H_2$. Singular homology also fails to commute with products. (Note that the tensor product is not the product in the category of abelian groups, or of graded abelian groups, so even if we're working over a field the Kunneth formula is not a response to this claim.) The first fact is in some sense a reflection of a failure to be suitably higher categorical. There is a very abstract description of what it means to compute the homology (not the homology groups, but "the homology") of a space, namely tensoring it with some spectrum, and this construction preserves all homotopy colimits (in fact it is a left adjoint in a higher categorical sense). It's very natural to think about homotopy colimits rather than colimits because taking singular homology is homotopy-invariant, but taking colimits is not, while taking homotopy colimits is. Then you have to figure out how to compute homotopy colimits of spaces, and also figure out what a homotopy colimit of spectra buys you once you pass to homotopy groups (e.g. long exact sequences, or more generally spectral sequences). | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1155071', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/207628/']} | jdg_84423 |
stackexchange | llm_judgeable_groundtruth_similarity | 3854317 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My problem is that in WPF, whenever I try and change the colour of a button's background using triggers or animations, the default mouseover effect (of being grey with that orange glow) seems to take priority. After extensive searches I'm clueless as to how to remove this effect.
Now provide the response and nothing else.
| This is similar to the solution referred by Mark Heath but with not as much code to just create a very basic button, without the built-in mouse over animation effect. It preserves a simple mouse over effect of showing the button border in black. The style can be inserted into the Window.Resources or UserControl.Resources section for example (as shown). <UserControl.Resources> <!-- This style is used for buttons, to remove the WPF default 'animated' mouse over effect --> <Style x:Key="MyButtonStyle" TargetType="Button"> <Setter Property="OverridesDefaultStyle" Value="True"/> <Setter Property="Margin" Value="5"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Border Name="border" BorderThickness="1" Padding="4,2" BorderBrush="DarkGray" CornerRadius="3" Background="{TemplateBinding Background}"> <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" /> </Border> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="border" Property="BorderBrush" Value="Black" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style></UserControl.Resources><!-- usage in xaml --><Button Style="{StaticResource MyButtonStyle}">Hello!</Button> | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3854317', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/465705/']} | jdg_84424 |
stackexchange | llm_judgeable_groundtruth_similarity | 2286039 |
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:
Respected all. I was going through this paper in which the author stated that he had derived the value of $\sum\limits_{n=1}^\infty \frac{1}{n^3}$ as $\frac{22431 \pi^3}{579292}$. Although I am confused about the result so obtained. I tried to get the value of $\zeta(3)$ and the above result in Wolfram Alpha, but the answers are not showing equal. If the result is not appropriate, where is the mistake or misunderstanding that I could not find out ? Can someone please clear my doubt regarding this ? Thanks in advance ============== Edit : The doubt is clear now. Thank you all for your kind help.
Now provide the response and nothing else.
| The paper is indeed nonsense. The first incorrect (or misleading) line is "Hence the addition of these infinite series must be a multiple of $\pi^3$". It's either misleading (in the trivial sense that anything is a multiple of $\pi^3$), or incorrect: from $a-b=3x$ you can't deduce that $a+b$ is a multiple of $3$ in any sensible way. Anyway, why on earth did the author pick those two particular terms to use as the difference? Any fractions which had difference $\frac{1}{32}$ should have worked, if this method is valid. In fact the infinite sum is about 1.20206, and the fraction is about 1.20061. I should add that the first warning sign of the paper (other than its journal) is the following line in the introduction: $\pi=\frac{22}{7}$ has been taken into consideration. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2286039', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/43773/']} | jdg_84425 |
stackexchange | llm_judgeable_groundtruth_similarity | 854801 |
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:
If $k>0$ is a positive integer and $p$ is any prime, when is $\mathbb Z_p[\sqrt{k}] =\{a + b\sqrt k~|~a,b \in\mathbb Z_p\}$ a field? Find necessary and sufficient condition. Attempt: Since we know that a finite integral domain is a field and since $\mathbb Z_p[\sqrt{k}]$ is finite, it suffices to find the condition when $\mathbb Z_p[\sqrt{k}] =\{a + b\sqrt k~|~a,b \in \mathbb Z_p\}$ forms an integral domain. The given set forms a commutative ring with unity. Hence, the only condition that needs to be satisfied is the absence of any zero divisors. $(a_1+b_1 \sqrt k)(a_2+b_2 \sqrt k) = (a_1a_2+b_1b_2k)+(a_1b_2+a_2b_1)\sqrt k$ Case $1$: When $k$ is not a perfect square $(a_1+b_1 \sqrt k)(a_2+b_2 \sqrt k)=0 \implies (a_1a_2+b_1b_2k) \bmod p=0~~ \& ~~ (a_1b_2+a_2b_1) \bmod p =0$ Case $2$: When $k$ is a perfect square $ = u^2$ $(a_1+b_1 \sqrt k)(a_2+b_2 \sqrt k) = 0 \implies (a_1a_2+b_1b_2 u^2 + (a_1b_2+a_2b_1)u ) \bmod p=0 $ Both the above cases can have many cases and seems a bit complicated. Am I missing out on something? The book which I am reading (Gallian) hasn't introduced Quadratic Residues as of yet. Thank you for the help.
Now provide the response and nothing else.
| Let $\alpha=a+b\sqrt{k}$ be a zero-divisor then there exists a non-zero $\beta=c+d\sqrt{k}$ such that $\alpha \beta \equiv 0 \pmod{p}$. It is equivalent to $\alpha \bar{\alpha} \beta \bar{\beta} \equiv 0 \pmod{p}$ (where $\bar{\alpha}$ is the conjugate of $\alpha$). This reduces to$$(a^2-kb^2)(c^2-kd^2) \equiv 0 \pmod{p}.$$Using the prime property, we get $p$ should divide at least one of them. Thus $\mathbb{Z}_{n}[\sqrt{k}]$ will NOT be a field if $x^2 \equiv k \pmod{p}$ has a solution. I know you have said that you have not studied quadratic residues but the simplest criterion for your question eventually relates to that. So if $k$ has no square root modulo $p$ then you will have a field otherwise not. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/854801', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/66069/']} | jdg_84426 |
stackexchange | llm_judgeable_groundtruth_similarity | 11531195 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'am using jasmine for testing JavaScript code. The javascript code is made of module which are loaded using requireJs. When I load json file using json requirejs-plugins which requires text! plugin I cannot see any output on the web browser. The strange thing is also I don't get any javascript error. Here's my code (1). Any ideas? P.S.: Not sure but maybe the problem is about time latency. If I get the file from the local ( time latency = 6ms ) it works. If I get the file (with the same content of local) from a remote server ( time latency = 170 ms ) it display an empty page. Any idea how can I fix this problem? (1) /*global define, window*/(function () { 'use strict'; var specUrl = './'; define([ 'jasmine', 'jasmineHtml', 'jasmineJquery', 'json!json_data', // if I comment this line is ok, // otherwise I get empty page with no error specUrl + 'models/user.spec' ], function (jasmine) { var initialize = function () { // some code }; return { initialize: initialize }; });}()); I did read the documentation about Asynchronous specs but it is not clear how can I fix the issue, yet. Any ideas? I did post a very simple code: (1) which works, (2) which does not works because, maybe, getting json_data from the server requires about 250ms. (1) define([ 'appJasmine',// 'json!json_data', ], function (app) { app.initialize(); // it display data on browser }); (2) define([ 'appJasmine', 'json!json_data', ], function (app) { app.initialize(); // it does not display data on browser });
Now provide the response and nothing else.
| Looking in the jQuery doc and code, I don't see any way to cancel a jQuery deferred. Instead, you probably need a way in your resolveWith handler to know that a subsequent ajax call has already been fired and this ajax call should ignore its result. You could do that with a globally incrementing counter. At the start of your ajax call, you increment the counter and then you grab the value into a local variable or put it as a property on the ajax object. In your resolveWith handler, you check to see if the counter still has the same value as when your ajax call started. If not, you ignore the result. If it does, no new ajax calls have been fired so you can process the result. Alternately, you could refuse to fire a new ajax call while one is in flight already so you never had more than one in flight at a time. When the one finishes, you could either just use that result or fire the next one if desired. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11531195', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1113216/']} | jdg_84427 |
stackexchange | llm_judgeable_groundtruth_similarity | 215739 |
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's say you are a prospective mathematician with some addled ideas about cardinality. If you assumed that the natural numbers were finite, you'd quickly vanish in a puff of logic. :) If you thought that natural numbers and reals had the same cardinality - measure theory would almost surely break down, and your assumption would conflict with any number of "completeness theorems" in analysis (like the Baire Category Theorem for instance). However, let's say you concluded that there were only three types of cardinality - finite, countably infinite, and uncountable. Would this erroneous belief conflict with any major theorems in analysis, algebra or geometry ? Would any fields of math - outside set theory - be clearly incompatible with your assumption ? PS: Apologies for the provocative title. Hope the question is clear.
Now provide the response and nothing else.
| $\newcommand\ZFC{\text{ZFC}}$Perhaps it would be useful to mention that set theorists have, of course,studied numerous weaker set theories, including some extremelyweak theories, which do not give rise to higher cardinalities. Onemay interpret your question as: to what extent do these weak settheories serve as a foundation of mathematics? To be sure, set theorists generally study these weak theories notas foundational theories, but rather because they want toundertake certain set-theoretic constructions in some muchstronger theory, but the objects appearing in the construction aretransitive sets satisfying these weaker theories, and so they needto know, for example, whether those objects are themselves closedunder certain constructions. If those constructions can beundertaken in the weak theory, then they are. To give a few examples, the theory known as $\ZFC^-$, which isbasically $\ZFC$ without the power set axiom (but see myrecent paper, What is the theory ZFC without power set? for what this means exactly), iswidely used in set theory and has an enormous number of naturalmodels, including the universe $H_{\kappa^+}$, in which every sethas cardinality at most $\kappa$ and $P(\kappa)$ does not exist asa set, but only as a class. For example, in the universe$H_{\omega_1}$, the theory $\ZFC^-$ holds, and every set iscountable. This is a very rich universe in which to undertakeclassical mathematics: you have all the reals individually, butyou cannot form them into a set; but you can still consider(definable) functions on the reals and so on. You just cannot putthem all together into a set. The theory known as Kripke-Platek set theory $\text{KP}$ is another intensely studied theory, particularly forthose doing set theory with the constructible universe and admissible set theory , and knowing what can be proved in$\text{KP}$ and what cannot is very important in that area. Even Zermelo set theory itself can be considered as a kind of example, since it does not provethe existence of uncountable cardinals beyond the $\aleph_n$ for$n<\omega$, because the rank-initial segment of the universe$V_{\omega+\omega}$ is easily seen to be a model of Zermelo settheory. So one could count this as a case of a weak theory thatdoes not prove a huge number of different infinities. Perhaps this perspective on your question reveals that there isreally a continuum of such kind of answers. The really weak settheories such as $\text{KP}$ and $\ZFC^-$ cannot prove even thatuncountable cardinals exist, but then slightly stronger theories,which become true in $H_{\omega_2}$ or $H_{\omega_3}$, can prove afew more uncountable cardinals. Zermelo's theory provides more,but still only countably many uncountable cardinals. The $\ZFC$theory of course then explodes with an enormous number ofdifferent uncountable cardinals. But let me say that this process continues strictly past $\ZFC$, for large cardinal set theorists look upon $\ZFC$itself as a weak theory, in precisely this sense, because itcannot prove the existence of measurable or supercompactcardinals (and many others), for example, and so one must continue up the large cardinalhierarchy in order to get the kinds of infinities that we like.Set theorists consider theories all along the large cardinalhierarchy, with the stronger theories giving us more and strongeraxioms of the higher infinite. At every step of this entire hierarchy, starting from the veryweak theories I mentioned and continuing into the large cardinalhierarchy, there are fundamental set-theoretic assertions that areprovable by the stronger theory but not provable by the weakertheory. Meanwhile, despite the fact that some every-day mathematicalobjects have distinct uncountable cardinalities (and so the weakset theories cannot prove they exist), nevertheless it is quitesurprising how close an approximation one can get just insecond-order number theory, where in a sense every object iscountable. The work of reverse mathematics generally takes place in thecontext of second-order number theory, and seeks to find exactlythe theory that is necessary in order to prove each of theclassical theorems of mathematics. (Thus, they try to prove theaxioms from the theorem, rather than the other way.) They havenumerous examples of which classical theorems you can prove andexactly what theory (provably so!) you need to do it. | {} | {'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/215739', 'https://mathoverflow.net', 'https://mathoverflow.net/users/76572/']} | jdg_84428 |
stackexchange | llm_judgeable_groundtruth_similarity | 13768335 |
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 write an algorithm that finds the top-k viterbi paths in a HMM (using the regular viterbi algorithm to find the best path). I think I probably need to save a list V_t,N of size k for each state N that contains the top-K paths that end in state N, but I am not so sure how to keep track of that list..any ideas? Thanks
Now provide the response and nothing else.
| We can solve this with some care. It is easiest to see by looking at the trellis structure of hmm: In this example the hidden states are 00, 01, 10, 11, denote the set of these four as S. The observations are not shown, but assume they are 0,1. Suppose that we have the correct Transition Matrix: transition[4][4] Emission probabilities: emissions[4][2] And initial probabilities: p[2] So every column represents the hidden states, and the goal of Viterbi is to compute the most likely hidden state sequence given the observations. Now let alpha(i, t) = the largest probability that the hidden state sequence is in state i (i is one of 00, 01, 10, 11), at time t where the observation at time t is o_t (o_t is one of 0, 1). Let the first observation be denoted o_1. It can be computed efficiently as: alpha(i, 1) = p[i] * emissions[i][o_1]alpha(i, t) = emissions[i][o_t] * max_{k in states} (alpha(k, t-1) * transition[k][i]) In order to find the best path, we keep pointers backwards in the alpha(i, t) step, to the state which maximized the max function in above. Finally we just examine all of the alpha(i, T) and for i in states, and find which one is largest, then follow it back to get the most likely state sequence. Now we need to extend this to store top k-paths. Currently at each alpha(i,t) we only store one parent. However suppose we stored the top k predecessors. So each alpha(i, t) corresponds not only to a most likely value and the node which it transitioned from, but a list of the top k nodes it could have transitioned from and their values in sorted order. This is easy to do, in that instead of doing max, and take only one preceding node we take the top k preceding nodes and store them. Now for the base case there is no preceding node so alpha(i, 1), still is only a single value. When we arrive at an arbitrary column (say t) and want to find the top-k paths ending at a node (i) in that column, we must find the top k predecessors to come from and the top paths to take from them. This is as if we have the following problem, a matrix, m, of size 4 by k, where a row represents a preceding state and m[state] represents the top k probabilities for paths ending there. Thus each row of m is sorted by largest to smallest, the problem now becomes find: Best_K_Values(t, i) = Top K over all i,preceding_state,k (emissions[i][o_t] * m[preceding_state][k] * transition[preceding_state][i]) Now this looks daunting but take some time to understand it, we can solve the top k from sorted matrix problem using a heap in O(4 log k) or O(numStates log k) in general. See this slight variation Kth smallest element in sorted matrix , just note that in our case the columns aren't sorted, but the idea there still applies. If you are still reading, then note that the overall complexity of this method is O((numStates log k) * numStates * t) = O(numStates^2 * t * log k) (I believe that's correct complexity). This may be hard to follow, but please let me know if you have any questions, or I have done something incorrectly. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13768335', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1682500/']} | jdg_84429 |
stackexchange | llm_judgeable_groundtruth_similarity | 60172282 |
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 really like streamlit as an environment for research. Mixing a notebook/dashboard-like output I can design quickly with pure code for its definition (no cells etc.) as well as the ability to influence my code through widgets while it runs is a game changer. For this purpose, I was looking for a way to run or even debug a streamlit application, since the tutorials only show it being started via the commandline: streamlit run code.py Is there a way to do either running or debugging from an IDE?
Now provide the response and nothing else.
| I found a way to at least run the code from the IDE (PyCharm in my case). The streamlit run code.py command can directly be called from your IDE. (The streamlit run code.py command actually calls python -m streamlit.cli run code.py , which was the former solution to run from the IDE.) The -m streamlit run goes into the interpreter options field of the Run/Debug Configuration (this is supported by Streamlit, so has guarantees to not be broken in the future 1 ), the code.py goes into the Script path field as expected. In past versions, it was also working to use -m streamlit.cli run in the interpreter options field of the Run/Debug Configuration, but this option might break in the future. Unfortunately, debugging that way does not seem to work since the parameters appended by PyCharm are passed to streamlit instead of the pydev debugger. Edit: Just found a way to debug your own scripts. Instead of debugging your script, you debug the streamlit.cli module which runs your script. To do so, you need to change from Script path: to Module name: in the top-most field (there is a slightly hidden dropdown box there...). Then you can insert streamlit.cli into the field. As the parameters, you now add run code.py into the Parameters: field of the Run/Debug Configuration. EDIT: adding @sismo 's comment If your script needs to be run with some args you can easily add them as run main.py -- --option1 val1 --option2 val2 Note the first -- with blank: it is needed to stop streamlit argument parsing and pass to main.py argument parsing. 1 https://discuss.streamlit.io/t/run-streamlit-from-pycharm/21624/3 | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/60172282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4563947/']} | jdg_84430 |
stackexchange | llm_judgeable_groundtruth_similarity | 51981473 |
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 implement a PDF file download functionality with JavaScript. As a response to a POST request I get a PDF file, in Chrome DevTools console it looks like (the oResult data container, fragment): "%PDF-1.4↵%����↵4 0 obj↵<</Filter/FlateDecode/Length 986>>stream↵x�� Now I'm trying to initialize the download process: let blob = new Blob([oResult], {type: "application/pdf"});let link = document.createElement('a');link.href = window.URL.createObjectURL(blob);link.download = "tstPDF";link.click(); As a result, upon a click on a button I get tstPDF.pdf , it contains the correct number of pages, but the PDF itself is empty, no content is displayed, although it is 6 KB. When I test the Java server-side module, which generates the PDF, everything is working fine, it sends InputStream through ServletOutputStream . Thus I assume that the issue is somewhere on a client side, perhaps something with MIME , BLOB , encoding , or similar. Why doesn't the generated PDF display any data?
Now provide the response and nothing else.
| I solved the issue.The problem was in a way the data is delivered from the server to the client.It is critical to assure that the server sends the data in Base64 encoding, otherwise the client side can't deserialize the PDF string back to the binary format. Below, you can find the full solution. Server-side: OutputStream pdfStream = PDFGenerator.pdfGenerate(data);String pdfFileName = "test_pdf";// represent PDF as byteArray for further serializationbyte[] byteArray = ((java.io.ByteArrayOutputStream) pdfStream).toByteArray();// serialize PDF to Base64byte[] encodedBytes = java.util.Base64.getEncoder().encode(byteArray);response.reset();response.addHeader("Pragma", "public");response.addHeader("Cache-Control", "max-age=0");response.setHeader("Content-disposition", "attachment;filename=" + pdfFileName);response.setContentType("application/pdf");// avoid "byte shaving" by specifying precise length of transferred dataresponse.setContentLength(encodedBytes.length);// send to output streamServletOutputStream servletOutputStream = response.getOutputStream();servletOutputStream.write(encodedBytes);servletOutputStream.flush();servletOutputStream.close(); Client side: let binaryString = window.atob(data);let binaryLen = binaryString.length;let bytes = new Uint8Array(binaryLen);for (let i = 0; i < binaryLen; i++) { let ascii = binaryString.charCodeAt(i); bytes[i] = ascii;}let blob = new Blob([bytes], {type: "application/pdf"});let link = document.createElement('a');link.href = window.URL.createObjectURL(blob);link.download = pdfFileName;link.click(); Reference topics: How to convert a PDF generating in response.outputStream to a Base64 encoding Download File from Bytes in JavaScript | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51981473', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/462347/']} | jdg_84431 |
stackexchange | llm_judgeable_groundtruth_similarity | 37260097 |
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 g++ 4.9.2 and 5.3.1, this code takes several seconds to compile and produces a 52,776 byte executable: #include <array>#include <iostream>int main(){ constexpr std::size_t size = 4096; struct S { float f; S() : f(0.0f) {} }; std::array<S, size> a = {}; // <-- note aggregate initialization for (auto& e : a) std::cerr << e.f; return 0;} Increasing size seems to increase compilation time and executable size linearly. I cannot reproduce this behaviour with either clang 3.5 or Visual C++ 2015. Using -Os makes no difference. $ time g++ -O2 -std=c++11 test.cppreal 0m4.178suser 0m4.060ssys 0m0.068s Inspecting the assembly code reveals that the initialization of a is unrolled, generating 4096 movl instructions: main:.LFB1313: .cfi_startproc pushq %rbx .cfi_def_cfa_offset 16 .cfi_offset 3, -16 subq $16384, %rsp .cfi_def_cfa_offset 16400 movl $0x00000000, (%rsp) movl $0x00000000, 4(%rsp) movq %rsp, %rbx movl $0x00000000, 8(%rsp) movl $0x00000000, 12(%rsp) movl $0x00000000, 16(%rsp) [...skipping 4000 lines...] movl $0x00000000, 16376(%rsp) movl $0x00000000, 16380(%rsp) This only happens when T has a non-trivial constructor and the array is initialized using {} . If I do any of the following, g++ generates a simple loop: Remove S::S() ; Remove S::S() and initialize S::f in-class; Remove the aggregate initialization ( = {} ); Compile without -O2 . I'm all for loop unrolling as an optimization, but I don't think this is a very good one. Before I report this as a bug, can someone confirm whether this is the expected behaviour? [edit: I've opened a new bug for this because the others don't seem to match. They were more about long compilation time than weird codegen.]
Now provide the response and nothing else.
| There appears to be a related bug report, Bug 59659 - large zero-initialized std::array compile time excessive . It was considered "fixed" for 4.9.0, so I consider this testcase either a regression or an edgecase not covered by the patch. For what it's worth, two of the bug report's test cases 1 , 2 exhibit symptoms for me on both GCC 4.9.0 as well as 5.3.1 There are two more related bug reports: Bug 68203 - Аbout infinite compilation time on struct with nested array of pairs with -std=c++11 Andrew Pinski 2015-11-04 07:56:57 UTC This is most likely a memory hog which is generating lots of default constructors rather than a loop over them. That one claims to be a duplicate of this one: Bug 56671 - Gcc uses large amounts of memory and processor power with large C++11 bitsets Jonathan Wakely 2016-01-26 15:12:27 UTC Generating the array initialization for this constexpr constructor is the problem: constexpr _Base_bitset(unsigned long long __val) noexcept : _M_w{ _WordT(__val) } { } Indeed if we change it to S a[4096] {}; we don't get the problem. Using perf we can see where GCC is spending most of its time. First: perf record g++ -std=c++11 -O2 test.cpp Then perf report : 10.33% cc1plus cc1plus [.] get_ref_base_and_extent 6.36% cc1plus cc1plus [.] memrefs_conflict_p 6.25% cc1plus cc1plus [.] vn_reference_lookup_2 6.16% cc1plus cc1plus [.] exp_equiv_p 5.99% cc1plus cc1plus [.] walk_non_aliased_vuses 5.02% cc1plus cc1plus [.] find_base_term 4.98% cc1plus cc1plus [.] invalidate 4.73% cc1plus cc1plus [.] write_dependence_p 4.68% cc1plus cc1plus [.] estimate_calls_size_and_time 4.11% cc1plus cc1plus [.] ix86_find_base_term 3.41% cc1plus cc1plus [.] rtx_equal_p 2.87% cc1plus cc1plus [.] cse_insn 2.77% cc1plus cc1plus [.] record_store 2.66% cc1plus cc1plus [.] vn_reference_eq 2.48% cc1plus cc1plus [.] operand_equal_p 1.21% cc1plus cc1plus [.] integer_zerop 1.00% cc1plus cc1plus [.] base_alias_check This won't mean much to anyone but GCC developers but it's still interesting to see what's taking up so much compilation time. Clang 3.7.0 does a much better job at this than GCC. At -O2 it takes less than a second to compile, produces a much smaller executable (8960 bytes) and this assembly: 0000000000400810 <main>: 400810: 53 push rbx 400811: 48 81 ec 00 40 00 00 sub rsp,0x4000 400818: 48 8d 3c 24 lea rdi,[rsp] 40081c: 31 db xor ebx,ebx 40081e: 31 f6 xor esi,esi 400820: ba 00 40 00 00 mov edx,0x4000 400825: e8 56 fe ff ff call 400680 <memset@plt> 40082a: 66 0f 1f 44 00 00 nop WORD PTR [rax+rax*1+0x0] 400830: f3 0f 10 04 1c movss xmm0,DWORD PTR [rsp+rbx*1] 400835: f3 0f 5a c0 cvtss2sd xmm0,xmm0 400839: bf 60 10 60 00 mov edi,0x601060 40083e: e8 9d fe ff ff call 4006e0 <_ZNSo9_M_insertIdEERSoT_@plt> 400843: 48 83 c3 04 add rbx,0x4 400847: 48 81 fb 00 40 00 00 cmp rbx,0x4000 40084e: 75 e0 jne 400830 <main+0x20> 400850: 31 c0 xor eax,eax 400852: 48 81 c4 00 40 00 00 add rsp,0x4000 400859: 5b pop rbx 40085a: c3 ret 40085b: 0f 1f 44 00 00 nop DWORD PTR [rax+rax*1+0x0] On the other hand with GCC 5.3.1, with no optimizations, it compiles very quickly but still produces a 95328 sized executable. Compiling with -O2 reduces the executable size to 53912 but compilation time takes 4 seconds. I would definitely report this to their bugzilla. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37260097', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4885801/']} | jdg_84432 |
stackexchange | llm_judgeable_groundtruth_similarity | 16745777 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
example here: http://jsfiddle.net/D7v2Y/ In firefox/webkit this works great. The text is centered. Not in IE10 or IE9 input { display: block; box-sizing: border-box; line-height: 50px; height: 50px; padding: 10px;} What's goin' on here and how do I get the text input to display "correctly" with the text vertically centered in IE? Thank you!
Now provide the response and nothing else.
| You need to reconcile the padding and line-height . With box-sizing: border-box , they are essentially fighting for the same real estate. In other words, you are saying "fit 50px of line height into 50px of total vertical space, but also pad it by 20px". A simple solution is to reduce the line-height so that padding * 2 + line-height = 50px. Or, if you want more line-height , reduce the padding. If you want to keep the same line-height and padding, increase the height to 70px. Example: http://jsfiddle.net/D7v2Y/11/ input { display: block; box-sizing: border-box; line-height: 30px; height: 50px; padding: 10px;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16745777', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/220761/']} | jdg_84433 |
stackexchange | llm_judgeable_groundtruth_similarity | 7165582 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Are there conventions how to name resources in Android? For example, buttons, textViews, menus, etc.
Now provide the response and nothing else.
| Android SDK will be a good place to start. For example, I try to scope IDs within the activity. If I had a ListView it simply would be @android:id/list in all the activities. If, however, I had two lists then I would use the more specific @id/list_apple and @id/list_orange So generic (ids, ...) gets reused in the R.java file while the unique ones (sometimes gets reused) get prefixed with generic ones separated by an underscore . The underscore is one thing, I observed, for example: Layout width is layout_width in xml and layoutWidth in code , so I try to stick to it as list_apple So a Login button will be login , but if we have two logins then login_foo and login_bar . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7165582', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/397991/']} | jdg_84434 |
stackexchange | llm_judgeable_groundtruth_similarity | 129456 |
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:
I was looking at my bank website's certificate and discovered that it's issued to multiple websites, and the bank's domain name is only listed among many other domains in the 'alternative names' field. Is this considered a bad practice? What risks are their customers subjected to? (man in the middle? impersonation?)
Now provide the response and nothing else.
| It is a certificate of a content delivery network – a U.S. company Incapsula Inc. – intercepting your whole communication with the bank. The certificate itself does not pose a direct risk to customers' data, but: Is this considered a bad practice? Unlike the other answers , I would say it is not normal and the situation indicates a certain level of incompetence on the bank's side. According to Incapsula's pricing plans , your bank might be using $59/month, while the company offers custom SSL for $299/month (feature "Supports custom SSL certificates") and a real plan for enterprises. Even if the bank pays more to CDN, the bank is using functionality aimed at professional blogs and not using the features their plan/agreement offers. Your bank may be violating privacy laws in your country by letting a company from another country, under a different legislature, process customers' personally identifiable data. What risks are their customers are subjected to? (man in the middle? impersonation?) The data in a encrypted between your browser and the CDN's endpoint. The private key is (hopefully) stored only on CDN's servers, so there is no risk other companies from the list could impersonate the bank. As long as security standards are met on a link between CDN and the bank, the MitM is technically not possible either. | {} | {'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/129456', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/116881/']} | jdg_84435 |
stackexchange | llm_judgeable_groundtruth_similarity | 12040 |
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 2 questions. During Linux installation we specify memory space for 2 mount points - root and swap. Are there any other mount points created without the users notice? Is this statement correct: "mounting comes into the picture only when dealing with different partitions. i.e, you cannot mount, say, /proc unless it's a different partition"?
Now provide the response and nothing else.
| There are misconceptions behind your questions. Swap is not mounted. Mounting isn't limited to partitions. Partitions A partition is a slice¹ of disk space that's devoted to a particular purpose. Here are some common purposes for partitions. A filesystem , i.e. files organized as a directory tree and stored in a format such as ext2, ext3, FFS, FAT, NTFS, … Swap space, i.e. disk space used for paging (and storing hibernation images ). Direct application access. Some databases store their data directly on a partition rather than on a filesystem to gain a little performance. (A filesystem is a kind of database anyway.) A container for other partitions. For example, a PC extended partition , or a disk slice containing BSD partitions, or an LVM physical volume (containing eventually logical volumes which can themselves be considered partitions), … Filesystems Filesystems present information in a hierarchical structure. Here are some common kinds of filesystems: Disk-backed filesystems, such as ext2, ext3, FFS, FAT, NTFS, … The backing need not be directly on a disk partition, as seen above. For example, this could be an LVM logical volume, or a loop mount . Memory-backed filesystems, such as Solaris and Linux's tmpfs . Filesystems that present information from the kernel, such as proc and sysfs on Linux. Network filesystems, such as NFS , Samba , … Application-backed filesystems, of which FUSE has a large collection . Application-backed filesystems can do just about anything: make an FTP server appear as a filesystem, give an alternate view of a filesystem where file names are case-insensitive or converted to a different encoding, show archive contents as if they were directories, … Mounting Unix presents files in a single hierarchy, usually called “the filesystem” (but in this answer I'll not use the word “filesystem” in this sense to keep confusion down). Individual filesystems must be grafted onto that hierarchy in order to access them.³ You make a filesystem accessible by mounting it. Mounting associates the root directory of the filesystem you're mounting with a existing directory in the file hierarchy. A directory that has such an association is known as a mount point. For example, the root filesystem is mounted at boot time (before the kernel starts any process²) to the / directory. The proc filesystem over which some unix variants such as Solaris and Linux expose information about processes is mounted on /proc , so that /proc/42/environ designates the file /42/environ on the proc filesystem, which (on Linux, at least) contains a read-only view of the environment of process number 42. If you have a separate filesystem e.g. for /home , then /home/john/myfile.txt designates the file whose path is /john/myfile.txt from the root of the home filesystem. Under Linux, it's possible for the same filesystem to be accessible through more than one path, thanks to bind mounts . A typical Linux filesystems has many mounted filesystems. (This is an example; different distributions, versions and setups will lead to different filesystems being mounted.) / : the root filesystem, mounted before the kernel loads the first process. The bootloader tells the kernel what to use as the root filesystem (it's usually a disk partition but could be something else such as an NFS export). /proc : the proc filessytem, with process and kernel information. /sys : the sysfs filesystem, with information about hardware devices. /dev : an in-memory filesystem where device files are automatically created by udev based on available hardware. /dev/pts : a special-purpose filesystem containing device files for running terminal emulators . /dev/shm : an in-memory filesystem used for internal purposes by the system's standard library. Depending on what system components you have running, you may see other special-purpose filesystems such as binfmt_misc (used by the foreign executable file format kernel subsystem ), fusectl (used by FUSE ), nfsd (used by the kernel NFS server), … Any filesystem explicitly mentioned in /etc/fstab (and not marked noauto ) is mounted as part of the boot process. Any filesystem automatically mounted by HAL (or equivalent functionality) following the insertion of a removable device such as a USB key. Any filesystem explicitly mounted with the mount command. ¹ Informally speaking here. ² Initrd and such are beyond the scope of this answer. ³ This is unlike Windows, which has a separate hierarchy for each filesystem, e.g. c: or \\hostname\sharename . | {} | {'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/12040', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/6962/']} | jdg_84436 |
stackexchange | llm_judgeable_groundtruth_similarity | 54942977 |
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 creating a new app with Flutter, and I'm trying to design it, separating the business logic from the view. I've read about Bloc and MVVM (I know there are other patterns but these were the ones I preferred), but I don't understand the differences between them. They look pretty much the same to me. Does anyone can help me understand them?
Now provide the response and nothing else.
| Looking at this illustration for MVVM ( source ): You can see that there are seperate data and business logic models. However, using BLoC there is not really a distinction like that. The classes that handle the business logic also handle the data, which can also apply to MVVM . To be fair, there really is not much of a difference. The key part to take away is the same for both: Isolating the business logic from the UI. Hence, the implementation of either of the two will look very similar, i.e. using Stream 's and StreamBuilder 's. Additionally, there are packages that make working with Stream 's easier, e.g. rxdart which is what the Flutter team uses as far as I am concerned. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54942977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2719216/']} | jdg_84437 |
stackexchange | llm_judgeable_groundtruth_similarity | 10713923 |
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 come up with the following code but the problem is, there will be duplication of the anchor tag for each menu item.Is there a better way to do this? ul.nav - if(menu="Home") li.active a(href="#") Dashboard else li a(href="#") Dashboard li a(href="#") About li a(href="#") Contact
Now provide the response and nothing else.
| Found this in another question that was similar : Use a ternary at each "li" ul li(class=(title === 'Home' ? 'active' : '')) a(href='#') Home li(class=(title === 'Dashboard' ? 'active' : '')) a(href='#') Dashboard You can setup your routes to pass the "menu" value instead of using "title" if you want: exports.index = function(req, res) { res.render('index', {title: 'Home', menu: 'Home'});} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10713923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/622551/']} | jdg_84438 |
stackexchange | llm_judgeable_groundtruth_similarity | 32795227 |
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 went over the alpha release notes for Django 1.9 and saw that the startapp management command now adds an apps.py file . What's the purpose of this file? The startapp documentation didn't provide more information.
Now provide the response and nothing else.
| Purpose of apps.py file: This file is created to help the user include any application configuration for the app. Using this, you can configure some of the attributes of the application. From Application Configuration documentation: Application configuration objects store metadata for an application. Some attributes can be configured in AppConfig subclasses. Others are set by Django and read-only. Example from the docs: Lets say you’re creating a pluggable app called "Rock ’n’ roll" , then to provide a proper name for the admin we can do the following: In rock_n_roll app, we create a RockNRollConfig AppConfig class. #rock_n_roll/apps.pyfrom django.apps import AppConfigclass RockNRollConfig(AppConfig): # Our app config class name = 'rock_n_roll' verbose_name = "Rock ’n’ roll" We can make your application load this AppConfig subclass by default by specifying the default_app_config in the rock_n_roll/__init__.py file. # rock_n_roll/__init__.py default_app_config = 'rock_n_roll.apps.RockNRollConfig' Doing this will cause RockNRollConfig to be used when INSTALLED_APPS just contains 'rock_n_roll' . This allows us to make use of AppConfig features without requiring our users to update their INSTALLED_APPS setting. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/32795227', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/308204/']} | jdg_84439 |
stackexchange | llm_judgeable_groundtruth_similarity | 53885431 |
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 developing a Laravel application. My application is using Laravel built-in auth feature. In the Laravel auth when a user registers, a verification email is sent. When a user verifies the email click on the link inside the email, the user has to login again to confirm the email if the user is not already logged in. VerificationController class VerificationController extends Controller{ use VerifiesEmails, RedirectsUsersBasedOnRoles; /** * Create a new controller instance. * @return void */ public function __construct() { $this->middleware('auth'); $this->middleware('signed')->only('verify'); $this->middleware('throttle:6,1')->only('verify', 'resend'); } public function redirectPath() { return $this->getRedirectTo(Auth::guard()->user()); }} I tried commenting on this line. $this->middleware('auth'); But it's s not working and instead, throwing an error. How can I enable Laravel to be able to verify email even if the user is not logged in?
Now provide the response and nothing else.
| First, remove the line $this->middleware('auth'); , like you did. Next, copy the verify method from the VerifiesEmails trait to your VerificationController and change it up a bit. The method should look like this: public function verify(Request $request){ $user = User::find($request->route('id')); if (!hash_equals((string) $request->route('hash'), sha1($user->getEmailForVerification()))) { throw new AuthorizationException; } if ($user->markEmailAsVerified()) event(new Verified($user)); return redirect($this->redirectPath())->with('verified', true);} This overrides the method in the VerifiesUsers trait and removes the authorization check. Security (correct me if I'm wrong!) It's still secure, as the request is signed and verified. Someone could verify another user's email address if they somehow gain access to the verification email, but in 99% of cases this is hardly a risk at all. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53885431', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4675736/']} | jdg_84440 |
Subsets and Splits