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
16032840
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have read a lot about closures in JavascriptWhat are those braces for??I read on mozilla.org which says closure should be defined as (function(){...})(); but on http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html , it says the closure function is (function(){...}()); What's the difference or the latter one is wrong?what's the purpose of the last ()? Would you put some parameters inside?I am looking for a good reference. Edit:Moreover, there is an example on Mozilla.org var makeCounter = function() {var privateCounter = 0; function changeBy(val) { privateCounter += val; } return { increment: function() { changeBy(1); }, decrement: function() { changeBy(-1); }, value: function() { return privateCounter; } } }; why the semicolon is needed for this 'function'? If it needs to be invoked immediately after its declaration, a () should be put before the ending semicolon. But there is not. Now provide the response and nothing else.
The syntax (function(){...})() is simply an immediately invoked anonymous function. It does not matter how you use your brackets, as the underlying code is a function being declared, and invoked. Closures are instead used to describe a situation where a function has access to variables declared outside of its scope, accessible via closures For clarity : If we have the following function function hello() { alert("Hello"); } We can call the function with the following hello() Which invokes the function 'hello'. But if we do not wish to give it a name, but still invoke it, then we can do (function hello() { alert("Hello");})() Which will do the exact same as the previous example of calling hello However, in this scenario there is no point in giving the function the name 'hello', so we can simply remove it: (function() { alert("Hello");})() Which is the notation used in your original question.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16032840', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1978421/']}
jdg_71941
stackexchange
llm_judgeable_groundtruth_similarity
1120190
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I determine and force users to view my website using HTTPS only? I know it can be done through IIS, but want to know how its done programmatically. Now provide the response and nothing else.
You can write an HttpModule like this: /// <summary>/// Used to correct non-secure requests to secure ones./// If the website backend requires of SSL use, the whole requests /// should be secure./// </summary>public class SecurityModule : IHttpModule{ public void Dispose() { } public void Init(HttpApplication application) { application.BeginRequest += new EventHandler(application_BeginRequest); } protected void application_BeginRequest(object sender, EventArgs e) { HttpApplication application = ((HttpApplication)(sender)); HttpRequest request = application.Request; HttpResponse response = application.Response; // if the secure connection is required for backend and the current // request doesn't use SSL, redirecting the request to be secure if ({use SSL} && !request.IsSecureConnection) { string absoluteUri = request.Url.AbsoluteUri; response.Redirect(absoluteUri.Replace("http://", "https://"), true); } }} Where {use SSL} is a some condition whether to use SSL or not. EDIT : and, of course, don't forget to add a module definition to a web.config : <system.web> <httpModules> <!--Used to redirect all the unsecure connections to the secure ones if necessary--> <add name="Security" type="{YourNamespace}.Handlers.SecurityModule, {YourAssembly}" /> ... </httpModules></system.web>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1120190', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1316/']}
jdg_71942
stackexchange
llm_judgeable_groundtruth_similarity
24108063
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 create a figure in python and make is so that the same annonate text will have two colors, half of the annonate will be blue and the other half will be red. I think the code explain itself. I have 3 lines 1 green with green annonate, 1 blue with blue annonate. The 3rd is red its the summation of plot 1 and plot 2, and I want it to have half annonate blue and half green. ipython -pylab x=arange(0,4,0.1)exp1 = e**(-x/5)exp2 = e**(-x/1)exp3 = e**(-x/5) +e**(-x/1) figure()plot(x,exp1)plot(x,exp2)plot(x,exp1+exp2)title('Exponential Decay')annotate(r'$e^{-x/5}$', xy=(x[10], exp1[10]), xytext=(-20,-35), textcoords='offset points', ha='center', va='bottom',color='blue', bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3), arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0.95', color='b'))annotate(r'$e^{-x/1}$', xy=(x[10], exp2[10]), xytext=(-5,20), textcoords='offset points', ha='center', va='bottom',color='green', bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3), arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=-0.5', color='g'))annotate(r'$e^{-x/5} + e^{-x/1}$', xy=(x[10], exp2[10]+exp1[10]), xytext=(40,20), textcoords='offset points', ha='center', va='bottom', bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3), arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=-0.5', color='red')) Is it possible? Now provide the response and nothing else.
You can use r'$\textcolor{blue}{e^{-x/5}} + \textcolor{green}{e^{-x/1}}$' to make the text half blue, half green. Using your own code for example: The image is generated by the following code. Testd with matplotlib v2.1.2 with the default matplotlibrc settings. import matplotlib as matplotlibmatplotlib.use('pgf')matplotlib.rc('pgf', texsystem='pdflatex') # from running latex -vpreamble = matplotlib.rcParams.setdefault('pgf.preamble', [])preamble.append(r'\usepackage{color}')from numpy import *from matplotlib.pyplot import *x=arange(0,4,0.1)exp1 = e**(-x/5)exp2 = e**(-x/1)exp3 = e**(-x/5) +e**(-x/1) figure()plot(x,exp1)plot(x,exp2)plot(x,exp1+exp2)title('Exponential Decay')annotate(r'$e^{-x/5}$', xy=(x[10], exp1[10]), xytext=(-20,-25), textcoords='offset points', ha='center', va='bottom',color='blue', bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3), arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0.95', color='b'))annotate(r'$e^{-x/1}$', xy=(x[10], exp2[10]), xytext=(25,20), textcoords='offset points', ha='center', va='bottom',color='green', bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3), arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=-0.5', color='g'))annotate(r'$\textcolor{blue}{e^{-x/5}} + \textcolor[rgb]{0.0, 0.5, 0.0}{e^{-x/1}}$', xy=(x[10], exp2[10]+exp1[10]), xytext=(40,20), textcoords='offset points', ha='center', va='bottom', bbox=dict(boxstyle='round,pad=0.2', fc='yellow', alpha=0.3), arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=-0.5', color='red'))savefig('test.png') It is mainly your code with the following changes: You need to use a pgf backend. Usepackage color in pgf.preamble There's some overlapping with the 1st and 2nd annotations, so xytext is changed. The color='g' in te 2nd annotation actually didn't use the pure "Green" color like (0, 255, 0) of rgb. \textcolor[rgb]{0.0, 0.5, 0.0} makes it looking alike.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24108063', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3720002/']}
jdg_71943
stackexchange
llm_judgeable_groundtruth_similarity
43000653
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 DialogFragment with a simple custom layout (TextView and EditView). When the user clicks the Positive Button of the Dialog, the app should save the user input from the EditText field into the variable "playerName". No matter what i'm trying, the Toast-output always shows an empty string "", or rather when i hardcode a text into the EditText (as shown in the XML) it shows always that text. The changes the user does with the keyboard input don't get processed in the code, any ideas what's wrong? DialogFragment @Overridepublic Dialog onCreateDialog(Bundle savedInstanceState) { builder.setPositiveButton("Save", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { LayoutInflater inflater = getActivity().getLayoutInflater(); View view = inflater.inflate(R.layout.addplayer_fragment, null); // declare the text input field EditText playerNameEdit = (EditText)view.findViewById(R.id.playerNameEdit); //read text into String String playerName = playerNameEdit.getText().toString(); // make toast with input of the edit text field Toast.makeText(getActivity().getApplicationContext(), playerName, Toast.LENGTH_SHORT).show(); } Layout (addplayer_fragment.xml) <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:padding= "10dip" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name: "/> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TestText" android:id="@+id/playerNameEdit"/> </LinearLayout> </RelativeLayout> Now provide the response and nothing else.
I try to found solution my self (JS ES6) but find only-partially. We are able to load img from no-CORS support src into canvas but browser switch cavnas into ' taint mode ' which not allow us to call toDataURL (and any other access to content). function loadImgAsBase64(url, callback) { let canvas = document.createElement('CANVAS'); let img = document.createElement('img'); //img.setAttribute('crossorigin', 'anonymous'); img.src = url; img.onload = () => { canvas.height = img.height; canvas.width = img.width; let context = canvas.getContext('2d'); context.drawImage(img, 0, 0); let dataURL = canvas.toDataURL('image/png'); canvas = null; callback(dataURL); };}let url = 'http://lorempixel.com/500/150/sports/9/';this.loadImgAsBase64(url, (dataURL) => { msg.innerText = dataURL.slice(0,50)+'...';}); IMAGE DATA: loading...<br><div id="msg"></div> So only way to overcome this obstacle is to create proxy server (e.g. in PHP) which will have CORS 'on' and it will download images for given url and send back to our app in JS. I found some free server https://cors-anywhere.herokuapp.com which we can use to in development to tests. Below there is full functional code which return dataUri from given image url: function loadImgAsBase64(url, callback) { let canvas = document.createElement('CANVAS'); let img = document.createElement('img'); img.setAttribute('crossorigin', 'anonymous'); img.src = 'https://cors-anywhere.herokuapp.com/' + url; img.onload = () => { canvas.height = img.height; canvas.width = img.width; let context = canvas.getContext('2d'); context.drawImage(img, 0, 0); let dataURL = canvas.toDataURL('image/png'); canvas = null; callback(dataURL); };}let url = 'http://lorempixel.com/500/150/sports/9/';this.loadImgAsBase64(url, (dataURL) => { msg.innerText = dataURL.slice(0,50)+'...'; // show pic document.body.innerHTML += `<img src="${dataURL}">`}); IMAGE DATA Loading...<br><div id="msg"></div> Thats all :) (I tested it on chrome, firefox and safari)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43000653', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2534677/']}
jdg_71944
stackexchange
llm_judgeable_groundtruth_similarity
141717
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Paul Melvin gave a talk at Knots in Washington last year in which he asked whether the connected sum of an odd twist-spin of a classical knot and a standard cross-cap embedding of ${\mathbb R}P^2$ is a standard cross-cap. I believe this question to be a standard one, and I have two questions about it. First, I think that Paul stated that if the result is knotted, then there is a non-standard ${\mathbb C}P^2$. Please may I have an outline of the argument that gives the construction of the non-standard ${\mathbb C}P^2?$ Second, for aesthetic reasons, I imagine that there is a difference in using a cross-cap with normal Euler class $2$ and using one with normal Euler class $-2$. Won't the construction give a $\pm {\mathbb C}P^2$ (or better ${\mathbb C}P^2$ or $\overline{{\mathbb C}P}^2$) depending on the normal Euler class of the cross-cap? Any other folk-lore would be appreciated. Now provide the response and nothing else.
I haven't been to Melvin's talks, but I suspect he's using the cyclic 2-sheeted branch cover construction. Specifically, the cyclic 2-sheeted branched cover of $S^4$ branched over the unknotted embedded $\mathbb RP^2$ is either $\mathbb CP^2$ or its mirror reflection depending on the normal Euler class of the $\mathbb RP^2$. A sort of algebraic-geometric way to see this would be to observe that $\mathbb CP^2$ modulo complex conjugation is $S^4$. You can check the $\mathbb CP^1$ in $\mathbb CP^2$ maps down to the standard embedding of $\mathbb RP^2$. Checking that the orientation of $\mathbb CP^2$ corresponds to the normal Euler class is perhaps simplest in this model. Another way to see this is to think of $\mathbb CP^2$ remove a ball as a disc bundle over $S^2$ with Euler class $1$, and similarly as $S^4$ as the union of two mapping cylinders from $S^3 / \{ \pm 1, \pm i, \pm j, \pm k\}$ to $\mathbb RP^2$. I am apparently not the first to think of this relation, there's a paper of Terry Lawson on this: T.Lawson, Splitting $S^4$ on $RP^2$ via the Branched Cover of $CP^2$ over $S^4$. Proceedings of the American Mathematical Society. Vol. 86, No. 2 (Oct., 1982), pp. 328-330
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/141717', 'https://mathoverflow.net', 'https://mathoverflow.net/users/36108/']}
jdg_71945
stackexchange
llm_judgeable_groundtruth_similarity
20880
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a Python script that need to be run with a particular python installation.Is there a way to craft a shebang so that it runs with $FOO/bar/MyCustomPython ? Now provide the response and nothing else.
The shebang line is very limited. Under many unix variants (including Linux), you can have only two words: a command and a single argument. There is also often a length limitation. The general solution is to write a small shell wrapper. Name the Python script foo.py , and put the shell script next to foo.py and call it foo . This approach doesn't require any particular header on the Python script. #!/bin/shexec "$FOO/bar/MyCustomPython" "$0.py" "$@" Another tempting approach is to write a wrapper script like the one above, and put #!/path/to/wrapper/script as the shebang line on the Python script. However, most unices don't support chaining of shebang scripts, so this won't work. If MyCustomPython was in the $PATH , you could use env to look it up: #!/usr/bin/env MyCustomPythonimport … Yet another approach is to arrange for the script to be both a valid shell script (which loads the right Python interpreter on itself) and a valid script in the target language (here Python). This requires that you find a way to write such a dual-language script for your target language. In Perl, this is known as if $running_under_some_shell . #!/bin/sheval 'exec "$FOO/bar/MyCustomPerl" -wS $0 ${1+"$@"}' if $running_under_some_shell;use … Here's one way to achieve the same effect in Python. In the shell, "true" is the true utility, which ignores its arguments (two single-character strings : and ' ) and returns a true value. In Python, "true" is a string which is true when interpreted as a boolean, so this is an if instruction that's always true and executes a string literal. #!/bin/shif "true" : '''\'thenexec "$FOO/bar/MyCustomPython" "$0" "$@"exit 127fi'''import … Rosetta code has such dual-language scripts in several other languages.
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/20880', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/10800/']}
jdg_71946
stackexchange
llm_judgeable_groundtruth_similarity
8204
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is it true that for all proofs $\forall x \exists y : R(x, y)$, then $y = y(x)$? A while back I remember reading a book on functional programming that was leading into some questions about what exactly mathematical proofs were and how they were related to functions. In fact, I just found the book: link to PDF , page 16 (marked page 3). The author mentions that if we have a proof that $\forall x \exists y : R(x, y)$, then, in a sense, because $x$ is bound before $y$, then $y$ is dependent on $x$, and therefore $y = y(x)$. There may be counterexamples. Perhaps $y$ is a constant itself, but then $y(x)$ can also just be a constant function. I'm trying to understand under what circumstances this is not true. Example: Let $f : \mathbb {R}^n \to \mathbb R$ be continuous at a point $\vec{v_0}$ and $f(\vec{v_0}) = A < 0$. Prove that there exists a number $\delta > 0$ such that if $\| \vec{v} - \vec{v_0} \| < \delta $ then $f(\vec{v}) < 0$. My argument was simply to use the statement of continuity at $\vec{v_0}$ to prove this. That is, since $f$ is continuous, the following holds: $$ \forall \epsilon > 0 \quad \exists \delta > 0 : \quad \| \vec{v} - \vec{v_0} \| < \delta \Rightarrow \| f(\vec{v}) - f(\vec{v_0}) \| < \epsilon .$$ So, as referred to above, we must have $\delta = \delta(\epsilon)$. Then we can make the replacement $\delta = \delta(|A|)$, and we have the necessary $\delta$ to prove that $f(\vec{v}) < 0$. I have one main question (the one that closes this), and one side question. Under what conditions can we assume that $\forall x \exists y : R(x, y)$, then $y = y(x)$? Are there indirect ways to prove a proposition of the form $\forall x \exists y : R(x, y)$ where $y$ is somehow not dependent on $x$ and also not a constant? Perhaps it varies on $R$, but that is given, I suppose. Certainly all $\epsilon$-$\delta$ proofs that I've come across have been constructive in this way. Is there a canonical way to prove the proposition above? I actually struggled with a possible proof for a while before I came up with the technique above. I used this technique in a HW assignment and on my latest Advanced Calculus test. The HW was marked as correct although with the note that it was "indirect", while the test was marked as wrong. Granted, the HW was done by the TA, the test by my prof. I personally don't see a more "direct" way to prove this result. Now provide the response and nothing else.
You seem to be asking: if for every $x$ there is a $y$ for which $R(x,y)$ holds, can we then define a function $f$ (in the usual sense) such that for every $x$, $R(x,f(x))$ holds? From a set-theoretic point of view, that statement is in fact none other than the Axiom of Choice . The Axiom of Choice has many forms, but one form is the following: given a nonempty family of nonempty sets, $S_i$ with $i\in I$ ("nonempty family" means that $I$ is not empty, so we have some sets; "nonempty sets" means that each $S_i$ is not empty), there exists a "choice function": a way to select for each $i\in I$ an element of the corresponding $S_i$. Formally, there exists a function $f\colon I\to \cup S_i$ from the index set to the union of the sets, with the property that $f(i)\in S_i$ for each $i$. Suppose that by assumption, for every $x$ in our universe $X$, the set $S_x = \{y\mid R(x,y)\}$ is nonempty, and you have a function $f$ with the desried property. The function $f$ will be a "choice function": a function $f:X \to \cup_{x\in U}S_x$ such that for each $x\in X$, $f(x)\in S_x$. Conversely, a choice function for the family $\{S_x\}_{x\in X}$ will yield and $f$ with the desired property. The existence of such functions for every nonempty family of nonempty sets is precisely the Axiom of Choice. Conversely, suppose that the Axiom of Choice fails, and let $\{S_x\}_{x\in X}$ be a nonempty family of nonempty sets for which no choice function exists. Then let $R(x,y)$ be "$y$ is in $S_x$". For every $x$ there exists a $y$ such that $R(x,y)$, since $S_x\neq\emptyset$. But since we are assuming that the family has no choice function, there does not exist any function $f$ such that for every $x$, $f(x)$ is in $S_x$. Thus, the question not only depends on the Axiom of Choice, but is equivalent to the Axiom of Choice. In some circumstances, the exact nature of the sets $S_x$ mean that you do not need to invoke the Axiom of Choice, because we have some "natural way" of defining the choice. For instance, if every set $S_x$ is a subset of the natural numbers, then you can define $f(x)$ to be "the least element of $S_x$". Another standard example is when $S_x$ is a singleton for every $x$; that is, for each $x$ there exists one and only one $y$ for which $R(x,y)$ holds. In that case, you can define your function $f$ to be "$f(x)$ is the unique $y$ for which $R(x,y)$ holds". But in general, the Axiom of Choice is, in some sense, "inherently non-constructive". And the thing is, the Axiom of Choice is independent of the usual axioms of set theory. Like the parallel postulate in geometry, you can accept it or not at your taste (the consequences of accepting and of not accepting it are different; for example, if you accept the Axiom of Choice, then that means that there is a way to slice a ball of radius 1 into a finite number of parts, and then rearrange the parts without changing their shape or size, into two balls of radius of 1; this is called the Banach-Tarski paradox ; on the other hand, if you want all your vector spaces to have bases , then you must accept the Axiom of Choice. In short, it has good consequences and weird/bad consequences). Edit: In the situation you have, it is possible to describe a function that will work; however, the "description" is a bit like cheating, in the sense that you can give an explicit rule for what the value of the function will be, but in practice it would be difficult to actually find the value. Namely, for every $\epsilon\gt 0$ you know that the set of $\delta\gt 0$ for which the implication $||v-v_0||\lt\delta\Rightarrow ||f(v)-f(v_0)||\lt\epsilon$ holds is nonempty. In particular, by the Archimedean property, the set $A_{\epsilon}=\{n\in\mathbb{N}| ||v-v_0||\lt\frac{1}{n} \Rightarrow ||f(v)-f(v_0)||\lt\epsilon\}$ is nonempty. This is a nonempty set of positive integers, so it has a least element. You can then define your function $\mathbf{f}\colon (0,\infty)\to(0,\infty)$ by the "formula" $\mathbf{f}(\epsilon)=1/\min(A_{\epsilon})$, the reciprocal of the smallest $n$ in the set. This definition would not require you to invoke the Axiom of Choice. As to your question 2: you almost had it, I think, but you should not invoke (implicitly) the Axiom of Choice: pick a specific $\epsilon$ (for example, $|A|/2$). You know that there exists a $\delta\gt 0$ that works for that epsilon, so you pick any $\delta_0$ that works and use that . That would be the standard way of proving the proposition at hand. If you assume you have some kind of "black-box function" that will hand you a $\delta$ whenever you hand it an $\epsilon$, you are invoking the Axiom of Choice and you are making your proof somewhat non-constructive.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/8204', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/33271/']}
jdg_71947
stackexchange
llm_judgeable_groundtruth_similarity
49189
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 $X_{i}$ be independent and identically distributed random variables such that $S_n/n\to 0$ almost surely where $S_n=X_1+\dots+X_n$. How to prove that $E|X_1|<\infty$ and therefore $EX_1=0.$ Now provide the response and nothing else.
For every positive $n$ call $U_n=S_n/n$. There are two simple facts at the basis of the characterization of the behaviour of the sequence $(U_n)$ when the increments $(X_n)$ are i.i.d. but not integrable. (1) Stochastic fact: if $(X_n)$ is i.i.d. and $X_1$ is not integrable then, for every finite $x$, infinitely many events $A_n=[|X_n|\ge xn]$ are realized, almost surely. (2) Deterministic fact: consider a deterministic sequence $(x_n)$ and for every positive $n$ define $u_n=(x_1+\cdots+x_n)/n$. If there exists a positive $x$ such that $|x_n|\ge xn$ for infinitely many indices $n$, then the sequence $(u_n)$ is divergent. Putting facts (1) and (2) together yields that $(U_n)$ is almost surely divergent, in particular the event $[U_n\to0]$ has probability zero. To prove fact (1), note that $(A_n)$ is an independent sequence of events and that the series $\sum P(A_n)$ is divergent hence Borel-Cantelli lemma yields the result. To prove fact (2), assume that $(u_n)$ is convergent and that $u_n\to u$. Then, $$x_n/n=u_n-u_{n-1}(n-1)/n\to u-u=0,$$hence $|x_n|\le\frac12xn$ for every $n$ large enough, which is a contradiction. Added later on Thought I might as well recall the proof that, in (1), the series $\sum P(A_n)$ in divergent. The idea is that $P(A_n)=P(|X_1|\ge xn)$ and that$$\sum_{n\ge0}P(|X_1|\ge xn)=\sum_{n\ge0}(n+1)P(x(n+1)>|X_1|\ge xn)\ge x^{-1}E(|X_1|).$$And finally, this upper bound loses almost nothing, since one also has$$\sum_{n\ge1}P(|X_1|\ge xn)=\sum_{n\ge1}nP(x(n+1)>|X_1|\ge xn)\le x^{-1}E(|X_1|).$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/49189', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12273/']}
jdg_71948
stackexchange
llm_judgeable_groundtruth_similarity
7193698
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 Parallel.Foreach for populating an external ConcurrentBag. I tried also to use a common List and everything works fine. I have been lucky or I missed the special scope of ConcurrentBag? Now provide the response and nothing else.
You have been lucky; Parallel.ForEach to populate a List is not thread-safe, you will eventually run into problems. According to MSDN, List<T> is not thread safe: Any instance members are not guaranteed to be thread safe. A List<T> can support multiple readers concurrently, as long as the collection is not modified. Enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with one or more write accesses, the only way to ensure thread safety is to lock the collection during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization. ConcurrentBag is what you should use for this, which is thread-safe for multiple readers and writers.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7193698', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/435056/']}
jdg_71949
stackexchange
llm_judgeable_groundtruth_similarity
29844097
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there any implementation of javax.ws.rs.core.UriInfo which I can use to create an instance quickly for testing. This interface is long, I just need to test something. I don't want to waste time on whole implementation of this interface. UPDATE: I want to write a unit test for a function similar to this: @GET@Path("/my_path")@Produces(MediaType.TEXT_XML)public String webserviceRequest(@Context UriInfo uriInfo); Now provide the response and nothing else.
You simply inject it with the @Context annotation, as a field or method parameter. @Path("resource")public class Resource { @Context UriInfo uriInfo; public Response doSomthing(@Context UriInfo uriInfo) { }} Other than your resource classes, it can also be injected into other providers, like ContainerRequestContext , ContextResolver , MessageBodyReader etc. EDIT Actually I want to write a junit test for a function similar to your doSomthing() function. I didn't pick that up in your post. But a couple options I can think of for unit tests Simply create a stub, implementing only the methods you use. Use a Mocking framework like Mockito , and mock the UriInfo . Example @Path("test")public class TestResource { public String doSomthing(@Context UriInfo uriInfo){ return uriInfo.getAbsolutePath().toString(); }}[...]@Testpublic void doTest() { UriInfo uriInfo = Mockito.mock(UriInfo.class); Mockito.when(uriInfo.getAbsolutePath()) .thenReturn(URI.create("http://localhost:8080/test")); TestResource resource = new TestResource(); String response = resource.doSomthing(uriInfo); Assert.assertEquals("http://localhost:8080/test", response);} You'll need to add this dependency <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-all</artifactId> <version>1.9.0</version></dependency> If you want to do an integration test, where the actual UriInfo is injected, you should look into Jersey Test Framework Here's a complete example with the Jersey Test Framework public class ResourceTest extends JerseyTest { @Path("test") public static class TestResource { @GET public Response doSomthing(@Context UriInfo uriInfo) { return Response.ok(uriInfo.getAbsolutePath().toString()).build(); } } @Override public Application configure() { return new ResourceConfig(TestResource.class); } @Test public void test() { String response = target("test").request().get(String.class); Assert.assertTrue(response.contains("test")); }} Just add this dependency <dependency> <groupId>org.glassfish.jersey.test-framework.providers</groupId> <artifactId>jersey-test-framework-provider-inmemory</artifactId> <version>${jersey2.version}</version></dependency> It uses an in-memory container, which is the most efficient for small tests. There are other containers with Servlet support if needed. Just see the link I posted above.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29844097', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2266682/']}
jdg_71950
stackexchange
llm_judgeable_groundtruth_similarity
374949
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 learning how to perform K-fold CV and I have a few questions about the method. This is an excerpt from the website: https://towardsdatascience.com/cross-validation-in-machine-learning-72924a69872f . In K Fold cross validation, the data is divided into k subsets. Now the holdout method is repeated k times, such that each time, one of the k subsets is used as the test set/ validation set and the other k-1 subsets are put together to form a training set. The error estimation is averaged over all k trials to get total effectiveness of our model. As can be seen, every data point gets to be in a validation set exactly once, and gets to be in a training set k-1 times. This significantly reduces bias as we are using most of the data for fitting, and also significantly reduces variance as most of the data is also being used in validation set. Interchanging the training and test sets also adds to the effectiveness of this method. As a general rule and empirical evidence, K = 5 or 10 is generally preferred, but nothing’s fixed and it can take any value. Notice that the much of the explanation done here is about the error itself. Let's say that I am performing a linear regression on sets of data. (This is the model I want to have.) Additionally I have 10 sets of data where I fit a model on. If I decide to have $k = 5$ (from this text), I will have 2 sets of data per $k$ . So I can fit a model on these 2 sets, and test the data with the other sets and record their errors. My question: So I will need to repeat this procedure with other sets of data (so that each $k$ will become a validation set exactly once), what happens to my model? Which model do I choose? Insights please. Now provide the response and nothing else.
The following code illustrates how this computation is done: grid <- with(data, expand.grid(f1 = levels(f1), f2 = levels(f2)))X <- model.matrix(~ f1 * f2, data = grid)V <- vcov(m)betas <- fixef(m)grid $emmean <- c(X %*% betas)grid$ SE <- sqrt(diag(X %*% V %*% t(X)))grid
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/374949', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/67413/']}
jdg_71951
stackexchange
llm_judgeable_groundtruth_similarity
5956067
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 occasionaly create images with rmagick in a cache dir. To then get rid of them fast, without loosing them for the view, I want to delete the image-files while my Ruby Instance of the Image-Class get's destructed or enters the Garbage Collection. What ClassMethod must I overwrite to feed the destructor with code? Now provide the response and nothing else.
You can use ObjectSpace.define_finalizer when you create the image file, and it will get invoked when the garbage man comes to collect. Just be careful not to reference the object itself in your proc, otherwise it won't be collected by the garbage man. (Won't pick up something that's alive and kicking) class MyObject def generate_image image = ImageMagick.do_some_magick ObjectSpace.define_finalizer(self, proc { image.self_destruct! }) endend
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5956067', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/179602/']}
jdg_71952
stackexchange
llm_judgeable_groundtruth_similarity
317874
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: LINQ equivalent of foreach for IEnumerable<T> The linq extension methods for ienumerable are very handy ... but not that useful if all you want to do is apply some computation to each item in the enumeration without returning anything. So I was wondering if perhaps I was just missing the right method, or if it truly doesn't exist as I'd rather use a built-in version if it's available ... but I haven't found one :-) I could have sworn there was a .ForEach method somewhere, but I have yet to find it. In the meantime, I did write my own version in case it's useful for anyone else: using System.Collections;using System.Collections.Generic;public delegate void Function<T>(T item);public delegate void Function(object item);public static class EnumerableExtensions{ public static void For(this IEnumerable enumerable, Function func) { foreach (object item in enumerable) { func(item); } } public static void For<T>(this IEnumerable<T> enumerable, Function<T> func) { foreach (T item in enumerable) { func(item); } }} usage is: myEnumerable.For<MyClass>(delegate(MyClass item) { item.Count++; }); Now provide the response and nothing else.
Shedding a little more light on why: LINQ is functional in nature. It is used to query data and return results. A LINQ query shouldn't be altering the state of the application (with some exceptions like caching). Because foreach doesn't return any results, it doesn't have many uses that don't involve altering the state of something besides what you are passing in to it. And if you need a Foreach() extension method, it is easy to roll your own. If, on the other hand, what you want is to take input and call a function on each item that returns a result, LINQ provides a way through its select method. For example, the following code calls a function delegate on every item in a list, returning true if that item is positive: static void Main(string[] args) { IEnumerable<int> list = new List<int>() { -5, 3, -2, 1, 2, -7 }; IEnumerable<bool> isPositiveList = list.Select<int, bool>(i => i > 0); foreach (bool isPositive in isPositiveList) { Console.WriteLine(isPositive); } Console.ReadKey(); }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/317874', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5416/']}
jdg_71953
stackexchange
llm_judgeable_groundtruth_similarity
12127278
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 view controller,that is a UINavigationController , that at some point pushes ( navigationcontroller pushViewController: animated: ) a second view that later pushes a third view where I have a button that pops back to the root view ( popToRootViewController: animated: ). The problem is that after the view is poped back to the root one, the method viewWillApper of the root view is not being called. I've set some breakpoints to check it and it's just not passing through it. I have a method to reload some contents of my root view placed in the viewWillApper and its being completely passed by after the popToRootViewController: animated .Any idea of what's going on? Thanks Now provide the response and nothing else.
Postgres has a dedicated function for that purpose. Introduced with Postgres 8.4. The manual: pg_get_function_identity_arguments(func_oid) ... get argument list to identify a function (without default values) ... pg_get_function_identity_arguments returns the argument listnecessary to identify a function, in the form it would need to appearin within ALTER FUNCTION , for instance. This form omits default values. Using that (and format() , introduced with Postgres 9.1), the following query generates DDL statements to drop functions matching your search terms: SELECT format('DROP %s %I.%I(%s);' , CASE WHEN p.proisagg THEN 'AGGREGATE' ELSE 'FUNCTION' END , n.nspname , p.proname , pg_catalog.pg_get_function_identity_arguments(p.oid) ) AS stmtFROM pg_catalog.pg_proc pJOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespaceWHERE p.proname = 'dblink' -- function name-- AND n.nspname = 'public' -- schema name (optional)-- AND pg_catalog.pg_function_is_visible(p.oid) -- function visible to userORDER BY 1; The system catalog pg_proc changed in Postgres 11 . proisagg was replaced by prokind , true stored procedures were added. You need to adapt. See: How to drop all of my functions in PostgreSQL? Returns: stmt--------------------------------------------------- DROP FUNCTION public.dblink(text); DROP FUNCTION public.dblink(text, boolean); DROP FUNCTION public.dblink(text, text); DROP FUNCTION public.dblink(text, text, boolean); Found four matches in the example because dblink uses overloaded functions . Run DROP statements selectively! Alternatively , you can use the convenient cast to the object identifier type regprocedure which returns a complete function signature including argument types: -- SET LOCAL search_path = ''; -- optional, to get all names schema-qualifiedSELECT format('DROP %s %s;' , CASE WHEN proisagg THEN 'AGGREGATE' ELSE 'FUNCTION' END , oid::regprocedure ) AS stmtFROM pg_catalog.pg_procWHERE proname = 'dblink' -- function nameORDER BY 1;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12127278', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1222373/']}
jdg_71954
stackexchange
llm_judgeable_groundtruth_similarity
189480
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: From a system of PDEs where i used the following ansatz: $$\theta_w(x,y) = e^{-\beta_h x} f(x) e^{-\beta_c y} g(y)$$ . $F(x) := \int f(x) \, \mathrm{d}x$ and $G(y) := \int g(y) \, \mathrm{d}y$ So, $$\theta_w(x,y) = e^{-\beta_h x} F'(x) e^{-\beta_c y} G'(y)$$ I have two linear ODEs of which one i am mentioning here $$\lambda_hF'''-2\lambda_h\beta_hF''+((\lambda_h\beta_h-1)\beta_h-\mu)F'+\beta_h^2F=0 $$ with the b.c. $$ F(0)=0 $$ $$ \frac{F''(0)}{F'(0)}=\beta_h $$ $$\frac{F''(1)}{F'(1)}=\beta_h$$ Here $\mu$ is the separation constant A general solution of this ODE will be of the form: $$F(x) = \sum_k C_k e^{-\delta_k(\mu)x}$$ $k$ attains values $1,2,3$ because of the cubic nature of the characterstic equation. I need to find the eigenvalues of this ODE. I know i need to consider $\mu><=$$0$ . A second order ODE has a well defined form of its rootswhich is not the case here. I will mention here that i am not too well accustomed to Mathematica But is there any way through which these eigen values could bedetermined using Mathematica ? I am at a dead end here. (Finally i need to repeat the complete procedure for $G$ and then proceed to find $\theta_w$ ) Now provide the response and nothing else.
I have a package for numerically calculating solutions of eigenvalue problems using the Evans function via the method of compound matrices, which is hosted on github . See my answers to other questions or the github for some more details. First we install the package (only need to do this the first time): Needs["PacletManager`"]PacletInstall["CompoundMatrixMethod", "Site" -> "http://raw.githubusercontent.com/paclets/Repository/master"] Then we first need to turn the ODEs into a matrix form $\mathbf{y}'=\mathbf{A} \cdot \mathbf{y}$ , using my function ToMatrixSystem : Needs["CompoundMatrixMethod`"]sys = ToMatrixSystem[{λ F'''[x] - 2 λ β F''[x] + ((λ β - 1) β - μ) F'[x] + β^2 F[x] == 0}, {F[0] == 0, F''[0] == β F'[0], F''[1] == β F'[1]}, F, {x, 0, 1}, μ] The object sys contains the matrix $\mathbf{A}$ , as well as similar matrices for the boundary conditions and the range of integration. Now the function Evans will calculate the Evans function (also known as the Miss-Distance function) for any given value of $\mu$ provided that $\lambda$ and $\beta$ are specified; this is an analytic function whose roots coincide with eigenvalues of the original equation. Evans[1, sys /. {λ -> 1, β -> 2}](* -0.023299 *) We can also plot this: Plot[Evans[μ, sys /. {λ -> 1, β -> 1}], {μ, -300, 300}, AxesLabel -> {"μ", "E(μ)"}] For these parameter values you can see there are six eigenvalues within the plot region, the function findAllRoots (by user Jens, available from this post ) will give you them all: findAllRoots[Evans[μ, sys /. {λ -> 1, β -> 1}], {μ, -300, 300}](* {-247.736, -158.907, -89.8156, -40.4541, -10.7982, -0.635232} *) For the values $\lambda=0.02, \beta=10$ , it helps to remove the normalisation that is applied by default in Evans , and I've also plotted the values given by bbgodfrey's solution: Plot[Evans[μ, sys /. {λ -> 1/50, β -> 10}, NormalizationConstants -> 0], {μ, -21, -2}, Epilog -> Point[{#, 0} & /@ {-20.88, -17.48, -14.36, -11.53, -9.03, -6.92, -5.26, -4.08, -3.16}]] It looks like there is an infinite set of solutions for negative $\mu$ for this set of parameters. For $\beta=0$ the eigenvalues are $-\lambda (n \pi)^2$ , the general behaviour as $\mu->-\infty$ looks the same. As you vary $\beta$ and $\lambda$ you can see how the function changes and eigenvalues can move and coalesce. Note there is a discrepancy with bbgodfrey's results, which missed the root at $-3.392$ and gave a spurious one at $-3.165$ . That isn't to say that you can't manage to get spurious solutions by applying FindRoot to this technique if you aren't careful. Additionally, as the Evans function is (complex) analytic, you can use the Winding Number to find how many roots are within a contour. I have some functions for this, so you can see that there are only these 9 roots within the circular contour of size 21 located at the origin: PlotEvansCircle[sys /. {λ -> 1/50, β -> 10}, ContourRadius -> 21, nPoints -> 500, Joined -> True] Here the left hand side is a circle in the complex plane, and the right hand side is the Evans function applied to the points on that circle. The winding number is how many times the right hand contour goes round the origin. There is also a PlotEvansSemiCircle for seeing if there is a root in the positive half-plane (as that is a common question for instability). To get the eigenfunctions, replace the right BC with $F'(0)$ to some arbitrary value and use NDSolve. This is at high precision to check the boundary conditions are being met: Block[{β = 10, λ = 1/50}, μc = μ /. FindRoot[Evans[μ, sys, NormalizationConstants -> 0, WorkingPrecision -> 50], {μ, -3}, WorkingPrecision -> 50, AccuracyGoal -> 15, PrecisionGoal -> 15] // Quiet; sol = First[NDSolve[{λ F'''[x] - 2 λ β F''[x] + ((λ β - 1) β - μ) F'[x] + β^2 F[x] == 0, F[0] == 0, F''[0] == β F'[0], F'[0] == 1/10} /. μ -> μc, F, {x, 0, 1}, WorkingPrecision -> 50, AccuracyGoal -> 30, PrecisionGoal -> 30]]; Plot[(F[x]/F[1]) /. sol, {x, 0, 1}, PlotLabel -> "Eigenfunction for μ=" <> ToString@Round[μc, 0.0001] <> ", with BC error: " <> ToString@Round[((F''[1] - β F'[1]) /. sol), 0.0001], AxesLabel -> {"x", "F(x) (scaled)"}, PlotRange -> All] ] The eigenfunctions get increasingly oscillatory as the eigenvalue gets more negative: roots = Reverse@findAllRoots[Evans[μ, sys /. {λ -> 1/50, β -> 10}, NormalizationConstants -> 0], {μ, -200, -2}]Plot[Evaluate[Table[(F[x]/F[1]) /. NDSolve[{λ F'''[x] - 2 λ β F''[x] + ((λ β - 1) β - μ) F'[x] + β^2 F[x] == 0, F[0] == 0, F''[0] == β F'[0], F'[0] == 1/1000} /. {λ -> 1/50, β -> 10}, F, {x, 0, 1}], {μ, roots}]], {x, 0, 1}, PlotRange -> All, AxesLabel -> {"x", "F(x), scaled"}] The method will work for higher order systems (up to 10th order generally), and does not require DSolve to be able to solve the underlying ODE.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/189480', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/62160/']}
jdg_71955
stackexchange
llm_judgeable_groundtruth_similarity
3624345
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 command to delete a line (or several lines) that is immediately below current line?Currently I'm doing it as: j dd and then . to repeat as needed.Is there a command that would combine all these? UPDATE: The reason I would like to have such command is that I don't like to move away from current position, yet be able to delete lines below. Now provide the response and nothing else.
The delete ex command will work nicely. :+,$d This will delete all the lines from current +1 till the end ($) To delete the next 2 lines the follow range would work, +1,+2 or shorthand +,+2 :+,+2d As @ib mentioned the :delete or :d command will move the cursor to the start of the line next to the deleted text. (Even with nostartofline set). To overcome this we can issue the `` normal mode command. `` will jump back to the exact position before the last jump, in this case the :d command. Our command is now : + , + 2 d enter ` ` Or as one ex command :+,+2d|norm! `` To make this easier we wrap this all up in a command: command! -count=1 -register D :+,+<count>d <reg><bar>norm! `` Now to delete the next following 3 lines: :3D This command can also take a {reg} like :delete and :yank do. So deleting the next 4 lines into register a would be: :4D a For more information :h :d:h :command:h :command-register:h :command-count:h ``
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/3624345', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/430254/']}
jdg_71956
stackexchange
llm_judgeable_groundtruth_similarity
366721
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 am in a situation where I cannot have passwordless login for ssh and ssh server could not be run over any other port other than the default port. So, I have chosen to use stunnel to tunnel ssh. On my personal pc I use stunnel on client mode and use it to login to server like so: ssh -p 8888 user@localhost . The problem is that ssl client certificate is public, so anyone can easily setup a ssl tunnel to my server. If any one queries for https://myserver.com it shows that openssh 2.0 is running on ssl port. So it has become an easiest way to break in, much simpler than running ssl server on a non-default port. So, I would like to know if it is possible to make ssl client certificate private, so that it won't be offered to anyone who does a https query on my server. And I should be able to maintain it as secret as ssl private key. Now provide the response and nothing else.
So to clarify: You want passwords to be allowed from the office network, but not from anywhere else. You, however, need to be able to connect from anywhere. On my network SSH keys are required when logging in from outside but either keys or passwords can be used when connecting from another host on the inside. Here's how that works: /etc/ssh/sshd_config RSAAuthentication yesPasswordAuthentication noMatch Address 192.168.0.* PasswordAuthentication yes If you substitute your office subnet for 192.168.0.*, users will be able to use passwords to connect, but only from the office subnet. You, however, will be able to use your SSH keypair to connect from anywhere. When an ssh client connects to the server, it is presented with a list of authentication mechanisms it can try. Typically the list is "publickey, password." In this case, when someone connects from outside, they are only presented with "publickey" so their client will not even attempt to send a password. If they attempt to authenticate with any mechanism other than an SSH public key, the connection is immediately shut down by the server. So no possibility exists for brute-forcing the passwords.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/366721', 'https://serverfault.com', 'https://serverfault.com/users/59291/']}
jdg_71957
stackexchange
llm_judgeable_groundtruth_similarity
19631932
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 send HTML report emails to customers, which display nicely on most email clients. When displayed in Outlook 2013, the following message is sometimes displayed: if there are problems with how this message is displayed, click here to view it in a web browser. I would like to get rid of this message. This post suggests removing all thead and tbody tags from the message (there aren't any in my HTML code) and replace inline CSS with embedded CSS, which I can't do because other mail clients have problems with non-inline CSS. Are there any known ways to prevent this message from showing? Now provide the response and nothing else.
I found that by adding the following to the head section of the page, that the message is not displayed. <meta name="ProgId" content="Word.Document"> I learned this by saving a nearly blank word document as HTML and selectively removing bloat over and over until I narrowed it down to this. In my case, the email was being sent using TSQL in SQL Server 2008 R2 via the msdb.dbo.sp_send_dbmail function.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19631932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1795244/']}
jdg_71958
stackexchange
llm_judgeable_groundtruth_similarity
52015479
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was able to do it in Python and my Python code is: signs = {"+" : lambda a, b : a + b, "-" : lambda a, b : a - b}a = 5b = 3for i in signs.keys(): print(signs[i](a,b)) And the output is: 82 How do I do this same thing in Java through HashMap? Now provide the response and nothing else.
You can use BinaryOperator<Integer> in this case like so : BinaryOperator<Integer> add = (a, b) -> a + b;//lambda a, b : a + bBinaryOperator<Integer> sub = (a, b) -> a - b;//lambda a, b : a - b// Then create a new Map which take the sign and the corresponding BinaryOperator// equivalent to signs = {"+" : lambda a, b : a + b, "-" : lambda a, b : a - b}Map<String, BinaryOperator<Integer>> signs = Map.of("+", add, "-", sub);int a = 5; // a = 5int b = 3; // b = 3// Loop over the sings map and apply the operationsigns.values().forEach(v -> System.out.println(v.apply(a, b))); Outputs 82 Note for Map.of("+", add, "-", sub); I'm using Java 10, If you are not using Java 9+ you can add to your map like so: Map<String, BinaryOperator<Integer>> signs = new HashMap<>();signs.put("+", add);signs.put("-", sub); Ideone demo Good practice As already stated by @Boris the Spider and @Holger in the comments, Its better to use IntBinaryOperator to avoid boxing, in the end your code can look like this : // signs = {"+" : lambda a, b : a + b, "-" : lambda a, b : a - b}Map<String, IntBinaryOperator> signs = Map.of("+", (a, b) -> a + b, "-", (a, b) -> a - b);int a = 5; // a = 5int b = 3; // b = 3// for i in signs.keys(): print(signs[i](a,b))signs.values().forEach(v -> System.out.println(v.applyAsInt(a, b)));
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52015479', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9016809/']}
jdg_71959
stackexchange
llm_judgeable_groundtruth_similarity
27644617
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 couldnt understand the difference between n and size parameters in np.random.binomial. N = 1200p =0.53q = 1000np.random.binomial(N, p, size = q) np.random.binomial(1, p, size = q)np.random.binomial(N,p, size= q) N is the number of trials, but is what is the size doing in the above formula. also kindly explain the vabove three versions of binomials. Now provide the response and nothing else.
np.random.binomial(N, p, size = q) np.random.binomial(1, p, size = q) np.random.binomial(N,p, size= q) 1st and 3rd are similar, i can see. These two are binomial random number generator And, 2nd one is bernoulli random number generator Explanation of binomial: A binomial random variable counts how often a particular event occurs in a fixed number of tries or trials. Here, n = number of trials p = probability event of interest occurs on any one trial size = number of times you want to run this experiment Suppose, You wanna check how many times you will get six if you roll dice 10 times. Here, n = 10, p = (1/6) # probability of getting six in each roll But, You have to do this experiment multiple times. Let, In 1st experiment, you get 3 six In 2nd expwriment, you get 2 six In 3rd experiment, you get 2 six In Pth experiment, you get 2 six, here P is the size Explanation of bernoulli: Suppose you perform an experiment with two possible outcomes: either success or failure. Success happens with probability p, while failure happens with probability 1-p. A random variable that takes value 1 in case of success and 0 in case of failure is called a Bernoulli random variable. Here, n = 1, Because you need to check whether it is success or failure one time p = probability of success size = number of times you will check this You can also read this, numpy.random.binomial Also, Difference between Binomial and Bernoulli
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27644617', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4273266/']}
jdg_71960
stackexchange
llm_judgeable_groundtruth_similarity
40994610
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 advice in situation: I have several JSON where may be several types of transport are (for example, only train (first variant) or train and bus (second variant). I know that there are only 3 types of transport maximum. So, I'd like to show info from JSON about train in first view controller, info from JSON about bus in second end etc. How better to do: create several view controllers (for maximum variants - 3), several tabBar.items (3) and when I get data from JSON in AppDelegate I will know: "OK, I know that in that JSON info only about train and I should show only tabBar.item = "train" and work only with TrainViewController and others tabBar.items I must hide from user? Is it good experience? Now provide the response and nothing else.
The link you posted says: "we get a "batch" of one hundred random data points from our training set" . In my example I use a global function (not a method like in your example) so there will be a difference in syntax. In my function you'll need to pass the number of samples wanted and the data array. Here is the correct code, which ensures samples have correct labels: import numpy as npdef next_batch(num, data, labels): ''' Return a total of `num` random samples and labels. ''' idx = np.arange(0 , len(data)) np.random.shuffle(idx) idx = idx[:num] data_shuffle = [data[ i] for i in idx] labels_shuffle = [labels[ i] for i in idx] return np.asarray(data_shuffle), np.asarray(labels_shuffle)Xtr, Ytr = np.arange(0, 10), np.arange(0, 100).reshape(10, 10)print(Xtr)print(Ytr)Xtr, Ytr = next_batch(5, Xtr, Ytr)print('\n5 random samples')print(Xtr)print(Ytr) And a demo run: [0 1 2 3 4 5 6 7 8 9][[ 0 1 2 3 4 5 6 7 8 9] [10 11 12 13 14 15 16 17 18 19] [20 21 22 23 24 25 26 27 28 29] [30 31 32 33 34 35 36 37 38 39] [40 41 42 43 44 45 46 47 48 49] [50 51 52 53 54 55 56 57 58 59] [60 61 62 63 64 65 66 67 68 69] [70 71 72 73 74 75 76 77 78 79] [80 81 82 83 84 85 86 87 88 89] [90 91 92 93 94 95 96 97 98 99]]5 random samples[9 1 5 6 7][[90 91 92 93 94 95 96 97 98 99] [10 11 12 13 14 15 16 17 18 19] [50 51 52 53 54 55 56 57 58 59] [60 61 62 63 64 65 66 67 68 69] [70 71 72 73 74 75 76 77 78 79]]
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40994610', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5928311/']}
jdg_71961
stackexchange
llm_judgeable_groundtruth_similarity
32782
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: When I evalute the following expression, N[95881665812878 - 120000000000000 (121576521638975 - (321097753837557 Log[1/3 (1 + (19 - 3 Sqrt[33])^(1/3) + (19 + 3 Sqrt[33])^(1/3))])/ Log[5]) + ( 321097753837557 Log[(-1 + 1/3 (1 + (19 - 3 Sqrt[33])^(1/3) + (19 + 3 Sqrt[33])^(1/3)))/(-6 + 4/3 (1 + (19 - 3 Sqrt[33])^(1/3) + (19 + 3 Sqrt[33])^(1/3)))])/ Log[5]] I obtain -1.875*10^12 But, when I evalute it asking for 3-digits, I get 0.487 What is the reason for the different results? Now provide the response and nothing else.
As others have mentioned, the wrong result is given by N[expr] and the errors are due to cancellation. Let's discuss a bit why N[expr, 3] is able to give a good result. Mathematica can do computations with inexact ( = floating point) numbers in two ways: Using the computers native floating point arithmetic, which is very fast, but has no precision tracking. This is what happens when you use N[expr] or the completely equivalent N[expr, MachinePrecision] . Using Mathematica's own implementation of arbitrary precision arithmetic which does have precision tracking. This is what happens when you use N[expr, precision] , where precision is a number. Note that N[expr, $MachinePrecision] will use Mathematica's arithmetic to give a result to about 16 digits of precision, the value of the numerical constant $MachinePrecision . This is different from N[expr, MachinePrecision] . MachinePrecision is a symbol and $MachinePrecision is a number. Unlike most other similar programs, Mathematica is able to keep track of the precision of inexact numbers . Every inexact number has an attached property which indicates its precision: In[17]:= Precision[1.0]Out[17]= MachinePrecisionIn[18]:= Precision[1.0`5]Out[18]= 5. If you use MachinePrecision , the precision is not tracked: In[19]:= Precision[1.1 - 1.0]Out[19]= MachinePrecision If you use arbitrary precision arithmetic, then Mathematica computes an estimate of the precision of the result: In[20]:= Precision[1.1`5 - 1.0`5]Out[20]= 3.67778 Note the loss of precision when we subtract two numbers to obtain a result an order of magnitude smaller than both. We started with numbers specified to 5 digits and ended up with a result precise to only ~3.68 digits. Note that the precision of the result is only estimated , so don't rely on it being 100% accurate. This feature allows Mathematica to increase the number of digits it uses for calculations to obtain as many precise digits in the result as you request: expr = 95881665812878 - 120000000000000 (121576521638975 - (321097753837557 Log[ 1/3 (1 + (19 - 3 Sqrt[33])^(1/3) + (19 + 3 Sqrt[33])^(1/ 3))])/Log[ 5]) + (321097753837557 Log[(-1 + 1/3 (1 + (19 - 3 Sqrt[33])^(1/3) + (19 + 3 Sqrt[33])^(1/ 3)))/(-6 + 4/3 (1 + (19 - 3 Sqrt[33])^(1/3) + (19 + 3 Sqrt[33])^(1/ 3)))])/Log[5] As you noticed, N[expr, 3](* ==> 0.487 *) Let's do an experiment now and convert all exact numbers in the input expression to inexact numbers with only 16 digits of precision (which is what machine precision arithmetic uses): In[22]:= expr /. x_?NumberQ :> N[x, 16]Out[22]= 0.*10^13 This time the result seems to be "0", but notice the red highlight (if you try this in a notebook), and let's check its precision: In[23]:= Precision[%]Out[23]= 0. Mathematica estimates that when doing the calculations with 16 digits only, there's no precision left in the result, so it's useless! This explains why the result obtained with machine precision arithmetic is wrong. Let's try with 50 digits now: In[24]:= expr /. x_?NumberQ :> N[x, 50]Out[24]= 0.48687991410140791970In[25]:= Precision[%]Out[25]= 20.3909 Now we got a result that's accurate to 20 digits. When you request N[expr, 3] , the number of digits the system uses for calculations is automatically increased so the result will be accurate to 3 digits. If you come from, or switch to, a different system that can do arbitrary precision arithmetic, it's good to remember that in other systems the number of digits typically indicated the working precision, not the precision of the requested result. Here's an example with Maple: expr := -14589182596676904118334187122+38531730460506840000000000000*ln((1/3)*(19+3*sqrt(33))^(1/3)+(1/3)*(19-3*sqrt(33))^(1/3)+1/3)/ln(5)+321097753837557*ln(((1/3)*(19+3*sqrt(33))^(1/3)+(1/3)*(19-3*sqrt(33))^(1/3)-2/3)/((4/3)*(19+3*sqrt(33))^(1/3)+(4/3)*(19-3*sqrt(33))^(1/3)-14/3))/ln(5);evalf(expr, 20);3.34187122499671*10^8 # incorrect result computed with (insufficient) 20 digits of working precisionevalf(expr, 50);0.486879914101407919700386926722921333 Further reading: When I can assume that all decimal digits returned by Mathematica are provably correct?
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/32782', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/6766/']}
jdg_71962
stackexchange
llm_judgeable_groundtruth_similarity
11784878
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 seen the following code in one of our applications: public class First(){ private Second _second; public First() { _second = new Second(this); // Doing some other initialization stuff, }}public class Second{ public Second(First f) { }} In the First() constructor, isn't it bad that we are sending a reference of class First() before it is fully constructed? I am thinking that the object is only fully constructed once the control logic leaves the constructor. Or is this okay? Now provide the response and nothing else.
My question is, in the First() constructor, isnt it bad that we are sending a reference of class First() BEFORE it is fully constructed? Somewhat. It can be a problem, certainly. If the Second constructor just holds onto a reference for later use, that's not too bad. If, on the other hand, the Second constructor calls back into First : public Second(First f){ f.DoSomethingUsingState();} ... and the state hasn't been set up yet, then that would of course be a Very Bad Thing. If you call a virtual method on First then it could be even worse - you could end up calling into some code which hasn't even had a chance to run any of its constructor body yet (although its variable initializers will have been executed). In particular, readonly fields may be seen first with one value and then later with another... I blogged about this a while ago, which may provide some more information. Of course, without doing this sort of thing, it's pretty hard to create two mutually-referential immutable objects...
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11784878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1202434/']}
jdg_71963
stackexchange
llm_judgeable_groundtruth_similarity
7375075
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 been hearing of the advent of html5 for iOS development. I know nothing about web dev technologies and am wondering, can this really be used for iOS game development? Just hearing html makes me think this will be used for web related apps, not things like graphically dynamic 2d games, but being unfamiliar, I'm hoping to get some insight from the experts here. Is html5 going to be useful at all for games, or should I basically expect to be sticking with the likes of cocos2d for iphone? Now provide the response and nothing else.
The short answer is "Yes, you can develop full speed, interactive games with HTML5". Check out "Private Joe", "Biolab Disaster" and "FUBAR" in the Apple app store. All were created with HTML5, Javascript, and a few javascript libraries (ImpactJS and Box2D). One thing you'll see as you explore this is the repeated caveat that "web games aren't fast enough", also "Web games can't use the device's goodies - like GPS, vibration, etc." These statements represent "common thought" and are not really true anymore. Companies like PhoneGap and appMobi have tools that make it possible to do anything in HTML/JS that can be done in native apps. Browsers keep getting faster, and smartphone processors also keep getting faster. Qualcomm's new chipset even has GPU acceleration for future smartphones. As an added bonus from coding your app in HTML5, you will have the choice of whether to compile it app into a native app and post to one of the app stores (using appmobi or phonegap), or to offer it yourself as a web app (saving the Apple censorship and 30% tax). Viva HTML5!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7375075', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/323787/']}
jdg_71964
stackexchange
llm_judgeable_groundtruth_similarity
7508813
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can you use Jsoup to submit a search to Google, but instead of sending your request via "Google Search" use "I'm Feeling Lucky"? I would like to capture the name of the site that would be returned. I see lots of examples of submitting forms, but never a way to specify a specific button to perform the search or form submission. If Jsoup won't work, what would? Now provide the response and nothing else.
According to the HTML source of http://google.com the "I am feeling lucky" button has a name of btnI : <input value="I'm Feeling Lucky" name="btnI" type="submit" onclick="..." /> So, just adding the btnI parameter to the query string should do (the value doesn't matter): http://www.google.com/search?hl=en&btnI=1&q=your+search+term So, this Jsoup should do: String url = "http://www.google.com/search?hl=en&btnI=1&q=balusc";Document document = Jsoup.connect(url).get();System.out.println(document.title()); However, this gave a 403 (Forbidden) error. Exception in thread "main" java.io.IOException: 403 error loading URL http://www.google.com/search?hl=en&btnI=1&q=balusc at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:387) at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:364) at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:143) at org.jsoup.helper.HttpConnection.get(HttpConnection.java:132) at test.Test.main(Test.java:17) Perhaps Google was sniffing the user agent and discovering it to be Java. So, I changed it: String url = "http://www.google.com/search?hl=en&btnI=1&q=balusc";Document document = Jsoup.connect(url).userAgent("Mozilla").get();System.out.println(document.title()); This yields (as expected): The BalusC Code The 403 is however an indication that Google isn't necessarily happy with bots like that. You might get (temporarily) IP-banned when you do this too often.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7508813', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/904681/']}
jdg_71965
stackexchange
llm_judgeable_groundtruth_similarity
15997320
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 divs with CSS that represent boxes, they wrap html code. <div class="box indent"> <div class="padding"> my code here </div></div> I created a "layoutbundle" where every HTML wrapper (such as boxes, tabs, grids, and so on) is put inside separate twig files. In such a way, views on other bundles can be implemented with other layouts. But I get tired of includes. Every small html wrapper requires an include, and I wonder if there is a simpler way to wrap HTML code. Let's have an example with a simple box. Actually, I created several files : A box.html.twig file that contain the box and include the content : <div class="box indent"> <div class="padding"> {% include content %} </div></div> Several box-content .html.twig files, containing content of my boxes. And finally, I create a box in a view by doing : {% include 'AcmeDemoBundle:layout:box.html.twig' with { 'content': 'ReusableBundle:feature:xxx.html.twig' }%} Is there a way to create wrappers such as : a) I declare once a new wrapper : {% wrapperheader "box" %} <div class="box indent"> <div class="padding">{% endwrapperheader %}{% wrapperfooter "box" %} </div> </div>{% endwrapperfooter %} b) And then in my pages, I use : {% wrapper "box" %} {# here my content #}{% endwrapper %} I think I'll need to add new tag extensions in Twig, but first I want to know if something similar is natively possible. Now provide the response and nothing else.
The block method This method was proposed by Sebastiaan Stok on GitHub. This idea uses the block function . It writes the given block contents, and can be called several times. Wrappers file : {# src/Fuz/LayoutBundle/Resources/views/Default/wrappers.html.twig #}{% block box_head %} <div class="box indent"> <div class="padding">{% enblock %}{% block box_foot %} </div> </div>{% enblock %} Feature page : {{ block('box_head') }}Some content{{ block('box_foot') }} The wrap extension with macros This idea was proposed by Charles on GitHub. First you declare a macro in a macro.html.twig file. {% macro box(content) %} <div class="box indent"> <div class="padding"> {{ content | raw }} </div> </div>{% endmacro %} Amd then, instead of calling {{ macros.box('my content') }} (see the doc you develop a {% wrap %} tag that will handle the macro call, with what's between [% wrap %} and {% endwrap %} as parameter. This extension was easy to develop. I thought it could be hard to access macros, but in fact, they are stored in the context as objects, and calls can be compiled easily. Just some changes : we will use the following syntax : {# to access a macro from an object #}{% wrap macro_object macro_name %} my content here{% endwrap %}{# to access a macro declared in the same file #}{% wrap macro_name %} macro{% endwrap %} In the following code, don't forget to change namespaces if you want to get it work! First, add the extension in your services.yml: parameters: fuz_tools.twig.wrap_extension.class: Fuz\ToolsBundle\Twig\Extension\WrapExtensionservices: fuz_tools.twig.wrap_extension: class: '%fuz_tools.twig.wrap_extension.class%' tags: - { name: twig.extension } Inside your bundle, create a Twig directory. Add the extension, it will return the new TokenParser (in english: it will declare the new tag). Twig/Extension/WrapExtension.php: <?php// src/Fuz/ToolsBundle/Twig/Extension/WrapExtension.phpnamespace Fuz\ToolsBundle\Twig\Extension;use Fuz\ToolsBundle\Twig\TokenParser\WrapHeaderTokenParser;use Fuz\ToolsBundle\Twig\TokenParser\WrapFooterTokenParser;use Fuz\ToolsBundle\Twig\TokenParser\WrapTokenParser;class WrapExtension extends \Twig_Extension{ public function getTokenParsers() { return array ( new WrapTokenParser(), ); } public function getName() { return 'wrap'; }} Then add the TokenParser itself, it will be met when the parser will find a {% wrap %} tag. This TokenParser will check if the tag is called correctly (for our example, it has 2 parameters), store those parameters and get the content between {% wrap %} and {% endwrap %}`. Twig/TokenParser/WrapTokenParser.php: <?php// src/Fuz/ToolsBundle/Twig/TokenParser/WrapTokenParser.phpnamespace Fuz\ToolsBundle\Twig\TokenParser;use Fuz\ToolsBundle\Twig\Node\WrapNode;class WrapTokenParser extends \Twig_TokenParser{ public function parse(\Twig_Token $token) { $lineno = $token->getLine(); $stream = $this->parser->getStream(); $object = null; $name = $stream->expect(\Twig_Token::NAME_TYPE)->getValue(); if ($stream->test(\Twig_Token::BLOCK_END_TYPE)) { if (!$this->parser->hasMacro($name)) { throw new \Twig_Error_Syntax("The macro '$name' does not exist", $lineno); } } else { $object = $name; $name = $stream->expect(\Twig_Token::NAME_TYPE)->getValue(); } $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); $body = $this->parser->subparse(array ($this, 'decideWrapEnd'), true); $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); return new WrapNode($object, $name, $body, $token->getLine(), $this->getTag()); } public function decideWrapEnd(\Twig_Token $token) { return $token->test('endwrap'); } public function getTag() { return 'wrap'; }} Next, we need a compiler (a Node in the twig dialect), it will generate the PHP code associated with our {% wrap %} tag. This tag is an alias of {{ macro_object.box(content) }} , so I wrote that line in a template and watched the resulting code in the resulting generated php file (stored in your app/cache/dev/twig directory). I got : echo $this->getAttribute($this->getContext($context, "(macro object name)"), "(name)", array("(body)"), "method"); So my compiler became : Twig/Node/WrapNode.php: <?php// src/Fuz/ToolsBundle/Twig/Node/WrapNode.phpnamespace Fuz\ToolsBundle\Twig\Node;class WrapNode extends \Twig_Node{ public function __construct($object, $name, $body, $lineno = 0, $tag = null) { parent::__construct(array ('body' => $body), array ('object' => $object, 'name' => $name), $lineno, $tag); } public function compile(\Twig_Compiler $compiler) { $compiler ->addDebugInfo($this) ->write('ob_start();'); $compiler ->addDebugInfo($this) ->subcompile($this->getNode('body')); if (is_null($this->getAttribute('object'))) { $compiler ->write(sprintf('echo $this->get%s(ob_get_clean());', $this->getAttribute('name')) . "\n"); } else { $compiler ->write('echo $this->getAttribute($this->getContext($context, ') ->repr($this->getAttribute('object')) ->raw('), ') ->repr($this->getAttribute('name')) ->raw(', array(ob_get_clean()), "method");') ->raw("\n"); } }} Note : to know how work the subparsing / subcompiling, I read the spaceless extension source code. That's all! We get an alias that let us use macros with a large body. To try it: macros.html.twig: {% macro box(content) %} <div class="box indent"> <div class="padding"> {{ content | raw }} {# Don't forget the raw filter! #} </div> </div>{% endmacro %} some layout.html.twig: {% import "FuzLayoutBundle:Default:macros.html.twig" as macros %}{% wrap macros box %}test{% endwrap %}{% macro test(content) %}some {{ content | raw }} in the same file{% endmacro %}{% wrap test %}macro{% endwrap %} Outputs: <div class="box indent"> <div class="padding">test </div> </div>some macro in the same file The wrapperheader, wrapperfooter, wrapper extension This method is the one I tell you about in my question. You can read / implement it if you want to train yourself with token parsers, but functionnaly, that's less nice than the previous method. In a wrapper.html.twig file, you declare all wrappers : {% wrapperheader box %} <div class="box">{% endwrapper %}{% wrapperfooter box %} </div>{% endwrapperfooter %} In your features twig files, you use your wrappers : {% wrapper box %}This is my content{% endwrapper %} The following extension has 3 issues : There is no way to store data (such as context variables) in the Twig Environnement. So when you define a {% wrapperheader NAME %} , you have basically no clean way to check if a header for NAME is already defined (in this extension, I use static properties). When you include a twig file, it is parsed at runtime, not immediately (I mean, the included twig template is parsed while the generated file is executed, and not when the include tag is parsed). So that's not possible to know if a wrapper exists on a previousely included file when you parse the {% wrapper NAME %} tag. If your wrapper does not exist, this extension just displays what's between {% wrapper %} and {% endwrapper %} without any notice. The idea of this extension is : when the parser meet a wrapperheader and wrapperfooter tag, the compiler store the content of the tag somewhere for a later use with the wrapper tag. But the twig context is passed to {% include %} as a copy, not by reference. So that's not possible to store the {% wrapperheader %} and {% wrapperfooter %} information inside that context, for an usage at upper level (in files that include files). I needed to use a global context too. Here is the code, take care to change your namespaces. First we need to create an extension that will add new token parsers to Twig. Inside services.yml of a bundle, add the following lines to activate the extension : parameters: fuz_tools.twig.wrapper_extension.class: Fuz\ToolsBundle\Twig\Extension\WrapperExtensionservices: fuz_tools.twig.wrapper_extension: class: '%fuz_tools.twig.wrapper_extension.class%' tags: - { name: twig.extension } Inside your bundle, create a Twig directory. Create the following Twig\Extension\WrapperExtension.php file : <?php// src/Fuz/ToolsBundle/Twig/Extension/WrapperExtension.phpnamespace Fuz\ToolsBundle\Twig\Extension;use Fuz\ToolsBundle\Twig\TokenParser\WrapperHeaderTokenParser;use Fuz\ToolsBundle\Twig\TokenParser\WrapperFooterTokenParser;use Fuz\ToolsBundle\Twig\TokenParser\WrapperTokenParser;class WrapperExtension extends \Twig_Extension{ public function getTokenParsers() { return array( new WrapperHeaderTokenParser(), new WrapperFooterTokenParser(), new WrapperTokenParser(), ); } public function getName() { return 'wrapper'; }} Now we need to add the token parsers : our syntax is {% wrapper NAME %} ... {% endwrapper %} and the same with wrapperheader and wrapperfooter . So those token parsers are used to declare the tags, to retrive the wrapper's NAME , and to retrieve the body (what's between wrapper and endwrapper`). The token parser for wrapper: Twig\TokenParser\WrapperTokenParser.php: <?php// src/Fuz/ToolsBundle/Twig/TokenParser/WrapperTokenParser.phpnamespace Fuz\ToolsBundle\Twig\TokenParser;use Fuz\ToolsBundle\Twig\Node\WrapperNode;class WrapperTokenParser extends \Twig_TokenParser{ public function parse(\Twig_Token $token) { $stream = $this->parser->getStream(); $name = $stream->expect(\Twig_Token::NAME_TYPE)->getValue(); $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); $body = $this->parser->subparse(array($this, 'decideWrapperEnd'), true); $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); return new WrapperNode($name, $body, $token->getLine(), $this->getTag()); } public function decideWrapperEnd(\Twig_Token $token) { return $token->test('endwrapper'); } public function getTag() { return 'wrapper'; }} The token parser for wrapperheader: Twig\TokenParser\WrapperHeaderTokenParser.php: <?php// src/Fuz/ToolsBundle/Twig/TokenParser/WrapperHeaderTokenParser.phpnamespace Fuz\ToolsBundle\Twig\TokenParser;use Fuz\ToolsBundle\Twig\Node\WrapperHeaderNode;class WrapperHeaderTokenParser extends \Twig_TokenParser{ static public $wrappers = array (); public function parse(\Twig_Token $token) { $lineno = $token->getLine(); $stream = $this->parser->getStream(); $name = $stream->expect(\Twig_Token::NAME_TYPE)->getValue(); if (in_array($name, self::$wrappers)) { throw new \Twig_Error_Syntax("The wrapper '$name''s header has already been defined.", $lineno); } self::$wrappers[] = $name; $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); $body = $this->parser->subparse(array($this, 'decideWrapperHeaderEnd'), true); $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); return new WrapperHeaderNode($name, $body, $token->getLine(), $this->getTag()); } public function decideWrapperHeaderEnd(\Twig_Token $token) { return $token->test('endwrapperheader'); } public function getTag() { return 'wrapperheader'; }} The token parser for wrapperfooter: Twig\TokenParser\WrapperFooterTokenParser.php: <?php// src/Fuz/ToolsBundle/Twig/TokenParser/WrapperFooterTokenParser.phpnamespace Fuz\ToolsBundle\Twig\TokenParser;use Fuz\ToolsBundle\Twig\Node\WrapperFooterNode;class WrapperFooterTokenParser extends \Twig_TokenParser{ static public $wrappers = array (); public function parse(\Twig_Token $token) { $lineno = $token->getLine(); $stream = $this->parser->getStream(); $name = $stream->expect(\Twig_Token::NAME_TYPE)->getValue(); if (in_array($name, self::$wrappers)) { throw new \Twig_Error_Syntax("The wrapper '$name''s footer has already been defined.", $lineno); } self::$wrappers[] = $name; $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); $body = $this->parser->subparse(array($this, 'decideWrapperFooterEnd'), true); $this->parser->getStream()->expect(\Twig_Token::BLOCK_END_TYPE); return new WrapperFooterNode($name, $body, $token->getLine(), $this->getTag()); } public function decideWrapperFooterEnd(\Twig_Token $token) { return $token->test('endwrapperfooter'); } public function getTag() { return 'wrapperfooter'; }} The token parsers retrieve all the required information, we now need to compile those information into PHP. This PHP code will be generated by the twig engine inside a Twig_Template implementation (you can find generated classes in your cache directory). It generates code in a method, and the context of included files is not available (because the context array is not given by reference). In such a way, this is not possible to access what's inside the included file without a global context. That's why here, I use static attributes... That's not nice at all but I don't know how to avoid them (if you have ideas, please let me know! :)). Compiler for the wrapper tag : Twig\Nodes\WrapperNode.php <?php// src/Fuz/ToolsBundle/Twig/Node/WrapperNode.phpnamespace Fuz\ToolsBundle\Twig\Node;class WrapperNode extends \Twig_Node{ public function __construct($name, $body, $lineno = 0, $tag = null) { parent::__construct(array ('body' => $body), array ('name' => $name), $lineno, $tag); } public function compile(\Twig_Compiler $compiler) { $compiler ->addDebugInfo($this) ->write('if (isset(\\') ->raw(__NAMESPACE__) ->raw('\WrapperHeaderNode::$headers[') ->repr($this->getAttribute('name')) ->raw('])) {') ->raw("\n") ->indent() ->write('echo \\') ->raw(__NAMESPACE__) ->raw('\WrapperHeaderNode::$headers[') ->repr($this->getAttribute('name')) ->raw('];') ->raw("\n") ->outdent() ->write('}') ->raw("\n"); $compiler ->addDebugInfo($this) ->subcompile($this->getNode('body')); $compiler ->addDebugInfo($this) ->write('if (isset(\\') ->raw(__NAMESPACE__) ->raw('\WrapperFooterNode::$footers[') ->repr($this->getAttribute('name')) ->raw('])) {') ->raw("\n") ->indent() ->write('echo \\') ->raw(__NAMESPACE__) ->raw('\WrapperFooterNode::$footers[') ->repr($this->getAttribute('name')) ->raw('];') ->raw("\n") ->outdent() ->write('}') ->raw("\n"); }} Compiler for the wrapperheader tag : Twig\Nodes\WrapperHeaderNode.php <?php// src/Fuz/ToolsBundle/Twig/Node/WrapperHeaderNode.phpnamespace Fuz\ToolsBundle\Twig\Node;/** * @author alain tiemblo */class WrapperHeaderNode extends \Twig_Node{ static public $headers = array(); public function __construct($name, $body, $lineno = 0, $tag = null) { parent::__construct(array ('body' => $body), array ('name' => $name), $lineno, $tag); } public function compile(\Twig_Compiler $compiler) { $compiler ->write("ob_start();") ->raw("\n") ->subcompile($this->getNode('body')) ->write(__CLASS__) ->raw('::$headers[') ->repr($this->getAttribute('name')) ->raw('] = ob_get_clean();') ->raw("\n"); }} Compiler for the wrapperfooter tag : Twig\Nodes\WrapperFooterNode.php <?php// src/Fuz/ToolsBundle/Twig/Node/WrapperFooterNode.phpnamespace Fuz\ToolsBundle\Twig\Node;class WrapperFooterNode extends \Twig_Node{ static public $footers = array(); public function __construct($name, $body, $lineno = 0, $tag = null) { parent::__construct(array ('body' => $body), array ('name' => $name), $lineno, $tag); } public function compile(\Twig_Compiler $compiler) { $compiler ->write("ob_start();") ->raw("\n") ->subcompile($this->getNode('body')) ->write(__CLASS__) ->raw('::$footers[') ->repr($this->getAttribute('name')) ->raw('] = ob_get_clean();') ->raw("\n"); }} The implementation is ok now. Let's try it! Create a view named wrappers.html.twig : {# src/Fuz/LayoutBundle/Resources/views/Default/wrappers.html.twig #}{% wrapperheader demo %}HEAD{% endwrapperheader %}{% wrapperfooter demo %}FOOT{% endwrapperfooter %} Create a view named what you want.html.twig : {# src/Fuz/HomeBundle/Resources/views/Default/index.html.twig #}{% include 'FuzLayoutBundle:Default:wrappers.html.twig' %}{% wrapper demo %}O YEAH{% endwrapper %} This shows up : HEAD O YEAH FOOT
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15997320', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/731138/']}
jdg_71966
stackexchange
llm_judgeable_groundtruth_similarity
13756591
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 setting up a UIPickerView to have choices like choice a , choice b , choice c and so on. I have tried to interpret the sample code from Apple but that seems very difficult to understand for a beginner like me. I also would like the choices from the picker view to take me to another page if that is possible. Now provide the response and nothing else.
It's obvious for every beginner that it is some what tedious to understand these things the first time. Anyways, do you know how to use UITableView s? Do you know how to use UITableViewDelegate and UITableViewDataSource ? If your answer is yes, then just imagine UIPickerView s are like UITableView s (but remember they are not UITableViewController s). Let's say, I've a UIPickerView : UIPickerView *objPickerView = [UIPickerView new]; // You need to set frame or other properties and add to your view...you can either use XIB code... 1) First you need to assign the delegate and dataSource to the UIPickerView either via IB or code. It depends on your implementation (So this step looks very similar to a UITableView , doesn't it?) Like this: objPickerView.delegate = self; // Also, can be done from IB, if you're usingobjPickerView.dataSource = self;// Also, can be done from IB, if you're using 2) Next, you need to define number of sections, like this: - (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)thePickerView { return 1; // Or return whatever as you intend} 2) Then you need to define the number of rows you need: - (NSInteger)pickerView:(UIPickerView *)thePickerView numberOfRowsInComponent:(NSInteger)component { return 3;//Or, return as suitable for you...normally we use array for dynamic} 3) Then, define title for row (And if you have multiple section, then title for each section): - (NSString *)pickerView:(UIPickerView *)thePickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { return [NSString stringWithFormat:@"Choice-%d",row];//Or, your suitable title; like Choice-a, etc.} 4) Next, you need to get the event when someone clicks on an element (As you want to navigate to other controller/screen): - (void)pickerView:(UIPickerView *)thePickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {//Here, like the table view you can get the each section of each row if you've multiple sections NSLog(@"Selected Color: %@. Index of selected color: %i", [arrayColors objectAtIndex:row], row); //Now, if you want to navigate then; // Say, OtherViewController is the controller, where you want to navigate: OtherViewController *objOtherViewController = [OtherViewController new]; [self.navigationController pushViewController:objOtherViewController animated:YES];} That's all the implementation you need.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13756591', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1738345/']}
jdg_71967
stackexchange
llm_judgeable_groundtruth_similarity
950840
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 $U,V$ are ideals of a ring $R$, then which of the following is also an ideal of $R$? $U+V=\{u+v\mid u\in U,v\in V\}$ $U\cdot V=\{u\cdot v\mid u\in U,v\in V\}$ $U\cap V$ My attempt: I have proved $U+V$ and $U\cap V$ are ideals of $R$. My problem: I have problem about the second option. I think it is not ideal of $R$. If I am wrong then please prove this otherwise give one counter example to show that $U\cdot V$ is not ideal of $R$. Now provide the response and nothing else.
In the ring $\mathbb{Z}[X,Y]$, what happens if we take $U=V=(X,Y)$? Does $X^2 + Y^2$ lie in $U.V$?
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/950840', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/163998/']}
jdg_71968
stackexchange
llm_judgeable_groundtruth_similarity
3188014
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: This appears in my guide of definite integrals ; I haven't seen complex analysis yet.. $$\int_1^e\sin{(\ln{(x)})}\mathrm{d}x\tag1$$ I used integration by parts and substitution 3 times in (1), but I get nowhere.. any help? Now provide the response and nothing else.
If you use the substitution $u = \ln x$ , then $du = \frac{1}{x} dx = e^{-u}dx$ and we get $$I=\int_{1}^{e} \sin(\ln x) dx = \int_{0}^{1} e^{u}\sin u du. $$ This is a quite famous integral, and you can compute this by using the integration by parts twice. See here .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3188014', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/570946/']}
jdg_71969
stackexchange
llm_judgeable_groundtruth_similarity
46905
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 need to draw a set of curves on one graph (characteristics equations). As you can see they have exchanged x and y axes. My goal is to plot all those curves on one graph. Are there ways to do that? f[t_, t0_] := -(2 - 4/Pi*ArcTan[2])*Exp[-t]*(t - t0);g[x_, x0_] := (x - x0)/(-(2 - 4/Pi*ArcTan[x + 2]));Show[Table[Plot[f[t, t0], {t, 0, 1}, PlotRange -> {0, -0.3}, AxesLabel -> {t, x}], {t0, 0, 1, 0.1}]] Show[ Table[ Plot[g[x, x0], {x, 0, -0.3}, PlotRange -> {0, 1}, AxesLabel -> {x, t}], {x0, 0, -0.3, -0.05}]] Now provide the response and nothing else.
Kuba's answer using ParametricPlot is the most convenient way to get the result you need. Alternatively, you can use a geometric transformation function that rotates and then reflects s2 around the vertical axis: f[t_, t0_] := -(2 - 4/Pi*ArcTan[2])*Exp[-t]*(t - t0);g[x_, x0_] := (x - x0)/(-(2 - 4/Pi*ArcTan[x + 2]));s1 = Show[Table[Plot[f[t, t0], {t, 0, 1}, PlotRange -> {0, -0.3}, AxesLabel -> {"t", "x"}, PlotStyle -> Red], {t0, 0, 1, 0.1}]];s2 = Show[Table[Plot[g[x, x0], {x, 0, -0.3}, PlotRange -> {0, 1}, AxesLabel -> {"x", "t"}], {x0, 0, -0.3, -0.05}]]; Define trF = GeometricTransformation[#, Composition[ReflectionTransform[{-1, 0}], RotationTransform[Pi/2]]] &; This transformation can be Apply 'ed to s2 Show[s1, Graphics@(trF @@ s2)] or MapAt 'ed at position {1} of s2 Show[s1, MapAt[trF, s2, {1}]] to get
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/46905', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/13981/']}
jdg_71970
stackexchange
llm_judgeable_groundtruth_similarity
47266089
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 run a migration for a table inventories that I have created with this migration: Schema::create('inventories', function (Blueprint $table) { $table->increments('id'); $table->integer('remote_id')->unsigned(); $table->integer('local_id')->unsigned(); $table->string('local_type'); $table->string('url')->nullable()->unique(); $table->timestamps();}); I am trying to add a run a migration where I am adding a foreign key to the table: Schema::table('inventories', function (Blueprint $table) { $table->foreign('local_id')->references('id')->on('contents')->onDelete('cascade');}); But, I am getting an error when I try to run the migration: [Illuminate\Database\QueryException] SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ( middleton . #sql-5d6_162a , CONSTRAINT inventories_local_id_foreign FOREIGN KEY ( local_id ) REFERENCES contents ( id ) ON DELETE CASCADE ) (SQL: alter table inventories add constraint inventories_local_id_foreign foreign key ( local_id ) references contents ( id ) on delete cascade) [PDOException] SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ( middleton . #sql-5d6_162a , CONSTRAINT inventories_local_id_foreign FOREIGN KEY ( local_id ) REFERENCES contents ( id ) ON DELETE CASCADE ) What am I doing wrong? Now provide the response and nothing else.
You probably have some records in the inventories table with local_id that does not have corresponding id in the contents table, hence the error. You could solve it by one of the two ways: Run the migration with foreign_key_checks turned off. This will disabled the foreign key constraints for the existing rows (if that's what you want). It's documented here Insert only those records that have corresponding id field in contents table. You can use INSERT INTO.. WHERE EXISTS query to filter the records out, and insert only those records.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47266089', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7071069/']}
jdg_71971
stackexchange
llm_judgeable_groundtruth_similarity
24006199
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 virtual inheritance is covered here before and before asking this question, I went through the detail of the virtual inheritance and went through the details of a similar problem like the followings: multiple-diamond-inheritance-compiles-without-virtual-but-doesnt-with and why does GCC give me an error - final overrider My problem is slightly different as I am not using pure virtual function and explicitly using virtual inheritance to have one unique base class. The hierarchy is as follows: base /\ / \ der1 der2 \ / der3 I know about the dreadful diamond on the derivation issue, and that's why I am using virtual inheritance. #include <iostream>class base{public : base() { std::cout<<"base()" << std::endl; } virtual void fun() { std::cout<<"base" << std::endl; }};class der1: virtual public base{public : void fun() { std::cout<<"der1" << std::endl; }};class der2 : virtual public base{public : void fun() { std::cout<<"der2" << std::endl; }};class der3 : public der1,public der2{ public : /*void fun() { std::cout<<"der3" << std::endl; }*/ //if I took out the comment and the function //is defined it compiles fine as expected};int main(){ base *p=new der3; //used scope operation explicitly to avoid ambiguity p->base::fun(); //here it complains about 'no unique final overrider for fun' return 0;} My understanding is since I am using virtual inheritance, there should only be one instance of the base, and using the scope operator, I can invoke without ambiguity the virtual fun function. The function is not pure virtual. If I do leave an implementation on the der3 class it is giving me a compiler error: error: no unique final override for ‘virtual void base::fun()’ in ‘der3’ I can see how this issue works ( final overrider ). But mine doesn't. Is it getting confused between base::fun , der1::fun and der2::fun ? Does the scope operator help in any way? Any clue or help is appreciated. I am using g++ 4.6.3. Now provide the response and nothing else.
The most-derived class has to provide an implementation of the virtual functions in the virtual base class - otherwise how would it provide that base class interface, given the intermediate classes (i.e. your der1 and der2 ) provide two alternatives already - which one should it call? You have to disambiguate the situation (i.e. with der3::fun() ). Sure you're not actually calling der3::fun() as you're explicitly requesting base::fun() , but that doesn't mean the rules don't apply, any more than thinking you could instantiate an abstract class if you don't try to call the pure-virtual functions.... The program is ill-formed until the code ties off these loose ends.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24006199', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/775790/']}
jdg_71972
stackexchange
llm_judgeable_groundtruth_similarity
3662065
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: class A { private synchronized f() { ... ... } private void g() { ... ... }} If thread T1 is running f() which is synchronized, can thread t2 run g() which is not synchronized at the same point of time, while T1 is still running f()? Now provide the response and nothing else.
Not on the same instance of A. The instance itself is the lock so two execute the two methods at the same time with two threads you would need two instances of A.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3662065', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/441775/']}
jdg_71973
stackexchange
llm_judgeable_groundtruth_similarity
2786792
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 at treeview TextBox, and I want convert my Enum: <TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text="{Binding Path=AcceptationStatusGlobalFlag}" />public enum AcceptationStatusGlobalFlag { NotReady = 0, Ready = 1, AcceptedByAdmin=2 } to Icons. There will be 3 icons, let say ready.jpg, notready.jpg and AcceptedByAdmin.jpg Country and Region has pool AcceptationStatusGlobalFlag and on both I want to display this enum/Icon <TreeView Name="structureTree" SelectedItemChanged="structureTree_SelectedItemChanged" Grid.Row="0" Grid.Column="0" ItemsSource="{Binding}" Height="413" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Visible" Width="Auto" PreviewMouseRightButtonUp="structureTree_PreviewMouseRightButtonUp" FontFamily="Verdana" FontSize="12"> <TreeView.Resources> <HierarchicalDataTemplate DataType="{x:Type ServiceMy:Country}" ItemsSource="{Binding Path=ListOfRegions}"> <StackPanel Orientation="Horizontal"> <TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text="{Binding Path=Name}"/> <TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text=" H:"/> <TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text="{Binding Path=NumberOfHotels}"/> <TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text=" "/> <TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text=" FG:"/> <TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text="{Binding Path=AcceptationStatusGlobalFlag}" /> <!--<Button Name="BTNAddRegion" Height="20" Content="+" Click="BTNAddRegion_Click"></Button>--> </StackPanel> </HierarchicalDataTemplate> <HierarchicalDataTemplate DataType="{x:Type ServiceMy:Region}" ItemsSource="{Binding Path=ListOfProvinces}"> <StackPanel Orientation="Horizontal"> <TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text="{Binding Path=Name}"/> <TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text=" H:"/> <TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text="{Binding Path=NumberOfHotels}"/> <TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text=" "/> <!--<Button Name="BTNAddProvince" Height="20" Content="+" Click="BTNAddProvince_Click"></Button>--> </StackPanel> </DataTemplate> </TreeView.Resources> </TreeView> </GroupBox> </StackPanel></Grid> Now provide the response and nothing else.
Create a Value Converter It takes your enum value and returns the filename of the appropriate icon. [ValueConversion(typeof(AcceptationStatusGlobalFlag), typeof(string))]public class AcceptationStatusGlobalFlagToIconFilenameConverter : IValueConverter{ public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { switch ((AcceptationStatusGlobalFlag)value) { case AcceptationStatusGlobalFlag.Ready: return "ready.jpg"; case AcceptationStatusGlobalFlag.NotReady: return "notready.jpg"; case AcceptationStatusGlobalFlag.AcceptedByAdmin: return "AcceptedByAdmin.jpg"; default: return null; } // or return Enum.GetName(typeof(AcceptationStatusGlobalFlag), value) + ".jpg"; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotSupportedException(); }} You will need to add a reference to this converter in your XAML <Window ... xmlns:converters="clr-namespace:App.Converters" ...> <Window.Resources> <converters:AcceptationStatusGlobalFlagToIconFilenameConverter x:Key="IconConverter"/> </Window.Resources> Replace your TextBlock <TextBlock TextAlignment="Justify" VerticalAlignment="Center" Text="{Binding Path=AcceptationStatusGlobalFlag}" /> with an Image and tell it use your converter <Image Source="{Binding AcceptationStatusGlobalFlag, Converter={StaticResource IconConverter}}"/>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2786792', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/278618/']}
jdg_71974
stackexchange
llm_judgeable_groundtruth_similarity
71117304
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 making a discord bot for fun and have run into some inconvenience. For example in this function @client.event async def on_message(message): When I write message. PyCharm (does this work in other editors?) doesn't show suggestions for available methods, properties, etc. Is it possible to set this up so that for example when I type message. suggestions will come up, such as author , etc. Now provide the response and nothing else.
Don't disable validations without understanding them! I can't believe what I see in the replies here. For anybody coming here, please don't disable the validation (either via MIKRO_ORM_ALLOW_GLOBAL_CONTEXT env var or via allowGlobalContext configuration). Disabling the validation is fine only under very specific circumstances, mainly in unit tests. In case you don't know me, I am the one behind MikroORM, as well as the one who added this validation - for a very good reason, so please don't just disable that, it means you have a problem to solve, not that you should add one line to your configuration to shut it up. This validation was added to MikroORM v5 (so not typeorm, please dont confuse those two), and it means exactly what it says - you are trying to work with the global context, while you should be working with request specific one. Consult the docs for why you need request context here: https://mikro-orm.io/docs/identity-map#why-is-request-context-needed . In general using single (global) context will result in instable API response and basically a one huge memory leak. So now we should understand why the validation is there and why we should not disable it. Next how to get around it properly. As others mentined (and as the validation error message mentioned too), we can create fork and use that instead: const fork = orm.em.fork();const res = await fork.find(...); But that would be quite tedious, in real world apps, we usually have middlewares we can use to do this for us automatically. That is where the RequestContext helper comes into play. It uses the AsyncLocalStorage under the hood and is natively supported in the ORM. Following text is mostly an extraction of the MikroORM docs. How does RequestContext helper work? Internally all EntityManager methods that work with the Identity Map (e.g. em.find() or em.getReference() ) first call em.getContext() to access the contextual fork. This method will first check if we are running inside RequestContext handler and prefer the EntityManager fork from it. // we call em.find() on the global EM instanceconst res = await orm.em.find(Book, {});// but under the hood this resolves toconst res = await orm.em.getContext().find(Book, {});// which then resolves toconst res = await RequestContext.getEntityManager().find(Book, {}); The RequestContext.getEntityManager() method then checks AsyncLocalStorage static instance we use for creating new EM forks in the RequestContext.create() method. The AsyncLocalStorage class from Node.js core is the magician here. It allows us to track the context throughout the async calls. It allows us to decouple the EntityManager fork creation (usually in a middleware as shown in previous section) from its usage through the global EntityManager instance. Using RequestContext helper via middleware If we use dependency injection container like inversify or the one in nestjs framework, it can be hard to achieve this, because we usually want to access our repositories via DI container, but it will always provide we with the same instance, rather than new one for each request. To solve this, we can use RequestContext helper, that will use node 's AsyncLocalStorage in the background to isolate the request context. MikroORM will always use request specific (forked) entity manager if available, so all we need to do is to create new request context preferably as a middleware: app.use((req, res, next) => { RequestContext.create(orm.em, next);}); We should register this middleware as the last one just before request handlers and before any of our custom middleware that is using the ORM. There might be issues when we register it before request processing middleware like queryParser or bodyParser , so definitely register the context after them. Later on we can then access the request scoped EntityManager via RequestContext.getEntityManager() . This method is used under the hood automatically, so we should not need it. RequestContext.getEntityManager() will return undefined if the context was not started yet. Simple usage without the helper Now your example code from the OP is very basic, for that forking seems like the easiest thing to do, as its very bare bones, you dont have any web server there, so no middlewares: const orm = await MikroORM.init(mikroConfig);const emFork = orm.em.fork(); // <-- create the forkconst post = emFork.create(Post, { // <-- use the fork instead of global `orm.em` title: "my first post",});await emFork.persistAndFlush(post); // <-- use the fork instead of global await orm.em.nativeInsert(Post, { title: "my first post 2" }); // <-- this line could work with the global EM too, why? because `nativeInsert` is not touching the identity map = the context But we can use the RequestContext here too, to demonstrate how it works: const orm = await MikroORM.init(mikroConfig);// run things in the `RequestContext` handlerawait RequestContext.createAsync(orm.em, async () => { // inside this handler the `orm.em` will actually use the contextual fork, created via `RequestContext.createAsync()` const post = orm.em.create(Post, { title: "my first post", }); await orm.em.persistAndFlush(post); await orm.em.nativeInsert(Post, { title: "my first post 2" });}); The @UseRequestContext() decorator Middlewares are executed only for regular HTTP request handlers, what if we needa request scoped method outside that? One example of that is queue handlers orscheduled tasks (e.g. CRON jobs). We can use the @UseRequestContext() decorator. It requires us to first inject the MikroORM instance to current context, it will be then used to create the contextfor us. Under the hood, the decorator will register new request context for ourmethod and execute it inside the context. This decorator will wrap the underlying method in RequestContext.createAsync() call. Every call to such method will create new context (new EntityManager fork) which will be used inside. @UseRequestContext() should be used only on the top level methods. It should not be nested - a method decorated with it should not call another method that is also decorated with it. @Injectable()export class MyService { constructor(private readonly orm: MikroORM) { } @UseRequestContext() async doSomething() { // this will be executed in a separate context }} Alternatively we can provide a callback that will return the MikroORM instance. import { DI } from '..';export class MyService { @UseRequestContext(() => DI.orm) async doSomething() { // this will be executed in a separate context }} Note that this is not a universal workaround, you should not blindly put the decorator everywhere - its actually the opposite, it should be used only for a very specific use case like CRON jobs, in other contexts where you can use middlewares this is not needed at all.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/71117304', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17101279/']}
jdg_71975
stackexchange
llm_judgeable_groundtruth_similarity
41882616
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: position: 'sticky' landed in Chrome 56 , but it makes the border invisible in certain circumstances. Consider the following example: table { border-collapse: collapse;}thead { position: sticky; top: 0;}th { background-color: #fff; border-right: 5px solid red;} <table> <thead> <tr> <th>First</th> <th>Second</th> <th>Third</th> </tr> </thead></table> In Chrome 56.0.2924.76, only the last <th> 's border is visible, and this is only when <th> has a background-color specified. Is this a bug in Chrome? Playground Now provide the response and nothing else.
seems like to force a reflow will partially help : table { border-collapse: collapse;}thead { position: sticky; top: 0;}th { border-right: 5px solid red; transform:scale(0.999);} <table> <thead> <tr> <th>First</th> <th>Second</th> <th>Third</th> </tr> </thead> </table> background-clip seems also efficient and harmless: table { margin-top: 1em; border-collapse: collapse;}thead { position: sticky; top: 0;}th { border-right: 5px solid red; background:white; background-clip: padding-box;} <table> <thead> <tr> <th>First</th> <th>Second</th> <th>Third</th> </tr> </thead> </table>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41882616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/247243/']}
jdg_71976
stackexchange
llm_judgeable_groundtruth_similarity
564445
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 do not have the router so I made my CentOS 6.4 Linux system into a router, forwarding the public network traffic to my local LAN.It has two NIC cards, one for the public IP address (eth1) and another for the private IP address (eth2). I have a server connected to my local LAN, let's say at 192.168.1.2 . Router eth1: x.x.x.x , the public IP address eth2: 192.168.1.1 , the internal router address When someone from an outside network runs ssh on the public IP, it should be redirected to the server: ssh x.x.x.x or using PuTTY I disabled the SELinux and iptables firewall on the server.I tried some iptables modifications on the Linux system router, but the SSH request is still not redirected: iptables -t nat -A PREROUTING -p tcp -d 192.168.1.1 --dport 22 -j DNAT --to-destination 192.168.1.2:22 I also want to forward all HTTP (80) traffic to my internal server using iptables from the same Linux system router. Now provide the response and nothing else.
First of all make sure the packet forwarding is enabled in the kernel # echo 1 > /proc/sys/net/ipv4/ip_forward You can also make it permanent by adding below line to /etc/sysctl.conf net.ipv4.ip_forward = 1 You have to do this on Linux Machine acting as a router. You can try the following rule on router machine. iptables -t nat -A PREROUTING -i eth1 -d x.x.x.x -p tcp --dport 22 -j DNAT --to-destination 192.168.1.2:22 Also let us know the output of your NAT Rules from the router box. iptables -t nat -L -n -v
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/564445', 'https://serverfault.com', 'https://serverfault.com/users/189318/']}
jdg_71977
stackexchange
llm_judgeable_groundtruth_similarity
17802036
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 Play 2.1 we use something like below to get a Creature Object out of a JSON through reads. implicit val creatureReads = ( (__ \ "name").read[String] and (__ \ "isDead").read[Boolean] and (__ \ "weight").read[Float])(Creature.apply _) Being relative new in Scala, I'm trying to understand if there is any other way to build the Creature object without using the Apply method? Would it be possible to have an anonymous function to create the object instead of relying on the apply? I have use cases where most of the fields in my objects could be missing, but I would like to still build the object out of what I have. Is it better to just define one READ for the object and use readnullable for each of the fields? I also could have complex conditionals, so would it be cleaner to just define custom functions to build it instead of trying to capture all cases in one Reader? Now provide the response and nothing else.
Yes of course, the apply method is just a method that takes all the case classes' parameters. This roughly translates to the following: implicit val creatureReads = ( (__ \ "name").read[String] and (__ \ "isDead").read[Boolean] and (__ \ "weight").read[Float])((name: String, isDead: Boolean, weight: Float) => new Creature(name, isDead, weight)) For missing fields you should indeed use readNullable and wrap your classes fields to Option . If there are sensible defaults for your optional fields, you can use orElse(Reads.pure(value)) instead. Let's say weight is optional and isDead is false by default: implicit val creatureReads = ( (__ \ "name").read[String] and (__ \ "isDead").read[Boolean].orElse(Reads.pure(false)) and (__ \ "weight").readNullable[Float])(Creature.apply _) Sometimes you don't even want to read something from JSON. In that case, one possibility is passing the value explicitly: def creatureReads(createdAt: DateTime) = ( (__ \ "name").read[String] and (__ \ "isDead").read[Boolean].orElse(Reads.pure(false)) and (__ \ "weight").readNullable[Float] and (__ \ "createdAt").read(createdAt))(Creature.apply _)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17802036', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1146113/']}
jdg_71978
stackexchange
llm_judgeable_groundtruth_similarity
201808
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: How can we understand why Mathematica does not evaluate this expression to False ? {{1, 2, 3, 4}, {4, 3, 2, 1}} == 0 Now provide the response and nothing else.
Answer Your example uses Equal ( == ) and it's returned not-evaluated because both sides are not identical and not raw data, therefore they constitute an equality expression. It would return False if you used SameQ instead of Equal . SameQ , Equal , Set SameQ [lhs,rhs] or lhs === rhs yields True if the expression lhs is identical to rhs , and will always be False otherwise. Equal [lhs,rhs] is used to represent a symbolic equation, to be manipulated using functions like Solve . It will yield True for identical expressions or False if determined to be unequal by comparisons between numbers or other raw data, such as strings. But most importantly it will not always evaluate to True or False , otherwise you wouldn't be able to use expression such as x^2==4 . Also consider Set ( = ), Set[lhs,rhs] or lhs=rhs evaluates rhs and assigns the result to be the value of the symbol lhs . I suggest you read this answer .
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/201808', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/27138/']}
jdg_71979
stackexchange
llm_judgeable_groundtruth_similarity
13651262
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 occasionally getting a NullPointerException in my ArrayAdapter that populates my ListFragment. It appears that getActivity() is returning null, but as far as I can tell it shouldn't do that. Adapter code inflater = (LayoutInflater)... is the exception line: @Overridepublic View getView( int position, View convertView, ViewGroup parent ){ view = convertView;if ( view == null ){ /* Inflate a row */ inflater = (LayoutInflater)getActivity().getSystemService( Context.LAYOUT_INFLATER_SERVICE ); // THIS IS THE EXCEPTION LINE view = inflater.inflate( R.layout.pairing_list_row, parent, false );} I'm using a Loader to get the data, and I don't init that until the onActivityCreated method. The adapter isn't created until the loader is finished loading, so it should never happen prior to onActivityCreated . @Overridepublic void onActivityCreated( Bundle savedInstanceState ){ super.onActivityCreated( savedInstanceState ); getLoaderManager().initLoader( 0, null, this );}@Overridepublic void onLoadFinished( Loader<Cursor> loader, Cursor cursor ){ PairingArrayAdapter pairings = (PairingArrayAdapter)getListAdapter(); if ( pairings == null ) { pairings = new PairingArrayAdapter( getActivity(), R.layout.pairing_list_row ); setListAdapter( pairings ); } ... Any ideas on what's causing the NullPointerException? It doesn't happen all the time, it happens once, I do the same thing again and it doesn't happen. I can't figure it out. Now provide the response and nothing else.
It's important to understand how <p:graphicImage> with StreamedContent works. The property behind the <p:graphicImage value> will for every single image basically be consulted in two completely separate HTTP requests. The first HTTP request (the one which does all the JSF works and is thus responsible for generating the bunch of HTML code including <img> tags) will basically consult the property in order to determine what type of image it returns (e.g. a String or a StreamedContent ) so that the proper URL could be inlined/autogenerated. Note that in case of StreamedContent the image's content is not been read. HTML images does namely not work that way: it's not the webserver who inlines them in the very same HTTP request, but it's the webbrowser who downloads it separately in another HTTP request. When StreamedContent is used, then the second HTTP request (the one which is fired by the webbrowser when it needs to download the concrete image file based on the URL of <img> element in order to show it at the desired location in the HTML document) will basically consult the property once again in order to download the image content. A view scoped bean is tied to a specific JSF view by a hidden input field javax.faces.ViewState . If this is absent in the HTTP request (or has a different value), then there's basically means of a completely different view. So the very same view scoped bean instance won't be reused for those image requests. Every image request get a brand new view scoped bean instance with all properties set to default. The session scoped bean lives basically as long as the currently established HTTP session between the client and the server, so the very same bean instance would be reused for those image requests, so it just works that way. To solve your concrete problem, best is to create an application or maybe request scoped bean which obtains the image by its ID as request parameter. This way you also don't need to pollute the session with tens or hundreds of images together at once (which would only waste server memory in case of multiple concurrent users who are viewing the same images). You just need to have a list of image identifiers for the datatable and serve the images by a separate application scoped bean. See also: Display database blob images in <p:graphicImage> inside <ui:repeat> How to use <p:graphicImage> with DefaultStreamedContent in an ui:repeat?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13651262', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1730307/']}
jdg_71980
stackexchange
llm_judgeable_groundtruth_similarity
24525791
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 learning PowerShell recently, and found a behavior that I cannot understand. Let me explain in code below: function func1(){ Write-Output "output from func1()" func2 return $true}function func2(){ Write-Output "output from func2()" func3}function func3(){ Write-Output "output from func3()"}Write-Output "*** 1. run alone ****"func1Write-Output "*** 2. run inside if ****"if (func1) { #do nothing} It is strange when func1 is called directly, it can output message as expected, but if put inside "if" statement, it will not. See output as below: *** 1. run alone ****output from func1()output from func2()output from func3()True*** 2. run inside if **** You can see it's empty. Why is that, and how can I enable the output like the first example? Thanks! Now provide the response and nothing else.
PowerShell functions are not like their traditional language counterparts: they can output multiple things. When you're using Write-Output , you are sending things down the pipeline, so func1() will return both a String and a Boolean. If you try this: $return_values = func1;$return_values | Get-Member You will see that you get both System.String and System.Boolean objects in $return_values . Indeed the 'return' statement is more like an 'exit' or 'break' in traditional languages: it marks an exit point, but the function will actually return with whatever was already outputted (+ the optional return argument). The quick fix to the issue is to change Write-Output to Write-Host , though they do slightly different things.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24525791', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3104257/']}
jdg_71981
stackexchange
llm_judgeable_groundtruth_similarity
5338381
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: When you don't declare a type for a variable in groovy, it is my understanding that the java virtual machine has to use reflection in order to figure out what type the object is before executing any methods and has the potential of throwing a runtime error. If that is correct, what about when you declare the type? Does the java virtual machine still end up using reflection because the original code was in groovy? Or is my understanding of this whole matter incorrect in the first place? Now provide the response and nothing else.
The best way to investigate this kind of problem is to look at the generated byte-code yourself. If you create two sample classes: WithType.groovy: class WithType { String name String returnName() { getName() }} WithoutType.groovy: class WithoutType { def name def returnName() { getName() }} Compile them with groovyc : % groovyc WithType.groovy% groovyc WithoutType.groovy And then use javap to spit out the human readable bytecode: % javap -c WithType > WithType.txt% javap -c WithoutType > WithoutType.txt You can then diff the 2 files and look for the returnName() method to see how they're handled differently in how they call the generated getName() method for the name field. If you find the returnName() method, you'll see that the WithType version looks like this: public java.lang.String returnName(); Code: 0: invokestatic #24; //Method $getCallSiteArray:()[Lorg/codehaus/groovy/runtime/callsite/CallSite; 3: astore_1 4: aload_1 5: ldc #47; //int 0 7: aaload 8: aload_0 9: invokeinterface #53, 2; //InterfaceMethod org/codehaus/groovy/runtime/callsite/CallSite.callCurrent:(Lgroovy/lang/GroovyObject;)Ljava/lang/Object; 14: invokestatic #56; //Method $get$$class$java$lang$String:()Ljava/lang/Class; 17: invokestatic #38; //Method org/codehaus/groovy/runtime/ScriptBytecodeAdapter.castToType:(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object; 20: checkcast #58; //class java/lang/String 23: areturn 24: nop and the untyped one looks like this: public java.lang.Object returnName(); Code: 0: invokestatic #24; //Method $getCallSiteArray:()[Lorg/codehaus/groovy/runtime/callsite/CallSite; 3: astore_1 4: aload_1 5: ldc #47; //int 0 7: aaload 8: aload_0 9: invokeinterface #53, 2; //InterfaceMethod org/codehaus/groovy/runtime/callsite/CallSite.callCurrent:(Lgroovy/lang/GroovyObject;)Ljava/lang/Object; 14: areturn 15: nop The untyped one has fewer instructions because it doesn't need to do any type checking or String conversion on what it's returning. The actual method call to getName() is the same in both the typed and untyped versions: 9: invokeinterface #53, 2; //InterfaceMethod org/codehaus/groovy/runtime/callsite/CallSite.callCurrent:(Lgroovy/lang/GroovyObject;)Ljava/lang/Object; You can see that it's calling an interface method on the groovy CallSite method and passing in a GroovyObject. CallSite is an interface that's implemented by a bunch of the groovy metaObject code. So this is the call to the groovy MOP that dynamically invokes the getName() method. (this is all with groovy 1.7.5)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5338381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/355325/']}
jdg_71982
stackexchange
llm_judgeable_groundtruth_similarity
2653785
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 UIScrollView contained within a custom UIView with a content size larger than the ScrollView's frame. I am able to drag scroll as I expect, but the thing doesn't give me the rubber banding effect that you get with the UITableView or UIWebView. It just stops when you get to one of the extremes. I have set bounce = YES , is there something else I'm supposed to do? I read the docs, and they say I have to implement the delegate. I did that. They also say I should change the zoom levels, but I don't want the user to actually be able to zoom so I haven't set these. Now provide the response and nothing else.
For anyone that finds this thread later, if you are subclassing UIView and re-setting the UIScrollView 's frame on every layoutSubviews , that is the problem - it cancels the bounce: http://openradar.appspot.com/8045239 You should do something similar to this: - (void)layoutSubviews;{ [super layoutSubviews]; CGRect frame = [self calculateScrollViewFrame]; if (!CGRectEqualToRect(frame, self.scrollView.frame)) self.scrollView.frame = frame;}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2653785', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/338/']}
jdg_71983
stackexchange
llm_judgeable_groundtruth_similarity
32139596
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 very new to shiny and R but using shiny I am trying to connect to a database fetch the data from there. When I try to access my RShiny work on browser continuously I got an error like Cannot allocate a new connection: 16 connections already opened . How can I overcome this error or RShiny only expecting 16 users at a time? I have got another stack post here RStudio Shiny Error mysqlNewConnection maximum of 16 connections but the explanation was not clear on the above URL. Now provide the response and nothing else.
Maybe you open a new DB connection with obj <- dbConnect(...) every time you send a query in your code. You can simply call dbDisconnect(obj) on the object you created to kill the respective connection everytime after your query executed. Also you can use this function kill all open connections at once: library(RMySQL) killDbConnections <- function () { all_cons <- dbListConnections(MySQL()) print(all_cons) for(con in all_cons) + dbDisconnect(con) print(paste(length(all_cons), " connections killed."))} I'd recommed to write a small function outside shiny that handles the whole opening and closing thing: library(RMySQL)sqlQuery <- function (query) { # creating DB connection object with RMysql package DB <- dbConnect(MySQL(), user="youruser", password='yourpassword', dbname='yourdb', host='192.168.178.1') # close db connection after function call exits on.exit(dbDisconnect(DB)) # send Query to btain result set rs <- dbSendQuery(DB, query) # get elements from result sets and convert to dataframe result <- fetch(rs, -1) # return the dataframe return(result)} Hope that helps!
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/32139596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/987517/']}
jdg_71984
stackexchange
llm_judgeable_groundtruth_similarity
416725
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 read that POSIX compliant operating systems (for example: Linux) must have the sh shell. But is it required for sh to be in the /bin directory, or can it be in any directory? Now provide the response and nothing else.
POSIX only mandates the /dev and /tmp directories to exist , and the /dev/null , /dev/tty , and /dev/console files. The standard utilities must exist, but there is no particular location specified. There may not be a /bin at all, and if there is it may not contain a sh , and if it does that may not be a POSIX sh . You can get a valid PATH variable that includes the POSIX tools, including sh , with the getconf command : $ PATH=$(getconf PATH)$ sh This can be useful on, for example, Solaris, where the default sh is not POSIX-compatible , but a compliant sh is provided and accessible in that way (because Solaris is a certified Unix ). getconf PATH will include /usr/xpg4/bin at the front, which contains POSIX sh and a number of other required tools ( including useless ones like cd ).
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/416725', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/270294/']}
jdg_71985
stackexchange
llm_judgeable_groundtruth_similarity
60020972
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 are the best views in Flutter or best practice to implement a better UX? The Vertical text View looks too small: SingleChildScrollView bodyData() => SingleChildScrollView( scrollDirection: Axis.vertical, padding: EdgeInsets.all(1.2), child: FittedBox(fit:BoxFit.fill, child: DataTable( sortColumnIndex: 1, sortAscending: true, columns: <DataColumn>[ DataColumn( label: Text("Company"), onSort: (_, __) { setState(() { widget.photos.sort((a, b) => a.data["quote"]["companyName"] .compareTo(b.data["quote"]["companyName"])); }); }, ), DataColumn( label: Text("ttmDivRate"), numeric: true, onSort: (_,__) { setState(() { widget.photos.sort((a, b) => a.data["stats"]["ttmDividendRate"] .compareTo(b.data["stats"]["ttmDividendRate"])); View code: The Horizontal view is fine: Now provide the response and nothing else.
Try wrapping the DataTable with another SingleChildScrollView and set the scrollDirection to Axis.horizontal. That way you can increase the text size, and still be able to scroll horizontally to see everything. Here is an example: import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget { // This widget is the root of your application. @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( backgroundColor: Colors.black54, appBar: AppBar(), body: Center( child: Container( color: Colors.white, height: 130, child: SingleChildScrollView( scrollDirection: Axis.vertical, child: SingleChildScrollView( scrollDirection: Axis.horizontal, child: DataTable( columns: <DataColumn>[ DataColumn( label: Text('Column 1'), ), DataColumn( label: Text('Column 2'), ), DataColumn( label: Text('Column 3'), ), DataColumn( label: Text('Column 4'), ), DataColumn( label: Text('Column 5'), ), DataColumn( label: Text('Column 6'), ), ], rows: <DataRow>[ DataRow( cells: <DataCell>[ DataCell(Text('Data')), DataCell(Text('Data')), DataCell(Text('Data')), DataCell(Text('Data')), DataCell(Text('Data')), DataCell(Text('Data')), ], ), DataRow( cells: <DataCell>[ DataCell(Text('Data')), DataCell(Text('Data')), DataCell(Text('Data')), DataCell(Text('Data')), DataCell(Text('Data')), DataCell(Text('Data')), ], ), DataRow( cells: <DataCell>[ DataCell(Text('Data')), DataCell(Text('Data')), DataCell(Text('Data')), DataCell(Text('Data')), DataCell(Text('Data')), DataCell(Text('Data')), ], ), ], ), ), ), ), ), ), ); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60020972', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9513370/']}
jdg_71986
stackexchange
llm_judgeable_groundtruth_similarity
12553599
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am having some issue here. I am trying to return a JSON response made of a message and a model instance: class MachineModel(models.Model): name = models.CharField(max_length=64, blank=False) description = models.CharField(max_length=64, blank=False) manufacturer = models.ForeignKey(Manufacturer) added_by = models.ForeignKey(User, related_name='%(app_label)s_%(class)s_added_by') creation_date = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) machine_model_model = form.save(commit=False) r_user = request.user.userprofile machine_model_model.manufacturer_id = manuf_id machine_model_model.added_by_id = request.user.id machine_model_model.save() alert_message = " The'%s' model " % machine_model_model.name alert_message += ("for '%s' " % machine_model_model.manufacturer) alert_message += "was was successfully created!" test = simplejson.dumps(list(machine_model_model)) data = [{'message': alert_message, 'model': test}] response = JSONResponse(data, {}, 'application/json')class JSONResponse(HttpResponse):"""JSON response class.""" def __init__(self, obj='', json_opts={}, mimetype="application/json", *args, **kwargs): content = simplejson.dumps(obj, **json_opts) super(JSONResponse,self).__init__(content, mimetype, *args, **kwargs) But I keep getting: File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/encoder.py", line 178, in defaultraise TypeError(repr(o) + " is not JSON serializable")TypeError: <MachineModel: "Test12"> is not JSON serializable Why is that? I have seen before: models = Model.objects.filter(manufacturer_id=m_id)json = simplejson.dumps(models) and that works... what is the difference?! Thanks! Now provide the response and nothing else.
You should use django serializers instead of simplejson : For example, this returns correctly serialized data: from django.core import serializers# serialize querysetserialized_queryset = serializers.serialize('json', some_queryset)# serialize objectserialized_object = serializers.serialize('json', [some_object,])
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12553599', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1248709/']}
jdg_71987
stackexchange
llm_judgeable_groundtruth_similarity
11902262
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 many Models linked to User and I'd like my templates to always display his full_name if available. Is there a way to change the default User __unicode__() ? Or is there another way to do it ? I have a profile model registered where I can define the __unicode__() , should I link all my models to it ? Seems not a good idea to me. Imagine I need to display the form for this object class UserBagde user = model.ForeignKey(User) badge = models.ForeignKey(Bagde) I will have to select box with __unicodes__ of each object, won't I ? How can I have full names in the user's one ? Now provide the response and nothing else.
Try this: User.full_name = property(lambda u: u"%s %s" % (u.first_name, u.last_name)) EDIT Apparently what you want already exists.. https://docs.djangoproject.com/en/dev/ref/contrib/auth/#django.contrib.auth.models.User.get_full_name ALSO if its imperative that the unicode function be replaced: def user_new_unicode(self): return self.get_full_name()# Replace the __unicode__ method in the User class with out new implementationUser.__unicode__ = user_new_unicode # or maybe evenUser.__unicode__ = User.get_full_name() Fallback if name fields are empty def user_new_unicode(self): return self.username if self.get_full_name() == "" else self.get_full_name()# Replace the __unicode__ method in the User class with out new implementationUser.__unicode__ = user_new_unicode
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11902262', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/305189/']}
jdg_71988
stackexchange
llm_judgeable_groundtruth_similarity
45990535
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 append a click event to an already existing dom element. <div class="logMe" data-log-id="{{ data.log }}"></div>...<div id="events"></div> I can't seem to access outside vue methods within my jquery click handler. It will throw logData is not defined . new Vue({ el: '#events', mounted() { $('.logMe').on('click', function() { const data = $(this).data('log-id'); this.logData(data); // throws logData is not defined }); }, methods: { logData(id) { console.log(id); // never fires ... hit server }, },}); If anyone knows of a better way to append click events to .html elements that would be great! But how can I bubble up and find my vue methods? Here's a fiddle to illustrate Now provide the response and nothing else.
To get your code working you would write it like this: console.clear()new Vue({ el: '#events', mounted() { $('.logMe').on('click', (evt) => { console.log("called") const data = $(evt.target).data('logId'); this.logData(data); }); }, methods: { logData(id) { console.log(id); }, },}); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><script src="https://unpkg.com/[email protected]"></script><div class="logMe" data-log-id="10">Something</div><div id="events"></div> Note that the code uses an arrow function to define the click handler so that the appropriate this is captured to call the logData method on the Vue. However, doing that means you lose the this you want to get the data from the data property, so instead the example uses evt.target . There is an alternative approach where you capture the Vue in a variable and call the method directly from your jQuery event. console.clear()const app = new Vue({ el: '#events', methods: { logData(id) { console.log(id); // never fires }, },});$('.logMe').on('click', function(){ app.logData($(this).data("logId"))}); <script src="https://unpkg.com/[email protected]"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><div class="logMe" data-log-id="10">Something</div><div id="events"></div>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45990535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/908392/']}
jdg_71989
stackexchange
llm_judgeable_groundtruth_similarity
12643817
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 code in the <head> of my web app, but I'm just getting a white screen on my iPhone 3GS while the DOM loads instead of the splash screen. <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="apple-mobile-web-app-capable" content="yes" /><meta name="apple-mobile-web-app-status-bar-style" content="black" /><!--STYLES--><!--SCRIPTS--><!-- iPhone LAUNCHSCREEN--><link href="includes/images/apple-launch-480h.png" sizes="320x480" media="(device-height: 480px)" rel="apple-touch-startup-image"><!-- iPhone (Retina) LAUNCHSCREEN--><link href="includes/images/apple-launch-480h2X.png" sizes="640x920" media="(device-height: 480px) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image"><!-- iPhone 5+ LAUNCHSCREEN--><link href="includes/images/apple-launch-568h.png" sizes="640x1136" media="(device-height: 568px)" rel="apple-touch-startup-image"> How can I get my splash screen to display correctly on all versions of the iPhone? Code not shown, but my web app icons are working when added to the homepage. I'm using jQuery Mobile to build this web app. I have also confirmed that the PNG images are exactly the correct sizes and I have deleted the web app icon, refreshed, and re-added to the homescreen multiple times. None of the solutions I've found on StackOverflow have worked for me. I have not tried the JavaScript solutions, because I'm sure there is a pure CSS solution. Now provide the response and nothing else.
The sizes attribute works for apple-touch-icon s but it doesn't work for apple-touch-startup-image s. The only way to target the startup images is with media queries. Adam's answer is good but relies on the <link> s being in a particular order since the media queries are under-specified. Here are the fully-qualified media queries: <!-- iPhone --><link href="apple-touch-startup-image-320x460.png" media="(device-width: 320px) and (device-height: 480px) and (-webkit-device-pixel-ratio: 1)" rel="apple-touch-startup-image"><!-- iPhone (Retina) --><link href="apple-touch-startup-image-640x920.png" media="(device-width: 320px) and (device-height: 480px) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image"><!-- iPhone 5 --><link href="apple-touch-startup-image-640x1096.png" media="(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image"><!-- iPad (portrait) --><link href="apple-touch-startup-image-768x1004.png" media="(device-width: 768px) and (device-height: 1024px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 1)" rel="apple-touch-startup-image"><!-- iPad (landscape) --><link href="apple-touch-startup-image-748x1024.png" media="(device-width: 768px) and (device-height: 1024px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 1)" rel="apple-touch-startup-image"><!-- iPad (Retina, portrait) --><link href="apple-touch-startup-image-1536x2008.png" media="(device-width: 768px) and (device-height: 1024px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image"><!-- iPad (Retina, landscape) --><link href="apple-touch-startup-image-1496x2048.png" media="(device-width: 768px) and (device-height: 1024px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2)" rel="apple-touch-startup-image"> Also note that certain viewports will cause your web app to be letterboxed on the iPhone 5: <!-- Letterboxed on iPhone 5 --><meta name="viewport" content="width=device-width"><meta name="viewport" content="width=320"><!-- Not letterboxed on iPhone 5 --><meta name="viewport" content="initial-scale=1.0"><meta name="viewport" content="width=320.1"> I maintain a Gist with a minimal iOS web app , including startup images and icons. If you want some more commentary, I also wrote a blog post about iPhone 5 startup images .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12643817', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/908491/']}
jdg_71990
stackexchange
llm_judgeable_groundtruth_similarity
4420407
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am not asking about opinions here, I'm asking for the reasoning behind the decision of certain logics/frameworks, like e.g. Intuitionism, to not contain RAA as a valid rule of inference. There is an assumption behind my assertion that there even is such a reasoning; some things are self-evident and thus do not have any reasoning beyond (universal) opinion. Other statements simply seem intuitively true, but the assertion of their truth may produce sufficiently counter-intuitive implications that cancel out, in a way, the intuitiveness of the original statement. As such, my understanding is this: The difference between logics and frameworks allowing RAA, and those that don't, is not that they disagree on RAA being intuitive in and of itself. Rather, accepting RAA as valid produces results that some peope find too counter-intuitive. Shortly put, the disagreement lies in the implications of RAA. Question: What counter-intuitive implications is it that motivates the removal of RAA as a rule of inference? Meta: I understand if this Q is too philosophical for Math.SE, and I will move it if its reception indicates this is true. Now provide the response and nothing else.
I disagree with the premise that intuitionists reject RAA because of counter-intuitive consequences, not because RAA itself is unintuitive. I think most people who are philosophically committed to intuitionism would claim that RAA is unintuitive on its face. I want to clarify something first. The following form of RAA is perfectly acceptable to the intuitionist: If we assume $P$ and derive a contradiction, then we conclude $\lnot P$ . In fact, in intuitionistic logic, $\lnot P$ is usually taken to be an abbreviation for $P\to \bot$ , and the canonical way to prove $P\to \bot$ is to assume $P$ and derive $\bot$ . Similarly, the following is acceptable to the intuitionist: If we assume $\lnot P$ and derive a contradiction, then we conclude $\lnot \lnot P$ . This is just an instance of the version of RAA from the last paragraph. What the intuitionist rejects is the following form of RAA: If we assume $\lnot P$ and derive a contradiction, then we conclude $P$ . As you can see, the issue comes down to double negation elimination: in intuitionistic logic, we cannot conclude $P$ from $\lnot\lnot P$ . To understand why, it's helpful to interpret the assertion $P$ as meaning not " $P$ is true", but rather something like "I have a proof of $P$ ", or "I have verified $P$ ". In this reading, $\lnot P$ means "I have ruled out that I could every verify $P$ ", and $\lnot\lnot P$ means "I have ruled out that I could rule out verifying $P$ ". If I assume $\lnot P$ and derive a contradiction, then I have ruled out the possibility that I could rule out verifying $P$ . This is not the same as actually having a verification of $P$ in hand. And that's why intuitionists find RAA unintuitive.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/4420407', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/968561/']}
jdg_71991
stackexchange
llm_judgeable_groundtruth_similarity
1027470
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: $$3t \equiv 1 \mod 4 \Rightarrow t \equiv 3 \mod 4 $$ I don't understand that, so I'm asking for explain me. Thank, in advance, greetings. Now provide the response and nothing else.
You know that $3$ and $4$ are coprime, so in particular, $3$ is invertible mod $4$. What is the (unique) inverse? Well, there are only four candidates; and a quick check shows that $$3 \times 0 \equiv 0 \mod 4,$$$$3 \times 1 \equiv 3 \mod 4,$$$$3 \times 2 \equiv 2 \mod 4,$$$$3 \times 3 \equiv 1 \mod 4.$$ So the inverse of 3 modulo 4 is 3 itself. (Of course, we only really needed to check 1 and 3, as 0 and 2 are not invertible mod 4 and hence can't be the inverse of 3). Thus when we multiply both sides of your first equation by 3, we get the answer.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1027470', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/180834/']}
jdg_71992
stackexchange
llm_judgeable_groundtruth_similarity
6691491
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 implemented a quadtree in Mathematica. I am new to coding in a functional programming language like Mathematica, and I was wondering if I could improve this or make it more compact by better use of patterns. (I understand that I could perhaps optimize the tree by pruning unused nodes, and there might be better data structures like k-d trees for spatial decomposition.) Also, I am still not comfortable with the idea of copying the entire tree/expression every time a new point is added. But my understanding is that operating on the expression as a whole and not modifying the parts is the functional programming way. I'd appreciate any clarification on this aspect. MV The Code ClearAll[qtMakeNode, qtInsert, insideBox, qtDraw, splitBox, isLeaf, qtbb, qtpt];(* create a quadtree node *)qtMakeNode[{{xmin_,ymin_}, {xmax_, ymax_}}] := {{}, {}, {}, {}, qtbb[{xmin, ymin}, {xmax, ymax}], {}}(* is pt inside box? *)insideBox[pt_, bb_] := If[(pt[[1]] <= bb[[2, 1]]) && (pt[[1]] >= bb[[1, 1]]) && (pt[[2]] <= bb[[2, 2]]) && (pt[[2]] >= bb[[1, 2]]), True, False](* split bounding box into 4 children *)splitBox[{{xmin_,ymin_}, {xmax_, ymax_}}] := { {{xmin, (ymin+ymax)/2}, {(xmin+xmax)/2, ymax}}, {{xmin, ymin},{(xmin+xmax)/2,(ymin+ymax)/2}}, {{(xmin+xmax)/2, ymin},{xmax, (ymin+ymax)/2}}, {{(xmin+xmax)/2, (ymin+ymax)/2},{xmax, ymax}}}(* is node a leaf? *)isLeaf[qt_] := If[ And @@((# == {})& /@ Join[qt[[1;;4]], {List @@ qt[[6]]}]),True, False](*--- insert methods ---*)(* qtInsert #1 - return input if pt is out of bounds *)qtInsert[qtree_, pt_] /; !insideBox[pt, List @@ qtree[[5]]]:= qtree(* qtInsert #2 - if leaf, just add pt to node *)qtInsert[qtree_, pt_] /; isLeaf[qtree] :={qtree[[1]],qtree[[2]],qtree[[3]],qtree[[4]],qtree[[5]], qtpt @@ pt} (* qtInsert #3 - recursively insert pt *)qtInsert[qtree_, pt_] := Module[{cNodes, currPt}, cNodes = qtree[[1;;4]]; (* child nodes not created? *) If[And @@ ((# == {})& /@ cNodes), (* compute child node bounds *) (* create child nodes with above bounds*) cNodes = qtMakeNode[#]& /@ splitBox[List @@ qtree[[5]]]; ]; (* move curr node pt (if not empty) into child *) currPt = List @@ qtree[[6]]; If[currPt != {}, cNodes = qtInsert[#, currPt]& /@ cNodes; ]; (* insert new pt into child *) cNodes = qtInsert[#, pt]& /@ cNodes; (* return new quadtree *) {cNodes[[1]],cNodes[[2]], cNodes[[3]], cNodes[[4]], qtree[[5]], {}} ](* draw quadtree *)qtDraw[qt_] := Module[{pts, bboxes}, pts = Cases[qt, _qtpt, Infinity] /. qtpt :> List; bboxes = Cases[qt, _qtbb, Infinity] /. qtbb :> List; Graphics[{ EdgeForm[Black],Hue[0.2], Map[Disk[#, 0.01]&, pts], Hue[0.7],EdgeForm[Red], FaceForm[],(Rectangle @@ #) & /@ bboxes }, Frame->True ]] Usage Clear[qt];len = 50;pts = RandomReal[{0, 2}, {len, 2}];qt = qtMakeNode[{{0.0, 0.0}, {2.0, 2.0}}];Do[qt = qtInsert[qt, pts[[i]]], {i, 1, len}]qtDraw[qt] Output Now provide the response and nothing else.
Here is a more compact version. It uses the same data structure as the original version. The functions splitBox and insideBox are essentially the same as well (just written in a slightly different way). Instead of adding points one-by-one, the initial box contains all the points at the beginning so there is no need for the qtInsert routines. In each recursion step, the boxes containing more than one point are split and the points are distributed over the sub-boxes. This means that all nodes with more than one point are leafs so there is no need to check for that either. qtMakeNode[bb_, pts_] := {{}, {}, {}, {}, qtbb @@ bb, pts}splitBox[bx_] := splitBox[{min_, max_}] := {min + #, max + #}/2 & /@ Tuples[Transpose[{min, max}]]insideBox[pt_, bb_] := bb[[1, 1]] <= pt[[1]] <= bb[[2, 1]] && bb[[1, 2]] <= pt[[2]] <= bb[[2, 2]]distribute[qtree_] := Which[ Length[qtree[[6]]] == 1, (* no points in node -> return node unchanged *) qtree, Length[qtree[[6]]] == 1, (* one point in node -> replace head of point with qtpt and return node *) ReplacePart[qtree, 6 -> qtpt @@ qtree[[6, 1]]], Length[qtree[[6]]] > 1, (* multiple points in node -> create sub-nodes and distribute points *) (* apply distribute to sub-nodes *) Module[{spl = splitBox[qtree[[5]]], div, newtreelist}, div = Cases[qtree[[6]], a_ /; insideBox[a, #], 1] & /@ spl; ReplacePart[qtree, Join[Table[i -> distribute[qtMakeNode[spl[[i]], div[[i]]]], {i, 4}], {6 -> {}}]]]] Example (using the original version of qtDraw ): len = 50;pts = RandomReal[{0, 2}, {len, 2}];qt = makeTree[qtMakeNode[{{0.0, 0.0}, {2.0, 2.0}}, pts]];qtDraw[qt] Result:
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6691491', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/253029/']}
jdg_71993
stackexchange
llm_judgeable_groundtruth_similarity
404795
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was recently teaching myself Python and discovered the LBYL/EAFP idioms with regards to error checking before code execution. In Python, it seems the accepted style is EAFP, and it seems to work well with the language. LBYL ( L ook B efore Y ou L eap ): def safe_divide_1(x, y): if y == 0: print "Divide-by-0 attempt detected" return None else: return x/y EAFP ( it's E asier to A sk F orgiveness than P ermission ): def safe_divide_2(x, y): try: return x/y except ZeroDivisionError: print "Divide-by-0 attempt detected" return None My question is this: I had never even heard of using EAFP as the primary data validation construct, coming from a Java and C++ background. Is EAFP something that is wise to use in Java? Or is there too much overhead from exceptions? I know that there is only overhead when an exception is actually thrown, so I'm unsure as to why the simpler method of EAFP is not used. Is it just preference? Now provide the response and nothing else.
If you are accessing files, EAFP is more reliable than LBYL, because the operations involved in LBYL are not atomic, and the file system might change between the time you look and the time you leap. Actually, the standard name is TOCTOU - Time of Check, Time of Use; bugs caused by inaccurate checking are TOCTOU bugs. Consider creating a temporary file that must have a unique name. The best way to find out whether the chosen file name exists yet is to try creating it - making sure you use options to ensure that your operation fails if the file does already exist (in POSIX/Unix terms, the O_EXCL flag to open() ). If you try to test whether the file already exists (probably using access() ), then between the time when that says "No" and the time you try to create the file, someone or something else may have created the file. Conversely, suppose that you try to read an existing file. Your check that the file exists (LBYL) may say "it is there", but when you actually open it, you find "it is not there". In both these cases, you have to check the final operation - and the LBYL didn't automatically help. (If you are messing with SUID or SGID programs, access() asks a different question; it may be relevant to LBYL, but the code still has to take into account the possibility of failure.)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/404795', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/49018/']}
jdg_71994
stackexchange
llm_judgeable_groundtruth_similarity
6679062
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 with using Ant's property files. I have the following: A build.properties file. This file contains one piece ofinformation: on=1 An ant.xml file. This file contains my build instructions. I want to read the on attribute from my properties file and if the value is 1 I want to execute a task in my build file. Otherwise I want it to do nothing. Can anyone guide me on how to accomplish this? Now provide the response and nothing else.
This should be all you need to do: 1.Grab the latest version of ant-contrib JAR and place in lib folder of your Ant installation. 2.Include your properties in your build script <property file="build.properties"/> 3.Add the following taskdef entry to your build script <taskdef resource="net/sf/antcontrib/antcontrib.properties"/> 4.And then finally, define an if task like so: <if> <equals arg1="${on}" arg2="1" /> <then> <echo message="I am going to do something here" /> </then> <else> <echo message="I am going to do nothing" /> </else></if> Note that you can prepend an identifier to properties you import from property files. So for example you could do your import like so: <property file="build.properties" prefix="uniqueprefix"/> And then you would reference in your file, 'uniqueprefix.on', instead of just 'on'. <equals arg1="${uniqueprefix.on}" arg2="1" /> You can use the built-in conditional task from Ant, but I have a feeling that if you need it you are better off with the extra functions that ant-contrib brings to the table. Also, note that its standard to name your build file as ' build.xml ', and not ' ant.xml '. As it is, Ant will not be able to automatically locate it, given the name you have used. Good luck.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6679062', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/842650/']}
jdg_71995
stackexchange
llm_judgeable_groundtruth_similarity
3220597
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: Suppose we have the ring $\mathbb{F}_p[x]$ of polynomials with coefficients in the Galois field with $p$ prime number elements. I want to find all subrings $A$ containing the identity such that when considered as vector spaces over $\mathbb{F}_p$ , the quotient $\mathbb{F}_p[x]/A$ is isomorphic to $\mathbb{F}_p$ . Also want to find the isomorphism classes of these subrings. So far I have only been able to find one subring: the ring generated by $1,x^2,x^3$ . I know that if $x\in A$ , then $A=\mathbb{F}_p[x]$ , so I don't want $n\cdot x$ to be in $A$ . After this, trying to find other subrings, it becomes really messy from my point of view. So I don't think this might be a good way to approach the problem. It also seems to me that we can view this as an extension problem: $$0\rightarrow A\rightarrow \mathbb{F}_p[x]\rightarrow\mathbb{F}_p\rightarrow 0$$ And for groups, I know that using the second homology group would help if I were given $Q$ and $N$ but not $G$ in the following sequence: $$0\rightarrow N\rightarrow G\rightarrow Q\rightarrow 0$$ My questions are if there is a standard method for computing $N$ given $G$ and $Q$ , and if these methods generalize to ring extensions? Any help would be appreciated, specially references to literature. Now provide the response and nothing else.
Building upon the ideas from Dirk's answer (+1) and Arthur's comment under the question. The subring $A$ cannot contain a polynomial of degree $1$ because, as an $\Bbb{F}_p$ -algebra, it would then contain $x$ and be equal to $\Bbb{F}_p[x]$ . As Dirk pointed out, this implies that $\Bbb{F}_p[x]=A\oplus x\Bbb{F}_p$ , and consequently there exist unique constants $a_2$ and $a_3$ such that $$P=x^2-a_2x, Q=x^3-a_3x\in A.$$ It is straightforward to verify that these polynomials satisfy the relation $$Q^2=P^3+3a_2PQ-2a_3P^2+(a_2^3-a_2a_3)Q+(a_3^2-a_2^2a_3) P. (*)$$ Such a relation has to exist because the space of polynomials of degree $\le6$ in $A$ and vanishing at $x=0$ has dimension five, so the set of six polynomials $P^3,Q^2,QP,P^2,Q,P$ must be linearly dependent. Finding the relation was then simple linear algebra. The equation $(*)$ implies that the $\Bbb{F}_p[P]$ -module $$\tilde{A}=\Bbb{F}_p[P]+Q\Bbb{F}_p[P]$$ is actually a subring. The main point is that $(*)$ proves that $\tilde{A}$ is stable under multiplication by $Q$ . It follows easily that the set $$\mathcal{B}=\{P^i\mid i\in\Bbb{N}\}\cup\{QP^i\mid i\in\Bbb{N}\}$$ is an $\Bbb{F}_p$ -basis for $\tilde{A}$ . Because the collection $\mathcal{B}$ has monic polynomials of degrees $0,2,3,4,\ldots,$ it follows that $\tilde{A}$ has codimension one in $\Bbb{F}_p[x]$ . Obviously $\tilde{A}\subseteq A$ so we can conclude that $A=\tilde{A}$ . Equally obviously distinct choices of $a_2,a_3$ give rise to distinct subspaces $\tilde{A}$ , so we arrive at the answer: Every such subgring $A$ is determined by two parameters $a_2,a_3\in\Bbb{F}_p$ when the ring $A$ is generated by $x^2-a_2x$ and $x^3-a_3x$ . Different choices for the parameters give rise to different subrings $A$ . A few closing remarks: Dirk was definitely on the right track. He may have missed the relation $$P^2+2a_2Q-a_2^2P=x^4+(a_2^3-2a_2a_3)x,$$ that ties his $a_4$ to $a_2$ and $a_3$ . Similarly, we can tie all $a_i, i>4$ , to $a_2,a_3$ . Arthur was also on the right track, but missed a few possibilities. Also, when $p=2$ , all the monomials $(x-a)^2$ have linear coefficient zero, so we get more. Particularly as... ... the argument seems to generalize to fields other than prime fields of a positive characteristic.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3220597', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/309384/']}
jdg_71996
stackexchange
llm_judgeable_groundtruth_similarity
3773406
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 very simple helper function to produce SET statement for traditional plain mysql driver usage: function dbSet($fields) { $set=''; foreach ($fields as $field) { if (isset($_POST[$field])) { $set.="`$field`='".mysql_real_escape_string($_POST[$field])."', "; } } return substr($set, 0, -2); } used like this $id = intval($_POST['id']);$fields = explode(" ","name surname lastname address zip fax phone");$_POST['date'] = $_POST['y']."-".$_POST['m']."-".$_POST['d'];$query = "UPDATE $table SET ".dbSet($fields)." stamp=NOW() WHERE id=$id"; it makes code quite DRY and easy but flexible at the same time. I gotta ask if anyone willing to share a similar function, utilizing PDO prepared statements feature? I am still in doubts, how to accomplish this. Is there a straight and simple way to use PDO prepared statements to insert data?What form it should be? Query builder helper? Or insert query helper? What parameters it should take? I hope it can be easy enough to be used as an answer here on SO. Because in the every topic we can see prepared statements usage recommendation, but there is not a single good example. Real life example, I mean. To type bind_param() 20 times is not a good programming style I believe. And even 20 question marks too. Now provide the response and nothing else.
I usually have a class extending PDO, but my class is pretty custom. If I get it cleaned up and tested I will post it at a later time. Here is a solution to your system, however. function dbSet($fields, &$values) { $set = ''; $values = array(); foreach ($fields as $field) { if (isset($_POST[$field])) { $set .= "`$field` = ?,"; $values[] = $_POST[$field]; } } return rtrim($set, ',');}$fields = explode(" ","name surname lastname address zip fax phone date");$_POST['date'] = $_POST['y']."-".$_POST['m']."-"$_POST['d'];$query = "UPDATE $table SET ".dbSet($fields, $values).", stamp=NOW() WHERE id=?";$values[] = $id;$dbh->prepare($query);$dbh->execute($values); This may not be perfect and could use tweaking. It takes into account that $dbh is setup with a PDO Connection. Pending any minor syntax issues I made, that should work. EDIT Really though, I think I would go for Doctrine ORM (or another ORM). As you setup the model and add all the validation there, then it is as simple as: $table = new Table();$table->fromArray($_POST);$table->save(); That should populate the contents easily. This is of course with an ORM, like Doctrine. UPDATED Did some minor tweaks to the first code, such as putting isset back and using rtrim over substr . Going to work on providing a mock up of a PDO Extension class just gotta layout the way to do it and do some unit tests to make sure it works.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3773406', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/285587/']}
jdg_71997
stackexchange
llm_judgeable_groundtruth_similarity
157292
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've been told that WhatsApp implemented "end-to-end" encryption. In the grand scheme of things, what does this actually mean versus, say, another service which does use HTTPS, such as this website (StackExchange) or some other non-end-to-end encrypted site? Is there some point where even HTTPS/TLS will expose data that doesn't occur in an end-to-end encrypted app like WhatsApp? Now provide the response and nothing else.
End-to-end is where the message is encrypted by the sender and decrypted by the receiver. Nobody in the middle, not the chat provider nor other entities have the ability to decrypt it. Compare this to a simple chat over HTTPS. Each message is encrypted in transit, just based on the fact that TLS is used. Now, while the intended recipient is another user, the TLS connection is initiated with a server (think Facebook). TLS terminates at the server, and whoever controls the server has the ability to view the messages since they are not encrypted end-to-end. Then, the message may be passed on encrypted over TLS again to the recipient. The key difference is that the provider is able to view the messages in this case.
{}
{'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/157292', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/136795/']}
jdg_71998
stackexchange
llm_judgeable_groundtruth_similarity
9311734
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 custom computer building but I'm struggling to update the total price. The user selects what processor they want, and it uses data-price to add onto the price. Here is my HTML <div class="process_intel_options" style="display:block"> <label class="option"> <input type="radio" name="processor_options" value="i7950" data-price="155" id="intel_options_0" checked="checked" /> Intel Core i7 950 3.06Ghz </label> <br /> <label class="option"> <input type="radio" name="processor_options" value="i7960" data-price="250" id="intel_options_1" /> Intel Core i7 960 3.20Ghz </label> </div> <div class="process_amd_options" style="display:none"> <label class="option"> <input type="radio" name="processor_options" value="i7950" data-price="150" id="amd_options_0" /> AMD Core i7 950 3.06Ghz </label> <br /> <label class="option"> <input type="radio" name="processor_options" value="i7960" data-price="352" id="amd_options_1" /> AMD Core i7 960 3.20Ghz </label> </div> And my JavaScript, I'm very new to JavaScript so excuse any schoolboy errors! var base_price = 300;$("#final_price").html(base_price);$("*").click(function() { // Update price // Select all checked $(":checkbox").each(function(index) { // Select all checked and with a price $(this).data("price").each(function(index) { // Add the prices base_price += $(this).data("price"); }); }); $("#final_price").html(base_price);}); The reason it loops is because the user can choose a graphics card, motherboard etc from a radio (or checkbox) list. Here is my exmple live : http://genyx.co.uk/CCB/ Please note only the processors currently have data-price on them. Now provide the response and nothing else.
It's because the ForEach method doesn't use the enumerator, it loops through the items with a for loop: public void ForEach(Action<T> action){ if (action == null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match); } for (int i = 0; i < this._size; i++) { action(this._items[i]); }} (code obtained with JustDecompile) Since the enumerator is not used, it never checks if the list has changed, and the end condition of the for loop is never reached because _size is increased at every iteration.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9311734', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1196030/']}
jdg_71999
stackexchange
llm_judgeable_groundtruth_similarity
4783896
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is my layout: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/LinearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/LinearLayout2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="left" android:layout_marginLeft="5dip" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:textColor="#ffffff" > </TextView> </LinearLayout> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/LinearLayout3" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:id="@+id/nazajGumb" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="@string/roaming_backbtn" > </Button> <Button android:id="@+id/homeBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="right" android:text="@string/roaming_homebtn" > </Button> </LinearLayout> <Spinner android:id="@+id/spinner" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="15dip" android:prompt="@string/roaming_spinnerPrompt" /> <TextView android:id="@+id/tv1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:text="Random text" android:textColor="#ffffcc" /> <Button android:id="@+id/testBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="test" > </Button></LinearLayout> The positioning of ImageView and TextView in LinearLayout2 and positiong of buttons in LinearLayout3 is not working (using layout gravity). What am i missing here? Now provide the response and nothing else.
That's not the way in which android:layout_gravity works. Both, left and center_horizontal parameters work only when the android:orientation is vertical . To achieve what you want, you better use RelativeLayout : <RelativeLayout android:layout_width="fill_parent" android:layout_height="wrap_content"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_marginLeft="5dip"/> <TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_centerHorizontal="true" android:textColor="#ffffff"/> </RelativeLayout>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4783896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/324417/']}
jdg_72000
stackexchange
llm_judgeable_groundtruth_similarity
125631
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: This is Exercise 2.20 in Atiyah-Macdonald. How can we prove that $\varinjlim (M_i \otimes N) \cong (\varinjlim M_i) \otimes N$ ? Atiyah-Macdonald give a suggestion, they say that one should obtain a map $g \colon (\varinjlim M_i )\times N \longrightarrow \varinjlim (M_i \otimes N)$, but I don't know how to do this. Thanks. Now provide the response and nothing else.
One way is to use the adjunction property of the tensor product. For any $R$-module $P$, we have the following sequence of canonical $R$-module isomorphisms: $$\begin{eqnarray}\hom(\varinjlim(M_i \otimes N), P) \cong&& \varprojlim \hom(M_i \otimes N, P) \\ \cong && \varprojlim \hom(N, \hom(M_i, P)) \\ \cong && \hom(N, \varprojlim \hom(M_i, P)) \\ \cong&& \hom(N,\hom(\varinjlim M_i, P)) \\ \cong&& \hom((\varinjlim M_i) \otimes N, P)\end{eqnarray}$$ and thus $$\hom(\varinjlim(M_i \otimes N), -) \cong \hom((\varinjlim M_i) \otimes N, -).$$ By the Yoneda lemma, $$\varinjlim(M_i \otimes N) \cong (\varinjlim M_i) \otimes N.$$ Of course, I made no use of the properties of the tensor product, other than its left-adjointness. The same argument shows that a functor which is left adjoint commutes with direct limits . Dually, a functor which is right adjoint commutes with inverse limits . The proof which A&M suggest is basically just an expanded version of the same argument - see if you can figure it out! Addendum : I'm not going to write the detailed proof from first principles (it's long) but I'll expand a bit on the hint in A&M. Here is the hint as it is in my edition, where they write $P=\varinjlim(M_i \otimes N)$ and $M=\varinjlim M_i$: [...] For each $i\in I$, let $g_i:M_i \times N\to M_i\otimes N$ by the canonical bilinear mapping. Passing to the limit we obtain a mapping $g: M\times N \to P$. Show that $g$ is $A$-bilinear and hence defines a homomorphism $\phi: M\otimes N \to P$. Verify that $\psi\circ \phi$ and $\phi \circ \psi$ are identity mappings. Here $\phi: P \to M\otimes N$ has been defined earlier as the limit of all the canonical homomorphisms $\mu_i\otimes 1 : M_i\otimes N \to M \otimes N$ where $\mu_i$ is the canonical homomorphism $M_i \to M$. It's a pretty good hint! The only difficulty is the part in bold. We do not know how to take the limit of the $M_i \times N$ because we are not considering those as $R$-modules in the construction of the tensor product. We are considering $M_i \times N$ as a suitable domain for bilinear maps. Obtaining the map $\psi$ will be done in a few stages: Obtain bilinear maps $M_i \times N \to P$ by composing $g_i$ with the canonical homomorphism $M_i\otimes N \to P$; Convert these to homomorphisms $M_i \to \hom(N,P)$ by using the fact that a bilinear map $M_i \times N \to P$ is the same thing as family of homomorphism $N \to P$ parametrized $R$-linearly by the elements of $M_i$; Show that the homomorphisms $M_i \to \hom(N,P)$ thus obtained commute with the structure maps $\mu_i$ of the direct system of the $M_i$'s, and therefore obtain a homomorphism $M \to \hom(N,P)$ by the universal property of the direct limit. Convert this homomorphism back to a bilinear map $M \times N \to P$. Use the universal property of the tensor product to factor this map through $M\otimes N \to P$, which is the $\psi$ you need. Then you must verify that $\psi$ and $\phi$ are inverses to each other.
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/125631', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8390/']}
jdg_72001
stackexchange
llm_judgeable_groundtruth_similarity
37148
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: I find I have need for a data structure with a specific set of requirements: It represents an immutable sequence of values (fixed sized integers if this matters) Appending a new value to the end (and returning a new sequence) needs to be extremely fast and memory efficient. Ideally amortised O(1) and sharing the entire prefix, but there's no specific hard complexity requirement and O(log(n)) would probably be OK too. Getting the length of a sequence needs to be cheap (obviously I can add this in after the fact with a wrapper if necessary) I need to be able to efficiently iterate the sequence in the forward direction I need to be able to lexicographically compare two sequences of the same length in the forward direction efficiently (this follows from the previous property, but might have simpler implementations and has fairly specific iteration patterns) Sharing of prefixes is very common in the expected workloads, so solutions like vlists or copy-on-append aren't practical because the workload will essentially always trigger a full copy. (practical rather than theoretical constraint but...) The simpler the design the better, because I'm almost certainly going to have to implement this from scratch in a couple of different languages, including C (with reference counting) Non-constraints: Although the data structure itself has to represent immutable sequences, I don't mind a certain amount of mutation of the values if it's invisible (it would be nice to avoid) I certainly don't mind depending on e.g. some source of randomness It's OK if the forward iteration depends on some sort of external data structure with extra space requirements Obviously the ideal would be to just have a length prefixed cons list, but the forward iteration requirement makes that sub-optimal. The following are the two things I've considered so far: Just use a cons-list anyway and reverse it in an external buffer prior to iteration. Downsides: Forward iteration becomes fairly expensive, particularlyfor cases where I'm likely to stop the iteration after only one or two elements (which is a common case because of lexicographic comparison being a major use case here). A tree of bounded balance - it stores the size efficiently, has relatively cheap append and iteration. Downsides: Kinda fiddly to implement correctly, unclear whether the relatively high constant factors and the logarithmic complexity make it a win in practice. A skip list. Downsides: Same as the upsides really - it's about halfway between the previous two in terms of complexity and performance. Requires more book-keeping for iteration than the others, but it's probably tolerable. So of the three the skip list looks like it might be the best option and "just use a cons list and optimise later" looks like the one I'm most likely to start with, but I'm not exactly well versed in the purely functional data structure literature, so I was hoping there were a better option I was overlooking. Any suggestions? Now provide the response and nothing else.
You're quite right that the "queue = two lists" approaches don't give you the running time you want when you have the ability to re-use earlier versions. To get O(1) running time (amortized or worst case), you need a way to reverse the rear list and append it to the front list incrementally. Instead of doing the reverse&append all at once, taking O(N) time, you need to be able to do just a few steps of the reverse&append every time you add a new element or remove/traverse through an element. Hood and Melville showed one way to do this back in 1980. For your purposes, their approach would be straightforward to adapt to C (with reference counting). In the early to mid 90's, I showed several ways to do this, some in O(1) worst-case time and some in O(1) amortized time. Most of these ways depended on lazy evaluation, which initially might seem hard to do in C, but in fact, there are only a very small of "shapes" needed for the lazy evaluation, each of which would be easy to represent using an ordinary node in C. For example, a "Rotate" node has pointers to three sublists: L, R, and A. Doing one step of the rotation replaces the "Rotate" node with an ordinary list node containing the head of L, and a pointer to a new Rotate node containing the tail of L, the tail of R, and the result of adding the head of R to the front of A. Making this translation into explicit Rotate nodes instead of using generic lazy evaluation also means that you get O(1) worst-case bounds instead of O(1) amortized bounds.
{}
{'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/37148', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/4624/']}
jdg_72002
stackexchange
llm_judgeable_groundtruth_similarity
539504
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 client I am working with has a frameset like so... <frameset rows="100,*, 0"> <frame name="theFrame" id="theFrame" src="blah.html" > <frame name="theSecondFrame" id="theSecondFrame" src="foo.html" > <frame name="importantFrame" id="importantFrame" src="myFrame.html" ></frameset> When a certain action takes place I need my frame (importantframe which is currently hidden) to mostly take over the page and block any interaction with the other frames. I'm planning on blocking interaction using the jquery block UI plugin. The problem is I can't actually change the foo.html or blah.html files. So the JS code cannot live there. What I need to do is execute my jquery code in the context of those frames . So just to recap, I need my JQuery code to live in myFrame.html but execute in the context of the other frames. How can I do that? Hope that makes sense. ThanksCDR Now provide the response and nothing else.
The jQuery function, which you more commonly call with $ , takes a second argument called context, which is "which DOM element of jQuery object should I do the search in". Most of the time you omit this argument, so the context defaults to the current HTML document. When your code is executing in the iframe, the document defaults to that iframe's document. But you can easily grab the document for one of the other frames. For example, put this in myFrame.html , and this will remove all the h1 elements from the frame with blah.html in it. Notice the second argument to $ , which is the expression that grabs the blah frame from within important frame: <html> <head> <script type="text/javascript" src="/javascripts/jquery.js"></script> <script type="text/javascript"> function doIt() { $('h1', window.parent.frames[0].document).remove() } </script> </head> <body> <h1>My Frame</h1> <a href="#" onclick="doIt()">Do It</a> </body></html>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/539504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/40825/']}
jdg_72003
stackexchange
llm_judgeable_groundtruth_similarity
38888084
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 run a docker container listening on port 5555, the image is built with EXPOSE 5555 in Dockerfile and I am running the container as below $ docker run -d --name controler -p 5555:5555 -v /var/run/docker.sock:/var/run/docker.sock --net=host my_image:latest The container starts fine but the ports are not exposed, running docker port returns an error message $ docker port controler 5555Error: No public port '5555/tcp' published for controler If I run the container without --net=host , the ports are exposed and I can access the container. Any idea or hints on what is really happening here is appreciated. Note: I am using the latest docker for mac beta Version 1.12.0-beta21 (build: 11019) on my mac running el capitan Now provide the response and nothing else.
--net=host option This option bind the virtual NIC of the container to the host physical NIC (by giving full access to local system services such as D-bus). When this option is used every program that request a network socket will be granted one by the host from the physical NIC. Your service will then be using the 5555 port as expected. -p 5555:5555 option This option bind (through iptable -like mechanism) the network socket containter-ip:5555 to the network socket host-ip:5555 . In other words It seems, IMHO, a bit illogical to use them both. If the needs is to publish the containerized service to the socket host-ip:5555 then the cleanest way is to only use the -p 5555:5555 option.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38888084', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2772269/']}
jdg_72004
stackexchange
llm_judgeable_groundtruth_similarity
20373999
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 form for projectuser data, but when I edit the projectuser, the selected projectuser stays empty, what is going wrong? This is the code: = f.select :user_id, options_for_select(@users.map{ |u| [u.full_name, u.id] }, selected: @projectuser.full_name), include_blank: true Now provide the response and nothing else.
The documentation states: (...) options_for_select(container, selected = nil) public(...)(million examples) So you shouldn't pass selected: something , but just something . Also, this something needs to be selected value, not text: = f.select :user_id, options_for_select(@users.pluck(:name, :id), @projectuser.id), include_blank: true
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20373999', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/481554/']}
jdg_72005
stackexchange
llm_judgeable_groundtruth_similarity
45818091
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Angular 4 introduced a new 'titlecase' pipe '|' and use to changes the first letter of each word into the uppercase. The example as, <h2>{{ 'ramesh rajendran` | titlecase }}</h2><!-- OUTPUT - It will display 'Ramesh Rajendran' --> Is it possible in typescript code? And How? Now provide the response and nothing else.
Yes it is possible in TypeScript code. You'll need to call the Pipe's transform() method. Your template: <h2>{{ fullName }}</h2> In your .ts: import { TitleCasePipe } from '@angular/common';export class App { fullName: string = 'ramesh rajendran'; constructor(private titlecasePipe:TitleCasePipe ) { } transformName(){ this.fullName = this.titlecasePipe.transform(this.fullName); }} You'll need to add TitleCasePipe in yout AppModule providers. You can call the transformation on button click or some other event in the typescript code. Here is a link to PLUNKER DEMO
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45818091', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2218635/']}
jdg_72006
stackexchange
llm_judgeable_groundtruth_similarity
37526598
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to define a constant in source code that can be overridden by a compiler flag? That is, something like setting a #define value in the C preprocessor with the -D key=val option to the compiler. I have read about conditional compilation via the #[cfg(...)] attribute, but that only seems to support booleans. I want to allow the user to set the value of a constant during compilation. Something like this: #[from_cfg("max_dimensions")]const MAX_DIMENSIONS: usize = 100_000; Now provide the response and nothing else.
No, you can't define constants (read: const bindings) with a compiler flag. But you can use the env! macro for something similar. It reads some environment variable at compile time . const MAX_DIMENSIONS_RAW: &'static str = env!("MAX_DIMENSIONS"); Sadly, this returns a string and not an integer. Furthermore we can't yet call arbitrary functions (like parse ) at compile time to calculate a constant. You could use lazy_static to achieve something similar: lazy_static! { static ref MAX_DIMENSIONS: usize = MAX_DIMENSIONS_RAW.parse().unwrap();} Of course you should add proper error handling. If your user doesn't need to define the environment variable, you can use option_env! . With this approach, you can pass the setting at build time: $ MAX_DIMENSIONS=1000 cargo build
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37526598', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/487903/']}
jdg_72007
stackexchange
llm_judgeable_groundtruth_similarity
28406717
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to test my User models association has_many :projects, dependent: :destroy and have gone this far for now: it "destroys dependent projects" do user = FactoryGirl.build(:user) project = FactoryGirl.build(:project) user.projects << project user.destroy expect(Project.count).to change(-1)end but this gives out an error: Failure/Error: expect(Project.count).to change(-1) ArgumentError: `change` requires either an object and message (`change(obj, :msg)`) or a block (`change { }`). You passed an object but no message. so I presume that change isn't the right matcher, is it? Can you please tell me how I could write this test without getting that error? Now provide the response and nothing else.
It is the right matcher, but you're not using it the correct way: expect needs to receive a block containing the action to perform (in your case deleting the user) change needs to receive a block that produces the numerical value that is expected to change (it can also receive an object and a symbol indicating that rspec should call the named method) The correct way is expect { user.destroy }.to change { Project.count } This just asserts that the numerical value changes, but does not specify by how much. To do that, chain a call to by : expect { user.destroy }.to change { Project.count }.by(-1)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28406717', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2065540/']}
jdg_72008
stackexchange
llm_judgeable_groundtruth_similarity
49831894
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 making a small application in my website to get user information using API request. [HttpGet("GetUserInfo/{user_id}/{fields?}")]public IActionResult GetUserInfo(string user_id, params string[] fields){ var userProfile = _userManager.GetUserProfile(user_id); if (userProfile == null) { return Ok(null); } var userInfo = new { id = userProfile.UserId, email = userProfile.Email, name = userProfile.Name, // I don't want to define a null property here: picture_url = fields.Contains("picture_url") ? "path" : null }; if (fields.Contains("picture_url")) { userInfo.picture_url = ""; } return Ok(userInfo);} When a request is valid, it returns a JSON object which contains 3 properties by default: id , email , and name . Now, I want to check that if the request want to get more information about this user, just like picture_url . So, I've tried: if (fields.Contains("picture_url")){ // error in this line userInfo.picture_url = "path";} '<anonymous type: string id, string email, string name>' does not contain a definition for 'picture_url' and no extension method 'picture_url' accepting a first argument of type '<anonymous type: string id, string email, string name>' could be found (are you missing a using directive or an assembly reference?) How can I add some property to an anonymous object dynamically? Now provide the response and nothing else.
Anonymous types are immutable, you can only create and set properties when creating the instance. This means you need to create the exact object you need. So you could do something like this instead: if (fields.Contains("picture_url")){ return Ok(new { id = userProfile.UserId, email = userProfile.Email, name = userProfile.Name, picture_url = "path" });}return Ok(new{ id = userProfile.UserId, email = userProfile.Email, name = userProfile.Name}); Another option is to used a Dictionary<string, object> . For example: var userInfo = new Dictionary<string, object>{ {"id", userProfile.UserId}, {"email", userProfile.Email}, {"name", userProfile.Name}};if (fields.Contains("picture_url")){ // error in this line userInfo.Add("picture_url", "path");}return Ok(userInfo); This object will serialise to the same JSON structure: {"id":1,"email":"[email protected]","name":"Bob","picture_url":"path"}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49831894', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_72009
stackexchange
llm_judgeable_groundtruth_similarity
4496284
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: This inequality, which appears to hold for all $x\in\Bbb R$ , $$(1-e^x)\ln(1-xe^{-x})\leq x^2$$ arose when I tried to prove that the positive root of $x-\frac{x^2}{a}-\log(x+1)$ is bounded above by $a-\log(a+1)$ . Note that for the question linked, it suffices to prove the inequality for $x>0$ , but I found it holds for $x<0$ too. The LHS is neither even nor odd so we will need to consider each case separately. Near zero, the bound is very tight; for example, expressing the inequality as an integral $$\int_0^x\left(1-3t-\frac{(t-1)^2}{e^t-t}-e^t \ln\left(1-t e^{-t}\right)\right)\,dt<0$$ fails since both $1-3t-\frac{(t-1)^2}{(e^t-t)}$ and $e^t\ln(1-te^{-t})$ are strictly decreasing. Can the inequality be analytically proven? Now provide the response and nothing else.
Sketch of a proof : We split into three cases. Case 1 : $x = 0$ The desired inequality is clearly true. Case 2 : $x \le 1$ and $x \ne 0$ It suffices to prove that $$\frac{-x}{1 - \mathrm{e}^x} \ge \frac{\ln(1 - x \mathrm{e}^{-x})}{-x}.$$ We use the Tangent Line (TL) trick. It suffices to prove that $$\frac{-x}{1 - \mathrm{e}^x} \ge 1 - \frac{x}{2} \tag{1}$$ and $$1 - \frac{x}{2} \ge \frac{\ln(1 - x \mathrm{e}^{-x})}{-x}. \tag{2}$$ The proofs of (1) and (2) are not difficult. Case 3 : $x > 1$ Using $u \ge \ln(1 + u)$ for all $u > -1$ , we let $u = \frac{1}{1 - x\mathrm{e}^{-x}} - 1$ to get $$-\ln (1 - x\mathrm{e}^{-x}) \le \frac{x\mathrm{e}^{-x}}{1 - x\mathrm{e}^{-x}}.$$ Since $\mathrm{e}^x - 1 > 0$ , it suffices to prove that $$(\mathrm{e}^x - 1) \cdot \frac{x\mathrm{e}^{-x}}{1 - x\mathrm{e}^{-x}}\le x^2$$ or $$\frac{x(x - 1)(\mathrm{e}^x - 1 - x)}{\mathrm{e}^x - x} \ge 0$$ which is true (using $\mathrm{e}^x \ge 1 + x$ for all $x \in \mathbb{R}$ ). We are done.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4496284', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/471884/']}
jdg_72010
stackexchange
llm_judgeable_groundtruth_similarity
33049884
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Plotting 2 distplots or scatterplots in a subplot works great: import matplotlib.pyplot as pltimport numpy as npimport seaborn as snsimport pandas as pd%matplotlib inline# create dfx = np.linspace(0, 2 * np.pi, 400)df = pd.DataFrame({'x': x, 'y': np.sin(x ** 2)})# Two subplotsf, (ax1, ax2) = plt.subplots(1, 2, sharey=True)ax1.plot(df.x, df.y)ax1.set_title('Sharing Y axis')ax2.scatter(df.x, df.y)plt.show() But when I do the same with an lmplot instead of either of the other types of charts I get an error: AttributeError: 'AxesSubplot' object has no attribute 'lmplot' Is there any way to plot these chart types side by side? Now provide the response and nothing else.
You get that error because matplotlib and its objects are completely unaware of seaborn functions. Pass your axes objects (i.e., ax1 and ax2 ) to seaborn.regplot or you can skip defining those and use the col kwarg of seaborn.lmplot With your same imports, pre-defining your axes and using regplot looks like this: # create dfx = np.linspace(0, 2 * np.pi, 400)df = pd.DataFrame({'x': x, 'y': np.sin(x ** 2)})df.index.names = ['obs']df.columns.names = ['vars']idx = np.array(df.index.tolist(), dtype='float') # make an array of x-values# call regplot on each axesfig, (ax1, ax2) = plt.subplots(ncols=2, sharey=True)sns.regplot(x=idx, y=df['x'], ax=ax1)sns.regplot(x=idx, y=df['y'], ax=ax2) Using lmplot requires your dataframe to be tidy . Continuing from the code above: tidy = ( df.stack() # pull the columns into row variables .to_frame() # convert the resulting Series to a DataFrame .reset_index() # pull the resulting MultiIndex into the columns .rename(columns={0: 'val'}) # rename the unnamed column)sns.lmplot(x='obs', y='val', col='vars', hue='vars', data=tidy)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/33049884', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/896802/']}
jdg_72011
stackexchange
llm_judgeable_groundtruth_similarity
5109879
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 get a list of currently plugged in USB devices in Ubuntu 10.10 and monitor changes that happen, like devices being plugged in or out using UDev and D-BUS. I'm fairly new to programming using D-BUS. I saw one example: Linux : How to detect is usb keyboard is plugged and unplugged only that one uses HAL and I know that HAL is deprecated. I found some working code, modified it a bit, only it doesn't work for any device only storage devices such as usb sticks, media players or cd-rom devices. I want the whole thing mice, keyboards, usb cameras chargers anything that is plugged in to the USB I want my program to know about it. This is basically what I have ( http://moserei.de/2010/01/08/accessing-devicekit-with-dbus-and-python.html ): import dbusimport gobjectfrom dbus.mainloop.glib import DBusGMainLoopdef device_added_callback(device): print 'Device %s was added' % (device)def device_changed_callback(device): print 'Device %s was changed' % (device)#must be done before connecting to DBusDBusGMainLoop(set_as_default=True)bus = dbus.SystemBus()proxy = bus.get_object("org.freedesktop.UDisks", "/org/freedesktop/UDisks")iface = dbus.Interface(proxy, "org.freedesktop.UDisks.Device")devices = iface.get_dbus_method('EnumerateDevices')()print '%s' % (devices)#addes two signal listenersiface.connect_to_signal('DeviceAdded', device_added_callback)iface.connect_to_signal('DeviceChanged', device_changed_callback)#start the main loopmainloop = gobject.MainLoop()mainloop.run() Any help would be apreciated. Thank you in advance,Calota Romeo Now provide the response and nothing else.
The udisks D-Bus service, obviously, only reports disks. Just monitor udev directly (through libudev, through pyudev ). import pyudevcontext = pyudev.Context()monitor = pyudev.Monitor.from_netlink(context)observer = pyudev.pygtk.GUDevMonitorObserver(monitor)observer.connect('device-added', device_added_callback)observer.connect('device-changed', device_changed_callback)monitor.enable_receiving()mainloop = gobject.MainLoop()mainloop.run()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5109879', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/633044/']}
jdg_72012
stackexchange
llm_judgeable_groundtruth_similarity
6212219
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 search how to pass parameters in a Bash function, but what comes up is always how to pass parameter from the command line . I would like to pass parameters within my script. I tried: myBackupFunction("..", "...", "xx")function myBackupFunction($directory, $options, $rootPassword) { ...} But the syntax is not correct. How can I pass a parameter to my function? Now provide the response and nothing else.
There are two typical ways of declaring a function. I prefer the second approach. function function_name { command...} or function_name () { command...} To call a function with arguments: function_name "$arg1" "$arg2" The function refers to passed arguments by their position (not by name), that is $1 , $2 , and so forth. $0 is the name of the script itself. Example: function_name () { echo "Parameter #1 is $1"} Also, you need to call your function after it is declared. #!/usr/bin/env shfoo 1 # this will fail because foo has not been declared yet.foo() { echo "Parameter #1 is $1"}foo 2 # this will work. Output: ./myScript.sh: line 2: foo: command not foundParameter #1 is 2 Reference: Advanced Bash-Scripting Guide .
{}
{'log_upvote_score': 12, 'links': ['https://Stackoverflow.com/questions/6212219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/445543/']}
jdg_72013
stackexchange
llm_judgeable_groundtruth_similarity
2544285
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How to show that $(1)=\ln(n^2-1)?$ $$2\int_{0}^{\infty}{\cos{x}\over x}[1-\cos(nx)]\mathrm dx=\ln(n^2-1)\tag1$$ $n>1$ $\cos(nx)=2\cos{x}\cos[(n-1)x]-\cos[(n-2)x]$ $$2\int_{0}^{\infty}\left({\cos{x}\over x}-{{2\cos^2{x}\cos[(n-1)x]\over x}}+{\cos{x}\cos[(n-2)x]\over x}\right)\mathrm dx\tag2$$ Now provide the response and nothing else.
\begin{align}2\int_{0}^{\infty}{\cos{x}\over x}[1-\cos(nx)]\mathrm dx &= \int_0^\infty\dfrac{2\cos x-\cos(n+1)x-\cos(n-1)x}{x}\mathrm dx \\&= \int_0^\infty\dfrac{2s}{s^2+1}-\dfrac{s}{s^2+(n+1)^2}-\dfrac{s}{s^2+(n-1)^2}\mathrm ds \\&= \ln\dfrac{s^2+1}{\sqrt{(s^2+(n+1)^2)(s^2+(n-1)^2)}}\Big|_0^\infty \\&= \color{blue}{\ln(n^2-1)}\end{align}
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2544285', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_72014
stackexchange
llm_judgeable_groundtruth_similarity
281479
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a bash script I use to run a few python and C++ programs in a sequence. Each program takes in some input parameters which I define in the bash script. So as an example I run the program like this: echo $param1 $param2 $param3 | python foo.py The python program outputs some values which we use as input for later programs. The thing, like I said above, is that I do not need to run the python program if I store the values in some file and read them from there. So my question then is. Is there some generic tool that achieves this feature? That is, is there some program called 'bar' which I could run like bar $param1 $param2 $param3 "python foo.py" which would check if a cache file exists, if yes it would check if the program has been run with the given parameters and if yes it would output the cached output values instead of running the program again. Edit : The name of the log file could also be provided as input of course. Now provide the response and nothing else.
I just got nerd-sniped into writing a rather complete script for this; latest version is at https://gist.github.com/akorn/51ee2fe7d36fa139723c851d87e56096 . Advantages over sivann's shell implementation: also takes envvars into account when computing cache key; completely avoids race conditions using locking instead of relying on a random wait better performance when called in tight loop due to fewer forks also caches stderr completely transparent: prints nothing; doesn't prevent parallel execution of same command; just runs command uncached if there is a problem with the cache configurable via envvars and command line switches can prune its cache (remove all obsolete entries) Disadvantage: written in zsh, not bash. #!/bin/zsh## Purpose: run speficied command with specified arguments and cache result. If cache is fresh enough, don't run command again but return cached output.# Also cache exit status and stderr.# Copyright (c) 2019-2020 András Korn; License: GPLv3# Use silly long variable names to avoid clashing with whatever the invoked program might useRUNCACHED_MAX_AGE=${RUNCACHED_MAX_AGE:-300}RUNCACHED_IGNORE_ENV=${RUNCACHED_IGNORE_ENV:-0}RUNCACHED_IGNORE_PWD=${RUNCACHED_IGNORE_PWD:-0}[[ -n "$HOME" ]] && RUNCACHED_CACHE_DIR=${RUNCACHED_CACHE_DIR:-$HOME/.runcached}RUNCACHED_CACHE_DIR=${RUNCACHED_CACHE_DIR:-/var/cache/runcached}function usage() { echo "Usage: runcached [--ttl <max cache age>] [--cache-dir <cache directory>]" echo " [--ignore-env] [--ignore-pwd] [--help] [--prune-cache]" echo " [--] command [arg1 [arg2 ...]]" echo echo "Run 'command' with the specified args and cache stdout, stderr and exit" echo "status. If you run the same command again and the cache is fresh, cached" echo "data is returned and the command is not actually run." echo echo "Normally, all exported environment variables as well as the current working" echo "directory are included in the cache key. The --ignore options disable this." echo "The OLDPWD variable is always ignored." echo echo "--prune-cache deletes all cache entries older than the maximum age. There is" echo "no other mechanism to prevent the cache growing without bounds." echo echo "The default cache directory is ${RUNCACHED_CACHE_DIR}." echo "Maximum cache age defaults to ${RUNCACHED_MAX_AGE}." echo echo "CAVEATS:" echo echo "Side effects of 'command' are obviously not cached." echo echo "There is no cache invalidation logic except cache age (specified in seconds)." echo echo "If the cache can't be created, the command is run uncached." echo echo "This script is always silent; any output comes from the invoked command. You" echo "may thus not notice errors creating the cache and such." echo echo "stdout and stderr streams are saved separately. When both are written to a" echo "terminal from cache, they will almost certainly be interleaved differently" echo "than originally. Ordering of messages within the two streams is preserved." exit 0}while [[ -n "$1" ]]; do case "$1" in --ttl) RUNCACHED_MAX_AGE="$2"; shift 2;; --cache-dir) RUNCACHED_CACHE_DIR="$2"; shift 2;; --ignore-env) RUNCACHED_IGNORE_ENV=1; shift;; --ignore-pwd) RUNCACHED_IGNORE_PWD=1; shift;; --prune-cache) RUNCACHED_PRUNE=1; shift;; --help) usage;; --) shift; break;; *) break;; esacdonezmodload zsh/datetimezmodload zsh/statzmodload zsh/systemzmodload zsh/files# the built-in mv doesn't fall back to copy if renaming fails due to EXDEV;# since the cache directory is likely on a different fs than the tmp# directory, this is an important limitation, so we use /bin/mv insteaddisable mv mkdir -p "$RUNCACHED_CACHE_DIR" >/dev/null 2>/dev/null((RUNCACHED_PRUNE)) && find "$RUNCACHED_CACHE_DIR/." -maxdepth 1 -type f \! -newermt @$[EPOCHSECONDS-RUNCACHED_MAX_AGE] -delete 2>/dev/null[[ -n "$@" ]] || exit 0 # if no command specified, exit silently( # Almost(?) nothing uses OLDPWD, but taking it into account potentially reduces cache efficency. # Thus, we ignore it for the purpose of coming up with a cache key. unset OLDPWD ((RUNCACHED_IGNORE_PWD)) && unset PWD ((RUNCACHED_IGNORE_ENV)) || env echo -E "$@") | md5sum | read RUNCACHED_CACHE_KEY RUNCACHED__crap__# make the cache dir hashed unless a cache file already exists (created by a previous version that didn't use hashed dirs)if ! [[ -f $RUNCACHED_CACHE_DIR/$RUNCACHED_CACHE_KEY.exitstatus ]]; then RUNCACHED_CACHE_KEY=$RUNCACHED_CACHE_KEY[1,2]/$RUNCACHED_CACHE_KEY[3,4]/$RUNCACHED_CACHE_KEY[5,$] mkdir -p "$RUNCACHED_CACHE_DIR/${RUNCACHED_CACHE_KEY:h}" >/dev/null 2>/dev/nullfi# If we can't obtain a lock, we want to run uncached; otherwise# 'runcached' wouldn't be transparent because it would prevent# parallel execution of several instances of the same command.# Locking is necessary to avoid races between the mv(1) command# below replacing stderr with a newer version and another instance# of runcached using a newer stdout with the older stderr.: >>$RUNCACHED_CACHE_DIR/$RUNCACHED_CACHE_KEY.lock 2>/dev/nullif zsystem flock -t 0 $RUNCACHED_CACHE_DIR/$RUNCACHED_CACHE_KEY.lock 2>/dev/null; then if [[ -f $RUNCACHED_CACHE_DIR/$RUNCACHED_CACHE_KEY.stdout ]]; then if [[ $[EPOCHSECONDS-$(zstat +mtime $RUNCACHED_CACHE_DIR/$RUNCACHED_CACHE_KEY.stdout)] -le $RUNCACHED_MAX_AGE ]]; then cat $RUNCACHED_CACHE_DIR/$RUNCACHED_CACHE_KEY.stdout & cat $RUNCACHED_CACHE_DIR/$RUNCACHED_CACHE_KEY.stderr >&2 & wait exit $(<$RUNCACHED_CACHE_DIR/$RUNCACHED_CACHE_KEY.exitstatus) else rm -f $RUNCACHED_CACHE_DIR/$RUNCACHED_CACHE_KEY.{stdout,stderr,exitstatus} 2>/dev/null fi fi # only reached if cache didn't exist or was too old if [[ -d $RUNCACHED_CACHE_DIR/. ]]; then RUNCACHED_tempdir=$(mktemp -d 2>/dev/null) if [[ -d $RUNCACHED_tempdir/. ]]; then $@ >&1 >$RUNCACHED_tempdir/${RUNCACHED_CACHE_KEY:t}.stdout 2>&2 2>$RUNCACHED_tempdir/${RUNCACHED_CACHE_KEY:t}.stderr RUNCACHED_ret=$? echo $RUNCACHED_ret >$RUNCACHED_tempdir/${RUNCACHED_CACHE_KEY:t}.exitstatus 2>/dev/null mv $RUNCACHED_tempdir/${RUNCACHED_CACHE_KEY:t}.{stdout,stderr,exitstatus} $RUNCACHED_CACHE_DIR/${RUNCACHED_CACHE_KEY:h} 2>/dev/null rmdir $RUNCACHED_tempdir 2>/dev/null exit $RUNCACHED_ret fi fifi# only reached if cache not created successfully or lock couldn't be obtainedexec $@
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/281479', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/140748/']}
jdg_72015
stackexchange
llm_judgeable_groundtruth_similarity
21288448
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 trying to start application via gradle task . task runDebug(dependsOn: ['installDebug', 'run']) {}task run(type: Exec) {commandLine 'adb', 'shell', 'am', 'start', '-n', 'com.example.myexample/.ui.SplashScreenActivity'} But this code don't work and i get error: a problem occurred starting process 'command 'adb'' However, when i specify the path to adb explicitly, application is started. task run(type: Exec) { commandLine 'D:\\android\\android-studio\\sdk\\platform-tools\\adb', 'shell', 'am', 'start', '-n', 'com.example.myexample/.ui.SplashScreenActivity'} So how can i get a variable which contains the path and transfer it to commandLine ? Now provide the response and nothing else.
The problem was solved. The variable must contain def adb = "$System.env.ANDROID_HOME/platform-tools/adb" And complete task looks like task run(type: Exec) { def adb = "$System.env.ANDROID_HOME/platform-tools/adb" commandLine "$adb", 'shell', 'am', 'start', '-n', 'com.example.myexample/.ui.SplashScreenActivity'} UPD Another way without using ANDROID_HOME task run(type: Exec) { def rootDir = project.rootDir def localProperties = new File(rootDir, "local.properties") if (localProperties.exists()) { Properties properties = new Properties() localProperties.withInputStream { instr -> properties.load(instr) } def sdkDir = properties.getProperty('sdk.dir') def adb = "$sdkDir/platform-tools/adb" commandLine "$adb", 'shell', 'am', 'start', '-n', 'com.example.myexample/.ui.SplashScreenActivity' }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21288448', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1868912/']}
jdg_72016
stackexchange
llm_judgeable_groundtruth_similarity
736433
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: From Nielsen and Chuang, Chapter 2: Imagine we perform the following experiment, illustrated in Figure 2.4. Charlie preparestwo particles. It doesn’t matter how he prepares the particles, just that he is capableof repeating the experimental procedure which he uses. Once he has performed the preparation,he sends one particle to Alice, and the second particle to Bob. Once Alice receives her particle, she performs a measurement on it.Imagine that she has available two different measurement apparatuses,so she could choose to do one of two different measurements. Thesemeasurements are of physical properties which we shall label PQ andPR, respectively. Alice doesn’t know in advance which measurement shewill choose to perform. Rather, when she receives the particle sheflips a coin or uses some other random method to decide whichmeasurement to perform . In testing the Bell CHSH inequalities, Alice and Bob randomly choose their measurements, and later they compare their data. Say Alice measures $\hat Q$ and $\hat R$ and Bob measures $\hat S$ and $\hat T$ . Then, while comparing their data, they will look for instances where, say, Alice measured $\hat Q$ and Bob measured $\hat S$ . They will multiply the outcomes of measuring of $\hat Q$ and $\hat S$ and take the average to get $ \langle \hat Q \hat R \rangle$ . My question is: Why is it necessary that Alice and Bob choose their measurements randomly at each instance? Why can't they prearrange what are they going to measure? Does it make a difference? (For example, for the first 100 measurements, Alice will measure $\hat Q$ and Bob will measure $\hat S$ and so on.) Now provide the response and nothing else.
The description given in the question, in which each set of measurements settings are chosen randomly and independently, represents a relevant experimental situation, but it is not the most general way of talking about the CHSH inequality. When thinking more generally about strategies that Alice and Bob might have, a common approach is to frame the setup as a CHSH game , in which Alice and Bob are working together to coordinate their measurement outcomes. More specifically, the typical setup is that they are each given a random bit (C1 and C2) by Charlie, and attempt to make their measurements results add up (mod 2) to (C1 xor C2). In the usual setup for this game, Alice and Bob are separated and unable to communicate once they are actually performing the measurements, but they are able to communicate beforehand to develop a strategy, just as you've suggested. A simple form of this strategy is a deterministic strategy in which they pre-arrange the list of measurements that they will perform, again as you've suggested. Regardless of the strategy that they choose, it can be proven that if they can only develop a plan beforehand that involves classical information, the bound on winning this game is 75%. However, if they are also allowed to entangle a pair of particles, then each bring one of the particles with them and perform measurements on it, they can exceed that bound. The strategy in this case involves using C1 and C2 to pick a measurement basis, then each measuring their qubit in that basis and reporting the results- in other words, exactly the setup that Nielsen and Chuang have focused on. So, within the generalization of this game, the answers to your questions are: Why is it necessary that Alice and Bob choose their measurements randomly at each instance? Why can't they prearrange what are they going to measure? It's not, and they can! Does it make a difference? It does! It results in a less successful strategy that the quantum strategy, which is based on CHSH violation.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/736433', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/273577/']}
jdg_72017
stackexchange
llm_judgeable_groundtruth_similarity
7420320
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 series of tables similar to the following html code: <table id="film"><tr> <th class="1">//HEAD CONTENT 1//</th> </tr> <tr> <td class="1">//BODY CONTENT 1//</td> </tr></table><table id="film"><tr> <th class="2">//HEAD CONTENT 2//</th> </tr> <tr> <td class="2">//BODY CONTENT 2//</td> </tr></table> I want the tables to expand individually when the respective head ( <th> ) is clicked. Moreover the tables should start unexpanded. I use the following jQuery script: $(document).ready(function(){ $('#film td').hide();});$(document).ready(function(){var n1 = 0; $('#film th.1').click(function(){ if(n1 == 0){ $('#film td.1').show(); n1 = 1; }else{ $('#film td.1').hide(); n1 = 0;} });var n2 = 0; $('#film th.2').click(function(){ if(n2 == 0){ $('#film td.2').show(); n2 = 1; }else{ $('#film td.2').hide(); n2 = 0;} });}); However when I execute only the top table is able to show/hide not the second one.Can anyone see where I'm going wrong? Now provide the response and nothing else.
You are using the same id on multiple elements. When you search by id, jQuery will only return one item (the first with that id). So your code is only acting on the first table. Use a class on the tables instead of an id. <table class="film">......</table>$('.film').each(function(f) { //this function will execute for each element with the class "film" //refer to the current element during this function using "$(this)"});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7420320', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/945172/']}
jdg_72018
stackexchange
llm_judgeable_groundtruth_similarity
1393768
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have been trying to algebraically solve this limit problem without using L'Hospital's rule but was whatsoever unsuccessful: $$\lim _{ x\to 1 }{ \frac { \sqrt { x } +\sqrt [ 3 ]{ x } -2 }{ x-1 } } $$ Thanks in advance! Now provide the response and nothing else.
Or without using L'Hospital, you can do this: $$\lim _{ x\rightarrow 1 }{ \frac { \sqrt { x } +\sqrt [ 3 ]{ x } -2 }{ x-1 } } \quad =\quad \lim _{ x\rightarrow 1 }{ \frac { \sqrt { x } -1+\sqrt [ 3 ]{ x } -1 }{ x-1 } } \\ \qquad \qquad \qquad \qquad \qquad \quad =\quad \quad \lim _{ x\rightarrow 1 }{ \frac { \sqrt { x } -1 }{ x-1 } } +\frac { \sqrt [ 3 ]{ x } -1 }{ x-1 } \\ \qquad \qquad \qquad \qquad \qquad \quad =\quad \lim _{ x\rightarrow 1 }{ \frac { \sqrt { x } -1 }{ \left( \sqrt { x } -1 \right) \left( \sqrt { x } +1 \right) } } +\frac { \sqrt [ 3 ]{ x } -1 }{ \left( \sqrt [ 3 ]{ x } -1 \right) \left( \sqrt [ 3 ]{ x } +{ \left( \sqrt [ 3 ]{ x } \right) }^{ 2 }+1 \right) } \\ \qquad \qquad \qquad \qquad \qquad \quad =\quad \quad \lim _{ x\rightarrow 1 }{ \frac { 1 }{ \sqrt { x } +1 } } +\frac { 1 }{ \sqrt [ 3 ]{ x } +{ \left( \sqrt [ 3 ]{ x } \right) }^{ 2 }+1 } \\ \qquad \qquad \qquad \qquad \qquad \quad =\quad \frac { 1 }{ 2 } +\frac { 1 }{ 3 } \\ \qquad \qquad \qquad \qquad \qquad \quad =\quad \frac { 5 }{ 6 } $$ Identities used: $a^2-b^2 =(a-b)(a+b) $ $a^3-b^3 = (a-b)(a^2+ab+b^2)$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1393768', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/261200/']}
jdg_72019
stackexchange
llm_judgeable_groundtruth_similarity
34427146
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 you have the following command stored in a variable: COMMAND='echo hello' What's the difference between $ eval "$COMMAND"hello$ bash -c "$COMMAND"hello$ $COMMANDhello ? Why is the last version almost never used if it is shorter and (as far as I can see) does exactly the same thing? Now provide the response and nothing else.
The third form is not at all like the other two -- but to understand why, we need to go into the order of operations when bash in interpreting a command, and look at which of those are followed when each method is in use. Bash Parsing Stages Quote Processing Splitting Into Commands Special Operator Parsing Expansions Word Splitting Globbing Execution Using eval "$string" eval "$string" follows all the above steps starting from #1. Thus: Literal quotes within the string become syntactic quotes Special operators such as >() are processed Expansions such as $foo are honored Results of those expansions are split on characters into whitespace into separate words Those words are expanded as globs if they parse as same and have available matches, and finally the command is executed. Using sh -c "$string" ...performs the same as eval does, but in a new shell launched as a separate process ; thus, changes to variable state, current directory, etc. will expire when this new process exits. (Note, too, that that new shell may be a different interpreter supporting a different language; ie. sh -c "foo" will not support the same syntax that bash , ksh , zsh , etc. do). Using $string ...starts at step 5, "Word Splitting". What does this mean? Quotes are not honored. printf '%s\n' "two words" will thus parse as printf %s\n "two words" , as opposed to the usual/expected behavior of printf %s\n two words (with the quotes being consumed by the shell). Splitting into multiple commands (on ; s, & s, or similar) does not take place. Thus: s='echo foo && echo bar'$s ...will emit the following output: foo && echo bar ...instead of the following, which would otherwise be expected: foobar Special operators and expansions are not honored. No $(foo) , no $foo , no <(foo) , etc. Redirections are not honored. >foo or 2>&1 is just another word created by string-splitting, rather than a shell directive.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34427146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4077294/']}
jdg_72020
stackexchange
llm_judgeable_groundtruth_similarity
222721
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Given a permutation $\sigma\in S_n$, let $P_\sigma$ denote the corresponding $n\times n$ permutation matrix. It is easy to see that for $n=3$, there is only one linear relation up to scaling given by $\sum_\sigma sign(\sigma)P_\sigma = 0$. For larger $n$, what are all linear relations $\sum_\sigma c_\sigma P_\sigma=0$? Now provide the response and nothing else.
The standard permutation representation $\mathbb{C}^n$ of $S_n$ breaks up as a direct sum of a trivial representation $1$ and an irreducible representation $V$ of dimension $n - 1$. Hence the natural map $\mathbb{C}[S_n] \to \text{End}(\mathbb{C}^n)$ has image in $\text{End}(1) \oplus \text{End}(V)$. In fact, in terms of the Peter-Weyl decomposition $$\mathbb{C}[S_n] \cong \bigoplus_V \text{End}(V)$$ where $V$ runs over all complex irreps of $S_n$,the map above is precisely the projection onto the two summands given by $\text{End}(1)$ and $\text{End}(V)$. So the kernel of this projection consists of the summands $\text{End}(W)$ where $W$ is neither trivial nor isomorphic to $V$. Somewhat more explicitly, there is an element of the kernel for each matrix coefficient of $W$. For example, if $\chi_W$ is the character of $W$ then there are linear relations of the form $$\sum_{\sigma \in S_n} \overline{\chi}_W(\sigma) \sigma = 0$$ and when $n = 3$ this is the only relation, coming from the only irrep of $S_3$ not appearing in $\mathbb{C}^3$, namely the sign rep.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/222721', 'https://mathoverflow.net', 'https://mathoverflow.net/users/82376/']}
jdg_72021
stackexchange
llm_judgeable_groundtruth_similarity
531554
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 always read that Linux kernel isn't pageable. If I'm not mistaken Windows, instead, divedes system virtual memory ina paged part (paged pool) and non-paged part (non-paged pool). The non-paged part is mapped directly to physical memory and stay there all the time because takes care of the most important tasks kernel must accomplish, while less important portions may be not. Linux kernel,instead, is divided into laodable modules, but no information I managed to gather on how these modules are implemented. I don't understand if they're paged and thus you can temporarily transfer them to the disk. What I usually read is that we can "free" memory by unloading them, what is meant with this is still obscure to me. When I writed "paged" or "pageable" along this post, I implicitly meant that you can swap out on disk these pages. I addressed this because usually Linux kernel is considered paged but it can't be swapped out Now provide the response and nothing else.
No part of the Linux kernel can be paged out, even parts that come from modules. A kernel module can be loaded and (if the module supports it) can be unloaded. This always happens from an explicit request from a userland process with the init_module and delete_module system calls (normally, via the insmod or modprobe utilities for loading, and via rmmod for unloading). Once a module is loaded, it's part of the kernel, like any other part of the kernel. In particular, there's no way to isolate the memory used by a specific module. The kernel keeps tracks of which part of the memory contains a specific module's code, but not where a module may have stored data. A module can modify any of the kernel's data structures, after all. A module can potentially add some code to any kernel subsystem. Most modules are hardware drivers, but some aren't (e.g. they can provide security functionality, filesystems, networking functionality, etc.). If data or code used by a module could be swapped out, then the rest of the kernel would have to load it when required, which would complicate the design of the system a lot. The kernel would also need to ensure that no part of the memory that's swapped out is ever necessary to swap it back in, which is difficult. What if the swap is in a swap file on a network filesystem, and the module provides firewall functionality that is involved in communicating with the server that stores the file? It's possible to completely unload a module because it's the module's job to provide code that ensures that the module is not needed for anything. The kernel runs the module's exit function, and only unloads the module if that function reports that the module can be safely unloaded. The exit function must free any remaining data memory that is “owned” by the module (i.e. data that the module needs, but no other part of the kernel needs), and must verify that no code in the module is registered to be called when something happens. There's no way to save a module's data to swap: a module can only be removed from RAM if it has no data left.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/531554', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/215663/']}
jdg_72022
stackexchange
llm_judgeable_groundtruth_similarity
24682680
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 aspx page with an asp:GridView control that lists documents that have been uploaded pertaining to a legal case. The first column in the GridView is a series of href tags that, if clicked on, will open the document in the default program associated with that document type. The relative path to the document is stored in SQL Server. I use the DataBinder.Eval method to populate the path, which is then sent to a Javascript function that opens the document. By example, I have one document record whose path is DATA\AR000001\AttachFiles\Case11\2.txt. The markup for the anchor in the grid is as follows: <ItemTemplate> <a href="javascript:void(0);" onclick="ViewAttachFile('<%#Databinder.Eval(Container.DataItem, "FullAttchPath") %>');">Open</a> </ItemTemplate> The Javascript function is: function ViewAttachFile(sFile) { docs = window.open(sFile); } If I view the page source, the relative path looks exactly as I would expect: <a href="javascript:void(0);" onclick="ViewAttachFile('DATA\AR000001\AttachFiles\Case11\2.txt');">Open</a> Setting a breakpoint at ViewAttachFile, however, I find that the following is being passed to the function, note all backslashes and the document name have been stripped: DATAAR000001AttachFilesCase11.txt (this is from the text visualizer) I have tried embedding the escape and replace functions around the DataBinder.Eval call, but with no success, as Javascript is not my strong suit, not that I'm sure either of these would be the right solution anyway. I have also tried bypassing the ViewAttachFile function altogether, and coding the link as: <a href="javascript:void(0);" onclick="javascript:window.open('<%#Databinder.Eval(Container.DataItem, "FullAttchPath") %>');">Open</a> but that essentially yields the same result, as the backslashes are stripped out of the URL, the period is converted to %02 and the window opened returns a 400 error for Bad Request - Invalid URL. I supposed I could double-up on the slashes in the path column in the database, but that seems like a bad idea, and I'm hoping for a cleaner resolution. Any insight is greatly appreciated! Now provide the response and nothing else.
Ok so this is how I do, I don't pretend to strictly follow the best practices, but I focus on precision of my tests, clarity of my code, and fast execution of my suite. So let take example of a UserController 1- I do not use FactoryGirl to define the attributes to post to my controller, because I want to keep control of those attributes. FactoryGirl is useful to create record, but you always should set manually the data involved in the operation you are testing, it's better for readability and consistency. In this regard we will manually define the posted attributes let(:valid_update_attributes) { {first_name: 'updated_first_name', last_name: 'updated_last_name'} } 2- Then I define the attributes I expect for the updated record, it can be an exact copy of the posted attributes, but it can be that the controller do some extra work and we also want to test that. So let's say for our example that once our user updated his personal information our controller automatically add a need_admin_validation flag let(:expected_update_attributes) { valid_update_attributes.merge(need_admin_validation: true) } That's also where you can add assertion for attribute that must remain unchanged. Example with the field age , but it can be anything let(:expected_update_attributes) { valid_update_attributes.merge(age: 25, need_admin_validation: true) } 3- I define the action, in a let block. Together with the previous 2 let I find it makes my specs very readable. And it also make easy to write shared_examples let(:action) { patch :update, format: :js, id: record.id, user: valid_update_attributes } 4- (from that point everything is in shared example and custom rspec matchers in my projects) Time to create the original record, for that we can use FactoryGirl let!(:record) { FactoryGirl.create :user, :with_our_custom_traits, age: 25 } As you can see we manually set the value for age as we want to verify it did not change during the update action. Also, even if the factory already set the age to 25 I always overwrite it so my test won't break if I change the factory. Second thing to note: here we use let! with a bang. That is because sometimes you may want to test your controller's fail action, and the best way to do that is to stub valid? and return false. Once you stub valid? you can't create records for the same class anymore, therefor let! with a bang would create the record before the stub of valid? 5- The assertions itself (and finally the answer to your question) before { action }it { assert_record_values record.reload, expected_update_attributes is_expected.to redirect_to(record) expect(controller.notice).to eq('User was successfully updated.')} Summarize So adding all the above, this is how the spec looks like describe 'PATCH update' do let(:valid_update_attributes) { {first_name: 'updated_first_name', last_name: 'updated_last_name'} } let(:expected_update_attributes) { valid_update_attributes.merge(age: 25, need_admin_validation: true) } let(:action) { patch :update, format: :js, id: record.id, user: valid_update_attributes } let(:record) { FactoryGirl.create :user, :with_our_custom_traits, age: 25 } before { action } it { assert_record_values record.reload, expected_update_attributes is_expected.to redirect_to(record) expect(controller.notice).to eq('User was successfully updated.') }end assert_record_values is the helper that will make your rspec simpler. def assert_record_values(record, values) values.each do |field, value| record_value = record.send field record_value = record_value.to_s if (record_value.is_a? BigDecimal and value.is_a? String) or (record_value.is_a? Date and value.is_a? String) expect(record_value).to eq(value) endend As you can see with this simple helper when we expect for a BigDecimal , we can just write the following, and the helper do the rest let(:expected_update_attributes) { {latitude: '0.8137713195'} } So at the end, and to conclude, when you have written your shared_examples, helpers, and custom matchers, you can keep your specs super DRY. As soon as you start repeating the same thing in your controllers specs find how you can refactor this. It may take time at first, but when its done you can write the tests for a whole controller in few minutes And a last word (I can't stop, I love Rspec) here is how my full helper look like. It is usable for anything in fact, not just models. def assert_records_values(records, values) expect(records.length).to eq(values.count), "Expected <#{values.count}> number of records, got <#{records.count}>\n\nRecords:\n#{records.to_a}" records.each_with_index do |record, index| assert_record_values record, values[index], index: index endenddef assert_record_values(record, values, index: nil) values.each do |field, value| record_value = [field].flatten.inject(record) { |object, method| object.try :send, method } record_value = record_value.to_s if (record_value.is_a? BigDecimal and value.is_a? String) or (record_value.is_a? Date and value.is_a? String) expect_string_or_regexp record_value, value, "#{"(index #{index}) " if index}<#{field}> value expected to be <#{value.inspect}>. Got <#{record_value.inspect}>" endenddef expect_string_or_regexp(value, expected, message = nil) if expected.is_a? String expect(value).to eq(expected), message else expect(value).to match(expected), message endend
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24682680', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/430984/']}
jdg_72023
stackexchange
llm_judgeable_groundtruth_similarity
12774075
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 class is for a midterm assignment. It's a dynamic array that works like a vector. The problem is that when a new index is added to the array then the destructor is called(when the program ends) the program throws an exception and takes to a file called dgbheap.c. it happens when I delete origin only in the destructor. DynamicArray.h #ifndef DYNAMICARRAY_H#define DYNAMICARRAY_H #include <new> #include <cstdlib> using namespace std; template <class T> class DynamicArray { private: T *origin; T *allocator; int size; int current; public: DynamicArray(); DynamicArray(int); DynamicArray(const DynamicArray&); ~DynamicArray(); void add(int); void empty(); void remove(int); int getSize(); T &operator[](const int&); const T operator=(const DynamicArray&); void put(T&); void put(T); }; template <class T> DynamicArray<T>::DynamicArray() { origin = new T[5]; allocator = NULL; size = 5; current = 0; } template <class T> DynamicArray<T>::DynamicArray(int s) { size = s; try { origin = new T[s]; allocator = NULL; current = 0; } catch(bad_alloc) { cout << "Error: Bad memery allocation\n"; exit(EXIT_FAILURE); } } template <class T> DynamicArray<T>::DynamicArray(const DynamicArray& obj) { empty(); for(int counter = 0; counter < obj.size - 1; counter++) { origin[counter] = obj.origin[counter]; } } template <class T> DynamicArray<T>::~DynamicArray() { delete [] origin; delete [] allocator; } template <class T> void DynamicArray<T>::add(int size) { allocator = new T[size]; for(int counter = 0; counter < this-> size - 1; counter++) { allocator[counter] = origin[counter]; } delete [] origin; origin = new T[size]; this->size = this->size + size; for(int counter = 0; counter < this->size - 1; counter++) { origin[counter] = allocator[counter]; } allocator = NULL; } template <class T> void DynamicArray<T>::empty() { if(size >= 0) delete [] origin; } template <class T> int DynamicArray<T>::getSize() { return size; } template <class T> T &DynamicArray<T>::operator[](const int &index) { return origin[index]; } template <class T> const T DynamicArray<T>::operator=(const DynamicArray &obj) { size = obj.size; delete [] origin; origin = new T[size]; for(int counter = 0; counter < size; counter++) *(origin + counter) = *(obj.origin + counter); return *origin; } template <class T> void DynamicArray<T>::put(T &obj) { if(current == size - 1) { add(1); origin[size - 1] = obj; ++current; } else { origin[current] = obj; ++current; } } template <class T> void DynamicArray<T>::put(T obj) { if(current > size - 1) { add(1); origin[size - 1] = obj; ++current; } else { origin[current] = obj; ++current; } } template <class T> void DynamicArray<T>::remove(int location) { allocator = new T[size - 1]; int skipper = 0; for(int counter = 0; counter < size - 1; counter++, skipper++) { if(counter != location) allocator[counter] = origin[skipper] else if(counter == location) { ++skipper; allocator[counter] = origin[skipper] continue; } } } #endif // !DYNAMICARRAY_H main.cpp #include <iostream> #include <string> #include "DynamicArray.h" using namespace std; int main() { DynamicArray<int> a(5); a.put(21); a.put(22); a.put(30); a.put(58); a.put(87); a.put(87); cout << a[0] << endl; cout << a[1] << endl; cout << a[2] << endl; cout << a.getSize() << endl; system("pause"); return 0; } Now provide the response and nothing else.
You're trying to implement an object-oriented style of design. In Java, for example, you'd have a List<Renderable> and you'd be all set. This design style is a little bit less natural in Haskell; you need to create a wrapper type for a bounded existential as demonstrated on the Haskell wiki page for existential types . For example: class Renderable_ a where render :: a -> IO Stringdata Renderable = forall a. Renderable_ a => Renderable ainstance Renderable_ Renderable where render (Renderable a) = render a You can then have a list of Renderable , which you can render however you like. Like I said, though, that is sort of an OO style which is less natural in Haskell. You can probably avoid this by rethinking your data structures. You say that you "wanted to make how you represent pages extendable"; consider other ways of doing that instead. Unrelated: I'm guessing render doesn't need to produce an IO String action. Try to keep IO out of the core of your design, if you can.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12774075', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1721803/']}
jdg_72024
stackexchange
llm_judgeable_groundtruth_similarity
11036644
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 create a json object to send as a post array, but I need to create the key on the fly var id = $('#myInput').val();var post = { 'product[123]': 'myValue', // this works fine - but isn't dynamic 'product['+id+']': 'myValue' // this does not work} Sending it in as a string works fine, but I get an issue when I want to make it more dynamic. Am I missing something really simple here, or am I trying to do something Javascript isn't supposed to do? Now provide the response and nothing else.
(Note that this has nothing to do with JSON. You're not using JSON there, you're using an object initializer . JSON is a textual (not code) format, which is a subset of JavaScript's object initializer syntax.) Do it outside the object initializer, using [] notation: var id = $('#myInput').val();var post = {};post[product[id]] = 'myValue'; That will take the value (at runtime) of product[id] and use that as the key for the property. If you wanted the key to literally be product[123] when id is 123 , you'd use this instead: post['product[' + id + ']'] = 'myValue'; A more generic discussion: var a = "foo";var obj = {};obj[a] = "bar";console.log(obj.foo); // "bar" JavaScript allows you to specify property keys in two ways: Using dotted notation and a literal ( obj.foo ), or using bracketed notation and a string ( obj["foo"] ). In the latter case, the string doesn't have to be a string literal, it can be the result of any expression.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11036644', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/849836/']}
jdg_72025
stackexchange
llm_judgeable_groundtruth_similarity
6385695
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 guys i try to create a custom product from a module with this code : $defaultLanguage = new Language((int)(Configuration::get('PS_LANG_DEFAULT'))); /* Add a new product */$object = new Product();$object->price = 22;$object->id_tax_rules_group = 0;$object->name = 'test';$object->id_manufacturer = 0;$object->id_supplier = 0;$object->quantity = 1;$object->minimal_quantity = 1;$object->additional_shipping_cost = 0; $object->wholesale_price = 0;$object->ecotax = 0;$object->width = 0;$object->height = 0;$object->depth = 0;$object->weight = 0;$object->out_of_stock = 0;$object->active = 0;$object->id_category_default = 18;$object->category = 18;$object->available_for_order = 0;$object->show_price = 1;$object->on_sale = 0;$object->online_only = 1;$object->meta_keywords = 'test';if($object->save()) $object->add();echo "produit ajouté"; The code works fine, the product was added to the database but wasn't display in the back office, someone have an idea to solve this problem ? Now provide the response and nothing else.
The name and meta keyword field are both multi-language arrays. If you look at AdminImport.php in admin/tabs you'll find the definition for a function: private static function createMultiLangField($field) Copy this function into your module and you can use it to create a suitable array for these multi-language fields if you call it by passing your text as the $field parameter (it will set the value for all languages to the string you pass in). You should also set a default value for the description_short and link_rewrite fields: $object->description_short = array((int)(Configuration::get('PS_LANG_DEFAULT')) => ''); and $object->link_rewrite = array((int)(Configuration::get('PS_LANG_DEFAULT')) => ''); The second point is that although you've set the default category, you will also have to explicitly set id_category as an array e.g. $object->category=array(18); I also think you should then set the categories explicitly with: $object->updateCategories($object->category, true); It should then appear in the catalog.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6385695', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/616095/']}
jdg_72026
stackexchange
llm_judgeable_groundtruth_similarity
1941599
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: Events A and B are such that P(A)=0.7, P(B)=0.2, and P(A∩B)=0.2. Find P(A|B'). I found out that P(A u B) = 0.7, but I'm not sure how to work out the conditional probability - I've tried using the formula and I got P(A|B') = (0.7*0.8)/0.8, but that seems wrong. Now provide the response and nothing else.
$$P(A\mid B')=\frac{P(A\cap B')}{P(B')}=\frac{P(A)-P(A\cap B)}{1-P(B)}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1941599', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/369684/']}
jdg_72027
stackexchange
llm_judgeable_groundtruth_similarity
1326564
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need some clarifications about the correct way to solve an exercise. I have this function:$$f(x,y)=\frac{(x-1)y^2}{\sin^2\sqrt{(x-1)^2+y^2}}$$ and I have to analyse the existence of partial derivatives and the differentiability in (1,0) say if f is differentiable in (0,0) About point 1 :I have this doubt. Do I have to calculate the partial derivatives considering the expression of g(x,y) in (1,0) (i.e. g(1,0)=0 -> $\displaystyle {\partial f}/\partial x=\partial 0 / \partial x=0={\partial f}/\partial y $ (*) or do I have to use $\displaystyle\frac{\partial}{\partial x}g(1,0)=\lim_{t->0} \frac{f(1+t,0)-g(1,0)}{t}$ ? (**) Or do I have to find the expressions of the partial derivatives without using the limit and then do the limit for (x,y)->(1,0)? If I want to analyse if $\frac{\partial}{\partial x}g(1,0)$ is continue, do I have to compare (*) and (**)? About point 2 :If a function has continue partial derivatives in a point, it is differentiable in that point. So I have thought that in Dom f, the partial derivatives are continue because thay're composition of continue function. Since $0 \in Dom f$, g(x,y) is differentiable in (0,0). Is this reasoning ok, or do I have to check with calculation? Many thanks for your help! Now provide the response and nothing else.
$$32(x + 1) = y^2 \implies 32 \mid y^2 \implies 4 \mid y$$ so let $y = 4z$. $$2(x+1) = z^2 \implies 2 \mid z$$ so let $z = 2w$ $$x + 1 = 2w^2 $$ so given any $w$ we can solve for $x$. So the set of solutions is$$\{(2w^2 - 1, 8w) \mid w \in \Bbb Z\}$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1326564', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/39260/']}
jdg_72028
stackexchange
llm_judgeable_groundtruth_similarity
4220
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: On the Wikipedia page about naive Bayes classifiers , there is this line: $p(\mathrm{height}|\mathrm{male}) = 1.5789$ (A probability distribution over 1 is OK. It is the area under the bell curve that is equal to 1.) How can a value $>1$ be OK? I thought all probability values were expressed in the range $0 \leq p \leq 1$. Furthermore, given that it is possible to have such a value, how is that value obtained in the example shown on the page? Now provide the response and nothing else.
That Wiki page is abusing language by referring to this number as a probability. You are correct that it is not. It is actually a probability per foot . Specifically, the value of 1.5789 (for a height of 6 feet) implies that the probability of a height between, say, 5.99 and 6.01 feet is close to the following unitless value: $$1.5789\, [1/\text{foot}] \times (6.01 - 5.99)\, [\text{feet}] = 0.0316$$ This value must not exceed 1, as you know. (The small range of heights (0.02 in this example) is a crucial part of the probability apparatus. It is the "differential" of height, which I will abbreviate $d(\text{height})$.) Probabilities per unit of something are called densities by analogy to other densities, like mass per unit volume. Bona fide probability densities can have arbitrarily large values, even infinite ones. This example shows the probability density function for a Gamma distribution (with shape parameter of $3/2$ and scale of $1/5$). Because most of the density is less than $1$, the curve has to rise higher than $1$ in order to have a total area of $1$ as required for all probability distributions. This density (for a beta distribution with parameters $1/2, 1/10$) becomes infinite at $0$ and at $1$. The total area still is finite (and equals $1$)! The value of 1.5789 /foot is obtained in that example by estimating that the heights of males have a normal distribution with mean 5.855 feet and variance 3.50e-2 square feet. (This can be found in a previous table.) The square root of that variance is the standard deviation, 0.18717 feet. We re-express 6 feet as the number of SDs from the mean: $$z = (6 - 5.855) / 0.18717 = 0.7747$$ The division by the standard deviation produces a relation $$dz = d(\text{height})/0.18717$$ The Normal probability density, by definition, equals $$\frac{1}{\sqrt{2 \pi}}\exp(-z^2/2)dz = 0.29544\ d(\text{height}) / 0.18717 = 1.5789\ d(\text{height}).$$ (Actually, I cheated: I simply asked Excel to compute NORMDIST(6, 5.855, 0.18717, FALSE). But then I really did check it against the formula, just to be sure.) When we strip the essential differential $d(\text{height})$ from the formula only the number $1.5789$ remains, like the Cheshire Cat's smile. We, the readers, need to understand that the number has to be multiplied by a small difference in heights in order to produce a probability.
{}
{'log_upvote_score': 9, 'links': ['https://stats.stackexchange.com/questions/4220', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/226/']}
jdg_72029
stackexchange
llm_judgeable_groundtruth_similarity
132065
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 set up automatic (password less) ssh login to some servers using ssh-copy-id. ssh-agent works only from the terminal where it was run. How do I get ssh-add to work in all my terminals? Naturally, I would not prefer SSH key without a passphrase. Now provide the response and nothing else.
If you're logging into a graphical session, arrange to start ssh-agent during your session startup. Some distributions already do that for you. If yours doesn't, arrange to run ssh-agent from your session startup script or from your window manager. How you do that depends on your desktop environment and your window manager. For example, if you start your window manager manually, simply replace the call to my_favorite_wm by ssh-agent my_favorite_wm . Do not start ssh-agent from .bashrc or .zshrc , since these files are executed by each new interactive shell. The place to start ssh-agent is in a session startup file such as .profile or .xsession . If you want to use the same SSH agent on all processes no matter where you logged in from, you can make it always use the same socket name, instead of using a randomly-named socket. For example, you might put this in your ~/.profile : export SSH_AUTH_SOCK=~/.ssh/ssh-agent.$HOSTNAME.sockssh-add -l 2>/dev/null >/dev/nullif [ $? -ge 2 ]; then ssh-agent -a "$SSH_AUTH_SOCK" >/dev/nullfi
{}
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/132065', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/16448/']}
jdg_72030
stackexchange
llm_judgeable_groundtruth_similarity
958967
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 want to build a One-Liner to Get the Notes of a specific Distribution Group and output it alongside the Name and other information of the Distribution Group. I've googled it and found differed sources with all the same solutions.This is one of the Solutions I found: https://richgski.blogspot.com/2012/03/powershell-get-exchange-distribution.html Get-DistributionGroup Head-of-Operations | Select-Object Name, GroupType, ManagedBy, @{Name="Notes";Expression={(Get-Group $_).Notes}} However, the Row with the Notes will always stay blank, and I don't know why: Name GroupType ManagedBy Notes---- --------- --------- -----Head-of-Ops Universal {} When I do the following command separately: Get-Group Head-of-Ops | Select-Object Notes ... it's giving me the correct Note as Output: Notes-----Owner- Paul J. I little later I checked if I have the correct parameters, so I tried to do it this way: $Result = Get-DistributionGroup Head-of-OperationsGet-Group $Result.Name | Select-Object Notes It worked. Output: Notes-----Owner- Paul J. I made some changes to my command, but when I try it this way, it's still not working: Get-DistributionGroup Head-of-Operations | Select-Object Name,GroupType,ManagedBy,@{Name="Notes";Expression={(Get-Group $_.Name | Select-Object Notes)}} Output: Name GroupType ManagedBy Notes---- --------- --------- -----Head-of-Ops Universal {} After that, I found another Post to this Topic here: https://www.oxfordsbsguy.com/2014/04/21/exchange-powershell-how-to-enumerate-distribution-lists-managers-and-members/#comment-4452 So I made some changes to the command one more time... Get-DistributionGroup Head-of-Ops | Select-Object Name,GroupType,ManagedBy,@{Expression={(Get-Group $_.Name).Notes};Label="Notes"} ... still, nothing has changed at all. Output: Name GroupType ManagedBy Notes---- --------- --------- -----Head-of-Ops Universal {} I just don't get it :/ Does someone of you guys see the issue and can point me to it? Kind regards, Kevin van Thiel p.S.: I've run this command with the -verbose parameter now and I think I'm now one step closer to the solution.I think at some point it's just missing a parameter, but I don't know which one.This is the Code: (I've marked sensitive information with an * asterisk) Get-DistributionGroup Head-of-Ops@h***.com -Verbose | Select-Object Name,GroupType,ManagedBy,@{Name="Notes";Expression={(Get-Group $_.Name).Notes}} -VerboseVERBOSE: [16:04:28.885 GMT] Get-DistributionGroup : Active Directory session settings for 'Get-DistributionGroup' are: View Entire Forest: 'False', Default Scope: 'h***.de', Configuration Domain Controller: 'H***.h***.de',Preferred Global Catalog: '***.h***.h***.de', Preferred Domain Controllers: '{ ****.h***.h***.de, H***.h***.de }'VERBOSE: [16:04:28.916 GMT] Get-DistributionGroup : Runspace context: Executing user: h***.de/Companies/H***/D***/User/IT Service/****, Executing user organization: , Current organization: , RBAC-enabled: Enabled.VERBOSE: [16:04:28.916 GMT] Get-DistributionGroup : Beginning processing &VERBOSE: [16:04:28.932 GMT] Get-DistributionGroup : Current ScopeSet is: { Recipient Read Scope: {{, }}, Recipient Write Scopes: {{, }}, Configuration Read Scope: {{, }}, Configuration Write Scope(s): {{, }, }, Exclusive RecipientScope(s): {}, Exclusive Configuration Scope(s): {} }VERBOSE: [16:04:28.932 GMT] Get-DistributionGroup : Resolved current organization: .VERBOSE: [16:04:28.932 GMT] Get-DistributionGroup : Searching objects "Head-of-Ops@h***.com" of type "ADGroup" under the root "$null".VERBOSE: [16:04:28.932 GMT] Get-DistributionGroup : Previous operation run on domain controller 'H***.h***.de'.VERBOSE: [16:04:28.932 GMT] Get-DistributionGroup : Previous operation run on domain controller 'H***.h***.de'.VERBOSE: [16:04:28.932 GMT] Get-DistributionGroup : Preparing to output objects. The maximum size of the result set is "1000".VERBOSE: [16:04:28.947 GMT] Get-DistributionGroup : Ending processing &Name GroupType ManagedBy Notes---- --------- --------- -----Head-of-Ops Universal {} The following Line is the one where I think the issue is buried: VERBOSE: [16:04:28.932 GMT] Get-DistributionGroup : Searching objects "Head-of-Ops@h***.com" of type "ADGroup" under the root "$null". Anyone any idea what it's missing and why? Now provide the response and nothing else.
There are some unexpected things that occur when using if inside location blocks in NGINX. It's not recommended. Here is a solution that uses map . https://www.nginx.com/resources/wiki/start/topics/depth/ifisevil/ and https://agentzh.blogspot.com/2011/03/how-nginx-location-if-works.html This setup allows me to make requests to any subdomain and any port on my-domain.com and localhost (for development). map $http_origin $allow_origin { ~^https?://(.*\.)?my-domain.com(:\d+)?$ $http_origin; ~^https?://(.*\.)?localhost(:\d+)?$ $http_origin; default "";}server { listen 80 default_server; server_name _; add_header 'Access-Control-Allow-Origin' $allow_origin; # ...} http://nginx.org/en/docs/http/ngx_http_map_module.html
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/958967', 'https://serverfault.com', 'https://serverfault.com/users/515062/']}
jdg_72031
stackexchange
llm_judgeable_groundtruth_similarity
108357
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I had the following question when I am learning von Neumann algebras: Let p be a finite projection in a finite von Neumann algebra $M$, let $p>p_1>p_2>\cdots$ be a decreasing sequence of projections such that $p_i\neq p_{i+1}$. Is such a sequence necessarily of finite length? Any help or recommendations on books/papers are greatly appreciated. Now provide the response and nothing else.
The answer to your question is no . Abelian von Neumann algebras are finite, but it is easy to find examples of such algebras with infinite decreasing sequences of projections. For instance, one may take $M = L^\infty(\mathbb{R},\lambda)$ where $\lambda$ is the Lebesgue measure, and let $p_i \in M$ be the element corresponding to the characteristic function of $[0,\frac{1}{i}]$. Update: Now that you've seen some counterexamples, this might be a good follow-up "homework" problem for you (depending on how much you know about measure theory and abelian von Neumann algebras ): prove that a (finite) von Neumann algebra $M$ satisfies your descending chain condition on projections if and only if it is a finite dimensional algebra. (Hint: think about a type decomposition.)
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/108357', 'https://mathoverflow.net', 'https://mathoverflow.net/users/9858/']}
jdg_72032
stackexchange
llm_judgeable_groundtruth_similarity
29813592
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 function that will generate random values between 0 and 1 , inclusive. I have generated 120,000 random values by using rand() function in octave, but haven't once got the values 0 or 1 as output. Does rand() ever produce such values? If not, is there any other function I can use to achieve the desired result? Now provide the response and nothing else.
If you read the documentation of rand in both Octave and MATLAB , it is an open interval between (0,1) , so no, it shouldn't generate the numbers 0 or 1. However, you can perhaps generate a set of random integers , then normalize the values so that they lie between [0,1] . So perhaps use something like randi ( MATLAB docs , Octave docs ) where it generates integer values from 1 up to a given maximum. With this, define this maximum number, then subtract by 1 and divide by this offset maximum to get values between [0,1] inclusive: max_num = 10000; %// Define maximum numberN = 1000; %// Define size of vectorout = (randi(max_num, N, 1) - 1) / (max_num - 1); %// Output If you want this to act more like rand but including 0 and 1, make the max_num variable quite large.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29813592', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2510165/']}
jdg_72033
stackexchange
llm_judgeable_groundtruth_similarity
220254
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am making a hybrid Android app. At first I decided to use localStorage, after spending 2 days, I realized that it is very strange and so dropped it. Then, I picked up indexedDB, after spending today's whole day and actually getting the output in Google Chrome, it is not running inside a WebView of the android app. And I never used Web SQL database at all because it was deprecated. Anyhow, it has come to my notice that PhoneGap still uses Web SQL and android's browsers support it. Why was Web SQL deprecated in the first place? And will it be a good idea for me to go with Web SQL now? Now provide the response and nothing else.
Short version: Web SQL was deprecated because standards are really important and turning Web SQL into a proper standard would have been prohibitively difficult. Since existing implementations of Web SQL are basically wrappers around SQLite, any attempt to define a standard of it was basically "do what SQLite does." This isn't good enough; a true standard needs to be self-contained, to define the interface and corner cases and exceptions itself instead of pointing to an existing implementation (especially a third-party implementation like SQLite). Otherwise, you run the risk of taking one particular implementation's quirks and enshrining them as the standard. From what I've read, the W3C prefers multiple independent implementations of proposed standards to help ensure that this happens; since Web SQL was so tied to SQLite, that just wasn't going to happen. Mozilla's blog gives more details on their reasoning in particular for not supporting Web SQL; apparently they were one of the major voices in getting Web SQL deprecated. Should you go with Web SQL now? I don't expect the vendors that currently support it (like Google and Apple) to drop it any time soon, but IE and Firefox won't be adding it, and since it's deprecated, why invest in it? (For example, Ido Green , with Google Developer Relations, doesn't recommend using it.)
{}
{'log_upvote_score': 7, 'links': ['https://softwareengineering.stackexchange.com/questions/220254', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/-1/']}
jdg_72034
stackexchange
llm_judgeable_groundtruth_similarity
21196814
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 a program to input a number and output its factorial's prime factorization in the form: 4!=(2^3)*(3^1)5!=(2^3)*(3^1)*(5^1) The problem is I still can't figure out how to get that result. Apparently each first number in brackets is for the ascending prime numbers up until the actual factorial. The second number in brackets is the amount of times the number occurs in the factorial. What I can't figure out is for example in 5!=(2^3)*(3^1)*(5^1) , how does 2 only occur 3 times, 3 only 1 time and 5 only one time in 120 (5!=120). I have now solved this thanks to the helpful people who commented but I'm now having trouble trying to figure out how could I take a number and get the factorial in this format without actually calculating the factorial. Now provide the response and nothing else.
Every number can be represented by a unique (up to re-ordering) multiplication of prime numbers, called the prime factorization of the number, as you are finding the prime factors that can uniquely create that number. 2^3=8 3^1=3 5^1=5 and 8*3*5=120 But this also means that: (2^3)*(3^1)*(5^1) = 120 It's not saying that 2 occurs 3 times as a digit in the number 120, which it obviously does not, but rather to multiply 2 by 2 by 2, for a total of 3 twos. Likewise for the 3 and 5, which occur once in the prime factorization of 120. The expression which you mention is showing you this unique prime factorization of the number 120. This is one way of getting the prime factorization of a number in Python: def pf(number): factors=[] d=2 while(number>1): while(number%d==0): factors.append(d) number=number/d d+=1 return factors Running it you get: >>> pf(120)[2, 2, 2, 3, 5] Which multiplied together give you 120, as explained above. Here's a little diagram to illustrate this more clearly:
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21196814', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3015991/']}
jdg_72035
stackexchange
llm_judgeable_groundtruth_similarity
26535415
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For watching an object scope variable, is $scope.$watch with objectEquality set to true OR $scope.$watchCollection better? For a $scope object variable (like 15 attributes, some nested 2 levels deep) updated with input elements and ng-model in the view, how bad is $scope.$watch with objectEquality set to true ? Is this a big thing to avoid? Is $watchCollection a better solution? I am looking for easy wins to improve performance on my AngularJS App (I'm still stuck on v1.2.2). // ctrl scope var $scope.filters = { name: '', info: {test: '', foo: '', bar: ''}, yep: '' // etc ... } // ctrl watch ? $scope.$watch('filters', function(newVal, oldVal) { if(newVal !== oldVal) { // call with updated filters } }, true); // or ctrl watch collection ? $scope.$watchCollection('filters', function(newVal, oldVal) { if(newVal !== oldVal) { // call with updated filters } }); // view input with ng-model <input type="text" ng-model="filters.name" /> <input type="text" ng-model="filters.info.test" /> <input type="text" ng-model="filters.yep" /> // etc ... Now provide the response and nothing else.
$watch() will be triggered by: $scope.myArray = [];$scope.myArray = null;$scope.myArray = someOtherArray; $watchCollection() will be triggered by everything above AND: $scope.myArray.push({}); // add element$scope.myArray.splice(0, 1); // remove element$scope.myArray[0] = {}; // assign index to different value $watch(..., true) will be triggered by EVERYTHING above AND: $scope.myArray[0].someProperty = "someValue"; JUST ONE MORE THING... $watch() is the only one that fires when an array is replaced with another with the same exact content. For example: $scope.myArray = ["Apples", "Bananas", "Orange" ];var newArray = [];newArray.push("Apples");newArray.push("Bananas");newArray.push("Orange");$scope.myArray = newArray; Below is a link to an example JSFiddle that uses all the different watch combinations and outputs log messages to indicate which "watches" were triggered: http://jsfiddle.net/luisperezphd/2zj9k872/
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/26535415', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2905173/']}
jdg_72036
stackexchange
llm_judgeable_groundtruth_similarity
59393369
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: coming from a primarily python background I have somewhat struggled with working with types in C++. I am attempting to initialise a class variable via one of several overloaded constructors that take different types as parameters. I have read that using the auto keyword can be used for auto declaration of a variable, however in my case it will not be initialised till a constructor is chosen. However the compiler is not happy about not initialising value . class Token {public: auto value; Token(int ivalue) { value = ivalue; } Token(float fvalue) { value = fvalue; } Token(std::string svalue) { value = svalue; } void printValue() { std::cout << "The token value is: " << value << std::endl; }}; In python this might look like: class Token(): def __init__(self, value): self.value = value def printValue(self): print("The token value is: %s" % self.value) What is the right way of using the auto keyword in this scenario? Should I use a different approach altogether? Now provide the response and nothing else.
Initialising a variable of unknown type via overloaded constructors in C++ There is no such thing as "variable of unknown type" in C++. What is the right way of using the auto keyword in this scenario? auto-deduced variables have a type that is deduced from the initialiser. If there is no initialiser, then you cannot use auto. auto cannot be used for a non-static member variable. One instance of a class cannot have differently typed members than another instance. There is no way of using auto keyword in this scenario. Should I use a different approach altogether? Probably. It looks like you're trying to implement a std::variant . If you need a variable to store one of X number of types, that is what you should use. However, you may be trying to emulate dynamic typing in C++. While it may be familiar to you due to experience with Python, in many cases that is not the ideal approach. For instance, in this particular example program, all that you do with the member variable is print it. So it would be simpler to store a string in each case. Other approaches are static polymorphism as shown by Rhathin or OOP style dynamic polymorphism as shown by Fire Lancer.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59393369', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4126814/']}
jdg_72037
stackexchange
llm_judgeable_groundtruth_similarity
14483837
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: May be a silly question, but does anybody know how to specify the output filename of a VSTEST.Console.exe run? My command line is as follows: vstest.console.exe [assembly] /logger:trx At the end of the run, the following comes up in the console: ResultsFile: somepath\TestResults\{username}_{workstation} {timestamp}.trx I tried using the .runsettings file to specify the output location, but that only seems to control the output directory, but not the output file. Have not found anything else that would seem to control it. I want to parse the TRX file and generate a report out of it (this already works, but if I can't specify the output path of the TRX file, I won't know where to pick it up from in the scripts!) I have to be missing something here... Now provide the response and nothing else.
EDIT: See @AnaFranco's answer - apparently since VS2017 the file name can be configured like so: vstest.console.exe [assembly] /logger:trx;LogFileName=[filename].trx I'll leave the old answer for posterity and pre-2017 versions. Nope, you're not missing anything. The TRX logger doesn't support any parameters (unlike the TFS publisher logger). The logger assembly is located in "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\CommonExtensions\Microsoft\TestWindow\Extensions\Microsoft.VisualStudio.TestPlatform.Extensions.TrxLogger.dll" . If you check it out in your favorite .NET decompiler, you'll see the method TrxLogger.GetTrxFileName . It uses some basic knowledge about the current test run to produce the mangled name of form {username}_{workstation} {timestamp}.trx and is in no appreciable way configurable. As far as I can tell, the TRX file is created in the TestResults\ folder under the current working directory unless otherwise configured. What you can do is: Create a new temporary folder Change the current directory to it Run the test runner Scan the folder for the result .trx file using your favorite recursive file search method and you're done At least that is what I do in our build (MSBuild, sob): <ItemGroup> <TestResult Include="**\*.trx"/></ItemGroup> I.e, gather all .trx files under the current directory and stuff them into the @(TestResult) item group for further processing.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14483837', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1169863/']}
jdg_72038
stackexchange
llm_judgeable_groundtruth_similarity
758410
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've got two AD virtual machines runnning on HyperV. AD1(PDC) syncs its time with pool.ntp.org and AD2(BDC) syncs with AD1 to get the time correct. Both are windows server 2008 servers. This worked fine for a while, but lately servers seem to drop out from AD1 and authenticate with AD2 instead, even though AD1 is up and running. I've tried to shut down AD2 and restart all servers on the domain to force them to authenticate to AD1 which works fine. But whenever I put AD2 on the network again servers will still auth to AD2 on reboot. This behavior is unknown to me and I'm having a hard time troubleshooting the issue. Now provide the response and nothing else.
This doesn't have anything to do with time synchronization. Your time sync configuration appears to be correct from what you've stated in your question. The DC that holds the PDCe role should sync with a reliable external time source. All other domain members should sync with the domain hierarchy. This includes all other Domain Controllers. Stop calling them PDC and BDC. That terminology is no longer valid and is a hint that you're not exactly up to snuff in your understanding of AD. AD uses a Multiple-Master model (referred to as Flexible Single Master Operations or FSMO), which you can read about at this link. - https://support.microsoft.com/en-us/kb/197132 Your domain clients are behaving exactly as expected. An AD domain client can authenticate to any available Domain Controller. You should neither try to control that behavior nor discourage it. The fact that you see this as a problem that needs to be solved is another clue that you really don't have a good understanding of AD. It might serve you to do some in depth reading on the subject.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/758410', 'https://serverfault.com', 'https://serverfault.com/users/272028/']}
jdg_72039
stackexchange
llm_judgeable_groundtruth_similarity
17719
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: Suppose I have a few lists of numbers and want to exponentiate element-wise, then sum up everything into a polynomial. For example, if I have a = {1,2,3}b = {2,4,6}c = {3,2,1} I would like to get poly = xy^2z^3 + x^2y^4z^6 + x^3y^2z Unfortunately, I am not too familiar with the functional programming style Mathematica is intended to be used for, and I can only write something like For[i = 1, i < Length[a] + 1, i++, term = x^Part[a, i]*y^Part[b, i]*z^Part[c, i];poly = poly + term;] As you may expect, this is taking quite a long time to evaluate. Would anybody have any thoughts as to how I would rewrite this to make it more efficient? Now provide the response and nothing else.
You can take advantage of listability . As a rule if a function has the Listable attribute listable operations will be faster than other alternatives such as mapping. {a, b, c} = Transpose[{a, b, c}];Apply[Plus, x^a*y^b*z^c] or {a, b, c} = Transpose[{a, b, c}];Total[x^a*y^b*z^c]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/17719', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5392/']}
jdg_72040