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
|
214092
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I just read the Wikipedia article on mock objects , but I'm still not entirely clear on their purpose. It appears they are objects that are created by a test framework when the actual object would be too complex or unpredictable (you know 100% sure what the values of the mock object are because you fully control them). However, I was under the impression that all testing is done with objects of known values, so I must be missing something. For example, in a course project, we were tasked with a calendar application. Our test suite consisted of event objects that we knew exactly what they were so we could test the interactions between multiple event objects, various subsystems, and the user interface. I'm guessing these are mock objects, but I don't know why you wouldn't do this because without the objects of known values, you can't test a system.
Now provide the response and nothing else.
|
A mock object is not just an object with known values. It is an object that has the same interface as a complex object that you cannot use in test (like a database connection and result sets), but with an implementation that you can control in your test. There are mocking frameworks that allow you to create these objects on the fly and in essence allow you to say something like: Make me an object with a method foo that takes an int and returns a bool. When I pass 0, it should return true. Then you can test the code that uses foo(), to make sure it reacts appropriately. Martin Fowler has a great article on mocking: http://martinfowler.com/articles/mocksArentStubs.html
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/214092', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/572/']}
|
jdg_370841
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
275954
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
It's a very basic (may be a trivial) question but what is the exact difference, if any, between Heine Borel Theorem and Bolzano Weierstrass Theorem. It is true that one (Heine Borel) can be proved from another (Bolzano Weierstrass ). Heine Borel Theorem : Subspace of $\mathbb{R}^n$ is compact iff it is closed and bounded. Bolzano Weierstrass Theorem : Every bounded sequence in $\mathbb{R}^n$ has a convergent subsequence.
Now provide the response and nothing else.
|
One answer is that the Bolzano-Weierstrass theorem says that every closed, bounded set in $\Bbb R^n$ is sequentially compact , while the Heine-Borel theorem says that every closed, bounded set in $\Bbb R^n$ is compact . (The Heine-Borel theorem also asserts the converse, of course.) In general the notions of compactness and sequential compactness are distinct. Here is an example (with proof) of a compact Hausdorff space that is not sequentially compact, and here , also with proof, is an example of a sequentially compact Hausdorff space that is not compact. However, in metric spaces the two notions of compactness coincide, so in $\Bbb R^n$ the Bolzano-Weierstrass theorem can be thought of as one direction of the Heine-Borel theorem.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/275954', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/45100/']}
|
jdg_370842
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13671178
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Foo looks has this in it : @ManyToManyprivate Set<User> favouritedBy; while user has this: @ManyToMany(mappedBy = "favouritedBy")private Set<Foo> favourites = new HashSet<Foo>();public Set<Foo> getFavourites() { return favourite;} And fooService has this, with the lazyloaded collection being accessed while session is opened, via the tranactional method : @Transactional(readOnly = true)public Set<Foo> getFavourites(User user) {user = dao.get(User.class, user.getId()); //the dao gets a sessionSet<Foo> favourites = user.getFavourites();//but the session is not here and the exception is thrown?return favourties;} EDIT This fixes it, without using criteria : Set<Foo> favourites = new HashSet<Foo>(user.getFavourites()); and this fixes it with criteria Session session = sessionFactory.getCurrentSession();final Criteria crit = session.createCriteria(Foo.class);crit.setFetchMode("favourites", FetchMode.JOIN);crit.add(Property.forName("id").eq(id));return (Foo) crit.uniqueResult();
Now provide the response and nothing else.
|
The default FetchType in a ManyToMany is LAZY and the hibernate documentation for working with lazy associations clearly calls out this kind of access as an error. You can interact with lazily associated objects only while the session is still open. That portion of the documentation also provides alternatives to access such lazily associated members of an object . We prefer to specify the fetch mode as JOIN in the criteria used, in our applications Edit : Set<Foo> favourites = user.getFavourites(); The above statement doesn't actually return a set that contains all the Foo objects. It is just a proxy. The actual Foo objects are fetched only when the elements in the set are accessed like favorites.iterator() etc., This operation is clearly happening outside your getFavorites() method. But the @Transactional annotation on the getFavorites() method indicates that the session will be closed at the end of this method. So, when methods are called on the favourites set, the session is already closed and hence the exception. To address this, you should use a Criteria object to retrieve the user and specify the fetch type as JOIN so that the Foo objects are populated in the User object returned.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13671178', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/106261/']}
|
jdg_370843
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13401789
|
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 logback.xml configuration: <configuration> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder by default --> <encoder> <pattern>%-4relative [%thread] %-5level %logger{35} - %msg %n</pattern> </encoder> </appender> <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender"> <file>logFile.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <!-- daily rollover --> <fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern> <!-- keep 30 days' worth of history --> <maxHistory>30</maxHistory> </rollingPolicy> <encoder> <pattern>%-4relative [%thread] %highlight(%-5level) %cyan(%logger{35}) - %msg%n</pattern> </encoder> </appender> <root level="DEBUG"> <appender-ref ref="STDOUT" /> <appender-ref ref="FILE" /> </root></configuration> If I edit the config file in eclipse (Juno), I get the following error: 11:02:54,114 INFO [main] Main - javax.xml.transform.TransformerFactory=null11:02:54,115 INFO [main] Main - java.endorsed.dirs=C:\Program Files\Java\jre7\lib\endorsed11:02:54,117 INFO [main] Main - launchFile: C:\Users\roberth\Programming_Projects\eclipse\.metadata\.plugins\org.eclipse.wst.xsl.jaxp.launching\launch\launch.xml11:02:54,145 FATAL [main] Main - No embedded stylesheet instruction for file: file:/C:/Users/roberth/Programming_Projects/eclipse/javaport/src/logback.xmlorg.eclipse.wst.xsl.jaxp.debug.invoker.TransformationException: No embedded stylesheet instruction for file: file:/C:/Users/roberth/Programming_Projects/eclipse/javaport/src/logback.xml at org.eclipse.wst.xsl.jaxp.debug.invoker.internal.JAXPSAXProcessorInvoker.transform(JAXPSAXProcessorInvoker.java:225) at org.eclipse.wst.xsl.jaxp.debug.invoker.internal.JAXPSAXProcessorInvoker.transform(JAXPSAXProcessorInvoker.java:186) at org.eclipse.wst.xsl.jaxp.debug.invoker.internal.Main.main(Main.java:73)Caused by: org.eclipse.wst.xsl.jaxp.debug.invoker.TransformationException: No embedded stylesheet instruction for file: file:/C:/Users/roberth/Programming_Projects/eclipse/javaport/src/logback.xml at org.eclipse.wst.xsl.jaxp.debug.invoker.internal.JAXPSAXProcessorInvoker.transform(JAXPSAXProcessorInvoker.java:214) ... 2 more If I delete and recreate the config, sometimes it works, sometimes not. If I edit the file in Notepad++ or another text editor, it works fine. Is this an eclipse issue or am I missing something?
Now provide the response and nothing else.
|
It's an Eclipse bug, I've noticed it too. Make sure that you're running the right Eclipse Runtime config (i.e. if you're clicking on the little green "Play" button on the top, thinking it will re-run the last (valid) Runtime you've ran, re-check (by clicking on the down arrow next to it) to make sure no new Runtime has been created). What I've noticed it that even though I create a perfectly valid run-time pointing to a Java main class and everything, which I run a few times and all is good, after a while, if I select an xml file (because I wanted to edit it for example) and then leave it selected as I click on my run button, Eclipse will create a new XSLT Transformation run time for that xml file and try to run it, failing with the exception you report. The solution is to erase that run time, make sure I have no xml file selected, and re-run the correct run time.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13401789', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1245240/']}
|
jdg_370844
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13615
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Suppose we have a torus action on a compact oriented manifold M. Assume the action has isolated fixed points. Why is it that the equivariant Euler class of the normal bundle at the fixed point (i.e. the tangent space at that point) is (upto a sign) the product of the weights of the action of the lie algebra of the Torus on the tangent space at that point? (Maybe this is obvious but I don't see it).
Now provide the response and nothing else.
|
I'm interpreting your question as "In what sense is the equivariant Euler class of a torus representation, thought of as a vector bundle on the point, just the product of the weights of the representation?" Because Euler classes multiply under direct sum, it's enough to answer this question for a 1-d representation. Now, it's a general principle that if a space is nice in some sense, there will be a bijections between complex line bundles on that space and $H^2(X;\mathbb{Z})$ via first Chern class. One way to think of this correspondence is that a line bundle is defined by an element of $H^1(X;\mathcal{O}^*)$ where $\mathcal{O}^*$ is the nonvanishing elements of whatever sheaf of functions is relevant. As long as the sheaf cohomology of $\mathcal{O}$ is boring, the boundary map in the long exact sequence for the exponential sequence $\mathbb{Z}\to \mathcal{O}\to\mathcal{O}^*$ induces this isomorphism. So, now what does this mean equivariantly? Well, remember that equivariant cohomology is the cohomology of a space. In the case of a point, it is the cohomology of the classifying space $BT$. On the other hand, a line bundle on $BT$ is the same thing as a 1-dimensional representation of $T$; you use the standard associated bundle construction. So, by the argument above, we get an identification between characters of $T$ and $H^2_T(pt;\mathbb{Z})$. This is being used implicitly when you make a statement like "the equivariant Euler class of the normal bundle at the fixed point (i.e. the tangent space at that point) is (upto a sign) the product of the weights of the action of the lie algebra of the Torus on the tangent space at that point," but having fixed this isomorphism, the statement above becomes tautological.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/13615', 'https://mathoverflow.net', 'https://mathoverflow.net/users/3709/']}
|
jdg_370845
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
44920094
|
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 list of dictionaries like the following: lst = [{'a': 5}, {'b': 6}, {'c': 7}, {'d': 8}] I wrote a generator expression like: next((itm for itm in lst if itm['a']==5)) Now the strange part is that though this works for the key value pair of 'a' it throws an error for all other expressions the next time.Expression: next((itm for itm in lst if itm['b']==6)) Error: Traceback (most recent call last):File "<stdin>", line 1, in <module>File "<stdin>", line 1, in <genexpr>KeyError: 'b'
Now provide the response and nothing else.
|
That's not weird. For every itm in the lst . It will first evaluate the filter clause . Now if the filter clause is itm['b'] == 6 , it will thus try to fetch the 'b' key from that dictionary. But since the first dictionary has no such key, it will raise an error. For the first filter example, that is not a problem, since the first dictionary has an 'a' key. The next(..) is only interested in the first element emitted by the generator. So it never asks to filter more elements. You can use .get(..) here to make the lookup more failsafe: next((itm for itm in lst if itm .get('b',None) ==6)) In case the dictionary has no such key, the .get(..) part will return None . And since None is not equal to 6, the filter will thus omit the first dictionary and look further for another match. Note that if you do not specify a default value , None is the default value, so an equivalent statement is: next((itm for itm in lst if itm.get('b')==6)) We can also omit the parenthesis of the generator: only if there are multiple arguments, we need these additional parenthesis: next(itm for itm in lst if itm.get('b')==6)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44920094', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3274313/']}
|
jdg_370846
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6430154
|
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 pass-through vertex and fragment shaders. vertex shader void main(void){ gl_TexCoord[0] = gl_MultiTexCoord0; gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;} fragment shader void main(void){ gl_FragColor = gl_Color;} Those produce empty rendering (black not background color like glClearBuffer does). If I modify the vertex shader to set the gl_FrontColor to gl_Color it does render untouched OpenGl buffer ... with is the expected behavior of pass-through shaders. void main(void){ gl_FrontColor = gl_Color; //Added line gl_TexCoord[0] = gl_MultiTexCoord0; gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;} I am confused, how settings the gl_FrontColor in the vertex shader can change the value of the gl_Color in the fragment one ? What I am missing ?
Now provide the response and nothing else.
|
gl_Color means different things in different places. In the vertex shader, gl_Color represents the primary per-vertex color attribute passed by the user. This is set using glColor* calls or array data fetched by glColorPointer . In the fragment shader, gl_Color represents the interpolated color for the facing of the triangle being rendered. Remember that triangles have a front-face and a back-face. If you enable face culling, then all faces of one kind or the other (or both) are not rendered. However, if you turn off face culling, then both sides are rendered. It is often useful to have different per-vertex output values based on the particular facing of the triangle. The primary color has a front color and a back color, representing the color for front-facing triangles and back-facing triangles. The vertex shader outputs for these are gl_FrontColor and gl_BackColor . If you are doing two-sided rendering, you will need to set both of these values in order for the fragment shader's gl_Color input to mean anything. If you are only doing front-face rendering, then you only need to set gl_FrontColor .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6430154', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/659003/']}
|
jdg_370847
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28641165
|
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 center a path vertically within an SVG element? This is one of the paths I need to center: <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 144 144"><path d="M127.782 40.348H15.802c-3.813 0-6.912 3.002-6.912 6.766v14.113c0 3.235 1.52 6.11 3.953 7.92h-.012s52.9 35.873 53.09 36c1.56.978 3.82 1.886 5.82 1.886 2.21 0 4.25-.71 5.9-1.886l52.54-35.675c2.69-1.78 4.494-4.81 4.494-8.246V47.194c0-3.772-3.07-6.846-6.885-6.846zm-38.05 29.864c-.066 1.966-.685 3.392-2.68 3.392H64.744c0 4.482 4.56 6.735 8.77 6.735 7.825 0 9.407-4.4 12.117-3.34 1.49.58 2.14 1.62 2.11 3.62-.08 4.48-5.292 7.864-14.94 7.864-11.637 0-19-6.573-19-17.353 0-10.31 7.63-17.88 18.184-17.88 10.465 0 17.757 7.04 17.757 16.74v.215zm-17.91-8.494c-3.434 0-6.28 2.284-6.695 5.597h13.47c-.068-3.45-3.116-5.597-6.776-5.597zm-.087 53.697c-3.328-.038-6.947-1.51-8.567-2.805L8.86 75.7v52.492c0 3.764 3.065 6.808 6.88 6.808h111.983c3.824 0 6.944-3.044 6.944-6.808v-52.49L80.53 112.61c-2.586 1.832-5.636 2.84-8.795 2.805z"/></svg>
Now provide the response and nothing else.
|
If you mean automatically, without intervention, then no. However you can add a transform to the path to centre it in the SVG. The bounding box for the path is: { x: 8.859999656677246, y: 40.347999572753906, width: 125.81500244140625, height: 94.6520004272461} The height of the document is 144, so the y should actually be at: (144 - 94.652) / 2 = 24.674 So the y position of the path has to be adjusted by: (24.674 - 40.348) = -15.674 So add the following attribute to the path element: transform="translate(0, -15.674)" Demo before and after: <svg xmlns="http://www.w3.org/2000/svg" width="300" height="300" viewBox="0 0 144 144" style="background-color: gray"><path d="M127.782 40.348H15.802c-3.813 0-6.912 3.002-6.912 6.766v14.113c0 3.235 1.52 6.11 3.953 7.92h-.012s52.9 35.873 53.09 36c1.56.978 3.82 1.886 5.82 1.886 2.21 0 4.25-.71 5.9-1.886l52.54-35.675c2.69-1.78 4.494-4.81 4.494-8.246V47.194c0-3.772-3.07-6.846-6.885-6.846zm-38.05 29.864c-.066 1.966-.685 3.392-2.68 3.392H64.744c0 4.482 4.56 6.735 8.77 6.735 7.825 0 9.407-4.4 12.117-3.34 1.49.58 2.14 1.62 2.11 3.62-.08 4.48-5.292 7.864-14.94 7.864-11.637 0-19-6.573-19-17.353 0-10.31 7.63-17.88 18.184-17.88 10.465 0 17.757 7.04 17.757 16.74v.215zm-17.91-8.494c-3.434 0-6.28 2.284-6.695 5.597h13.47c-.068-3.45-3.116-5.597-6.776-5.597zm-.087 53.697c-3.328-.038-6.947-1.51-8.567-2.805L8.86 75.7v52.492c0 3.764 3.065 6.808 6.88 6.808h111.983c3.824 0 6.944-3.044 6.944-6.808v-52.49L80.53 112.61c-2.586 1.832-5.636 2.84-8.795 2.805z"/></svg><svg xmlns="http://www.w3.org/2000/svg" width="300" height="300" viewBox="0 0 144 144" style="background-color: gray"> <path transform="translate(0, -15.674)" d="M127.782 40.348H15.802c-3.813 0-6.912 3.002-6.912 6.766v14.113c0 3.235 1.52 6.11 3.953 7.92h-.012s52.9 35.873 53.09 36c1.56.978 3.82 1.886 5.82 1.886 2.21 0 4.25-.71 5.9-1.886l52.54-35.675c2.69-1.78 4.494-4.81 4.494-8.246V47.194c0-3.772-3.07-6.846-6.885-6.846zm-38.05 29.864c-.066 1.966-.685 3.392-2.68 3.392H64.744c0 4.482 4.56 6.735 8.77 6.735 7.825 0 9.407-4.4 12.117-3.34 1.49.58 2.14 1.62 2.11 3.62-.08 4.48-5.292 7.864-14.94 7.864-11.637 0-19-6.573-19-17.353 0-10.31 7.63-17.88 18.184-17.88 10.465 0 17.757 7.04 17.757 16.74v.215zm-17.91-8.494c-3.434 0-6.28 2.284-6.695 5.597h13.47c-.068-3.45-3.116-5.597-6.776-5.597zm-.087 53.697c-3.328-.038-6.947-1.51-8.567-2.805L8.86 75.7v52.492c0 3.764 3.065 6.808 6.88 6.808h111.983c3.824 0 6.944-3.044 6.944-6.808v-52.49L80.53 112.61c-2.586 1.832-5.636 2.84-8.795 2.805z"/></svg>
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28641165', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1363751/']}
|
jdg_370848
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
40319
|
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:
Using the notation in the Wikipedia article on the hypergeometric distribution , I'm curious how one would obtain the maximum likelihood estimate for parameter $m$ , the number of white marbles, given $T$ trials from the same urn. For convenience, I'll copy/paste the notation from the article: Suppose you are to draw $n$ marbles without replacement from an urn containing $N$ marbles in total, $m$ of which are white. The hypergeometric distribution describes the distribution of the number of white marbles drawn from the urn, $k$ . Again, assuming I conduct $T$ trials, at each trial, I take $n$ balls from the urn, and $k_i$ is the number of white balls at trial $i$ . Define $K = (k_1,\ldots,k_T)$ . Then the likelihood function $L$ : $$L(m; K, N, n) = \prod_i^T \frac{\binom{m}{k_i}\binom{N-m}{n-k_i}}{\binom{N}{n}}$$ Taking a hint from this post , I first tried to solve the inequality: $$L(m;K,N,n) \geq L(m-1;K,N,n)$$ when $T=1$ . From this I obtained $$m \leq \frac{Nk+k}{n}$$ so the MLE should be $$m = \left\lfloor \frac{Nk+k}{n} \right\rfloor$$ Now, I'm stuck when I try to generalize to $T \geq 2$ . I first tried doing the same as above and I ended up with the following unwieldy inequality: $$\prod_i^T \frac{m}{m-k_i} \geq \prod_i^T \frac{N-m+1}{N-m-n+k_i+1}$$ which I'm not sure how to solve. Then I tried to take the log of the likelihood and differentiate as if $m$ were defined over positive reals and I ended up with an equally unwieldy equation to solve: $$\sum_i^T \left(\Psi(m+1) - \Psi(m-k_i+1) - \Psi(N-m+1) + \Psi(N-m-n+k_i+1)\right) = 0$$ where $\Psi$ is the digamma function (i.e. the derivative of the log-gamma function). My intuition tells me the solution to either of the above would look something like this: $$m = \left\lfloor \frac{(N+1)\sum_i^T k_i}{Tn} \right\rfloor$$ but I have no idea how to get here. The motivation for this problem is pure curiosity, since I've never seen a MLE for the hypergeometric distribution in terms of $m$ .
Now provide the response and nothing else.
|
Here is an approximate solution. The Poisson approximation to the hypergeometric disribution valid for $\frac{m}{N}<<1$ and $n>>1$, has the form: $P(K = k|n, M, N) = \frac{exp(-\frac{nm}{N}) (\frac{nm}{N})^k}{k!}$ The likelihood function becomes $L(m;n,N) = \frac{exp(-\frac{Tnm}{N}) (\frac{nm}{N})^{\sum_i^T k_i}}{\prod_i^T k_i!}$ which can be easily solved to obtain: $ m = \frac{N\sum_i^T k_i}{Tn} $
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/40319', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/6690/']}
|
jdg_370849
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
49088957
|
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 use vuejs in my fresh laravel setup. I run the follwing commands in my command line npm installnpm run dev This commands runs without any errors. When I import the default VUE componet located under ~/ressources/assets/components/ExampleComponent.vue in my template nothing happends. @section('content') <example-component></example-component>@endsection Here the app.js require('./bootstrap');window.Vue = require('vue');Vue.component('example-component', require('./components/ExampleComponent.vue'));const app = new Vue({ el: '#app'});
Now provide the response and nothing else.
|
If you are using Laravel Mix check your webpack.mix.js file, default config must look like this mix.js('resources/assets/js/app.js', 'public/js') .sass('resources/assets/sass/app.scss', 'public/css'); Now, look if you have linked JS file to you blade template Looks like this for older Laravel versions (<= 5.5): <script src="{{ asset('js/app.js') }}"></script> and like this for new once (> 5.5) <script src="{{ mix('js/app.js') }}"></script> Finally, see you have el: '#app' it mean # - id, like in CSS, VueJS will search for element with id app.Everything outside that element will not work. so you have to use it like <div id='app'> <example-component></example-component></div> or <section id='app'> <example-component></example-component> </section>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49088957', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7135968/']}
|
jdg_370850
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21197
|
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am doing vector analysis. I have figured out that the following expression won't be simplified in Mathematica : Simplify[Dot[x, y] - Dot[y, x]] I think the reason is that x and y could be matrices, so generally the operation does not commute. But for a vector, the commutation relation should hold. What I don't know is how to tell Mathematica to consider x and y to be vectors. Also, how can I expand Cross[x + y, z] to be Cross[x, y] + Cross[y, z] ? I tried to use Expand and ExpandAll but neither worked. BTW, in Mathematica , is it possible to define a abstract row/column vector without explicitly specifying the number of entries?
Now provide the response and nothing else.
|
Here is a way to do all the things you asked for automatically, independently of Mathematica version. The approach relies on a special symbol to identify when we're dealing with a vector: Instead of using things like x , y etc. for vectors, the convention now is that vectors are written as vec[x] , vec[y] , etc. You could also define the wrapper OverVector[x] for this purpose because it displays as $\vec{x}$. But for this post I want to keep it simple, and the arrows wouldn't display easily in the source code below. ClearAll[scalarProduct, vec]; SetAttributes[scalarProduct, {Orderless}]vec /: Dot[vec[x_], vec[y_]] := scalarProduct[vec[x], vec[y]]vec /: Cross[vec[x_], HoldPattern[Plus[y__]]] := Map[Cross[vec[x], #] &, Plus[y]]vec /: Cross[HoldPattern[Plus[y__]], vec[x_]] := Map[Cross[#, vec[x]] &, Plus[y]]scalarProduct /: MakeBoxes[scalarProduct[x_, y_], _] := RowBox[{ToBoxes[x], ".", ToBoxes[y]}]vec[x].vec[y](* ==> vec[x].vec[y] *)vec[x].vec[y] == vec[y].vec[x](* ==> True *)Cross[vec[x], vec[a] + vec[b]](* ==> vec[x]\[Cross]vec[a] + vec[x]\[Cross]vec[b] *)Cross[vec[a] + vec[b], vec[x]](* ==> vec[a]\[Cross]vec[x] + vec[b]\[Cross]vec[x] *) For the Dot product, I defined the behavior of vec such that it gets evaluated as a new function scalarProduct whose only algebraic property is that it's Orderless as you were expecting for the dot product of vectors. Of course this is only true for Euclidean dot products, so this assumption is implicit here. For more information on how this definition works, look up TagSetDelayed . In addition, scalarProduct is given a customized display format by defining that it should again display as if it were a dot product when it appears in the low-level formatting function MakeBoxes . For the distributive property of the cross product, I give vec the additional property that when it appears in Cross together with an expression of head Plus , the sum is expanded. Here the TagSetDelayed definitions are done for both orders, and contain a HoldPattern to prevent Plus from being evaluated too early in the definition. Now you may come back with many more wishes: e.g., what about multiplicative scalars in the dot or cross product, and what about matrices. However, that's a wide field that opens up a can of worms, so I would say just implement the bare minimum of features you can get away with symbolically, then proceed with a concrete working basis so that you can write vectors as lists instead. Another approach would be to define a new symbol for a custom dot product. That is done in this question . Using OverVector As mentioned above, you can replace vec by Overvector everywhere in the above source code, to get a better formatted result. Assuming you have done that (I won't bother to repeat the definitions with that change), here are some examples: To enter these vector expressions, refer to the Basic Math assistant palette. The cross product can be entered as Esc cross Esc . Another thing you asked for is to use the antisymmetry of the cross product in simplifications. That's actually done already if you invoke FullSimplify :
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/21197', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/6336/']}
|
jdg_370851
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
178333
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Since multiple inheritance is bad (it makes the source more complicated) C# does not provide such a pattern directly. But sometimes it would be helpful to have this ability. For instance I'm able to implement the missing multiple inheritance pattern using interfaces and three classes like that: public interface IFirst { void FirstMethod(); }public interface ISecond { void SecondMethod(); }public class First:IFirst { public void FirstMethod() { Console.WriteLine("First"); } }public class Second:ISecond { public void SecondMethod() { Console.WriteLine("Second"); } }public class FirstAndSecond: IFirst, ISecond{ First first = new First(); Second second = new Second(); public void FirstMethod() { first.FirstMethod(); } public void SecondMethod() { second.SecondMethod(); }} Every time I add a method to one of the interfaces I need to change the class FirstAndSecond as well. Is there a way to inject multiple existing classes into one new class like it is possible in C++? Maybe there is a solution using some kind of code generation? Or it may look like this (imaginary c# syntax): public class FirstAndSecond: IFirst from First, ISecond from Second{ } So that there won't be a need to update the class FirstAndSecond when I modify one of the interfaces. EDIT Maybe it would be better to consider a practical example: You have an existing class (e.g. a text based TCP client based on ITextTcpClient) which you do already use at different locations inside your project. Now you feel the need to create a component of your class to be easy accessible for windows forms developers. As far as I know you currently have two ways to do this: Write a new class that is inherited from components and implements the interface of the TextTcpClient class using an instance of the class itself as shown with FirstAndSecond. Write a new class that inherits from TextTcpClient and somehow implements IComponent (haven't actually tried this yet). In both cases you need to do work per method and not per class. Since you know that we will need all the methods of TextTcpClient and Component it would be the easiest solution to just combine those two into one class. To avoid conflicts this may be done by code generation where the result could be altered afterwards but typing this by hand is a pure pain in the ass.
Now provide the response and nothing else.
|
Consider just using composition instead of trying to simulate Multiple Inheritance. You can use Interfaces to define what classes make up the composition, eg: ISteerable implies a property of type SteeringWheel , IBrakable implies a property of type BrakePedal , etc. Once you've done that, you could use the Extension Methods feature added to C# 3.0 to further simplify calling methods on those implied properties, eg: public interface ISteerable { SteeringWheel wheel { get; set; } }public interface IBrakable { BrakePedal brake { get; set; } }public class Vehicle : ISteerable, IBrakable{ public SteeringWheel wheel { get; set; } public BrakePedal brake { get; set; } public Vehicle() { wheel = new SteeringWheel(); brake = new BrakePedal(); }}public static class SteeringExtensions{ public static void SteerLeft(this ISteerable vehicle) { vehicle.wheel.SteerLeft(); }}public static class BrakeExtensions{ public static void Stop(this IBrakable vehicle) { vehicle.brake.ApplyUntilStop(); }}public class Main{ Vehicle myCar = new Vehicle(); public void main() { myCar.SteerLeft(); myCar.Stop(); }}
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/178333', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/25782/']}
|
jdg_370852
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35800795
|
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 Pyspark, I can create a RDD from a list and decide how many partitions to have: sc = SparkContext()sc.parallelize(xrange(0, 10), 4) How does the number of partitions I decide to partition my RDD in influence the performance?And how does this depend on the number of core my machine has?
Now provide the response and nothing else.
|
The primary effect would be by specifying too few partitions or far too many partitions. Too few partitions You will not utilize all of the cores available in the cluster. Too many partitions There will be excessive overhead in managing many small tasks. Between the two the first one is far more impactful on performance. Scheduling too many smalls tasks is a relatively small impact at this point for partition counts below 1000. If you have on the order of tens of thousands of partitions then spark gets very slow.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/35800795', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2352319/']}
|
jdg_370853
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
810688
|
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 installed Elastic Search 1.7.4 on CentOS 7.2 this way: wget https://download.elastic.co/elasticsearch/elasticsearch/elasticsearch-1.7.4.noarch.rpmsudo rpm -ivh elasticsearch-1.7.4.noarch.rpm The service is started and ES works (verified with curl), however, it only listens to IPv6 with default configuration. netstat -na gives me the following: tcp6 0 0 :::9200 :::* LISTEN tcp6 0 0 :::9300 :::* LISTEN Using nmap from other servers I see that ports 9200 and 9300 are filtered, firewall is disabled. Editing /etc/elasticsearch/elasticsearch.yml and setting: network.bind_host: 0.0.0.0 doesn't change anything. Setting this to the external IPv4 address of the server does add the additional two entries in netstat -na output, but I need ES to be accessible to my local network, so this is useless and netstat still registers this as tcp6. tcp6 0 0 192.168.0.54:9200 :::* LISTEN tcp6 0 0 192.168.0.54:9300 :::* LISTEN setting: network.bind_host: _eth0:ipv4_ Causes ES to bind to the local IPv4 and then it is of course only available from the local server. Omitting the "ipv4" part causes ES to bind to IPv6 address of the NIC. How do I enable ES to bind to IPv4? I have no alternative, my network is IPv4 only and I have to use this old version of ES because I'm running some applications that require this version.
Now provide the response and nothing else.
|
From unix exchange. This is happening because by default, AF_INET6 sockets will actually work for both IPv4 and IPv6. See section 3.7 - Compatibility with IPv4 Nodes of RFC 3493 - Basic Socket Interface Extensions for IPv6 But as you've figured out, firewalld is enabled out of the box. create this file to your /etc/firewalld/services/elasticsearch.xml <?xml version="1.0" encoding="utf-8"?><service> <short>Elasticsearch</short> <description>Elasticsearch is a distributed, open source search and analytics engine, designed for horizontal scalability, reliability, and easy management.</description> <port protocol="tcp" port="9300"/> <port protocol="tcp" port="9200"/></service> Update permissions chmod 0400 /etc/firewalld/services/elasticsearch.xmlchown root: /etc/firewalld/services/elasticsearch.xml Run these commands firewall-cmd --zone=public --add-service=elasticsearch --permanentfirewall-cmd --reload
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/810688', 'https://serverfault.com', 'https://serverfault.com/users/382163/']}
|
jdg_370854
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
406604
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $\Omega$ be domain in $\mathbb{C}^n$ . Suppose we have taken two distinct points from $\Omega$ . Does there exist a domain $U$ in $\mathbb{C}$ such that there is a holomorphic function from $U$ to $\Omega$ whose range contains these two points? I tried to prove the identity theorem in several complex variables. Then my mind gave me that above question.
Now provide the response and nothing else.
|
The simplest blowup morphism $\mathrm{Bl}_0(\mathbb{A}^2) \to \mathbb{A}^2$ (with center at a point) is not flat. EDIT. Here is an example with affine morphism. Let $$X = \{ x_1y_1 + x_2y_2 + x_3y_3 = 0 \} \subset \mathbb{A}^4_{x_1,x_2,x_3,x_4} \times \mathbb{A}^4_{y_1,y_2,y_3}$$ and let $f \colon X \to \mathbb{A}^3$ be the projection to the second factor. This example, however, is singular at the point $(0,0)$ . EDIT 2. Consider the variety $$\bar{X} = \{x_1y_1 + x_2y_2 + x_3y_3 = 0\} \subset\mathbb{P}^2_{x_1:x_2:x_3} \times \mathbb{A}^3_{y_1,y_2,y_3}.$$ It is smooth, because the projection to $\mathbb{P}^2$ is a fibration with fiber $\mathbb{A}^2$ . On the other hand, the projection $\bar{f} \colon \bar{X} \to \mathbb{A}^3$ is not flat, because the dimension of the fiber jumps at $0$ . Now let $$X = \bar{X} \cap ((\mathbb{P}^2 \setminus C) \times \mathbb{A}^3),$$ where $C$ is a smooth conic. Then $X$ is smooth, because it is open in $\bar{X}$ ; $X$ is affine over $\mathbb{A}^3$ because $\mathbb{P}^2 \setminus C$ is affine, the map $f \colon X \to \mathbb{A}^3$ is surjective, because the smooth conic $C$ cannot contain a fiber of $\bar{f}$ (a line or the plane), the map $f$ is not flat, because the dimension of the fiber still jumps at $0$ .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/406604', 'https://mathoverflow.net', 'https://mathoverflow.net/users/422133/']}
|
jdg_370855
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5914
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I create an device running Linux (Android OS) with video output? PS. I don't want to use an existing very sophisticated dev board, I want to create one. Thanks!
Now provide the response and nothing else.
|
I've been doing something like this over the course of about 4 of the last 6 months (I worked on some other stuff in between). Building my own Linux board has been a tremendous learning experience, but it's also been quite challenging. Here are some things I wish I knew before I started: Generally, BGA packages mean you have to use fine-pitch traces and vias, and you it's difficult to assemble the boards yourself. Even if you were to succeed in soldering a BGA yourself, if you had a problem, you wouldn't know if it was due to bad soldering or bad design. The worst problem, though, is that this makes iterating on your design expensive-- around $1000 and 15 business days per rev if you live in the US. For the love of William Shockley, start with a reference design with Android support (well, just Linux in my case). My board is based off the Atmel AT91SAM9G20 eval kit; that's saved me a great deal of headache. Use the U-boot bootloader. It's the dominant one, which means that you can get support in more places. Before you start laying out a board, think very carefully about how to position the components to minimize trace length. I did this to some extent, but not as much as I should have. Buy the dev kit that is most similar to what you're planning to build, and build the bootloader and kernel from source. That will teach you a lot. If you're serious about video, I would probably try to validate whatever hardware platform I chose before laying out a board. Good luck.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/5914', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/1539/']}
|
jdg_370856
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27677
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been looking for a good explanation of the difference between running a regression with year dummies as fixed effects vs. year dummies as instrumental variables. A prominent example of this comes from Josh Angrist's 1991 paper, "Grouped-data estimation and testing in simple labor-supply models" http://www.sciencedirect.com/science/article/pii/030440769190101I
Now provide the response and nothing else.
|
Model estimation is the process of picking the best (according to some metric) kind and structure of model. Estimation may include calibration. Calibration is the process of finding the coefficients that enable a model (the kind and structure of which is already determined) to most closely (according to some metric) reflect a particular known dataset. So: estimation will set kind, structure and coefficients. Calibration will tweak coefficients, holding kind and structure constant. Newton's model of motion is fine for most purposes. By calibrating the gravitational coefficient in it, we can make estimates of the mass of the Earth. But it won't work as a model of relativistic motion - that needs the estimation of a different model: there is no recalibration of Newton's model that works for relativistic motion - no coeffecient will work, because the model itself is simply the wrong kind and structure. It omits mechanisms and responses that are absolutely crucial, if the model is to be useful. Similarly with economic models, Paul Krugman's point is that freshwater economists are saying that their model structures are fine, just the coefficients need tweaking. The problem with that is that if their structures are wrong, no amount of tweaking will make the models useful. Only by going back to basics, and re-estimating the whole model, would they incorporate the crucial mechanisms and responses. He argues that they won't do that, because that would require them to recognise that their existing paradigm is inadequate.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/27677', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/6877/']}
|
jdg_370857
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
130594
|
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:
Has there been any experiments, or are there any references, demonstrating gravity between atoms? If so, what are the key experiments/papers? Or if not, what is the smallest thing that has actually experimentally been shown to be affected by gravity? I don't know of specific papers demonstrating gravity between larger objects, but I can vaguely remember learning about them in my classical physics class as an undergraduate. However, I have never heard of experiments demonstrating gravity at atomic or subatomic levels. I don't have a physics background so it's not obvious to me, so just looking to see the actual research/evidence behind it, so I can start to try to imagine how gravity works at a quantum level.
Now provide the response and nothing else.
|
Groups in Seattle, Colorado, and perhaps others managed to measure and verify Newton's inverse-square law at submillimeter distances comparable to 0.1 millimeters, see e.g. Sub-millimeter tests of the gravitational inverse-square law: A search for "large" extra dimensions Motivated by higher-dimensional theories that predict new effects, we tested the gravitational $\frac{1}{r^{2}}$ law at separations ranging down to 218 micrometers using a 10-fold symmetric torsion pendulum and a rotating 10-fold symmetric attractor. We improved previous short-range constraints by up to a factor of 1000 and find no deviations from Newtonian physics. This is a 14 years old paper (with 600+ citations) and I think that these experiments were very hot at that time because the warped- and large-dimensions models in particle physics that may predict violations of Newton's law had been proposed in the preceding two years. But I believe that there's been some extra progress in the field. At that time, the very fine measurement up to 200 microns etc. allowed them to deduce something about the law of gravity up to 10 microns. These are extremely clever, fine mechanical experiments with torsion pendulums, rotating attractors, and resonances. The force they are able to see is really tiny. To see the gravitational force of a single atom is obviously too much to ask (so far?) – the objects whose gravity is seen in the existing experiments contain billions or trillions of atoms. Note that the (attractive) gravitational force between two electrons is about $10^{45}$ times weaker than the (repulsive) electrostatic one! Most of the research in quantum gravity has nothing whatever to do with proposals to modify Newton's laws at these distance scales. Indeed, gravity is the weakest force and it's so weak that for all routinely observable phenomena involving atoms, it can be safely neglected. The research in quantum gravity is dealing with much more extreme phenomena – like the evaporation of tiny black holes – that can't be seen in the lab. Plots and links to new papers available over here (thanks, alemi )
|
{}
|
{'log_upvote_score': 7, 'links': ['https://physics.stackexchange.com/questions/130594', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/16731/']}
|
jdg_370858
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1675005
|
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:
Here is Problem 11-11 on page 301 of John Lee’s book: Let $ M $ be a smooth manifold, and $ C \subset M $ be an embedded sub-manifold. Let $ f \in {C^{\infty}}(M) $ , and suppose $ p \in C $ is a point at which $ f $ attains a local maximum or minimum value among points in $ C $ . Given a smooth local defining function $ \Phi: U \to \mathbb{R}^{k} $ for $ C $ on a neighborhood $ U $ of $ p $ in $ M $ , there are real numbers $ \lambda_{1},\ldots,\lambda_{k} $ (called Lagrange multipliers ) such that $$\mathrm{d} f_{p} = \sum_{i = 1}^{k} \lambda_{i} \cdot \mathrm{d} \Phi^{i}|_{p}.$$ I got confused when I was trying to solve it. Here are my questions: (1) He didn’t say anything about the dimension of $ M $ and $ C $ , nor did he put corrections here . Is it necessary to assume that $ \operatorname{dim}(M) = n > k $ and $ \operatorname{dim}(C) = n - k $ , or do these results implicitly follow from the conditions of this problem? (2) Why do we need the condition that $ C $ is an embedded sub-manifold? Assume $ \operatorname{dim}(C) = n - k $ ; then Theorem 5.8 on page 102 tells us that $ C $ satisfies the local $ k $ -slice condition (this is the only theorem I can think of that is related to this condition), but what good can this condition do for us? (3) I think I need to apply the Lagrange Multiplier Theorem (see page 113) in multi-variable calculus, but we need to make sure that the rank of the Jacobian matrix of $ \Phi $ is of rank $ k $ at the point $ p $ . However, there aren’t any extra conditions on $ \Phi $ . You can either answer my questions separately or show me a detailed proof of it. Thank you in advance!
Now provide the response and nothing else.
|
Here are a few comments that might be helpful. (1) He didn't say anything about the dimension of $M$ and $C$, nor did he put corrections [here][1]. Is it necessary to assume that $dim> M=n>k$ and that $dim C=n-k$ or these results implicitly follow from the conditions in this problem? The definition of a local defining function (page 107) specifies that $C\cap U$ is a regular level set of $\Phi$, which implies that $d\Phi$ has rank $k$ everywhere on $C\cap U$, and therefore $C$ has codimension $k$ in $M$. (2) Why do we need the condition that $C$ is an embedded submanifold? Embedded submanifolds are the only ones that admit local defining functions in a neighborhood of each point. (3) I think I need to apply the Lagrange multipliers theorem in multi-variable calculus. But we need to make sure that the rank of the Jacobian matrix of $\Phi$ is of rank $k$ at the point $p$. However, there isn't any extra conditions on $\Phi$. The point of this problem is to prove the Lagrange multiplier theorem, albeit in a more general setting than the one usually introduced in advanced calculus courses. The fact that the Jacobian of $\Phi$ in coordinates has maximal rank is an immediate consequence of the definition of a local defining function.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1675005', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/185631/']}
|
jdg_370859
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
49198068
|
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 read Pandas change timezone for forex DataFrame but I'd like to make the time column of my dataframe timezone naive for interoperability with an sqlite3 database. The data in my pandas dataframe is already converted to UTC data, but I do not want to have to maintain this UTC timezone information in the database. Given a sample of the data derived from other sources, it looks like this: print(type(testdata))print(testdata)print(testdata.applymap(type)) gives: <class 'pandas.core.frame.DataFrame'> time navd88_ft station_id new0 2018-03-07 01:31:02+00:00 -0.030332 13 51 2018-03-07 01:21:02+00:00 -0.121653 13 52 2018-03-07 01:26:02+00:00 -0.072945 13 53 2018-03-07 01:16:02+00:00 -0.139917 13 54 2018-03-07 01:11:02+00:00 -0.152085 13 5 time navd88_ft station_id \0 <class 'pandas._libs.tslib.Timestamp'> <class 'float'> <class 'int'> 1 <class 'pandas._libs.tslib.Timestamp'> <class 'float'> <class 'int'> 2 <class 'pandas._libs.tslib.Timestamp'> <class 'float'> <class 'int'> 3 <class 'pandas._libs.tslib.Timestamp'> <class 'float'> <class 'int'> 4 <class 'pandas._libs.tslib.Timestamp'> <class 'float'> <class 'int'> new 0 <class 'int'> 1 <class 'int'> 2 <class 'int'> 3 <class 'int'> 4 <class 'int'> but newstamp = testdata['time'].tz_convert(None) gives an eventual error: TypeError: index is not a valid DatetimeIndex or PeriodIndex What do I do to replace the column with a timezone naive timestamp?
Now provide the response and nothing else.
|
The column must be a datetime dtype, for example after using pd.to_datetime .Then, you can use tz_localize to change the time zone, a naive timestamp corresponds to time zone None : testdata['time'].dt.tz_localize(None) Unless the column is an index ( DatetimeIndex ), the .dt accessor must be used to access pandas datetime functions .
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/49198068', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1653571/']}
|
jdg_370860
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
332152
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $(M,g)$ be a connected Riemannian manifold.Let $d_g$ be the induced distance metric of $g$ . Now let $d$ be some other metric on $M$ . Suppose that for each $x \in M$ , there is a neighborhood $U$ of $x$ so that $d = d_g$ on $U \times U$ . Question: Does this imply that $d = d_g$ on $M \times M$ ? I am not assuming that $d$ is the metric of some Riemannian metric; I know the answer is yes in that case. Remarks: It's clear to me that $d = d_g$ on a neighborhood of the diagonal in $M \times M$ ; this essentially is just a rephrasing of the hypothesis. Connectedness is necessary to avoid stupid counter examples. For example, we could take two disjoint points $\{x,y\}$ . Then $d_g$ between them is infinity, but we can take $d(x,y) = 1$ . They both agree in a neighborhood of $x$ , namely $x$ . (We can build similar examples by taking disjoint unions of non-zero dimensional manifolds.) Maybe the 'right' question is actually: let X be a (path) connected topological space and consider two metrics $g$ and $h$ on X, compatible with the topology on X. If these metrics are locally equal in the sense of the question (i.e. agree on a neighborhood of the diagonal), are they equal? (I feel like this either has an obvious proof or some terrible counter example. It appears to be true on graphs metrized by assigning edge lengths - oops, this is wrong by the cut off metric example.) I (think) I can prove a special case. See motivation section below. Motivation: Let $(N,h)$ be a connected Riemannian manifold, with geodesic distance function $d_N$ . Let $G$ be the group of a covering space action by isometries on $N$ , with quotient map $\pi$ , with $G$ finite . Then $N / G$ inherits a Riemannian metric $g$ by using local trivializations. $N / G$ also inherits a metric, defined by $d([x], [y]) = \inf_{g \in G} d_N(gx, y)$ . Locally $d = d_g$ because of local trivializations. I want to know if $d = d_g$ on all of $N / G$ . I think this is true if the geodesic distance between any two points in $N$ and $N / G$ is always realized by some shortest path, by using the covering space path lifting + being a geodesic is a local condition + isometry of covering actions in order to relate shortest paths in $N$ to those in $N / G$ . That is, if $g$ minimizes $d(gx, y)$ let $\gamma : [0,1] \to N$ be a shortest path in $N$ between $gx$ and $y$ . Then $\pi( \gamma)$ is a (potentially self intersecting) geodesic, of the same length as $\gamma$ , connecting $[x]$ and $[y]$ . Hence $d_g \leq d$ . On the other hand, if we have a geodesic path $\gamma$ from $[x]$ to $[y]$ , we can lift it to a geodesic from $x$ to $hy$ of the same length, for some $h \in G$ , and hence $d_g \geq d$ . I would like to be able to drop this condition about there always being shortest path witnesses to shortest distances (I mean that the inf in geodesic distance is achieved). I think that maybe in this covering space case one can achieve this by taking a sequence of paths approximating the geodesic distance, but the argument starts to get a lot fuzzier, and I am already outside my comfort zone and procrastinating on my actual work as it is... I would appreciate a reference for either the main question or the motivation.
Now provide the response and nothing else.
|
The answer is no. Take any non-convex region in the plane, and let the Riemannian metric be the ordinary Euclidean metric $ds^2=dx^2+dy^2$ . Then define the new metric as the infimum of Euclidean diameters of curves connecting $a$ to $b$ . This new metric coincides with the Riemannian metric locally, but does not coincide globally. This metric even has a name: Mazurkiewicz metric. One can also construct a compact example by taking $M$ to be a ramified covering of the sphere, and pullback of the spherical metric. This Riemannian metric in general does not coincide with the Mazurkiewicz metric corresponding to it. (Diameter used in the definition is the diameter of the projection of the curve on the sphere. Projection of the Riemannian-shortest path on $M$ can have small diameter but large length). In general, any distance $d$ which locally coincides with the Riemannian distance $d_R$ must satisfy $d\leq d_R$ . Just break the curve on which the Riemannian distance is (almost) achieved into small pieces, and use the triangle inequality for $d$ .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/332152', 'https://mathoverflow.net', 'https://mathoverflow.net/users/41873/']}
|
jdg_370861
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43436828
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to add a button and set the constraints programmatically, but I keep getting this error and can't figure out what's wrong with my code. I've looked at other questions on here but they haven't been too helpful in my case. btn.setTitle("mybtn", for: .normal) btn.setTitleColor(UIColor.blue, for: .normal) btn.backgroundColor = UIColor.lightGray view.addSubview(btn) btn.translatesAutoresizingMaskIntoConstraints = false let left = NSLayoutConstraint(item: btn, attribute: .leftMargin, relatedBy: .equal, toItem: view, attribute: .leftMargin, multiplier: 1.0, constant: 0) let right = NSLayoutConstraint(item: btn, attribute: .rightMargin, relatedBy: .equal, toItem: view, attribute: .rightMargin, multiplier: 1.0, constant: 0) let top = NSLayoutConstraint(item: btn, attribute: .top, relatedBy: .equal, toItem: topLayoutGuide, attribute: .bottom, multiplier: 1.0, constant: 0) btn.addConstraints([left, right, top])
Now provide the response and nothing else.
|
When adding constraints to a view, "any views involved [in the constraint] must be either the receiving view itself, or a subview of the receiving view". You're adding the constraint to btn , so it doesn't understand what to make of the view referenced by the constraint, because it's neither btn nor a subview of btn . The error would be resolved if you added the constraints to view , instead of btn . Or even better, as Khalid said, use activate instead, in which case you don't need to worry about where in the view hierarchy you are adding the constraint: let btn = UIButton(type: .system)btn.setTitle("mybtn", for: .normal)btn.setTitleColor(.blue, for: .normal)btn.backgroundColor = .lightGrayview.addSubview(btn)btn.translatesAutoresizingMaskIntoConstraints = falseNSLayoutConstraint.activate([ btn.leftAnchor.constraint(equalTo: view.leftAnchor), btn.rightAnchor.constraint(equalTo: view.rightAnchor), btn.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor)])
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43436828', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5404903/']}
|
jdg_370862
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3011510
|
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 to declare and use 1D and 2D byte arrays in Verilog? eg. how to do something like byte a_2D[3][3];byte a_1D[3];// using 1Dfor (int i=0; i< 3; i++){ a_1D[i] = (byte)i;}// using 2Dfor (int i=0; i< 3; i++){ for (int j=0; j< 3; j++) { a_2D[i][j] = (byte)i*j; }}
Now provide the response and nothing else.
|
Verilog thinks in bits, so reg [7:0] a[0:3] will give you a 4x8 bit array (=4x1 byte array). You get the first byte out of this with a[0] . The third bit of the 2nd byte is a[1][2] . For a 2D array of bytes, first check your simulator/compiler. Older versions (pre '01, I believe) won't support this. Then reg [7:0] a [0:3] [0:3] will give you a 2D array of bytes. A single bit can be accessed with a[2][0][7] for example. reg [7:0] a [0:3];reg [7:0] b [0:3] [0:3];reg [7:0] c;reg d;initial begin for (int i=0; i<=3; i++) begin a[i] = i[7:0]; end c = a[0]; d = a[1][2]; // using 2D for (int i=0; i<=3; i++) for (int j=0; j<=3; j++) b[i][j] = i*j; // watch this if you're building hardwareend
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3011510', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/252060/']}
|
jdg_370863
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4007828
|
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:
Consider the limit $$ \lim_{x \to \infty} x^a \left ( \left(x+\frac{1}{x}\right)^\frac{2}{7} - x^\frac{2}{7} \right ) $$ Does there exist a value for $a$ for which the limit exists, and it's value is different from $0$ and $\infty$ . I was able to confirm through trial that for $a = \frac{12}{7} $ the condition listed is satisfied. I'm not sure how to approach this problem, I've tried to use LHopital's but that didn't work and got very messy quickly. Cheers
Now provide the response and nothing else.
|
Answer is $12/7$ . In fact, write $$(x+1/x)^{2/7}-x^{2/7}=x^{2/7}[(1+x^{-2})^{2/7}-1].$$ In general when $c>0$ we have $\lim_{z\to 0}\frac{(1+z)^c-1}{z}=c$ by l'Hosptal. So $$x^{\frac{12}{7}}[(x+1/x)^{2/7}-x^{2/7}]=x^{\frac{12}{7}}x^{2/7}\frac{(1+x^{-2})^{2/7}-1}{x^{-2}}x^{-2}=\frac{(1+x^{-2})^{2/7}-1}{x^{-2}}\to \frac 27.$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4007828', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/655052/']}
|
jdg_370864
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
438843
|
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 have had some trouble with getting cron to send emails. My ISP requires that the "From:" field match the email address the email is being sent from, otherwise the email is rejected. As cron hardcodes the "From:" field to "root (Cron Daemon)", these emails are not being sent. I have set up msmtp and can send emails with no problem from the command line. In fact I have wrapped some of my cron jobs in a script that sends the email itself. This works fine, but I would like a more elegant solution. I originally used the package msmtp-mta , which just symlinks /usr/lib/sendmail to /usr/bin/msmtp so that cron will send emails using msmtp. Since that didn't work, I removed the package and put a bash script in /usr/lib/sendmail instead that should just read from standard input and send an email with the right headers: #!/bin/bashHEADERS="To: <myemail>From: Cron <myotheremail>Subject: Vixie-cron snooper ($@)"INPUT=$( cat /dev/stdin )echo -e "$HEADERS""Stdin:\n$INPUT\n" | msmtp <myemail>echo "$HEADERS""Stdin:\n$INPUT\n" > /tmp/vixielog However, this doesn't have the desired effect. I just receive an almost empty email and /tmp/vixielog contains the same: To: <myemail>From: Cron <myotheremail>Subject: Vixie-cron snooper (-i -FCronDaemon -oem <myemail>)Stdin: The emails come at the right time, so I know the cron job is being run properly, but I am not getting the output. How could I adjust this approach to get the output of the command in the email?
Now provide the response and nothing else.
|
Eventually I came to the following solution. Rather than using mstmp-mta , I wrote my own simple bash script that acts as my MTA. Placed in /usr/sbin/sendmail , it replaces the From header and sends the email on. #!/bin/bashsed -e "s/From: root (Cron Daemon)/From: WHATEVER YOU LIKE/" | msmtp $BASH_ARGV Hopefully this helps anybody else who wants a lightweight solution to the problem.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/438843', 'https://serverfault.com', 'https://serverfault.com/users/140748/']}
|
jdg_370865
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17902992
|
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 saw this code: if (cond) { perror("an error occurred"), exit(1);} Why would you do that? Why not just: if (cond) { perror("an error occurred"); exit(1);}
Now provide the response and nothing else.
|
In your example it serves no reason at all. It is on occasion useful when written as if(cond) perror("an error occured"), exit(1) ; -- then you don't need curly braces. But it's an invitation to disaster. The comma operator is to put two or more expressions in a position where the reference only allows one. In your case, there is no need to use it; in other cases, such as in a while loop, it may be useful: while (a = b, c < d) ... where the actual "evaluation" of the while loop is governed solely on the last expression.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17902992', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1248779/']}
|
jdg_370866
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14979753
|
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 add radio buttons to my menu items. I have seen a few answers where people were making radio buttons as the menu items. But I want my menu items to have the proper radio button that can be easily done in Winforms . To make sure I don't get the same answers as other people, here is a picture of what the menu items' radio buttons should look like: And by the way, I am using C#, WPF.
Now provide the response and nothing else.
|
Edited Template <Window.Resources> <Style x:Key="{x:Type MenuItem}" TargetType="MenuItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type MenuItem}"> <Border x:Name="templateRoot" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True"> <Grid VerticalAlignment="Center"> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="Auto"/> </Grid.ColumnDefinitions> <ContentPresenter x:Name="Icon" Content="{TemplateBinding Icon}" ContentSource="Icon" HorizontalAlignment="Center" Height="16" Margin="3" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Center" Width="16"/> <RadioButton Margin="3" IsChecked="{TemplateBinding IsChecked}" VerticalAlignment="Center" x:Name="GlyphPanel" Visibility="Collapsed"/> <ContentPresenter ContentTemplate="{TemplateBinding HeaderTemplate}" Content="{TemplateBinding Header}" Grid.Column="1" ContentStringFormat="{TemplateBinding HeaderStringFormat}" ContentSource="Header" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/> <Popup x:Name="PART_Popup" AllowsTransparency="True" Focusable="False" IsOpen="{Binding IsSubmenuOpen, RelativeSource={RelativeSource TemplatedParent}}" PopupAnimation="{DynamicResource {x:Static SystemParameters.MenuPopupAnimationKey}}" Placement="Bottom"> <Border x:Name="SubMenuBorder" BorderBrush="#FF999999" BorderThickness="1" Background="#FFF0F0F0" Padding="2"> <ScrollViewer x:Name="SubMenuScrollViewer" Style="{DynamicResource {ComponentResourceKey ResourceId=MenuScrollViewer, TypeInTargetAssembly={x:Type FrameworkElement}}}"> <Grid RenderOptions.ClearTypeHint="Enabled"> <Canvas HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0"> <Rectangle x:Name="OpaqueRect" Fill="{Binding Background, ElementName=SubMenuBorder}" Height="{Binding ActualHeight, ElementName=SubMenuBorder}" Width="{Binding ActualWidth, ElementName=SubMenuBorder}"/> </Canvas> <Rectangle Fill="#FFD7D7D7" HorizontalAlignment="Left" Margin="29,2,0,2" Width="1"/> <ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Cycle" Grid.IsSharedSizeScope="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" KeyboardNavigation.TabNavigation="Cycle"/> </Grid> </ScrollViewer> </Border> </Popup> </Grid> </Border> <ControlTemplate.Triggers> <Trigger Property="IsSuspendingPopupAnimation" Value="True"> <Setter Property="PopupAnimation" TargetName="PART_Popup" Value="None"/> </Trigger> <Trigger Property="Icon" Value="{x:Null}"> <Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/> </Trigger> <Trigger Property="IsChecked" Value="True"> <Setter Property="Visibility" TargetName="GlyphPanel" Value="Visible"/> <Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/> </Trigger> <Trigger Property="IsHighlighted" Value="True"> <Setter Property="Background" TargetName="templateRoot" Value="#3D26A0DA"/> <Setter Property="BorderBrush" TargetName="templateRoot" Value="#FF26A0DA"/> </Trigger> <Trigger Property="IsEnabled" Value="False"> <Setter Property="TextElement.Foreground" TargetName="templateRoot" Value="#FF707070"/> <Setter Property="Visibility" TargetName="GlyphPanel" Value="Collapsed"/> </Trigger> <Trigger Property="CanContentScroll" SourceName="SubMenuScrollViewer" Value="False"> <Setter Property="Canvas.Top" TargetName="OpaqueRect" Value="{Binding VerticalOffset, ElementName=SubMenuScrollViewer}"/> <Setter Property="Canvas.Left" TargetName="OpaqueRect" Value="{Binding HorizontalOffset, ElementName=SubMenuScrollViewer}"/> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> <Style x:Key="ItemcontainerStyle" TargetType="MenuItem"> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type MenuItem}"> <Border x:Name="templateRoot" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True"> <Grid Margin="-1"> <Grid.ColumnDefinitions> <ColumnDefinition MinWidth="22" SharedSizeGroup="MenuItemIconColumnGroup" Width="Auto"/> <ColumnDefinition Width="13"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="30"/> <ColumnDefinition SharedSizeGroup="MenuItemIGTColumnGroup" Width="Auto"/> <ColumnDefinition Width="20"/> </Grid.ColumnDefinitions> <ContentPresenter x:Name="Icon" Content="{TemplateBinding Icon}" ContentSource="Icon" HorizontalAlignment="Center" Height="16" Margin="3" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Center" Width="16"/> <Border x:Name="GlyphPanel" BorderBrush="#FF26A0DA" BorderThickness="1" Background="#3D26A0DA" ClipToBounds="False" HorizontalAlignment="Center" Height="22" Margin="-1,0,0,0" Visibility="Hidden" VerticalAlignment="Center" Width="22"> <RadioButton x:Name="Glyph" IsChecked="{TemplateBinding IsChecked}" GroupName="a" VerticalAlignment="Center" HorizontalAlignment="Center"/> </Border> <ContentPresenter x:Name="menuHeaderContainer" ContentTemplate="{TemplateBinding HeaderTemplate}" Content="{TemplateBinding Header}" Grid.Column="2" ContentStringFormat="{TemplateBinding HeaderStringFormat}" ContentSource="Header" HorizontalAlignment="Left" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="Center"/> <TextBlock x:Name="menuGestureText" Grid.Column="4" Margin="{TemplateBinding Padding}" Opacity="0.7" Text="{TemplateBinding InputGestureText}" VerticalAlignment="Center"/> </Grid> </Border> <ControlTemplate.Triggers> <Trigger Property="Icon" Value="{x:Null}"> <Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/> </Trigger> <Trigger Property="IsChecked" Value="True"> <Setter Property="Visibility" TargetName="GlyphPanel" Value="Visible"/> <Setter Property="Visibility" TargetName="Icon" Value="Collapsed"/> </Trigger> <Trigger SourceName="Glyph" Property="IsChecked" Value="False"> <Setter Property="Visibility" TargetName="GlyphPanel" Value="Hidden"/> <Setter Property="Visibility" TargetName="Glyph" Value="Collapsed"/> </Trigger> <Trigger Property="IsHighlighted" Value="True"> <Setter Property="Background" TargetName="templateRoot" Value="#3D26A0DA"/> <Setter Property="BorderBrush" TargetName="templateRoot" Value="#FF26A0DA"/> </Trigger> <Trigger Property="IsEnabled" Value="False"> <Setter Property="TextElement.Foreground" TargetName="templateRoot" Value="#FF707070"/> </Trigger> <MultiTrigger> <MultiTrigger.Conditions> <Condition Property="IsHighlighted" Value="True"/> <Condition Property="IsEnabled" Value="False"/> </MultiTrigger.Conditions> <Setter Property="Background" TargetName="templateRoot" Value="#0A000000"/> <Setter Property="BorderBrush" TargetName="templateRoot" Value="#21000000"/> </MultiTrigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style></Window.Resources> MainWindow.xaml: <Menu> <MenuItem Header="File" ItemContainerStyle="{StaticResource ItemcontainerStyle}"> <MenuItem IsCheckable="True" Header="Example Menu Item"/> <MenuItem IsCheckable="True" Header="Example Menu Item"/> </MenuItem> </Menu> App.xaml <Application x:Class="MenuItemTemplate.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" StartupUri="MainWindow.xaml"><Application.Resources> <!--Luna--> <ResourceDictionary Source="/PresentationFramework.Luna, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/luna.normalcolor.xaml" /> <!--Aero--> <!--<ResourceDictionary Source="/PresentationFramework.Aero, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml"/>--> <!--Classic--> <!--<ResourceDictionary Source="/PresentationFramework.Classic, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/classic.xaml" />--></Application.Resources> OutPut
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14979753', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1611563/']}
|
jdg_370867
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1820017
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I update the values of one hashtable by another hashtable, if second hashtable contains new keys then they must be added to 1st else should update the value of 1st hashtable.
Now provide the response and nothing else.
|
foreach (DictionaryEntry item in second){ first[item.Key] = item.Value;} If required you could roll this into an extension method (assuming that you're using .NET 3.5 or newer). Hashtable one = GetHashtableFromSomewhere();Hashtable two = GetAnotherHashtableFromSomewhere();one.UpdateWith(two);// ...public static class HashtableExtensions{ public static void UpdateWith(this Hashtable first, Hashtable second) { foreach (DictionaryEntry item in second) { first[item.Key] = item.Value; } }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1820017', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/144408/']}
|
jdg_370868
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7564
|
Below is a question asked on the forum robotics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am building an autonomous underwater robot. It will be used in swimming pools. It should be capable of running in any normal sized pool, not just the pool in which I test. So I cannot rely on a particular design or feature. It has to know it's position in the pool, either with respect to the initial position or with respect to the pool. I have a IMU, which is a Pololu MiniIMU but finding the displacement with an IMU is a near impossible task. What sensor can I use for this task? It should not be very expensive. (below 200$) Tank size: 25x20x2.5 meters
Now provide the response and nothing else.
|
Localization under water was always a problem in ocean robotics as electromagnetic signals do not propagate very well in water. I think your best localization sensor in that case would be the good old sonar, which works much faster in water. You could have four of them and detect how far are the pool walls on each side then with a triangulation algorithm locate your robot approximately. You can also add one looking down for estimating the depth.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://robotics.stackexchange.com/questions/7564', 'https://robotics.stackexchange.com', 'https://robotics.stackexchange.com/users/8981/']}
|
jdg_370869
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
33754443
|
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 reading this where Robert Love mentioned that mutex is implemented using memory barrier but I am not able to see the memory barrier instructions being used in Linux implementation of mutex lock. I was wondering if he was referring to mutex lock implementation in posix library which does use memory barrier instruction so that it doesn't get reordered with respect to the critical resource. Am I right?
Now provide the response and nothing else.
|
That Robert Love's answer is applicable to mutexes in any area . Implementation in the linux kernel you refers uses __mutex_fastpath_lock , which do most the work and usually implementing using assembler code. E.g., on x86_64 its implementation could be: 20 static inline void __mutex_fastpath_lock(atomic_t *v, 21 void (*fail_fn)(atomic_t *)) 22 { 23 asm_volatile_goto(LOCK_PREFIX " decl %0\n" 24 " jns %l[exit]\n" 25 : : "m" (v->counter) 26 : "memory", "cc" 27 : exit); 28 fail_fn(v); 29 exit: 30 return; 31 } The key here is LOCK prefix (LOCK_PREFIX) before dec ( decl ) operation. On x86 LOCK prefix means atomicity and always implies full memory barrier .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33754443', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5171437/']}
|
jdg_370870
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7766
|
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 would like to improve wireless security and certain other on-net security scenarios with a permanent ARP table entry. The idea being that someone on the same subnet or WiFi network will have a more difficult time spoofing my access point. What clients support / don't support the feature of a permanent ARP entry? How can I centralize the configuration, deployment and updates of this configuration?
Now provide the response and nothing else.
|
"Static" ARP entries is the more commonly used term than "Permanent"; you should know this if you're Googling and the like. Static ARP entries do provide protection against ARP poisoning / spoofing. However, someone in a position to perform ARP spoofing can also perform MAC spoofing to achieve close to the same effect, and overcome the obstacle that a static ARP entry presents. This reduces the relative value of putting this protection into place. Under both Windows and Unix, static arp entries are configured using the command line tool 'arp' which is often called from a script, as @chris points out. You will not find an easy distributed management mechanism like, say, Group Policy to do it for you. Unless you've already got a tool in place for centralized configuration (puppet, cfengine, BladeLogic) you're stuck with manual work, another reason this protection isn't as attractive as one might like. In my opinion, static ARP entries are a low-level security step which has limited advantages, whose management is troublesome, and whose over-riding of the way a dynamic network works will turn around and bite you in the MAC at some point. There are better places to spend your time and energy.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/7766', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/396/']}
|
jdg_370871
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37633
|
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'm setting up a few ubuntu boxes, and using opscode's chef as a configuration tool. It would be fairly easy to install public keys for each user on each of these servers, and disable password authentication. However, the users should also have sudo privileges though, which by default requires a password. If I want to use the users' public keys as a method of access management and allow the users sudo privileges, does that mean I should also set up the users with NOPASSWD: ALL in visduo , or is there a way that a user can change their own password if they only have public key authentication?
Now provide the response and nothing else.
|
Sudo, in its most common configuration, requires the user to type their password. Typically, the user already used their password to authenticate into the account, and typing the password again is a way to confirm that the legitimate user hasn't abandoned their console and been hijacked. In your setup, the user's password would be used only for authentication to sudo. In particular, if a user's SSH key is compromised, the attacker would not be able to elevate to root privileges on the server. The attacker could plant a key logger into the account, but this key logger would be detectable by other users, and could even be watched for automatically. A user normally needs to know their current password to change it to a different password. The passwd program verifies this (it can be configured not to, but this is not useful or at all desirable in your scenario). However, root can change any user's password without knowing the old one; hence a user with sudo powers can change his own password without entering it at the passwd prompt by running sudo passwd $USER . If sudo is configured to require the user's password, then the user must have typed the password to sudo anyway. You can disable password authentication selectively. In your situation, you would disable password authentication in ssh, and possibly in other services. Most services on most modern unices (including Ubuntu) use PAM to configure authentication methods. On Ubuntu, the PAM configuration files live in /etc/pam.d . To disable password authentication, comment out the auth … pam_unix.so line in /etc/pam.d/common-auth . Furthermore, make sure you have PasswordAuthentication no in /etc/ssh/sshd_config to disable sshd's built-in password authentication. You may want to allow some administrative users to log in with a password, or to allow password authentication on the console. This is possible with PAM (it's pretty flexible), but I couldn't tell you how off the top of my head; ask a separate question if you need help.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/37633', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/10287/']}
|
jdg_370872
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22777049
|
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 array that will be 100 * 100, I can access any point like map[x][y] It kinda will look like this: for i in map: for ii in i: print ii, print '\n', output: . . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . .. . . . . . . . . . . I want to make a circle in it like: . . . . . # . . . . .. . . # # . # # . . .. . # . . . . . # . .. # . . . . . . . # .. # . . . . . . . # .# . . . . . . . . . #. # . . . . . . . # .. # . . . . . . . # .. . # . . . . . # . .. . . # # . # # . . .. . . . . # . . . . . How can i do this? I want to try and make a triangulation system where i will find the point that 3 circles will overlap.Is there any other way I can achieve this. I just want to get the distance (dots from center) and the direction.
Now provide the response and nothing else.
|
The basic formula for a circle is (x - a)**2 + (y - b)**2 = r**2 Where (x, y) is a point, (a, b) is the center of the circle and r is the radius. width, height = 11, 11a, b = 5, 5r = 5EPSILON = 2.2map_ = [['.' for x in range(width)] for y in range(height)]# draw the circlefor y in range(height): for x in range(width): # see if we're close to (x-a)**2 + (y-b)**2 == r**2 if abs((x-a)**2 + (y-b)**2 - r**2) < EPSILON**2: map_[y][x] = '#'# print the mapfor line in map_: print ' '.join(line) This results in . . . # # # # # . . .. . # . . . . . # . .. # . . . . . . . # .# . . . . . . . . . ## . . . . . . . . . ## . . . . . . . . . ## . . . . . . . . . ## . . . . . . . . . #. # . . . . . . . # .. . # . . . . . # . .. . . # # # # # . . . You'll have to fiddle with the value for EPSILON with this method. Alternatively, iterate by angle and calculate the (x,y) coordinate as you go import math# draw the circlefor angle in range(0, 360, 5): x = r * math.sin(math.radians(angle)) + a y = r * math.cos(math.radians(angle)) + b map_[int(round(y))][int(round(x))] = '#' Gives: . . . # # # # # . . .. # # . . . . . # # .. # . . . . . . . # .# . . . . . . . . # ## . . . . . . . . . ## . . . . . . . . . ## . . . . . . . . . ## . . . . . . . . . #. # . . . . . . . # .. # # . . . . . # # .. . . # # # # # . . .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22777049', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3157252/']}
|
jdg_370873
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22992814
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Game I'm working on currently needs to let people time in their name for highscore board. I'm slightly familiar with how to deal with key presses, but I've only dealt with looking for specific ones. Is there an easy way to get the letter of any key pressed without having to do something like this: for event in pygame.event.get(): if event.type == KEYUP: if event.key == K_a: newLetter = 'a' elif event.key == K_b: newLetter = 'b' ... elif event.key == K_z: newLetter = 'z' While that would work, I have a feeling there is a more efficient way to go about it. I just can't figure it out or find any guides on it.
Now provide the response and nothing else.
|
There a basically two ways: Option 1: use pygame.key.name() . It's as simple as for event in pygame.event.get(): if event.type == pygame.KEYDOWN: print(pygame.key.name(event.key)) The advantage over using chr is that chr works only if the value of event.key is between 0 and 255 (inclusive). If you press menu , Alt Gr , Tab or LShift , pygame.key.name will happily return menu , alt gr , tab and left shift , while chr will crash, crash, return whitespace, and crash. Option 2: use the unicode attribute of the pygame.KEYDOWN event for event in pygame.event.get(): if event.type == pygame.KEYDOWN: print(event.unicode) It will get you the letter/number or an empty string when using a function key, and it will also take modifiers into account, e.g. if you hold Shift while pressing a it will return A instead of just a . The pygame.KEYDOWN event has additional attributes unicode and scancode. unicode represents a single character string that is the fully translated character entered. This takes into account the shift and composition keys. scancode represents the platform-specific key code.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22992814', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3474776/']}
|
jdg_370874
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15384
|
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the difference between superchargers and turbochargers? I looked it up before but I really don't understand what the difference is.
Now provide the response and nothing else.
|
Both turbochargers and superchargers perform the same function: compress air that will be fed into the engine. In other words, they are glorified air compressors. As with any compressor, both need energy in order to compress the air, which is where the difference between the two devices becomes relevant. Superchargers are belt-driven or chain-driven, so the compressor rotor is mechanically coupled to the rotation of the engine; when the engine rotates, the supercharger vanes rotate and compress air. Turbochargers use a completely different energy source - hot exhaust gases. The idea here is to make use of the hot gases to spin a turbine, which turns a shaft that turns the compressor vanes. As the hot exhaust gases perform work in turning the shaft, they cool down. The difference is concisely captured on this HowStuffWorks page: Unlike turbochargers, which use the exhaust gases created by combustion to power the compressor, superchargers draw their power directly from the crankshaft. Most are driven by an accessory belt, which wraps around a pulley that is connected to a drive gear. The drive gear, in turn, rotates the compressor gear. The rotor of the compressor can come in various designs, but its job is to draw air in, squeeze the air into a smaller space and discharge it into the intake manifold. Comparing the two... Both technologies have their advantages and disadvantages; the "better" choice depends on a number of factors which include design philosophy, cost, available space, controller complexity and desired torque/power gains. Having said that, there are plenty of "forced-induction" configurations out in the wild, ranging from single superchargers to twin-turbo and three-turbo (!) setups. In fact, some VW engines operate a turbocharger and a supercharger in tandem.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mechanics.stackexchange.com/questions/15384', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/9395/']}
|
jdg_370875
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
55597102
|
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 build a sidebar navigation menu and thought I'd take advantage of the new State hook in React. I've read the docs but can't seem to find an example similar to what I need, which is quite simply to toggle a CSS class on click which will in turn open and close my menu. Here's what I've tried: const SidebarMenuItem = ({ component }) => { const [ menuActive, setMenuState ] = useState(false); return ( <li className="p-sidebar-menu-item"> menuActive: { menuActive } <button className="p-sidebar-menu-item__link" onClick={() => setMenuState(!menuActive)}>{ component.component }</button> { component.children && ( <ul className="p-sidebar-menu"> <li><a href={`/${component.slug}`}>Overview</a></li> { component.children.map((subPage, key) => ( <li key={ key }> <a href={`/${subPage.slug}`}>{ subPage.name }</a> </li> ))} </ul> )} </li> )}export default SidebarMenuItem; Any ideas where I'm going wrong? Thanks
Now provide the response and nothing else.
|
Just make the className dynamic, so instead of setting <li className="p-sidebar-menu-item"> transform it in a template literal <li className={`p-sidebar-menu-item`}> and then add your class conditionally (the "yellow" class in my example) <li className={`p-sidebar-menu-item ${menuActive ? "yellow" : ""}`}> Take a look at this CodeSandbox : here I've just added your component and changed the way the className attribute is generated. If you want to avoid the ternary operator you could use the classnames module and then update your code to import c from "classnames";.........<li className={c("p-sidebar-menu-item", {yellow: menuActive})}> Another clean solution can be to generate the className string in advance, for example let classes = "p-sidebar-menu-item";if(menuActive) { classes += " yellow";}<li className={classes}> Let me know if you need some more help
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55597102', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/838685/']}
|
jdg_370876
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1931784
|
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 would I figure this out? I added delete-trailing-whitespace to the before-save-hook in my c-mode-common-hook , but it looks like delete-trailing-whitespace is getting called for every file, not just buffers using c-mode and derivatives. Can I make the before-save-hook buffer local?
Now provide the response and nothing else.
|
Add it to write-contents-functions instead: (add-hook 'c-mode-common-hook (lambda() (add-hook 'write-contents-functions (lambda() (save-excursion (delete-trailing-whitespace))) nil t))) As the Emacs Lisp Reference Manual explains: This works just like write-file-functions, but it is intended for hooks that pertain to the buffer's contents, not to the particular visited file or its location. Such hooks are usually set up by major modes, as buffer-local bindings for this variable. This variable automatically becomes buffer-local whenever it is set; switching to a new major mode always resets this variable, but calling set-visited-file-name does not. This works properly for me in Emacs 24.2.1 (i.e., it deletes all trailing whitespace from C files but preserves trailing whitespace in all other file types).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1931784', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/48082/']}
|
jdg_370877
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14580233
|
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 run simulations on a Windows 64bit-computer with 64 GB RAM . Memory use reaches 55% and after a finished simulation run I remove all objects in the working space by rm(list=ls()) , followed by a double gc() . I supposed that this would free enough memory for the next simulation run, but actually memory usage drops by just 1% . Consulting a lot of different fora I could not find a satisfactory explanation, only vague comments such as: "Depending on your operating system, the freed up memory might not be returned to the operating system, but kept in the process space." I'd like to find information on: 1) which OS and under which conditions freed memory is not returned to the OS, and 2) if there is any other remedy than closing R and start it again for the next simulation run?
Now provide the response and nothing else.
|
How do you check memory usage? Normally virtual machine allocates some chunk of memory that it uses to store its data. Some of the allocated may be unused and marked as free. What GC does is discovering data that is not referenced from anywhere else and marking corresponding chunks of memory as unused, this does not mean that this memory is released to the OS. Still from the VM perspective there's now more free memory that can be used for further computation. As others asked did you experience out of memory errors? If not then there's nothing to worry about. EDIT: This and this should be enough to understand how memory allocation and garbage collection works in R. From the first document: Occasionally an attempt is made to release unused pages back to the operating system. When pages are released, a number of free nodes equal to R_MaxKeepFrac times the number of allocated nodes for each class is retained. Pages not needed to meet this requirement are released. An attempt to release pages is made every R_PageReleaseFreq level 1 or level 2 collections. EDIT2: To see used memory try running gc() with verbose set to TRUE: gc(verbose=T) Here's a result with an array of 10'000'000 integers in memory: Garbage collection 9 = 1+0+8 (level 2) ... 10.7 Mbytes of cons cells used (49%)40.6 Mbytes of vectors used (72%) used (Mb) gc trigger (Mb) max used (Mb)Ncells 198838 10.7 407500 21.8 350000 18.7Vcells 5311050 40.6 7421749 56.7 5311504 40.6 And here's after discarding reference to it: Garbage collection 10 = 1+0+9 (level 2) ... 10.7 Mbytes of cons cells used (49%)2.4 Mbytes of vectors used (5%) used (Mb) gc trigger (Mb) max used (Mb)Ncells 198821 10.7 407500 21.8 350000 18.7Vcells 310987 2.4 5937399 45.3 5311504 40.6 As you can see memory used by Vcells fell from 40.6Mb to 2.4Mb.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14580233', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1459111/']}
|
jdg_370878
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
38459309
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Probably many of you (as me), have problem with creating ViewPager with bottom dots, like this: How do you create such an Android ViewPager?
Now provide the response and nothing else.
|
All we need are: ViewPager , TabLayout and 2 drawables for selected and default dots. Firstly, we have to add TabLayout to our screen layout, and connect it with ViewPager . We can do this in two ways: Nested TabLayout in ViewPager <androidx.viewpager.widget.ViewPager android:id="@+id/photos_viewpager" android:layout_width="match_parent" android:layout_height="match_parent"> <com.google.android.material.tabs.TabLayout android:layout_width="match_parent" android:layout_height="wrap_content"/></androidx.viewpager.widget.ViewPager> In this case TabLayout will be automatically connected with ViewPager , but TabLayout will be next to ViewPager , not over it. Separate TabLayout <androidx.viewpager.widget.ViewPager android:id="@+id/photos_viewpager" android:layout_width="match_parent" android:layout_height="match_parent"/><com.google.android.material.tabs.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="wrap_content"/> In this case, we can put TabLayout anywhere, but we have to connect TabLayout with ViewPager programmatically ViewPager pager = (ViewPager) view.findViewById(R.id.photos_viewpager);PagerAdapter adapter = new PhotosAdapter(getChildFragmentManager(), photosUrl);pager.setAdapter(adapter);TabLayout tabLayout = (TabLayout) view.findViewById(R.id.tab_layout);tabLayout.setupWithViewPager(pager, true); Once we created our layout, we have to prepare our dots. So we create three files: selected_dot.xml , default_dot.xml and tab_selector.xml . selected_dot.xml <?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape android:innerRadius="0dp" android:shape="ring" android:thickness="8dp" android:useLevel="false"> <solid android:color="@color/colorAccent"/> </shape> </item></layer-list> default_dot.xml <?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape android:innerRadius="0dp" android:shape="ring" android:thickness="8dp" android:useLevel="false"> <solid android:color="@android:color/darker_gray"/> </shape> </item></layer-list> tab_selector.xml <?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/selected_dot" android:state_selected="true"/> <item android:drawable="@drawable/default_dot"/></selector> Now we need to add only 3 lines of code to TabLayout in our XML layout. app:tabBackground="@drawable/tab_selector"app:tabGravity="center"app:tabIndicatorHeight="0dp"
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/38459309', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4631935/']}
|
jdg_370879
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3402214
|
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 about to work through a book, "Flex on Java" and it's asked me to install maven 2+ i downloaded maven from the apache site. Added : M2_HOME = C:\apache-maven-2.2.1 and M2 = %M2_HOME%\bin to the environment vars according to the instructions at http://maven.apache.org/download.html then it gets to number 6 which says "In the same dialog, update/create the Path environment variable in the user variables and prepend the value %M2% to add Maven available in the command line." Which environment variable should i edit and add %M2% to? After googling i found a post which says "append", not prepend to the value of JAVA_HOME I've tried prepending and appending it to the java home var but when i try to do an mvn command from the command line it says its not recognised. Never used maven before so this is my first set up. Can anyone see what i'm not doing right or what else i need to do to be able to use the mvn command, please and thank you.
Now provide the response and nothing else.
|
The environment variable you should edit is path . The route on Windows 7 is: Control Panel -> System -> Advanced system settings -> Advanced Tab -> Environment Variables -> The path variable is right on the system variable s area The path variable specifies a group of directories and/or paths that Windows searches for commands definitions. You should append to the end of this variable value the value ;%M2% ( note the semi-colon, different paths should be separated by them) in order for Windows to be able to find the Maven command definitions. Appending ;%M2 at the end of the path environment variables is the same as appending ;C:\apache-maven-2.2.1\bin To test that everything is ok, type mvn --version , if everything is right then the current Maven version you're using should be displayed on the screen.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3402214', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/400048/']}
|
jdg_370880
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4115115
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I extract a substring from within a string in Ruby? Example: String1 = "<name> <substring>" I want to extract substring from String1 (i.e. everything within the last occurrence of < and > ).
Now provide the response and nothing else.
|
String1.scan(/<([^>]*)>/).last.first scan creates an array which, for each <item> in String1 contains the text between the < and the > in a one-element array (because when used with a regex containing capturing groups, scan creates an array containing the captures for each match). last gives you the last of those arrays and first then gives you the string in it.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4115115', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/232619/']}
|
jdg_370881
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20
|
Below is a question asked on the forum earthscience.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Some weather models include GFS ( Global Forecast System ) and NAM ( North American Mesoscale Model ). Some climate models include CCSM ( Community Climate System Model ) and the NASA GISS ( Goddard Institute for Space Studies ) model. What are the differences in the types of physics, parameterizations, and other properties that they use?
Now provide the response and nothing else.
|
The major differences between weather and climate models are many. At their core lie the same set of primitive equations, but from here there are many differences. A weather model only (skillfully) predicts about 10 days into the future, while a climate model integrates forward in time for hundreds of years. The main difference here is that in a weather model, we care about the when and where of a storm or front. In a climate model, you get weather, but you don't really care too much where or exactly when the weather is as you are looking for a long term means (e.g. a weather model cares where a hurricane is, and when/where it will impact land, whereas a climate model may only care the average number of hurricanes per year and not about where the details of those storms). Other differences: Spatial / temporal resolution Because climate models run for much longer into the future than a weather model, it will have more integration timesteps for the same temporal scale. This is relaxed by increasing the model timestep, but for numerical stability reasons the higher your timestep the more coarse your spatial resolution must be. As a result, in general, climate models run at larger temporal and spatial scales than weather models. The coarser resolution may force more parameterizations in the climate models. For example a 3 km weather model may explicitly resolve convection, whereas a 30 km climate model will certainly not and need to parameterize convection. Data Assimilation (DA) Weather and climate models vary in their use of DA. The biggest difference is how DA is used to "spin up" the model to the initialization time. For weather models, if DA is used at all, you may only have a few DA steps spaced a few hours apart before the model starts integrating into the future. For a climate model the DA period may be 100 years long before the present time is reached and forecasting begun. However: This incorporation [of DA into climate models] occurs at a number of stages of the model development, including parametrization of sub-grid scale effects and model tuning. The process is not, however, done systematically and current practice is not thought of as "data assimilation." There seems to be a growing realization that DA will have a significant role to play in future climate model development. This is, in part, driven by the need to quantify uncertainty in the model predictions. Nevertheless, there is not a consensus as to how DA should be used in these large-scale climate models. (source: http://www.samsi.info/working-groups/data-assimilation-ipcc-level-models-climate-uq ) Coupled models Weather models may represent the ocean as a parameterized surface flux (of momentum, moisture, etc) or perhaps handle it through data assimilation. Climate models typically couple the atmosphere model to an ocean model and simulate the ocean as well. The climate models in actuality are typically suites of models that all communicate with each other. You may have a model for atmosphere, one for soil, one for ocean, one for vegetation, one for chemistry, etc. A weather model may have these features, but typically as parameterizations. Spatial coverage Weather models vary from global models to very localized regional models, which can in some cases be very idealized. Climate models tend to be global. This doesn't change the physics involved, but can influence the specific forms of the equations. A global model will solve in spherical coordinates and many use spectral methods. Regional weather models will use Cartesian coordinates and may make other assumptions that simplify the physics for the specific purpose the model (e.g. a storm scale idealized weather model may neglect Coriolis).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://earthscience.stackexchange.com/questions/20', 'https://earthscience.stackexchange.com', 'https://earthscience.stackexchange.com/users/10/']}
|
jdg_370882
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23106012
|
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 successfully setup a Raspberry PI VM on my Mac OS X via QEMU. Now I want to access the filesystem of this VM from my Mac. When I call ifconfig on my VM I get this. And here the content of my /etc/network/interfaces file On my Mac en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500 options=10b<RXCSUM,TXCSUM,VLAN_HWTAGGING,AV> ether 3c:07:54:65:da:50 inet6 fe80::3e07:54ff:fe65:da50%en0 prefixlen 64 scopeid 0x4 inet6 fdbf:a879:6730::3e07:54ff:fe65:da50 prefixlen 64 autoconf inet6 fdbf:a879:6730::401e:56f5:f2f9:a236 prefixlen 64 autoconf temporary inet 192.168.1.119 netmask 0xffffff00 broadcast 192.168.1.255 nd6 options=1<PERFORMNUD> media: autoselect (1000baseT <full-duplex,flow-control>) status: active I think the reason is, that the VM uses some kind of Shared Network. Is there a way that the VM get the IP address from my router?
Now provide the response and nothing else.
|
The easier method - less flexible but you don't need to muck around so much They way you have configured qemu appears to be the default host NAT network (aka. qemu -net nic -net user configuration) By default, your host (your Mac in this case) will be found on 10.0.2.2 when accessed from your guest. From inside your guest you can connect to services on your host (your MAC) at 10.0.2.2. But this is using NAT, so you can't go back the other way as easily. For example, if you decide to you want to connect to the SSH service and a web server running inside your guest, you will need to start qemu with modified options like the following: qemu -net nic -net user,hostfwd=tcp::2222-:22,hostfwd=tcp::22280-:80 What this will do is route connections from port 22280 on your host (your MAC) to port 80 inside your qemu guest, (same for port 2222 --> port 22 in the guest) Which means you can browse to http://localhost:22280 on your Mac, to get to the web server in your virtual Raspberry Pi, etc. FTP and SMB will be more complicated to setup this way because of the different ports used and they way they are used, etc. although if you setup FTP to use PASV mode it wont be too much of a problem. The more complicated method This involves doing what you suggested, configuring the virtual machine quest to be able to get an IP address from your router. In this case, you need to make a bridge from your virtual machine onto your hosts network. This requires a lot more setup than can be quickly explained here, but essentially, you need to assign your NIC to a vlan and add a tap interface, for example: qemu -net nic,vlan=0 -net tap,ifname=tap0 This however requires more setup on the host (initially, manual, as you figure out your own situation, but then, scriptable) to create a bridge and tap interface - which usually requires root access beyond that needed to simply run qemu . A bit of Googling brings up a variety of methods to do this, because it varies more depending on your setup. (I found an example setup script here: https://gist.github.com/EmbeddedAndroid/6572715 ) Note - network MAC addresses, network card models, etc. and other qemu options omitted for clarity. The SAMBA method Note: I have only tried this under Linux You can enable a samba server inside qemu: qemu -smb /path/to/files This creates a SMB share accessible from inside the guest at \10.0.2.4\qemu mapped from /path/to/files on the host.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23106012', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1356232/']}
|
jdg_370883
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2365786
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Find the number of integers between $1$ and $10000$ with at least one $8$ and at least one $9$ as digits. There are no $1$-digit such numbers. Two digit numbers are $89$, $98$. Three digit numbers are $989,899,998,988,889,898,999,888$, $89$_ ($8$ nos.), $98$_ ($8$ nos.), _$98$ ($7$ nos.), _$89$(nos.). I cannot count the $4$-digit such numbers using this method. Is there any better method to calculate the answer.The answer is $974$.
Now provide the response and nothing else.
|
Let's count the number of positive integers less than $10000$ in which the digit $8$ or the digit $9$ does not appear. Since both $0$ and $10000$ contain neither an $8$ nor a $9$, the number of positive integers less than or equal $10000$ in which the digit $8$ or the digit $9$ does not appear is equal to the number of nonnegative integers less than $10000$ in which the digit $8$ or the digit $9$ does not appear. A nonnegative integer less than $10000$ can be treated as a four-digit decimal sequence by appending leading zeros to a number with fewer than four digits. For instance, we treat the number $74$ as the sequence $0074$. The number of nonnegative integers less than $10000$ in which the digit $8$ does not appear is $9^4$ since we can fill the thousands place, hundreds place, tens place, and units place with any digit other than $8$. By symmetry, there are also $9^4$ positive integers less than $10000$ in which the digit $9$ does not appear. However, we have counted numbers in which neither the digit $8$ nor the digit $9$ appears twice. There are $8^4$ such numbers. Hence, there are $$2 \cdot 9^4 - 8^4$$positive integers less than or equal to $10000$ in which the digit $8$ or the digit $9$ does not appear. Therefore, there are $$10000 - 2 \cdot 9^4 + 8^4 = 974$$positive integers less than $10000$ in which at least one $8$ and at least one $9$ appear.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2365786', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/262230/']}
|
jdg_370884
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
680807
|
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 $\alpha$ and $\beta$ are the root of the equation $x^2 - 4x +6 =0$ , find the equation whose roots are $\alpha + 1/\beta$ and $\beta + 1/\alpha$.
Now provide the response and nothing else.
|
Hint: Use Viete's Formulas $$\alpha+\frac1\beta=\frac{\alpha\beta+1}\beta=\frac7\beta$$ $$\beta+\frac1\alpha=\frac{\alpha\beta+1}\alpha=\frac7\alpha$$ An equation's thus $$0=\left(x-\frac7\alpha\right)\left(x-\frac7\beta\right)=x^2-7\left(\frac{\alpha+\beta}{\alpha\beta}\right)x+\frac{49}{\alpha\beta}$$ and, again, Viete's handy here.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/680807', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/129019/']}
|
jdg_370885
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
60313719
|
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 not data binding, this is View binding which is new to Android Studio 3.6 Canary 11+ described here . For using inside an Activity it is clear, you just use it like this: Let's say we have a layout named activity_main.xml Then in the code we can use it like this: public class MainActivity extends Activity{ ActivityMainBinding binding; //Name of the layout in camel case + "Binding" @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); }} However, It's not clear how to use View Binding with RecyclerView? Edit: Please explain in Java.
Now provide the response and nothing else.
|
Let's say we have a RecyclerView inside activity_main.xml and its id is "@+id/rv_test" Inside the Activity we can use it like so: public class MainActivity extends Activity{ ActivityMainBinding binding; //Name of the layout in camel case + "Binding" @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); binding.rvTest.setLayoutManager(layoutManager); }} Let's name the layout for RecyclerView items test_list_item.xml Then we can implement our adapter inside Activity like this: public class MainActivity extends Activity{ ActivityMainBinding binding; //Name of the layout in camel case + "Binding" @Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); binding = ActivityMainBinding.inflate(getLayoutInflater()); setContentView(binding.getRoot()); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this); binding.rvTest.setLayoutManager(layoutManager); List<String> items = Arrays.asList("item", "item", "item"); binding.rvTest.setAdapter(new MyAdapter(items)); } private class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder>{ private List<String> items; private class MyViewHolder extends RecyclerView.ViewHolder{ TestListItemBinding binding;//Name of the test_list_item.xml in camel case + "Binding" public MyViewHolder(TestListItemBinding b){ super(b.getRoot()); binding = b; } } public MyAdapter(List<String> items){ this.items = items; } @NonNull @Override public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType){ return new MyViewHolder(TestListItemBinding.inflate(getLayoutInflater())); } @Override public void onBindViewHolder(MyViewHolder holder, int position){ String text = String.format(Locale.ENGLISH, "%s %d", items.get(position), position); //An example of how to use the bindings holder.binding.tvTest.setText(text); } @Override public int getItemCount(){ return items.size(); } }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/60313719', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2855059/']}
|
jdg_370886
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
546726
|
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'm creating two apps, master and slave, which communicate over d-bus. My apps work as expected when being run on the same host. Now I want to move slave app to docker container and I'm having problem sharing d-bus session between host and container. Here's my Dockerfile: FROM i386/ubuntu:16.04VOLUME /run/user/1000/ENV DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/busRUN apt-get updateRUN apt-get upgrade -yRUN apt-get install -y dbus#RUN apt-get install -y libnotify-bin#RUN apt-get install -y dbus-x11RUN adduser -u 1000 myuser#COPY dbus.conf /etc/dbus-1/session.d/USER 1000:1000ENTRYPOINT ["dbus-daemon", "--session", "--print-address"] /run/user/1000/bus is the value of my DBUS_SESSION_BUS_ADDRESS variable. And i create container with docker create --mount type=bind,source=/run/user/1000/bus,target=/run/user/1000/bus mycontainer /run/user/1000/bus is visible from within the container but when the container is started it prints the address unix:abstract=/tmp/dbus-iXrYzptYOX,guid=78a790f0f6a4387a39ac3d505da478a3 and my apps cannot communicate. If i add my dbus.conf to /etc/dbus-1/session.d/ in container and override <listen>unix:path=/run/user/1000/bus</listen> I get the message 'Failed to start message bus: Failed to bind socket "/run/user/1000/bus": Address already in use' I'm not sure whether I'm even supposed to be starting dbus-daemon inside docker. How can I make this work?
Now provide the response and nothing else.
|
I've found a solution. Here's my Dockerfile: FROM i386/ubuntu:16.04RUN apt-get updateRUN apt-get upgrade -yRUN apt-get install -y dbusCOPY dbus.conf /etc/dbus-1/session.d/ENTRYPOINT ["dbus-run-session", "slaveApp"] And my dbus.conf: <!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd"><busconfig> <listen>tcp:host=localhost,bind=*,port=6667,family=ipv4</listen> <listen>unix:tmpdir=/tmp</listen> <auth>ANONYMOUS</auth> <allow_anonymous/></busconfig> And set the address variable on host: export DBUS_SESSION_BUS_ADDRESS=tcp:host=${containerIp},port=6667,family=ipv4 In my master app I initiate a connection (I used Qt): QDBusConnection::connectToBus("tcp:host=${containerIp},port=6667", "qt_default_session_bus"); The master app can now send messages to slave app. I haven't tried to send messages from slave to master, though. The answer is taken from this post: https://stackoverflow.com/a/45487266/6509266
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/546726', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/290688/']}
|
jdg_370887
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18054720
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to understand the concept of callback. I have searched on internet about the callbacks and there are many examples using interface, and one class is calling a method of another class using that interface. But still I can't get the main concept of callbacks, what is the purpose of using callbacks?
Now provide the response and nothing else.
|
Here is a nice tutorial , which describes callbacks and the use-case well. The concept of callbacks is to inform a class synchronous / asynchronous if some work in another class is done. Some call it the Hollywood principle: "Don't call us we call you". Here's a example: class A implements ICallback { MyObject o; B b = new B(this, someParameter); @Override public void callback(MyObject o){ this.o = o; }}class B { ICallback ic; B(ICallback ic, someParameter){ this.ic = ic; } new Thread(new Runnable(){ public void run(){ // some calculation ic.callback(myObject) } }).start(); }interface ICallback{ public void callback(MyObject o);} Class A calls Class B to get some work done in a Thread. If the Thread finished the work, it will inform Class A over the callback and provide the results. So there is no need for polling or something. You will get the results as soon as they are available. In Android Callbacks are used f.e. between Activities and Fragments. Because Fragments should be modular you can define a callback in the Fragment to call methods in the Activity.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/18054720', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2523009/']}
|
jdg_370888
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
198560
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it generally safe to rest a low voltage powered up circuit board on an anti-static bag when debugging? A simple meter reading suggests it is a good insulator, but it must conduct to some extent? Ditto on anti-static mat on the workbench
Now provide the response and nothing else.
|
There are different bags available. Some of them are insulators (nearly, see below) and only prevent the build-up of static charge. Others are conducting (grey-metallic ones typically or black ones). I wouldn't place any powered electronics on conducting anti-static bags or mats. Even the fairly high resistance can have a big influence on the electronics (depending on function and design). Low powered stuff often works with fairly high resistance values, so the effect of parallel resistance there is quite profound. I often use a sheet of paper to put my circuit boards on (note it can be charged, so make sure to wipe the charges off). Or just a holder where you clamp it from both sides so the main area has no contact at all (like when it is installed somewhere). Update: I'm not an expert on ESD and anti-static materials, let me try anyway: Materials are divided into different classes depending on their sheet resistance (Ohms per square): \$10^{13}\$ and greater: insulators and basic plastics \$10^{9}\$-\$10^{12}\$: anti-static \$10^{5}\$-\$10^{9}\$: dissipative \$10^{3}\$-\$10^{5}\$: conductive Everything below that doesn't belong in the field of ESD anymore. So the insulators and basic plastics are not able in any way to let charges move on their surface or through them. If they get charged, the charge stays there until it is dissipated in some way (discharge on you or an IC, in humid air it will decrease over time). Anti-static materials have still a very high resistivity, so that you probably are not able to measure it with a normal multimeter. They are just a little bit conducting, so that the surface charge cannot build up. The triboelectric effect (charging through rubbing something etc.) is prevented. This gives a very basic protection. You can easily zap through a bag with a static discharge. These bags are usually pink in color, they are made of a pink polyethylene. This is what I had in mind when I wrote "Some of them are insulators and only prevent the build-up of static charge." So it's not true. It's just that the resistance is very very high (gigaohm range) and unlikely to cause a problem, but if the resistivity is at the lower end of the range, it might. I recommend watching the two videos from EEVblog: #247 and #250 . Dave actually shows that the mats are not conductive enough to make problems with measurements. One thing which is mentioned in the research is that the materials used do not behave as a simple Ohmic element, so the resistivity can be voltage dependent. The stuff gets usually tested at 500V to take that into account, but you never know.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/198560', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/56642/']}
|
jdg_370889
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1010080
|
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 $A$ be an $n\times n$ matrix and $\lambda_\max$ be the maximum eigenvalue of $A$. The trace of $A^T A$ is equal to the sum of its eigenvalues. I am trying to show that $$ \lambda_\max \le \text {tr}( A^TA)$$ It holds that $A$ and $A^T$ have the same eigenvalues. However, I don't know what to say about the eigenvalues of $A^T A$. I cannot come up with a relationship between them and the eigenvalues of $A$. Any ideas on where to start are appreciated.
Now provide the response and nothing else.
|
This identity appears false in general. Consider $$A = \begin{pmatrix} \frac{1}{2} \ \ 0 \\ 0 \ \ \frac{1}{3}\end{pmatrix}$$ Then $$\hbox{tr}(A^TA) = \hbox{tr}\begin{pmatrix} \frac{1}{4} \ \ 0 \\ 0 \ \ \frac{1}{9}\end{pmatrix} = \frac{13}{36} < \frac{1}{2} = \lambda_{max}$$ Perhaps the result is recoverable if all eigenvalues $\lambda \geq 1$. But that may not be useful to you.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1010080', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/54821/']}
|
jdg_370890
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
40661684
|
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 following the wildml blog on text classification using tensorflow. I am not able to understand the purpose of max_document_length in the code statement : vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length) Also how can i extract vocabulary from the vocab_processor
Now provide the response and nothing else.
|
I have figured out how to extract vocabulary from vocabularyprocessor object. This worked perfectly for me. import numpy as npfrom tensorflow.contrib import learnx_text = ['This is a cat','This must be boy', 'This is a a dog']max_document_length = max([len(x.split(" ")) for x in x_text])## Create the vocabularyprocessor object, setting the max lengh of the documents.vocab_processor = learn.preprocessing.VocabularyProcessor(max_document_length)## Transform the documents using the vocabulary.x = np.array(list(vocab_processor.fit_transform(x_text))) ## Extract word:id mapping from the object.vocab_dict = vocab_processor.vocabulary_._mapping## Sort the vocabulary dictionary on the basis of values(id).## Both statements perform same task.#sorted_vocab = sorted(vocab_dict.items(), key=operator.itemgetter(1))sorted_vocab = sorted(vocab_dict.items(), key = lambda x : x[1])## Treat the id's as index into list and create a list of words in the ascending order of id's## word with id i goes at index i of the list.vocabulary = list(list(zip(*sorted_vocab))[0])print(vocabulary)print(x)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40661684', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3898714/']}
|
jdg_370891
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2546249
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We are writing an API for iphone developers and we don't know what the best practice is for exception handling. We looked into NSError , standard POSIX way, NSException What is the convention that most APIs use? Which is the most "Objective-C friendly"?
Now provide the response and nothing else.
|
From the Introduction to Exception Programming Topics : Important : You should reserve the use of exceptions for programming or unexpected runtime errors such as out-of-bounds collection access, attempts to mutate immutable objects, sending an invalid message, and losing the connection to the window server. You usually take care of these sorts of errors with exceptions when an application is being created rather than at runtime. ... Instead of exceptions, error objects (NSError) and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors in Cocoa applications. For further information, see Error Handling Programming Guide For Cocoa . So as I understand it, only use exceptions when something is fatally wrong. Otherwise, use NSError objects.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2546249', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/64238/']}
|
jdg_370892
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31734
|
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Philipp comments : ...We all know that one side's terrorists are another side's freedom fighters... Suppose big Country X provides arms to little Country y 's native "freedom fighters" , who do certain scary things, ( "for freedom!" ), which goes on for a decade or so, but then Country y 's freedom fighters wind up fighting against Country X , doing the same scary things, which Country X now labels "terrorism" . Meanwhile Country y 's fighters still consider themselves freedom fighters, and let's suppose that for the average fighter from Country y the daily routine never changed, they still get up in the morning, report in, and follow orders to get the same-old same old scary things done. That'd be a subjective usage of the term "terrorism" . Is there a non -subjective usage of the term, one that both sides could agree upon as unequivocally terrorism, irrespective of the cause or target? If not, is there any non -subjective term, (which describes the job of doing the scary things Country y 's fighters do), that both sides would always agree upon?
Now provide the response and nothing else.
|
TL;DR: Yes, there is an objective term. No, there is no way to force people to use the term objectively in political contexts and they don't tend to. The term "terrorism" isn't subjective. Or to be more precise, it has a widely accepted, objective definition accepted by major institutions. Quoting Wikipedia : Since 1994, the United Nations General Assembly has repeatedly condemned terrorist acts using the following political description of terrorism: "Criminal acts intended or calculated to provoke a state of terror in the general public, a group of persons or particular persons for political purposes are in any circumstance unjustifiable, whatever the considerations of a political, philosophical, ideological, racial, ethnic, religious or any other nature that may be invoked to justify them." And: A definition proposed by Carsten Bockstette at the George C. Marshall Center for European Security Studies underlines the psychological and tactical aspects of terrorism: Terrorism is defined as political violence in an asymmetrical conflict that is designed to induce terror and psychic fear (sometimes indiscriminate) through the violent victimization and destruction of noncombatant targets (sometimes iconic symbols). Such acts are meant to send a message from an illicit clandestine organization. The purpose of terrorism is to exploit the media in order to achieve maximum attainable publicity as an amplifying force multiplier in order to influence the targeted audience(s) in order to reach short- and midterm political goals and/or desired long-term end states." Note that the three components are required, which makes this an objective definition: Acts that are intended to instill fear/terror Acts against general public (civilians/non-combatants) . This is why for example attacks on the military during armed conflict generally aren't universally considered terrorism. For a political purpose (note that just what the purpose is is 100% irrelevant to the definition, as long as it's politics and not, say, robbery ) Now, the confusion that birthed your question arises out of two things: You (or whatever your sources are) are confusing the well-defined objective tactics ( terrorism ) with a wholly orthogonal point, the goal of the movement. Yes. The oft-repeated "one man's terrorist is another man's freedom fighter" is basically a word game designed to confuse people. Someone is a terrorist if and only if they engage in above-defined objectively defined acts of terrorism as a tactic. Someone is a freedom fighter if they do something to advance freedom (whether they advance freedom or not is a bit more subjective and squishy, but let's pretend we can agree on that). The two are wholly orthogonal - you can be a freedom fighter using a wide variety of tactics, only one of which - and often, the least effective - is terrorism. You can be a freedom fighter and not a terrorist (Mahatma Gandhi is the typical example) or you can be a terrorist and NOT a freedom fighter (Taliban seems to fit here - they don't by any stretch of imagination fight for anyone's freedom in any stretch of the word; they fight to oppress other inhabitants of Afghanistan into their version of Sharia) or you can be a freedom fighter who engages in acts of terrorism and become both (IRA, Jewish fighters attacking the British during Mandate times, Basque separatists). Also very importantly, just because there is an objective definition, it does not at all mean that political bodies will not disingenuously ignore that definition when it suits their political/ideological purpose . The USSR didn't recognize the IRA as terrorists for a variety of political and ideological reasons. Many people in the USA and Israel refuse to recognize the PKK (a Kurdish organization) as terrorists for the same reason. This willful ignoring of the objective definition applies to both type 1 and type 2 errors. That is, not only people refuse to apply "terrorist" label to clearly objectively terrorist organizations (PKK, Hamas, IRA), but they also apply the label to things that don't fit that definition. TL;DR: Yes there is an objective term. No, there is no way to force people to use the term objectively in political contexts.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://politics.stackexchange.com/questions/31734', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/8647/']}
|
jdg_370893
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9540260
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Since the Windows 8 consumer preview was released a few days ago, I am working on the new WinRT (for Metro Applications) in C# and I had ported my self written IRC class to the new threading and networking. The problem is: My class is running an thread for receiving messages from the server. If this happens, the thread is making some parsing and then firing an event to inform the application about this. The subscribed function then 'should' update the UI (an textblock). This is the problem, the thread cannot update the UI and the invoker method that has worked with .NET 4.0 doesn't seem to be possible anymore. Is there an new workaround for this or even an better way to update the UI ? If I try to update the UI from the event subscriber i will get this Exception : The application called an interface that was marshalled for a different thread (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
Now provide the response and nothing else.
|
The preferred way to deal with this in WinRT (and C# 5 in general) is to use async - await : private async void Button_Click(object sender, RoutedEventArgs e){ string text = await Task.Run(() => Compute()); this.TextBlock.Text = text;} Here, the Compute() method will run on a background thread and when it finishes, the rest of the method will execute on the UI thread. In the meantime, the UI thread is free to do whatever it needs (like processing other events). But if you don't want to or can't use async , you can use Dispatcher , in a similar (although different) way as in WPF: private void Button_Click(object sender, RoutedEventArgs e){ Task.Run(() => Compute());}private void Compute(){ // perform computation here Dispatcher.Invoke(CoreDispatcherPriority.Normal, ShowText, this, resultString);}private void ShowText(object sender, InvokedHandlerArgs e){ this.TextBlock.Text = (string)e.Context;}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9540260', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1245878/']}
|
jdg_370894
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5919300
|
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: #include "stdafx.h"#include <iostream>using namespace std;#include <conio.h>#include <cstring>#include <iomanip>void swap(long a, long b){ long temp; temp=a; a=b; b=temp;}int _tmain(int argc, _TCHAR* argv[]){ int x = 5, y = 3; cout << x ; cout << y << endl; swap(x, y); cout << x ; cout << y << endl; getch(); return 0;} The program gives the output: 5 33 5 The program actually swaps the values! Why is that? The parameters of the swap() are not pointers or references. (I am using VS 2005)
Now provide the response and nothing else.
|
Your swap function isn't being called at all. One of the Standard Library includes that you have included is pulling in <utility> , which declares a function template named swap in the std namespace. Since you are using namespace std; , that swap function is being brought into the global namespace and it is called instead. Why is std::swap chosen instead of your swap function? Your swap function takes two long s by value; to call that function, an integer promotion is required for each of the int arguments. std::swap is a function template. It takes two references to T , and when that function template is instantiated with T = int , both arguments are an exact match. So, std::swap is a better match than your function and it is therefore selected during overload resolution. This is one reason that using namespace std; is evil and should be avoided. If you remove the using directive, your function will be the only function available and it will be called.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5919300', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/253656/']}
|
jdg_370895
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
356884
|
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 commutative associative unital algebra over a field of characteristic zero. Is it true that any derivation of it preseves its nil-radical? More explicitly, let $D$ be a derivation of an algebra $A$ . Let $N$ denote the nil-radical of $A$ . Is it true that $D(N)\subset N?$
Now provide the response and nothing else.
|
Suppose $x\in N$ , so that $x^n=0$ for some $n$ . Then using the product rule for derivations many times, we see that $$ 0=D^n(x^n)=n! D(x)^n+Y, $$ where $Y$ is divisible by $x$ . Therefore, $D(x)^{n^2}=(D(x)^n)^n$ is divisible by $x^n$ , and therefore vanishes. Thus, $D(x)$ is nilpotent, and therefore $D(N)\subset N$ .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/356884', 'https://mathoverflow.net', 'https://mathoverflow.net/users/16183/']}
|
jdg_370896
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7120052
|
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 hashmap:Map dateEvent = new HashMap(); where key is a date and time and value is a string.I fill collection with data where date is in format dd.MM.yyyy HH:mm.How I can get all keys with date based on this format: dd.MM.yyyy?
Now provide the response and nothing else.
|
This code will do the trick: public static void findEvents(Map<Date, Event> dateEvents, Date targetDate) { SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy"); String target = dateFormat.format(targetDate); for (Map.Entry<Date, Event> entry : dateEvents.entrySet()) { if (dateFormat.format(entry.getKey()).equals(target)) { System.out.println("Event " + entry.getValue() + " is on the specified date"); } }} The important thing here is that all dates are converted to a String with format "dd.MM.yyyy" before comparing, so any differences in hour/minute/second still match if the day is the same. This code also demonstrates the best way (IMHO) to iterate over a map.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7120052', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/902201/']}
|
jdg_370897
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29888172
|
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 to Implement Action bar app icon missing with Android 5 in mono.android and I have already used this link Action bar app icon missing with Android 5 but its not working.
Now provide the response and nothing else.
|
With first two options, you provide a certificate of your own, that might (should) be either signed by a recognized authority or by your client if you manage them (this happens either if your application is deployed in a context where you can install your certificate on each computer or if your client is not a web browser but your application and you can ship the certificate with it). This will show the user he is communicating with the real server, not with someone trying to eavesdrop the traffic. The third option will create a self-signed certificate, offering no guarantee to the user on that matter. In terms of user experience, using a self-signed certificate when the client is a Web browser will raise a worrying message about the certificate validity, and saying something like "serious web sites would not ask you to blindly accept an unknown certificate". To sum-up, you have three options (your options 1 & 2 are the same in the end): option 1 & 2 with a certificate signed by a recognized authority: the only good solution for a public Web application / Web site. option 1 & 2 with a certificate of your own (or signed by an authority of your own), deployed on every client: a good solution when you can install the certificate on each client. A poor solution if you have to ask your clients to do so. option 3: a good solution for testing in a lab. A terrible solution in any other context I can think of.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29888172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1552393/']}
|
jdg_370898
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3880307
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to trigger one event on page load complete using javascript/jquery. Is there any way to trigger event or call a simple function once page loading fully completes. Please suggest folks if you any reference.
Now provide the response and nothing else.
|
Everyone's mentioned the ready function (and its shortcuts), but even earlier than that, you can just put code in a script tag just before the closing body tag (this is what the YUI and Google Closure folks recommend), like this: <script type='text/javascript'>pageLoad();</script></body> At this point, everything above that script tag is available in the DOM. So your options in order of occurrence: Earliest: Function call in script tag just before closing the body tag. The DOM is ready at this point (according to the Google Closure folks, and they should know; I've also tested it on a bunch of browsers). Earlyish: the jQuery.ready callback (and its shortcut forms). Late, after all page elements including images are fully loaded: window onload event. Here's a live example: http://jsbin.com/icazi4 , relevant extract: </body><script type='text/javascript'> runPage(); jQuery(function() { display("From <tt>jQuery.ready</tt> callback."); }); $(window).load(function() { display("From <tt>window.onload</tt> callback."); }); function runPage() { display("From function call at end of <tt>body</tt> tag."); } function display(msg) { var p = document.createElement('p'); p.innerHTML = msg; document.body.appendChild(p); }</script> (Yes, I could have used jQuery for the display function, but I was starting with a non-jQuery template.)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3880307', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/373142/']}
|
jdg_370899
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
336066
|
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:
In relation to the following figure Kline (2016) writes on p194: The numerals (1) in Figure 9.3(b) that appear next to paths from the factors to one of their indicators are scaling constants, or unit loading identification (ULI) constraints. The specifications that $A \rightarrow X_1 = 1.0$ and $B \rightarrow X_4 = 1.0$ scale the factors in a metric related to that of the explained (common) variance of the corresponding indicator, or reference (marker) variable. I understand from this answer that the reason for having the reference variable is so we can determine the variance of the latent variable. However, it wasn't clear to me why this goal was not also relevant to exploratory factor analysis. Why don't we set $A \rightarrow X_1 = 1.0$ in the EFA model? Kline, R. B. (2016). Principles and practice of structural equation modeling. Guilford Press.
Now provide the response and nothing else.
|
Your test sample is a subset of your training sample: x_train = x[0:2635]x_test = x[0:658]y_train = y[0:2635]y_test = y[0:658] This means that you evaluate your model on a part of your training data, i.e., you are doing in-sample evaluation. In-sample accuracy is a notoriously poor indicator to out-of-sample accuracy, and maximizing in-sample accuracy can lead to overfitting. Therefore, one should always evaluate a model on a true holdout sample that is completely independent of the training data. Make sure your training and your testing data are disjoint, e.g., x_train = x[659:2635]x_test = x[0:658]y_train = y[659:2635]y_test = y[0:658]
|
{}
|
{'log_upvote_score': 7, 'links': ['https://stats.stackexchange.com/questions/336066', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/9162/']}
|
jdg_370900
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
107829
|
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:
If I generate a random float value between 0…1, say to 40 digits, or n digits, aren't the chances of getting a true zero (0) or a true one (1) incredibly small? On the zero condition, every 0–9 digit has to be zero, and on the one condition, the first integer must be one and the rest should default to zero. Does that logic of how a number is represented factor in to how random numbers are generated, or otherwise influence how unlikely that result is? I don't have great insight into the scope of how random numbers are generated. If you ask, "What is your definition of a random number?" assume a generated digit could exhibit statistical randomness . Part 2 If I generated numbers within a range, say 5…8, aren't all integer-value results [5,6,7,8] very unlikely as well? Note: This whole question has no intended application; I am just curious. This question was partly influenced by the mathematical elaborations of ViHart on Youtube , specifically Proof some infinities are bigger than other infinities , and extra-specifically Cantor's diagonal argument . P.S. If any moderators want to move this question elsewhere, that's okay with me!
Now provide the response and nothing else.
|
Let's start from theory, and worry about "How To" later. Let's suppose that $U \sim \mathrm{Uniform}(0, 10)$. Now, fix an integer, say $i$. The probability that $i-\epsilon/2 < U < i+\epsilon/2$ is obviously $\epsilon$, for any $0 < \epsilon < 1$. Now, mathematical equality requires $\epsilon \to 0$, and so the probability of observing any integer is 0. But there was nothing magical about choosing an integer. The same is true for any constant in the support of $U$: $\pi$, $e$, $\phi$. It doesn't matter. Now 0 is special (as is 10), because it forms one of the boundaries of the support of $U$, but it doesn't change the result in any way. The very definition of randomness requires that intervals of equal length have equal probability everywhere in the support. Now, on to "how to". Knuth's extremely lucid discussion of random number generation in Volume 2 ( Seminumerical Algorithms ) of The Art of Computer Programming is still an excellent place to learn the basics. One of the things Knuth shows quite clearly is that it is much easier to generate pseudorandom numbers (PRN) badly than it is to generate them well. Intuition suggests that using a PRN generator as input to another should make things "better". Intuition is generally wrong. Generally speaking, PRN algorithms have to be pretty well-balanced in their parameter choices. (This is the problem with Excel's generator, by the way: decent algorithm, bad constants. That is almost more frustrating than a crappy algorithm to me, because the message it sends is, "We don't care.") There are lots of ways PRN generators can screw things up: serial correlation, short periods, non-uniform results, and the list goes on. To the extent that a given PRN generator is bad, it will fail to generate ensembles of values that conform to theory. Users should be aware that lots of bad PRN generators are still out there and in broad use.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/107829', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/52026/']}
|
jdg_370901
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4066699
|
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 noticed that the google maps api has a option "sensor".
Now provide the response and nothing else.
|
"sensor" in GMaps API is not an option, it is an information parameter. Here is what docs say: Use of the Google Maps API(s) requires that you indicate whether your application is using a sensor (such as a GPS locator) to determine the user's location in any Maps API library or service requests. Google Maps doesn't know anything of your users, so it cannot provide their location. It is the other way around: you can determine user's location and give it to Google Maps to place a location pointer and so on. You have several options to get user's location in JS: W3C (HTML 5) Geolocation API (needs browser support); Google Gears API (needs Google Gears installed); gelocation by IP, for instance, MaxMind and HostIP (the least accurate, but works most of the time). If you're developing for a sensor-equipped device (like a mobile phone with GPS reciever) there should be some vendor-specific ways to get the location directly from the device.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4066699', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/84325/']}
|
jdg_370902
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
42407206
|
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 does actually happen in the project, when we do following ionic state commands? restore save clear reset In what kind of situations do we need to use them? I googled about this, but couldn't find any appropriate answer with details. I appreciate any kind of your help.
Now provide the response and nothing else.
|
You could always look into their source code for the Ionic CLI v1/v2 save: 'Save the platforms and plugins into package.json',restore: 'Restore the platforms and plugins from package.json',clear: 'Clear the package.json of cordovaPlugins and cordovaPlatforms, ' 'as well as clear out the platforms and plugins folders',reset: 'Clear out the platforms and plugins directories, and reinstall plugins and platforms', https://github.com/driftyco/ionic-cli/blob/fac1c4d7b49e7c102269f3d5e0acef660d762bf5/lib/ionic/state.js#L20-L33 state has been removed from CLI v3 : The plugins and platforms can be managed entirely by Cordova. Please remove the cordovaPlatforms and cordovaPlugins keys from your package.json file. If you're using Cordova 7, please review the announcement about how Cordova uses config.xml and package.json to manage plugins and platforms.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42407206', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5859957/']}
|
jdg_370903
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
34350514
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here's my fiddle. I just want the " background-image: " in the css to load fully and display after 3 seconds with a quick fade in effect, until then the entire div must be in black color. How it is possible in css or javascript . .initials { position:absolute; background:black; background-image: url("http://static.tumblr.com/lxn1yld/Hnxnxaqya/space.gif"); color:white; margin-top:20px; padding-top:20px; padding-bottom:20px; width:60px; text-align:center; margin-left:20px; font-size:17px; letter-spacing:5px; box-shadow:0px 2px 3px rgba(0,0,0,.15); overflow: hidden; white-space: nowrap;} <div class="initials">A</div>
Now provide the response and nothing else.
|
With some minor changes, I might have achieved what you want with only CSS3.Check the fiddle: http://jsfiddle.net/w11r4o3u/ CSS: .initials { position:relative; background:black; color:white; margin-top:20px; padding-top:20px; padding-bottom:20px; width:60px; text-align:center; margin-left:20px; font-size:17px; letter-spacing:5px; box-shadow:0px 2px 3px rgba(0,0,0,.15); overflow: hidden; white-space: nowrap;}.initials .text { position: relative;}@-webkit-keyframes test { 0% { opacity: 0; } 100% { opacity: 1 }}.initials:before{ content: ""; background-image: url("http://static.tumblr.com/lxn1yld/Hnxnxaqya/space.gif"); position: absolute; top: 0; left: 0; width: 100%; height: 100%; -webkit-animation-name: test; -webkit-animation-duration: 3s; -webkit-animation-fill-mode: forwards; -webkit-animation-timing-function: ease-out; } HTML: <div class="initials"><div class="text">A</div></div> Edited : Now the animation starts after 3 seconds and takes .3s to complete. Here is the fiddle: http://jsfiddle.net/w11r4o3u/1/ To adjust the "velocity" that fadeIn occurs, edit -webkit-animation-duration: .3s; If you want to adjust the animation "delay" to start, edit -webkit-animation-delay: 3s;
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34350514', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5694067/']}
|
jdg_370904
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15535240
|
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 Popen to call a shell script that is continuously writing its stdout and stderr to a log file. Is there any way to simultaneously output the log file continuously (to the screen), or alternatively, make the shell script write to both the log file and stdout at the same time? I basically want to do something like this in Python: cat file 2>&1 | tee -a logfile #"cat file" will be replaced with some script Again, this pipes stderr/stdout together to tee, which writes it both to stdout and my logfile. I know how to write stdout and stderr to a logfile in Python. Where I'm stuck is how to duplicate these back to the screen: subprocess.Popen("cat file", shell=True, stdout=logfile, stderr=logfile) Of course, I could just do something like this, but is there any way to do this without tee and shell file descriptor redirection?: subprocess.Popen("cat file 2>&1 | tee -a logfile", shell=True)
Now provide the response and nothing else.
|
You can use a pipe to read the data from the program's stdout and write it to all the places you want: import sysimport subprocesslogfile = open('logfile', 'w')proc=subprocess.Popen(['cat', 'file'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)for line in proc.stdout: sys.stdout.write(line) logfile.write(line)proc.wait() UPDATE In python 3, the universal_newlines parameter controls how pipes are used. If False , pipe reads return bytes objects and may need to be decoded (e.g., line.decode('utf-8') ) to get a string. If True , python does the decode for you Changed in version 3.3: When universal_newlines is True, the class uses the encoding locale.getpreferredencoding(False) instead of locale.getpreferredencoding(). See the io.TextIOWrapper class for more information on this change.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15535240', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1119779/']}
|
jdg_370905
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
54432936
|
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 compare two near identical files just one has missing entries and what is inside the parenthesis might be different. I am trying to iterate through all of the smaller list comparing to each entry in the larger list until it matches, copying the line into a new file if there is a match, and writing a blank line in the new file if there isn't yet. The problem is at each iteration it starts from the beginning I want it to skip the lines it has already checked from the previous iteration. Is there a way to do this or would it be better to delete lines from file as going along? #opening of filesfh = open('sampleparsefile.txt', "r")fh2 = open('sampleparsefile2.txt', "r")f = open('compared', 'w')#fhw = open('sampleparsefile.txt', "w")# Make each line a list split at open '('line1Split = [line1.split('(')[0] for line1 in fh.readlines()]line2Split = [line2.split('(')[0] for line2 in fh2.readlines()]print(line1Split)print(line2Split)# iterate through line2Split# for item2 in line2Split:for item2 in line2Split: #splitSingleLine = [aVariable.split('(')[0]] # Set a variable to false founditem = False # iterate through each entry in line1Split comparing # to item in line2Split for item1 in line1Split: # While match is not found # boolean variable set to false while (founditem == False): # if they match write the match to a file and break # change boolean variable to true if matched if item1 == item2: founditem = True # if there is a newline character strip it # if there isn't continue on if '\n' in str(item2): x = item2.split('\n')[0] f.write(str(x)) break else: f.write(item2) # WAS HERE but thinking deleting lines from original file would not be good idea #fhw = open('sampleparsefile.txt', "w") #for aLines in fhw.readlines: # if item1 != item2: # line1Split.pop[0] break # also will want to remove found entry from line2split # that way following passes wont search same first lines # will also need to re-attach what was in parenthesis # before writing to file # if match is not found write a new line to file and break else: f.write('\n') breakfh.close()fh2.close()f.close()#Sampleparsefile.txt sample ignore all ## Data1# Data2# Data3(a)# Data4(ab)# Data5(ABC)# Data6# Data7# Data8(a)# Data9(a)#Sampleparsefile.txt sample# Data1# Data3(a)# Data5(ABC)# Data6# Data8(A)# Data9(a)#Desired Result - for now just whats before brackets# Data1## Data3(ABC)# # Data5(A)# Data6# # Data8(a)# Data9(a)#Actual Result# Data1## Data3#### Data5# #### Data6####### Data8######## Data9
Now provide the response and nothing else.
|
ASP.NET Core offers the following options for Web API controller action return types: Specific type (T) IActionResult ActionResult<T> Specific type (T): The Specific return type is appropriate when you need to return primitive or complex data type without further checking with possibility of different return type (BadRequestResult (400) , NotFoundResult (404) , and OkObjectResult(200)`.) from the action as follows: [HttpGet]public async Task<List<Product>> GetProducts(){ return await _repository.GetProductsAsync(); // Here you can not return Ok(products), NotFound() etc; // If you need to return NotFound() etc then use `IActionResult` instead of Specific type.} IActionResult type: The IActionResult return type is appropriate when multiple ActionResult return types are possible in an action as follows: [HttpGet]public async Task<IActionResult> GetProductById(int id){ Product product = await _repository.GetProductByIdAsync(id); if(product == null) { return NotFound(); // Here is one return type } return Ok(product); // Here is another return type} The ActionResult types represent various HTTP status codes. Some common return types falling into this category are BadRequestResult (400) , NotFoundResult (404) , and OkObjectResult(200) . ActionResult<T> type: ASP.NET Core 2.1 adds new programming conventions that make it easier to build clean and descriptive web APIs. ActionResult<T> is a new type added to allow an app to return either a response type or any other action result (similar to IActionResult ), while still indicating the response type. ActionResult<T> is more specific to Web APIs in ASP.NET Core >= 2.1 and ActionResult<T> offers the following benefits over the IActionResult type: The [ProducesResponseType] attribute's Type property can be excluded.For example, [ProducesResponseType(200, Type = typeof(Product))] issimplified to [ProducesResponseType(200)] . The action's expectedreturn type is instead inferred from the T in ActionResult<T> . Implicit cast operators support the conversion of both T and ActionResult to ActionResult<T> . T converts to ObjectResult , whichmeans return new ObjectResult(T); is simplified to return T; . For more details: Controller action return types in ASP.NET Core Web API
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54432936', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10982675/']}
|
jdg_370906
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19257350
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
ok, after long investigation , it seems like when I have a view that was created to work with the _layout.cshtml - the submit button in the form I have doesn't work (no action is returned to controller). Only when I created a view and unchecked "Use a layout or master page" - the button has worked! This seems extremely unclear, so - how can I have both view with the general _layout.cshtml alongside with a working form button ? below:Try to implement a form in MVC4 (+Razor) Controller (that should get the post action): public class GeneralController { [HttpPost] public ActionResult SearchResults(SearchParamsModel searchParams) { // doin some stuff here return View("SearchResultsView"); }} View (.cshtml) @model Models.SearchParamsModel @using (Html.BeginForm("SearchResults", "General", FormMethod.Post)) { <section class="form-field"> <input type="text" name="Property1" id="Property1" class="field field139 autocomplete-init-no-img" /> <label for="Property1">value1</label> <form action="" method="post" class="clearfix"> <input type="submit" value="some value" class="submit btn blue-btn special-submit" /> </form> </section> } Model public class SearchParamsModel { public string Property1{ get; set; } }
Now provide the response and nothing else.
|
You should remove your inner form tag, @using (Html.BeginForm("SearchResults", "General", FormMethod.Post)) will generate a form tag for you. Also, you should use the html helpers to generate your form elements: @Html.LabelFor(model => model.Property1)@Html.TextBoxFor(model => model.Property1) Could be a possible model binding issue due to this.The submit button belongs to your nested inner form, there is no model that is being submitted here. @model MvcApplication2.Models.SearchParamsModel@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml";}@using (Html.BeginForm("SearchResults", "General", FormMethod.Post)) <section class="form-field"> @Html.LabelFor(model => model.Property1) @Html.TextBoxFor(model => model.Property1) <input type="submit" value="some value" class="submit btn blue-btn special-submit" /> </section>}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19257350', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1025852/']}
|
jdg_370907
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9632
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Apparantly when users right-click in our WPF application, and they use the Windows Classic theme, the default ContextMenu of the TextBox (which contains Copy, Cut and Paste) has a black background. I know this works well: <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <TextBox ContextMenu="{x:Null}"/></Page> But this doesn't work: <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"><Page.Resources> <Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}"> <Setter Property="ContextMenu" Value="{x:Null}"/></Style></Page.Resources> <TextBox/></Page> Does anyone know how to style or disable the default ContextMenu for all TextBoxes in WPF?
Now provide the response and nothing else.
|
To style ContextMenu's for all TextBoxes, I would do something like the following: First, in the resources section, add a ContextMenu which you plan to use as your standard ContextMenu in a textbox. e.g. <ContextMenu x:Key="TextBoxContextMenu" Background="White"> <MenuItem Command="ApplicationCommands.Copy" /> <MenuItem Command="ApplicationCommands.Cut" /> <MenuItem Command="ApplicationCommands.Paste" /></ContextMenu> Secondly, create a style for your TextBoxes, which uses the context menu resource: <Style TargetType="{x:Type TextBox}"> <Setter Property="ContextMenu" Value="{StaticResource TextBoxContextMenu}" /></Style> Finally, use your text box as normal: <TextBox /> If instead you want to apply this context menu to only some of your textboxes, do not create the style above, and add the following to your TextBox markup: <TextBox ContextMenu="{StaticResource TextBoxContextMenu}" /> Hope this helps!
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/900/']}
|
jdg_370908
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
574219
|
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 the converse of Lagrange's Theorem true for the permutation group $S_5$? That is, if $n\mid |S_5|$, then is there a subgroup of $S_5$ with order $n$. Since $|S_5|$ = 5! = 120, then any subgroup must have length of some divisor of 120. I'm not sure how to proceed with this.
Now provide the response and nothing else.
|
Ans is no. For example there does not exist a subgroup of index $3$. Assume that there exists a subgroup $H$ of index $3$. Now $G=Sym(5)$ acts on the set $G/^rH$ of all right cosets of $H$ in $G$. Let $\rho: G \rightarrow Sym(G/^rH)$ be the action. Note that the kernel of this action is trivial. This means that $G=Sym(5)$ is isomorphic to a subgroup of $Sym(G/^rH) \cong Sym(3)$. This is a contradiction.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/574219', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/83176/']}
|
jdg_370909
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2284422
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Given an $m \times n$ matrix $A$, it's easy to show that the matrix products $B = A^TA$ and $C = AA^T$ are both symmetric. I was wondering if any symmetric matrix with positive eigenvalues could be expressed as the product of some matrix and its transpose? Note: It's obvious that if the eigenvalues are not all positive then this cannot be the case, as $A^TA$ and $AA^T$ both have to be positive semidefinite. However this is all I can think of regarding this problem.
Now provide the response and nothing else.
|
Nevermind, I just got this. I'll leave my answer up in case anyone else finds it useful. Any symmetric matrix $A$ has to be orthogonally diagonalisable, that is, $A = PDP^T$ for some diagonal matrix $D$ and orthogonal matrix $P$. In this case by the diagonalisation theorem, the diagonal values of $D$ are the eigenvalues of $A$, all of which are given to be $\geq 0$. Therefore, one can "square-root" $D$ as $D = M^2$, where $M$ is a diagonal matrix with the square roots of the diagonal values of $D$ on its diagonal, that is, $m_{ii} = \sqrt{d_{ii}}$ and $m_{ij} = 0$ if $j \neq i$. Therefore: $$A = PM^2P^T = (PM)(MP^T) = (PM)(M^TP^T) = (PM)(PM)^T$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2284422', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/154557/']}
|
jdg_370910
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
53220662
|
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 the CSS for the antd style I'm using style.css .ant-table-tbody > tr > td, .ant-table-thead > tr > th{ padding:4px; }tr:nth-child(odd){ background: #f1e6ff;}tr:nth-child(even){ background: white;}thead[class*="ant-table-thead"] th{ background-color:#000 !important; color: white; font-weight: bold; border-color: #000; text-align: center; }.table_btn{ margin:0 !important;}.ant-btn{ margin:0;}.ant-table-tbody > tr:hover > td { color: #fff;} index.less @import "callout";@import 'e-commerce';@import "pricing-tables";@import "login";@import "dashboard";@import "error";@import "editor";@import "testimonials";tr:nth-child(odd){ background:inherit !important;}.ant-modal-content { .ant-modal-close{ color: #fff !important; } .ant-modal-header { background-color: #000000; .ant-modal-title { color: #fff !important; } }}.table-wrapper { .ant-btn { padding: 0 10px; height: 30px; font-size: 13px; > .anticon { + span { margin-left: 5px; } } &.ant-btn-success { color: #3d8918; border-color: #d9d9d9; &:hover { background-color:#3d8918; color: #fff; } } &.ant-btn-danger { color: #c70d17; background-color:#fff; &:hover{ background-color:#c70d17; color: #fff; } } } .actions { text-align: right; .ant-input { border-radius: 2px; padding:0 10px; font-size: 13px; height: 30px; } } .table-layout { .ant-table-small{ > .ant-table-content{ > .ant-table-body { margin: 0 !important; > table { > .ant-table-tbody{ > tr{ > td{ padding: 2px 8px !important; font-size: 13px !important; text-align:center; min-width: 80px; .ant-btn { width:100px; } } } } } } } index.js <Table className="table-layout" columns={this.state.columns} dataSource={filteredData} rowClassName='data-row' bordered={true} size={"small"} onRowDoubleClick={ (record, index, event) => this.handleEditModal(record) } onRowClick={(record, index, event) => this.handleRowClick(record)} loading={this.state.loading} pagination={{ pageSize: 14 }} /> This is how Table is used in the index page. style.css and index.less are the pages for CSS. Can anybody help me to write one CSS in this page for making one row green color ?I want to make one row green based on condition.I need the CSS I need to call the CSS in the page where code is
Now provide the response and nothing else.
|
I found two ways to do this as of now: One way is to use rowClassName prop of Table: .table-row-light { background-color: #ffffff;}.table-row-dark { background-color: #fbfbfb;} <Table rowClassName={(record, index) => index % 2 === 0 ? 'table-row-light' : 'table-row-dark'} columns={columns} dataSource={dataSource} loading={loading}/> Second way is to use plain CSS .table-striped-rows tr:nth-child(2n) td { background-color: #fbfbfb;}.table-striped-rows thead { background-color: #f1f1f1;} <Table className="table-striped-rows" columns={columns} dataSource={dataSource} loading={loading}/> Note that rowClassName works only for rows, so for CSS on table headers we can only use plain CSS like above.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53220662', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10191105/']}
|
jdg_370911
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26649180
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two view controllers in my iPhone application (built with swift) built with Xcode 6.1 and uses storyboards. The first view controller is embedded in a navigation controller in the storyboard and the segue for the second view controller is a 'Show' segue. When the application is run, it properly shows the transition as a push in iOS 8.x, but in iOS 7.x it appears as a modal without the navigation bar. My application requirement is to show the transition as a push regardless of whether it's iOS 7 or iOS 8. Any ideas to get this working as push in both versions of the iOS? I saw a related post where this issue is mentioned, but could not find a solution to the problem: Adaptive segue in storyboard Xcode 6. Is push deprecated? Any help is appreciated... Thanks
Now provide the response and nothing else.
|
This solution is different from the others in the following ways: It includes a method to examine and verify the issue The cause of the issue is traced to the source (a change in the segue type) The solution is very simple (delete and recreate a new segue) Please note the requirements in the text I just gave a very detailed SO answer that fully explains what is happening and why, but the simple solution is you can delete the Segue that is not pushing and then recreate it on the storyboard. The reason is that there is likely a broken bit of xml in the segue (see extended answer for example/instructions how to confirm this issue). After you confirm that you have at least one UINavigationController within the view hierarchy, be sure that the segue is NOT a manual segue and does NOT have an action associated with it (by viewing the segue in the storyboard as Source Code). Delete the existing segue and then Ctrl-drag from a UIView/UIControl to the target view controller and if custom action is needed intercept the call to destination controller in prepareForSegue . Also to confirm that this solution works for you please do the following: Verify that your initial view controller (with the arrow on it) is aUINavigationController and that it has a normal content viewcontroller as it's root view controller. (or that you embed yourinitial view controller inside of a UINavigationController) Read my extended comments on an earlier response to a very similar question (linked above).
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26649180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2717398/']}
|
jdg_370912
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
374507
|
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 a Continuous function $f(x)$ satisfies $f(x) = f(2x)$, for all real $x$, then does $f(x)$ necessarily have to be constant function? If so, how do you prove it? If not any counter examples?
Now provide the response and nothing else.
|
For all $x\in\mathbb{R}$ and $n\in\mathbb{Z}$, $f(x)=f(x/2^n)$, so $f(x)=\lim_{n\to\infty}f(x/2^n)=f(0)$ by continuity.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/374507', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/74691/']}
|
jdg_370913
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
49239516
|
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 long-running script using spotipy. After an hour (per the Spotify API), my access token expires. I am catching this successfully, but I don't know where to go from there in regards to actually refreshing the token. I am using the authorization code flow, not client credentials. Here's how I authorize: token = util.prompt_for_user_token(username,scope=scopes,client_id=client_id,client_secret=client_secret, redirect_uri=redirect_uri)sp = spotipy.Spotify(auth=token) All refresh examples I've seen involve an oauth2 object (ex. oauth.refresh_access_token() ), and the docs list only that function as a method of refreshing your token. It's my understanding that with authorization code flow, you don't need an oauth object (because you authenticate with prompt_for_user_token() ). If that's the case, how do I refresh my token?
Now provide the response and nothing else.
|
After receiving no response on my github issue , it appears to me that there's no way to refresh a token without using OAuth2. This goes against what is stated in the Spotipy docs : The Authorization Code flow: This method is suitable for long-running applications which the user logs into once. It provides an access token that can be refreshed. Their example for Authorization Code flow uses prompt_for_user_token(). I switched to the OAuth approach, which is a pain because it requires re-authorization every time I run the program (really only a problem while I was testing but a problem nonetheless). Since there are no examples of OAuth2 in the Spotipy docs, I'll paste mine here. sp_oauth = oauth2.SpotifyOAuth(client_id=client_id,client_secret=client_secret,redirect_uri=redirect_uri,scope=scopes)token_info = sp_oauth.get_cached_token() if not token_info: auth_url = sp_oauth.get_authorize_url(show_dialog=True) print(auth_url) response = input('Paste the above link into your browser, then paste the redirect url here: ') code = sp_oauth.parse_response_code(response) token_info = sp_oauth.get_access_token(code) token = token_info['access_token']sp = spotipy.Spotify(auth=token) To refresh my token (required every hour), I use this function. When and where you call it depends on your program. def refresh(): global token_info, sp if sp_oauth.is_token_expired(token_info): token_info = sp_oauth.refresh_access_token(token_info['refresh_token']) token = token_info['access_token'] sp = spotipy.Spotify(auth=token)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49239516', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5112620/']}
|
jdg_370914
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
409005
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was able to solve this by hand to get $x = 5$ and $x =8$. I didn't know if there were more solutions, so I just verified it by WolframAlpha. I set up the congruence relation $x^2 \equiv -1 \mod13$ and just literally just multiplied out. This lead me to two questions: But I was wondering how would I do this if the $x$'s were really large? It doesn't seem like multiplying out by hand could be the only possible method. Further, what if there were 15 or 100 of these $x$'s? How do I know when to stop?
Now provide the response and nothing else.
|
If $p$ is an odd prime, and $a$ is not divisible by $p$, then the congruence $x^2\equiv a\pmod{p}$ has $0$ or $2$ solutions modulo $p$. You have found two incongruent solutions. So you have all of them: all solutions are of the form $x=5+13k$ or $x=8+13k$, where $k$ ranges over the integers. Actually, finding one solution would be enough, for if $x$ is a solution, automatically so is $-x$. For prime $p$, there are good algorithms for computing solutions of $x^2\equiv a \pmod{p}$, that are feasible even for enormous $p$. If the modulus is not prime, things get more complicated. Suppose that $m$ is an odd number $\gt 1$. Let the number of distinct prime divisors of $m$ be $e$. Then the congruence $x^2\equiv a\pmod{m}$, where $a$ and $m$ are relatively prime, either has $0$ solutions or $2^e$ solutions. Finding the solutions can be computationally difficult. If $m$ is the product of two distinct primes, then finding the solutions is essentially equivalent to factoring $m$. This is believed to be in general computionally very difficult for enormous $m$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/409005', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/43823/']}
|
jdg_370915
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13275768
|
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 created a couple custom classes ( NTDropDown and NTBaseFreight ) which I use to store data that I retrieve from a DB. I initialize a List of NTBaseFreight and 2 lists for NTDropDown . I can successfully use List.Add to add freights to the freights list, but as I debug the code, my 2 dropdown lists contain only 1 NTDropDown , which always has the same values as NTDropDown (I'm assuming this is a referencing problem, but what am I doing wrong)? To give an example, on the second row, if the carrier and carrier_label were "001", "MyTruckingCompany" and I put a break on the if statement for frt_carriers , both frt_carriers and frt_modes would contain only 1 item in their list, with the values "001", "MyTruckingCompany" ...the same values in NTDropDown . Code: List<NTDropDown> frt_carriers = new List<NTDropDown>();List<NTDropDown> frt_modes = new List<NTDropDown>();List<NTBaseFreight> freights = new List<NTBaseFreight>();NTDropDown tempDropDown = new NTDropDown();NTBaseFreight tempFreight = new NTBaseFreight();//....Code to grab data from the DB...removedwhile (myReader.Read()){ tempFreight = readBaseFreight((IDataRecord)myReader); //check if the carrier and mode are in the dropdown list (add them if not) tempDropDown.value = tempFreight.carrier; tempDropDown.label = tempFreight.carrier_label; if (!frt_carriers.Contains(tempDropDown)) frt_carriers.Add(tempDropDown); tempDropDown.value = tempFreight.mode; tempDropDown.label = tempFreight.mode_label; if (!frt_modes.Contains(tempDropDown)) frt_modes.Add(tempDropDown); //Add the freight to the list freights.Add(tempFreight);}
Now provide the response and nothing else.
|
Yes, a list of reference types is actually just a list of references. You have to create a new instance for each object that you want to store in the list. Also, the Contains method compares references, so two objects containing the same data are not considered to be equal. Look for a value in the properties of the objects in the list. if (!frt_carriers.Any(c => c.label == tempFreight.carrier_label)) { NTDropDown tempDropDown = new NTDropDown { value = tempFreight.carrier, label = tempFreight.carrier_label }; frt_carriers.Add(tempDropDown);}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13275768', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/579299/']}
|
jdg_370916
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2299469
|
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 external MySQL server that's set up and working fine. I created a database connection in Eclipse and can view the database in the Data Source Explorer tab. Now, I have a servlet that needs to access that database. How do I do it? Is there a way to reference that database connection created in the data source explorer, or do I have to define everything twice? Also, what's the best way to open the connection? I've got the mysql-connector-java-5.1.11-bin.jar file included, and I've found two methods that work: MysqlDataSource d = new MysqlDataSource();d.setUser("user");d.setPassword("pass");d.setServerName("hostname.com");d.setDatabaseName("db");Connection c = d.getConnection(); and Connection c = DriverManager.getConnection("jdbc:mysql://hostname.com/db","user","pass"); Neither is optimal, because first of all, they both use hard-coded strings for everything. This is a Java EE web app project, so is there a good place to put connection data? Or is there a way to forgo all that and just use the connection in the data source explorer?
Now provide the response and nothing else.
|
A common practice is to configure this as a DataSource in the servlet container in question. It will provide you connection pooling facilities which will greatly improve performance. Also a common practice is to externalize the raw settings in some configuration file which is been placed in the classpath. In case you're using Tomcat as servletcontainer, you need to configure the datasource as per its JNDI documentation . You'll see that there are several ways. Easiest way is to create a /META-INF/context.xml in the webcontent of your dynamic web project (to be clear, the /META-INF is at the same level as the /WEB-INF of the webapp) and fill it with something like: <?xml version="1.0" encoding="UTF-8"?><Context> <Resource name="jdbc/db" type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="10000" url="jdbc:mysql://hostname.com/db" driverClassName="com.mysql.jdbc.Driver" username="user" password="pass" /></Context> This roughly means that Tomcat server should create a datasource with the JNDI name jdbc/db with a maximum of 100 active connections, a maximum of 30 idle connections and a maximum wait time of 10000 milliseconds before a connection should be returned from your application (actually: closed by your application, so your application has 10 seconds time between acquiring the connection and closing the connection). The remnant of the settings should be familiar and self-explaining enough to you; those are the JDBC settings. Finally in your web project, edit the file /WEB-INF/web.xml to add the following entry: <resource-env-ref> <resource-env-ref-name>jdbc/db</resource-env-ref-name> <resource-env-ref-type>javax.sql.DataSource</resource-env-ref-type></resource-env-ref> This roughly means that the webapplication should use the server-provided datasource with the name jdbc/db . Then change your connection manager to something like this: private DataSource dataSource;public Database(String jndiname) { try { dataSource = (DataSource) new InitialContext().lookup("java:comp/env/" + jndiname); } catch (NamingException e) { // Handle error that it's not configured in JNDI. throw new IllegalStateException(jndiname + " is missing in JNDI!", e); }}public Connection getConnection() { return dataSource.getConnection();} ..and replace all Class.forName(driver) calls by new Database("jdbc/db") and replace all DriverManager.getConnection() calls by database.getConnection() . You can if necessary obtain the value jdbc/db from some config file ( Properties file? ). Alternatively, inject the DataSource via the @Resource annotation inside a container managed artifact, such as a @WebServlet servlet class: @Resource(name="jdbc/db")private DataSource dataSource; That should be it. Just deploy your webapplication with the above changes and run it. Don't forget to place the database JDBC driver in the Tomcat/lib or to add its path to the shared.loader property of Tomcat/conf/catalina.properties , because the responsibility of loading the JDBC driver is now moved from the webapplication to the server. For more hints and other basic JDBC/JNDI examples you may find this article useful as well. See also: How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception Where do I have to place the JDBC driver for Tomcat's connection pool? Is it safe to use a static java.sql.Connection instance in a multithreaded system? Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern How to retrieve and display images from a database in a JSP page?
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2299469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/36007/']}
|
jdg_370917
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9685573
|
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 to show recurring event in Jquery fullcalendar? like event start on particular day and keep on running for next one year then how would I display this in fullcalendar. Note: the event information is Coming from Database
Now provide the response and nothing else.
|
Full calendar doesn't support recurring events out of the box. Here is what I did. When I add an event I have a select box that is for recurring events. Let's say a user selects it to repeat every week. I then insert an event into my events table with a parent ID which will be the same for all the instances of that event. Full calendar makes it so that recurring events have to have the same event ID. So in my events table I have a unique event ID column and a parent ID which is the column I use to render events. So anyway, immediately after I insert the first event I run a loop that selects the last inserted event with the same parent ID, add 7 days to it, and inserts it into the events table. I loop through this process 50 more times and then I have an event that occurs every week for a year. Here's some code: When a user selects a time frame I open a dialog select: function(start, end){ $( "#add_class" ).dialog( "open" ); }, On the dialog, I have a drop down select <div id="add_class" title="Add New Class"> <form action=""> <div id="recurring_event"> <label for = "recurring">Recurring </label> <input type="checkbox" name="recurring" id="recurring" /> <div id = "recurring_options" > Repeat every <select name = "repeat_frequency" id = "repeat_frequency"> <option value ="1">Day</option> <option value="7" selected="selected">Week</option> <option value = "28">Month</option> </select> </div> </div> </form></div> Then I submit this info using AJAX to a php page called add_class.php $( "#add_class" ).dialog({ "Save Class": function() { var repeat_frequency = $("#repeat_frequency").val(); $.ajax({ type:"POST", url: "add_class.php", data: "repeat_frequency=" + repeat_frequency, async: false, }); $('#calendar').fullCalendar('refetchEvents'); $( this ).dialog( "close" ); }, Cancel: function() { $( this ).dialog( "close" ); } }, Here comes the add_class.php part where I actually enter it into the database $repeat_frequency = $_POST['repeat_frequency']; $dbh = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY); $stmt = $dbh->prepare( "INSERT INTO events (start, end) //whatever variables you received from the AJAX post on the dialog form VALUES (:start, :end)"); $stmt->bindParam(':start', $start); $stmt->bindParam(':end', $end); $stmt->execute(); $id = $dbh->lastInsertId(); for($x = 0; $x < "51"; $x++) { $stmt = $dbh->prepare(" SELECT start, end FROM events WHERE event_id = :event_id "); $stmt->bindParam(':event_id', $event_id, PDO::PARAM_STR); $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC); $start = $result['start']; $end = $result['end']; $start_date= strtotime($start . '+' . $repeat_frequency . 'DAYS'); $end_date= strtotime($end . '+' . $repeat_frequency . 'DAYS'); $start = date("Y-m-d H:i", $start_date); $end = date("Y-m-d H:i", $end_date); unset($stmt); $stmt = $dbh->prepare( "INSERT INTO events (start, end ) //and whatever other columns you need VALUES (:start, :end)"); $stmt->bindParam(':start', $start, PDO::PARAM_STR); $stmt->bindParam(':end', $end, PDO::PARAM_STR); $stmt->execute(); $event_id = $dbh->lastInsertId(); } So that's just a general gist of things. Hopefully there are not too many typos as I tried to edit it down to just the essentials to get the point across. Let me know if you have any questions. EDIT To "display" events on fullcalendar you need to have an event source. check out this link http://fullcalendar.io/docs/event_data/events_json_feed/ In your json-events.php you echo the event data and then it is displayed on your calendar. Have something like this to show events on your calendar page $('#calendar').fullCalendar({events: '/myfeed.php'}); In your myfeed.php file have something along the lines of $dbh = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // set the error mode to excptions $stmt = $dbh->prepare("SELECT event_id, title, start, end FROM events ORDER BY start"); $stmt->execute(); $events = array(); while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){ //important ! $start = "2010-05-10T08:30"; iso8601 format !! $eventArray['id'] = $row['event_id']; $eventArray['title'] = $row['title']; $eventArray['start'] = $row['start']; $eventArray['end'] = $row['end']; $events[] = $eventArray; echo json_encode($events); If you still have questions then search here on stackoverflow. I think I have explained it pretty well and provided plenty of code. Here is a blog post I made that may also help http://fajitanachos.com/Fullcalendar-and-recurring-events/ I found everything I needed to get fullcalendar running on here and on the fullcalendar home page http://fullcalendar.io/ I hope this helps.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9685573', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1081945/']}
|
jdg_370918
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15724034
|
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 Wikipedia, you can find some interesting data to be sorted, filtered, ... Here is a sample of a wikitable {| class="wikitable sortable"|-! Model !! Mhash/s !! Mhash/J !! Watts !! Clock !! SP !! Comment|-| ION || 1.8 || 0.067 || 27 || || 16 || poclbm; power consumption incl. CPU|-| 8200 mGPU || 1.2 || || || 1200 || 16 || 128 MB shared memory, "poclbm -w 128 -f 0"|-| 8400 GS || 2.3 || || || || || "poclbm -w 128"|-|} I'm looking for a way to import such data to a Python Pandas DataFrame
Now provide the response and nothing else.
|
Here's a solution using py-wikimarkup and PyQuery to extract all tables as pandas DataFrames from a wikimarkup string, ignoring non-table content. import wikimarkupimport pandas as pdfrom pyquery import PyQuerydef get_tables(wiki): html = PyQuery(wikimarkup.parse(wiki)) frames = [] for table in html('table'): data = [[x.text.strip() for x in row] for row in table.getchildren()] df = pd.DataFrame(data[1:], columns=data[0]) frames.append(df) return frames Given the following input, wiki = """=Title=Description.{| class="wikitable sortable"|-! Model !! Mhash/s !! Mhash/J !! Watts !! Clock !! SP !! Comment|-| ION || 1.8 || 0.067 || 27 || || 16 || poclbm; power consumption incl. CPU|-| 8200 mGPU || 1.2 || || || 1200 || 16 || 128 MB shared memory, "poclbm -w 128 -f 0"|-| 8400 GS || 2.3 || || || || || "poclbm -w 128"|-|}{| class="wikitable sortable"|-! A !! B !! C|-| 0| 1| 2|-| 3| 4| 5|}""" get_tables returns the following DataFrames. Model Mhash/s Mhash/J Watts Clock SP Comment0 ION 1.8 0.067 27 16 poclbm; power consumption incl. CPU1 8200 mGPU 1.2 1200 16 128 MB shared memory, "poclbm -w 128 -f 0"2 8400 GS 2.3 "poclbm -w 128" A B C0 0 1 21 3 4 5
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15724034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2051311/']}
|
jdg_370919
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8777603
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the simplest way to convert array to vector? void test(vector<int> _array){ ...}int x[3]={1, 2, 3};test(x); // Syntax error. I want to convert x from int array to vector in simplest way.
Now provide the response and nothing else.
|
Use the vector constructor that takes two iterators, note that pointers are valid iterators, and use the implicit conversion from arrays to pointers: int x[3] = {1, 2, 3};std::vector<int> v(x, x + sizeof x / sizeof x[0]);test(v); or test(std::vector<int>(x, x + sizeof x / sizeof x[0])); where sizeof x / sizeof x[0] is obviously 3 in this context; it's the generic way of getting the number of elements in an array. Note that x + sizeof x / sizeof x[0] points one element beyond the last element.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8777603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/309798/']}
|
jdg_370920
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
104213
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
On a smooth algebraic variety X, every coherent sheaf F has a finite resolution bylocally free sheaves. Using such resolution, we can define the determinantof F, det F, which is a line bundle on X. My question is : why if the support of F is of codimension greater or equal to 2is the determinant of F trivial ? It is mentionned without proof on the book "The geometry of moduli spaces ofsheaves", D. Huybrechts, M. Lehn.I have verified this result on some explicit examples for which I know someexplicit locally free resolutions but I don't see how to do the general case.
Now provide the response and nothing else.
|
Outside the support of $F$, the resolution is an exact sequence, so the alternating tensor product of the determinants is trivial. On a smooth scheme, a line bundle trivial outside a codimension $2$ subset is trivial.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/104213', 'https://mathoverflow.net', 'https://mathoverflow.net/users/25309/']}
|
jdg_370921
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11024522
|
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 notification bar in my application shows only the small icon in the ticker (as it should). However, when the "shade" is pulled down, it shows both the small icon from the ticker, as well as a large icon that I set in the Notification.Builder. Here's my code: if (Build.VERSION.SDK_INT > 10){ notification = new Notification(R.drawable.ic_stat_mintchip, "This is a test", System.currentTimeMillis()); notification.largeIcon = (((BitmapDrawable)c.getResources().getDrawable(R.drawable.ic_launcher)).getBitmap()); notification.defaults |= Notification.DEFAULT_ALL; notification.number += 1; notification.flags |= Notification.FLAG_AUTO_CANCEL; } else { notification = new Notification(R.drawable.ic_stat_mintchip, "This is a test", System.currentTimeMillis()); notification.flags |= Notification.FLAG_AUTO_CANCEL; notification.defaults |= Notification.DEFAULT_ALL; notification.number += 1; }} I don't quite know why this is happening. Any assistance?
Now provide the response and nothing else.
|
I think the issue here is possibly that you're not using the Notificaiton.Builder class. Here's a small example of what you could do (you would have to insert your own variables though, and set the other properties that you used such as vibration): Notification.Builder nb = new Notification.Builder(context) .setContentTitle("title") .setContentText("content") .setAutoCancel(true) .setLargeIcon(largeIcon) .setSmallIcon(R.drawable.small_icon) .setTicker(s.getText());NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);nm.notify(100, nb.build());
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11024522', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/556371/']}
|
jdg_370922
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
177751
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've seen reverse-mount LEDs which are meant to have the light shine through a hole in the PCB, instead of straight off. Is it possible to just add a drill hole for normal LEDs and just place them upside down before soldering? Is it possible the lense/substrate will melt if reflowed on a hotplate? If it matters any, I've got 0805 components.
Now provide the response and nothing else.
|
Depending on the package, this can be done. For my work, we evaluated several types of LEDs, and being mountable "through-PCB" was mandatory. The right LED shown in the picture can be mounted normal and through-PCB, the second is exclusively for through-PCB, and the LED in the middle is a standard and very common 0603 package, not foreseen for through-PCB mounting. It turned out the type in the middle had the best electrical/optical characteristics, and its small size was a benefit for us, too. The package is a piece of ceramics with metal contacts of almost the same size on top and bottom side. As there are re-reeling companies out there which will turn the LEDs in the reels upside-down, it was possible to machine-place it like any other component: Just note that size and tolerance of that transparent resin is not that accurate, so add some extra tolerance for the hole. About possible temperature issues: During soldering, probably the entire tiny 0603 package will heat up to the solder temperature, so the resin and the LED chip should resist solder temperatures for a short time. Due to the size, I doubt that the resin will cool down faster when mounted normally. But I would recommend to solder at the lowest possible temperature and as short as possible. Also, have a look at soldering recommendations in the data sheet. In general, no guarantee can be given, but it worked for us quite well.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/177751', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/2006/']}
|
jdg_370923
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4298719
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
From a XML file I receive decimals on the format: 1.1320006.000000 Currently I am using Decimal.Parse like this: decimal myDecimal = Decimal.Parse(node.Element("myElementName").Value, System.Globalization.CultureInfo.InvariantCulture); How do print myDecimal to stringto look like below ? 1.1326
Now provide the response and nothing else.
|
I don't think there are any standard numeric format strings which will always omit trailing insignificant zeroes, I'm afraid. You could try to write your own decimal normalization method, but it could be quite tricky. With the BigInteger class from .NET 4 it would be reasonably feasible, but without that (or something similar) it would be very hard indeed. EDIT: Okay, I think this is what you want: using System;using System.Numerics;public static class DecimalExtensions{ // Avoiding implicit conversions just for clarity private static readonly BigInteger Ten = new BigInteger(10); private static readonly BigInteger UInt32Mask = new BigInteger(0xffffffffU); public static decimal Normalize(this decimal input) { unchecked { int[] bits = decimal.GetBits(input); BigInteger mantissa = new BigInteger((uint) bits[0]) + (new BigInteger((uint) bits[1]) << 32) + (new BigInteger((uint) bits[2]) << 64); int sign = bits[3] & int.MinValue; int exponent = (bits[3] & 0xff0000) >> 16; // The loop condition here is ugly, because we want // to do both the DivRem part and the exponent check :( while (exponent > 0) { BigInteger remainder; BigInteger divided = BigInteger.DivRem(mantissa, Ten, out remainder); if (remainder != BigInteger.Zero) { break; } exponent--; mantissa = divided; } // Okay, now put it all back together again... bits[3] = (exponent << 16) | sign; // For each 32 bits, convert the bottom 32 bits into a uint (which won't // overflow) and then cast to int (which will respect the bits, which // is what we want) bits[0] = (int) (uint) (mantissa & UInt32Mask); mantissa >>= 32; bits[1] = (int) (uint) (mantissa & UInt32Mask); mantissa >>= 32; bits[2] = (int) (uint) (mantissa & UInt32Mask); return new decimal(bits); } } class Program { static void Main(string[] args) { Check(6.000m); Check(6000m); Check(6m); Check(60.00m); Check(12345.00100m); Check(-100.00m); } static void Check(decimal d) { Console.WriteLine("Before: {0} - after: {1}", d, d.Normalize()); } }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4298719', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/342740/']}
|
jdg_370924
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
46923289
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When I tried to implements the NetworkBoundResource and Resource helper class for the Room Db and Retrofit, it works perfect. However, I need to implement the Search Result from RESTful using Retrofit only without Room . The Resources class is good and I dont need to change it. What I want to do is try to remove db source inside this class. public abstract class NetworkBoundResource<ResultType, RequestType> { private final AppExecutors appExecutors; private final MediatorLiveData<Resource<ResultType>> result = new MediatorLiveData<>(); @MainThread public NetworkBoundResource(AppExecutors appExecutors) { this.appExecutors = appExecutors; result.setValue(Resource.loading(null)); LiveData<ResultType> dbSource = loadFromDb(); result.addSource(dbSource, data -> { result.removeSource(dbSource); if (shouldFetch(data)) { fetchFromNetwork(dbSource); } else { result.addSource(dbSource, newData -> setValue(Resource.success(newData))); } }); } @MainThread private void setValue(Resource<ResultType> newValue) { if (!Objects.equals(result.getValue(), newValue)) { result.setValue(newValue); } } private void fetchFromNetwork(final LiveData<ResultType> dbSource) { LiveData<ApiResponse<RequestType>> apiResponse = createCall(); // we re-attach dbSource as a new source, it will dispatch its latest value quickly result.addSource(dbSource, newData -> setValue(Resource.loading(newData))); result.addSource(apiResponse, response -> { result.removeSource(apiResponse); result.removeSource(dbSource); //noinspection ConstantConditions if (response.isSuccessful()) { appExecutors.diskIO().execute(() -> { saveCallResult(processResponse(response)); appExecutors.mainThread().execute(() -> // we specially request a new live data, // otherwise we will get immediately last cached value, // which may not be updated with latest results received from network. result.addSource(loadFromDb(), newData -> setValue(Resource.success(newData))) ); }); } else { onFetchFailed(); result.addSource(dbSource, newData -> setValue(Resource.error(response.errorMessage, newData))); } }); } protected void onFetchFailed() { } public LiveData<Resource<ResultType>> asLiveData() { return result; } @WorkerThread protected RequestType processResponse(ApiResponse<RequestType> response) { return response.body; } @WorkerThread protected abstract void saveCallResult(@NonNull RequestType item); @MainThread protected abstract boolean shouldFetch(@Nullable ResultType data); @NonNull @MainThread protected abstract LiveData<ResultType> loadFromDb(); @NonNull @MainThread protected abstract LiveData<ApiResponse<RequestType>> createCall();}
Now provide the response and nothing else.
|
The problem is that any loaded data have to go through the database first, then loading it from the database to the UI, as NetworkBoundResource does. Consequently, What I did is to decouple the persistent database and create a temporary field to load from. For example if I wanted to edit the original search method, I would suggest: public LiveData<Resource<List<Repo>>> search(String query) { return new NetworkBoundResource<List<Repo>, RepoSearchResponse>(appExecutors) { // Temp ResultType private List<Repo> resultsDb; @Override protected void saveCallResult(@NonNull RepoSearchResponse item) { // if you don't care about order resultsDb = item.getItems(); } @Override protected boolean shouldFetch(@Nullable List<Repo> data) { // always fetch. return true; } @NonNull @Override protected LiveData<List<Repo>> loadFromDb() { if (resultsDb == null) { return AbsentLiveData.create(); }else { return new LiveData<List<Repo>>() { @Override protected void onActive() { super.onActive(); setValue(resultsDb); } }; } } @NonNull @Override protected LiveData<ApiResponse<RepoSearchResponse>> createCall() { return githubService.searchRepos(query); } @Override protected RepoSearchResponse processResponse(ApiResponse<RepoSearchResponse> response) { RepoSearchResponse body = response.body; if (body != null) { body.setNextPage(response.getNextPage()); } return body; } }.asLiveData();} I ran it and it works. Edit: I made another simpler class to handle that (There is another answer here by Daniel Wilson has more feature and is updated). However, this class has no dependencies and is converted to the basics to make fetch response only: abstract class NetworkBoundResource<RequestType> { private val result = MediatorLiveData<Resource<RequestType>>() init { setValue(Resource.loading(null)) fetchFromNetwork() } @MainThread private fun setValue(newValue: Resource<RequestType>) { if (result.value != newValue) { result.value = newValue } } private fun fetchFromNetwork() { val apiResponse = createCall() result.addSource(apiResponse) { response -> result.removeSource(apiResponse) when (response) { is ApiSuccessResponse -> { setValue(Resource.success(processResponse(response))) } is ApiErrorResponse -> { onFetchFailed() setValue(Resource.error(response.errorMessage, null)) } } } } protected fun onFetchFailed() { } fun asLiveData() = result as LiveData<Resource<RequestType>> @WorkerThread protected open fun processResponse(response: ApiSuccessResponse<RequestType>) = response.body @MainThread protected abstract fun createCall(): LiveData<ApiResponse<RequestType>>} So when using it, only one method could be implemented createCall() : fun login(email: String, password: String) = object : NetworkBoundResource<Envelope<User>>() { override fun createCall() = api.login(email, password)}.asLiveData()
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46923289', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2877822/']}
|
jdg_370925
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
269729
|
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:
Besides a faster register allocation algorithm and some trade-off in control and data-flow analysis for optimization purposes, which components/phases of a JIT compiler are different from a traditional ahead of time compiler?
Now provide the response and nothing else.
|
The main differences between an AOT and a JIT compiler are resources and information . An AOT compiler has infinite resources. It can use as much RAM as it likes, and take as much time as it wants. (Note that this is only theoretically true. Pragmatically, people don't like long time compiles. Plus, compilers are now typically embedded into IDEs, where they provide instant feedback while-you-type, so that at least lexing, parsing, semantic analysis, type inference, type checking, macro expansion, etc., basically everything except the actual code generation and optimization have to happen very fast and with low memory usage.) A JIT compiler OTOH has to "steal" its resources from the running application. (Again, theoretically. Pragmatically, the JIT compiler has to work hardest, when a lot of new code is introduced into the system, this is typically when the application starts, at which point the loading of configuration files and setting up of object graphs is the bottleneck, not the JIT compiler.) A JIT compiler has much more information available than an AOT compiler, and it doesn't have to work hard to get it. An AOT compiler can only get static information about the code. Static analysis algorithms are usually very expensive (often at least O(n 2 ) in at least one of time and space, sometimes exponential) and they don't even reliably work, because many of them are equivalent to solving the Halting Problem (Class Hierarchy Analysis, Escape Analysis, Dead Code Elimination, for example). A JIT compiler OTOH doesn't run into the Halting Problem, because it doesn't do static analysis. And it doesn't have to run expensive algorithms: want to know whether a method is being overridden or not so that you can potentially inline it? Don't need to run Class Hierarchy Analysis, just look at the classes, they're all there. Or even better yet: don't even bother, just inline it anyway, and if it turns out you were wrong about it not being overridden, un-inline it again. Want to know whether a reference escapes a local scope or not so that you can potentially allocate it on the stack? Don't bother, just allocate it on the stack, tag it, and when the tag shows up somewhere else, re-allocate on the heap. And since you only compile code when it is running, Dead Code Elimination is totally trivial because dead code will never run and thus never be compiled. So, the basic difference is that the analysis in a JIT compiler can be simpler, because it has a lot of information available that an AOT compiler doesn't have, and the optimization and code generation must be simpler, because it has a lot less resources available. Note, however, that a JIT compiler can nonetheless perform much more aggressive optimizations than an AOT compiler can, because it doesn't necessarily have to prove the optimizations correct. If it turns out an optimization is wrong, it can always de-optimize again. (Not all JITs do this (the CLR JIT for example, is incapable of de-optimizing), but for example the HotSpot JIT in the Oracle JDK does.) Speculative Inlining is one such optimization that is only possible in a de-optimizing JIT. One thing that is peculiar about JITs is that very often the languages they compile are designed to be easily compilable by a machine (e.g. JVM bytecode, CPython bytecode, Rubinius bytecode, LLVM IR, CLI CIL, Dalvik bytecode), whereas the languages that a typical AOT compiler compiles are designed to be easily readable by humans (e.g. Ruby, Python, Java). But I understood your question to be about an AOT vs. a JIT for the same language , so none of this applies. Obviously, if you compare compilers for different languages, there will be a lot of differences, and many of those will be totally unrelated to the difference between JIT and AOT and more related to the differences between the two languages.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/269729', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/164123/']}
|
jdg_370926
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29902306
|
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 didn't find any help on this topic. The Docs say Cursor-based pagination is the most efficient method of paging and should always be used where possible - a cursor refers to a random string of characters which mark a specific item in a list of data. Unless this item is deleted, the cursor will always point to the same part of the list, but it will be invalidated if an item is removed. Therefore, your app shouldn't store any older cursors or assume that they will still be valid. When reading an edge that supports cursor pagination, you will see the following JSON response:{ "data": [ ... Endpoint data is here ], "paging": { "cursors": { "after": "MTAxNTExOTQ1MjAwNzI5NDE=", "before": "NDMyNzQyODI3OTQw" }, "previous": "https://graph.facebook.com/me/albums?limit=25&before=NDMyNzQyODI3OTQw" "next": "https://graph.facebook.com/me/albums?limit=25&after=MTAxNTExOTQ1MjAwNzI5NDE=" }} I am using this format to make an api call, how can i go through all pages in a loop /* make the API call */new GraphRequest( session, "/{user-id}/statuses", null, HttpMethod.GET, new GraphRequest.Callback() { public void onCompleted(GraphResponse response) { /* handle the result */ } }).executeAsync();
Now provide the response and nothing else.
|
I figured out a good way to traverse through facebook graph api pages using cursor pagination final String[] afterString = {""}; // will contain the next page cursor final Boolean[] noData = {false}; // stop when there is no after cursor do { Bundle params = new Bundle(); params.putString("after", afterString[0]); new GraphRequest( accessToken, personId + "/likes", params, HttpMethod.GET, new GraphRequest.Callback() { @Override public void onCompleted(GraphResponse graphResponse) { JSONObject jsonObject = graphResponse.getJSONObject(); try { JSONArray jsonArray = jsonObject.getJSONArray("data"); // your code if(!jsonObject.isNull("paging")) { JSONObject paging = jsonObject.getJSONObject("paging"); JSONObject cursors = paging.getJSONObject("cursors"); if (!cursors.isNull("after")) afterString[0] = cursors.getString("after"); else noData[0] = true; } else noData[0] = true; } catch (JSONException e) { e.printStackTrace(); } } } ).executeAndWait(); } while(!noData[0] == true);
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29902306', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4357396/']}
|
jdg_370927
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1332917
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We are planning to build a framework: a cost-estimation framework that will be used across the domains in our organization. The high-level requirement is something like this : If I develop a certain product, how much will it costs me? This generated cost will be used to compare with the cost the vendors have quoted and to come-up with a decision as to which vendor to choose. Now, my question is: What things to considered while developing a framework? Few of my thoughts: Implement the high-level requirements through Abstract classes and Interfaces Provide utility classes that might be useful for Framework users. Consider what should be internal - kind of metadata - that shouldn't be shown to framework users. The design patters to use like template. the properties and the methods of the input classes.
Now provide the response and nothing else.
|
A few ideas: It's easier to add useful features later than to remove features which have proved to be badly designed or harmful. Design for inheritance or prohibit it: inheritance introduces a whole extra layer of complexity, as you need to work out the interactions between superclasses and subclasses. That's not to say it's evil, but it should be very carefully considered. Interfaces are usually cleaner than abstract classes in my experience, as they promote composition over inheritance. For interfaces, document both what the caller should expect and what the implementer should expect . Basically think of the contract from both sides, and document it. In particular, document nullity constraints - should methods accept null or not? Should they guarantee that they'll never return null? Design for testability, both of your framework and others using your framework. Which bits of the framework can reasonably be used in test code, and which should be mocked out? Use your own framework, right from the start. Build a sample application which others can use to understand the framework.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1332917', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/157705/']}
|
jdg_370928
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
121372
|
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'm new to Mathematica , and while this is potentially quite easy, I'm having difficulty using TimeObject s in the EventSeries function.After pulling out a column from an original dataset which had a series of time values, I then applied Count as Count @ Original which gave me a table akin to: Dataset[<| DateObject[{2016, 1, 1}, TimeObject[{12, 00, 0.}, TimeZone -> 10.], TimeZone -> 10.] -> 26, DateObject[{2016, 1, 1}, TimeObject[{01, 00, 0.}, TimeZone -> 10.], TimeZone -> 10.] -> 364, DateObject[{2016, 1, 1}, TimeObject[{02, 00, 0.}, TimeZone -> 10.], TimeZone -> 10.] -> 16|>] My question is 2-fold. 1) How do I pass that dataset to the EventSeries function, to be able to do a TimeSeries -esque plot? I'm finding it particularly difficult to find anything that references passing TimeObject s, hence the question. 2) Given that I am new to Mathematica , my second question is more conceptually, about the easiest way to pass multiple lists (or as I would previously call them, columns of a Dataset ) to a function?
Now provide the response and nothing else.
|
We can operate upon data contained within dataset by applying query operators. Assume that the dataset described in the question has been assigned to the variable ds . Then, for example, we can convert the embedded association into an event series by applying the EventSeries operator: ds[EventSeries] Alternatively, we could produce a plot by composing the EventSeries and DateListPlot operators: ds[EventSeries /* DateListPlot] It is likely that these operators can be applied directly to your original dataset. Let's consider the following dataset: ds2 = Query[Dataset, DateObject] @ {{2016, 1, 1}, {2016, 1, 1}, {2017, 1, 1}, {2017, 1, 1}, {2017, 1, 1}, {2018, 1, 1}}; As in the question, we could use Counts @ ds2 to get the number of occurrences of each date as an association (contained in a dataset). But instead, let's express this operation in query form: ds2[Counts] The advantage of using query operator syntax is that we can now compose it with our other query operators to produce the plot directly from the source dataset: ds2[Counts /* EventSeries /* DateListPlot] Dataset query syntax is quite elaborate. It is described in detail by the Dataset and Query documentation. Applying a Function to Multiple Columns As for the second question, a simple way to apply a function to multiple columns is to use named slot syntax (e.g. #columnName ). For example, consider this dataset: ds3 = Query[Dataset, AssociationThread[{"a", "b", "c"} -> #]&] @ RandomInteger[10, {5, 3}] We can add together the columns a and c by means of the query operator #a + #c& : ds3[All, #a + #c &] Alternatively, we could produce a bar chart of those sums: ds3[BarChart, #a + #c &]
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/121372', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/41834/']}
|
jdg_370929
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1880405
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've read a great deal of "go from svn to git" and other "git-svn workflow" articles on the web, and still I think they often deal with overly simple situations. They are often targeted at guys who just want to use git and hack locally, without using the full power of git, like pull, fetch, merge and the like between multiple developers who would all have cloned the svn repository with git-svn, then still expect to be able to push their changes any time to the (official) svn repository, and get back to working in git and sharing their stuff etc. Whenever these articles admit you can't do everything you'd do in pure git, the consequences and possible screw ups are never clearly explained (or maybe it's just me ?). Even the git-svn man page mentions caveats, but not really in an extensive manner. Based on what I've read, I feel there could be problems when git-svn is used in that specific way, which I'll describe below. Can someone tell me if I'm right about this ? Here is the "wanted" way of doing things: We have a project in a svn repository Developer A git-svn-clone's the svn repo. He begins to hack things locally Developer B git-svn-clone's the same svn repo. He begins to hack things on his own. After doing that for some time, possibly adding devs C/D/..., and having other developers who do "standard" svn commits to the original repo, the git users would want to share their code and do all kinds of git magic. Any one of those git users would like to be able to push the now merged changes to svn (dcommit?) My question is: am I dreaming? I read some time ago, in a git book I think, that git-svn-clone could create git repositories that are of course a "mirror" of the svn repo, but that git repos created that way by different developers would have different "ids" and commits would have different hashes. So my understanding was that those git repos wouldn't share any common git ancestor, and thus wouldn't be able to use all the git commands you need to share, merge, and so on. Is it true, are we going to face problems with this workflow ? Sometimes I read this could be done, using at least an "official" bare git repository, that would be the only one to be git-svn-cloned, and all git users would have to start form this one. Then you need someone who is in charge of this central git repo, and gathers the changes between the git devs, before dcommiting everything to the svn repo. This would be the only way for git users to be "unaware" that the original git repo comes from svn, and would let them use all git commands as they like. The only person who would need to be fluent in both git and svn (and know about git-svn caveats) would be the "merge manager" (or whatever he's called). Am I completely misunderstanding git-svn caveats ? Is there any simpler way of doing this ?
Now provide the response and nothing else.
|
The problem is step 4 of course. A dcommit tries to replay your local history to the server. Dcommit pretends that you're a SVN client. Now, if the code you're dcommitting isn't only from you, that's something that is hard to dcommit to SVN. Here's what the guru writes on the matter: For the sake of simplicity and interoperating with SVN, it is recommended that all git-svn users clone, fetch and dcommit directly from the SVN server (the remote SVN repository that is), and avoid all git-clone/pull/merge/push operations between git repositories and branches which are either retrieved via git svn clone and which are also used to push back changesets into the remote SVN repository. The recommended method of exchanging code between git branches and users is git format-patch and git am, or just git svn dcommit to the SVN repository. Since git svn dcommit uses git svn rebase internally, any git branches we git push to before git svn dcommit on them will require forcing an overwrite of the existing ref on the remote repository. This is generally considered bad practice, see the git-push documentation for details. Running git merge or git pull is not recommended on a branch we plan to git svn dcommit from. SVN does not represent merges in any reasonable or useful fashion so users using SVN cannot see any merges we have made. Furthermore, if we git merge or git pull from a git branch that is a mirror of an SVN branch, git svn dcommit may commit to the wrong branch. git clone does not clone branches under the refs/remotes/ hierarchy or any git-svn metadata, or config. So repositories created and managed with using git-svn should use rsync for cloning, if cloning is to be done at all. We should not use the --amend option of git commit on a change we have already dcommitted. It is considered bad practice to --amend commits we have already pushed to a remote repository for other users, and dcommit with SVN is analogous to that. More information on this can be found at Modifying a single commit and Problems with rewriting history .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1880405', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3744/']}
|
jdg_370930
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
47303017
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have following code snippet: private def buildProps(host: => String)(config: => List[KafkaConfig]) = (config.map { case ClientId(value: String) => (ProducerConfig.CLIENT_ID_CONFIG, value) case Acks(value: String) => (ProducerConfig.ACKS_CONFIG, value) case Retries(value) => (ProducerConfig.RETRIES_CONFIG, value) case BatchSize(value) => (ProducerConfig.BATCH_SIZE_CONFIG, value) case LingerMs(value) => (ProducerConfig.LINGER_MS_CONFIG, value) case BufferMemory(value) => (ProducerConfig.BUFFER_MEMORY_CONFIG, value) } ++ List( (ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, host), (ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer"), (ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.ByteArraySerializer")) ).toMap What is the type of the value from Map(String, ????) ? The type value of the case is very mixed: final case class ClientId(value: String) extends KafkaConfigfinal case class Acks(value: String) extends KafkaConfigfinal case class Retries(value: java.lang.Integer) extends KafkaConfigfinal case class BatchSize(value: java.lang.Integer) extends KafkaConfigfinal case class LingerMs(value: java.lang.Integer) extends KafkaConfigfinal case class BufferMemory(value: java.lang.Integer) extends KafkaConfig Some are Strings and another are Integers .
Now provide the response and nothing else.
|
I had the same problem and was just avoiding cleaning or rebuilding the whole project until I got the latest NDK update and the problem re-emerged. This happens because even after removing the targets, there are still files present in app/.externalNativeBuild that refers to them. To fix this I removed the Application.mk (which I was using to set the targets) and added this lines to app/build.gradle android { defaultConfig { // ... ndk { abiFilters 'armeabi-v7a', 'arm64-v8a' // 'x86', 'x86_64' may be added } } // ... task ndkClean(type: Delete) { // remove unused archs from build cache delete fileTree('.externalNativeBuild') { exclude defaultConfig.ndk.abiFilters.collect { '**/' + it } } } tasks.findByPath(':clean').dependsOn ndkClean}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47303017', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1743843/']}
|
jdg_370931
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3210496
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a project on Eclipse, Wicket, Spring, Hibernate. Every thing works normaly except : when I try public class SortableContactDataProvider extends SortableDataProvider<User>{ @SpringBean private Service service; public Iterator<User> iterator(int first, int count) { //SortParam sp = getSort(); return service.findAllUsers().subList(0, 15).iterator(); }... the service variable is null? In any another places when I use this constuction "service" is not null and working well. Please help me to solve this problem.
Now provide the response and nothing else.
|
@SpringBean works only in any Subclass of Component. You need to do the following in your Constructor Wicket 1.4 InjectorHolder.getInjector().inject(this); Wicket 1.5+ org.apache.wicket.injection.Injector.get().inject(this); See 'generic IDataProvider implementation' @ http://stronglytypedblog.blogspot.com/2009/03/wicket-patterns-and-pitfalls-1.html Enjoy
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3210496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/375983/']}
|
jdg_370932
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
908969
|
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:
Which is the correct identity? $dx \, dy = dx \otimes dy + dy \otimes dx$ $~~~$ or $~~~$ $dx \, dy = \dfrac{dx \otimes dy + dy \otimes dx}{2}~$ ? $dx \wedge dy=dx \otimes dy - dy \otimes dx$ $~~~$ or $~~~$ $dx \wedge dy=\dfrac{dx \otimes dy - dy \otimes dx}{2}~$ ? $$$$ Here is my understanding of the question from the point of view of: Linear algebra: Let $V$ be a vector space. The symmetric algebra $S(V)$ is a quotient of the tensor algebra $T(V)$ . The symmetric product $v \cdot w$ of elements of $V$ does not make sense a priori in $T(V)$ , but one can identify $S(V)$ with the space of symmetric tensors , which is a subspace of $T(V)$ where the restriction of the projection map $T(V) \to S(V)$ is an isomorphism. Under this isomorphism, the symmetric product $v \cdot w$ corresponds to the element $\dfrac{v \otimes w + w \otimes v}{2}$ of $T(V)$ . Same story for the exterior algebra $\Lambda(V)$ and alternating tensors: the wedge product $v \wedge w$ is identified with the alternating tensor $\dfrac{v \otimes w - w \otimes v}{2}$ . So contrary to what I have read in some places (e.g. accepted answer here ), in my opinion there is one natural way to identify symmetric products to symmetric tensors (resp. wedge products to alternating tensors) 1 . Conclusion: at least from the algebraic point of view, it seems to me that the natural thing to say is: $dx \, dy = \dfrac{dx \otimes dy + dy \otimes dx}{2}$ $dx \wedge dy = \dfrac{dx \otimes dy - dy \otimes dx}{2}$ Differential geometry : Again, I feel like there is only one choice we want to make here, contrary to what I have read sometimes: $dx \, dy = \dfrac{dx \otimes dy + dy \otimes dx}{2}$ , because $dxdx + dydy = dx^2 + dy^2 $ should be the standard metric (or inner product) on $\mathbb{R}^2$ (who would want $dx^2 + dy^2$ to mean something else?) $dx \wedge dy = dx \otimes dy - dy \otimes dx$ because $dx \wedge dy$ should be the standard area form (or determinant) on $\mathbb{R}^2$ (again, who would want $dx \wedge dy$ to mean something else 2 ?). Unfortunately, the answer 2. is different than what we found from the algebraic point of view. Worse, the choices made for the symmetric product and the wedge product do not seem to be consistent. Does anyone feel like they have a satisfying way to understand this issue? $$$$ 1 as I have tried to explain briefly. Said differently, it is natural to ask that the identification $\mathrm{Sym}^2 V \stackrel{\sim}{\to} S^2V$ should be the restriction of the projection map $p: V\otimes V \to S^2V$ . (Same story for the wedge product). 2 Said differently, when one defines integration of differential forms, integrating $f(x, y)\, dx \wedge dy$ should produce the Lebesgue integral $\int f(x,y) dx\,dy$ . I don't think anyone uses a different convention (?). Other remark: in complex differential geometry, I find the most natural identity between a Kähler Hermitian metric $h$ , the Riemannian metric $g$ and the Kähler form $\omega$ to be $h = g - i\omega$ . Try $h = dz \otimes d\overline{z}$ : then $g = dx \otimes dx + dy \otimes dy$ and $\omega = dx \otimes dy - dy \otimes dx$ . It is nice to write $g = dx^2 + dy^2$ and $\omega = dx \wedge dy$ , in particular, the Kähler form is the area form of the Riemannian metric.
Now provide the response and nothing else.
|
The motivation for the coefficient $\frac{1}{n!}$ is as follows : if $f : V\times...\times V\to\mathbb{K}$ is n-linear and alternate form, we define the alternator $\mathrm{Alt}$ so that $\mathrm{Alt}(f)=f$. That is$$f(x_1,...,x_n)=\frac{1}{n!}\sum_{\sigma\in S_n}\varepsilon(\sigma)f(x_{\sigma(1)},...x_{\sigma(n)})=\mathrm{Alt}(f)(x_1,...,x_n).$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/908969', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/91164/']}
|
jdg_370933
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52038417
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Which null-check is preferable? Optional.ofNullable(port).ifPresent(settings::setPort); or if (port != null) { settings.setPort(port);}
Now provide the response and nothing else.
|
In Java, an Optional value is a fusion of a bit that indicates presence or absence, with a value of an arbitrary reference type T or a primitive int , long , or double . Fusing these is especially useful when returning a value from a method, as methods have only a single return value. It's often necessary to use a special value such as null in the case of reference types, or -1 in the case of int , as a sentinel to indicate the "no-value" case. Using Optional as a return value avoids the problem of the caller accidentally misusing the sentinel value as the real return value. Given this, line of code such as Optional.ofNullable(port).ifPresent(settings::setPort); is strange in that it fuses a value with the present/absent bit in the first part of the line and then immediately separates them in the second part of the line. This adds complexity to what is ultimately a fairly simple task: checking whether port is non-null and conditionally performing some action. The alternative code snippet: if (port != null) { settings.setPort(port);} expresses quite clearly exactly what it does. It's true that the if-statement takes more vertical space than the Optional chain. The Optional chain is denser, but it's also harder to understand: a poor tradeoff.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52038417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10108131/']}
|
jdg_370934
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25630611
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Should the stores maintain their own state and have the ability to call network and data storage services in doing so ...in which case the actions are just dumb message passers, -OR- ...should the stores be dumb recipients of immutable data from the actions (and the actions be the ones that fetch/send data between external sources? Store in this instance would act as view-models and would be able to aggregate / filter their data prior to setting their own state base on the immutable data they were fed by the action. It seems to me that it should be one or the other (rather than a mix of both). If so, why is one preferred / recommended over the other?
Now provide the response and nothing else.
|
I've seen the flux pattern implemented both ways, and after having done both myself (initially going with the former approach), I believe that stores should be dumb recipients of data from the actions, and that asynchronous processing of writes should live in the action creators. ( Async reads can be handled differently .) In my experience, this has a few benefits, in order of importance: Your stores become completely synchronous. This makes your store logic much easier to follow and very easy to test—just instantiate a store with some given state, send it an action, and check to see if the state changed as expected. Furthermore, one of the core concepts in flux is to prevent cascading dispatches and to prevent multiple dispatches at once; this is very difficult to do when your stores do asynchronous processing. All action dispatches happen from the action creators. If you handle asynchronous operations in your stores and you want to keep your stores' action handlers synchronous (and you should in order to get the flux single-dispatch guarantees), your stores will need to fire additional SUCCESS and FAIL actions in response to asynchronous processing. Putting these dispatches in the action creators instead helps separate the jobs of the action creators and the stores; furthermore, you don't have to go digging through your store logic to figure out where actions are being dispatched from. A typical asynchronous action in this case might look something like this (change the syntax of the dispatch calls based on the flavor of flux you're using): someActionCreator: function(userId) { // Dispatch an action now so that stores that want // to optimistically update their state can do so. dispatch("SOME_ACTION", {userId: userId}); // This example uses promises, but you can use Node-style // callbacks or whatever you want for error handling. SomeDataAccessLayer.doSomething(userId) .then(function(newData) { // Stores that optimistically updated may not do anything // with a "SUCCESS" action, but you might e.g. stop showing // a loading indicator, etc. dispatch("SOME_ACTION_SUCCESS", {userId: userId, newData: newData}); }, function(error) { // Stores can roll back by watching for the error case. dispatch("SOME_ACTION_FAIL", {userId: userId, error: error}); });} Logic that may otherwise be duplicated across various actions should be extracted into a separate module; in this example, that module would be SomeDataAccessLayer , which handles doing the actual Ajax request. You need less action creators. This is less of a big deal, but nice to have. As mentioned in #2, if your stores have synchronous action dispatch handling (and they should), you'll need to fire extra actions to handle the results of asynchronous operations. Doing the dispatches in the action creators means that a single action creator can dispatch all three action types by handling the result of the asynchronous data access itself.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/25630611', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/232424/']}
|
jdg_370935
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2992075
|
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 getting the following error message when compiling or attempting to run my application on Windows 7 64 bit. I've scoured the Internet and many people have the same error message. However, none of the solutions address my problem or situation. I am using Visual Studio 2010 . Error message Error 38 Could not load file or assembly 'file:///D:/Projects/Windows Projects/Weld/Components/FileAttachments/FileAttachments/FileAttachments/bin/x86/Debug/FileAttaching.dll' or one of its dependencies. An attempt was made to load a program with an incorrect format. Line 1212, position 5. D:\Projects\Windows Projects\Weld\Weld\Weld.UI\frmMain.resx 1212 5 Weld.UI Description OK, so I have two projects, a UI project and a FileAttachment project. The UI project has a reference to the FileAttachment project. When I compile the UI project in "Any CPU" mode, everything works fine, and it runs. I assume 'Any CPU' will run in 64-bit mode when I compile as that is the platform I am using. I want to run/compile as x86, so I try to do that. I change the configuration for all projects to x86 and verify that these configurations are compiling to x86. I compile and get the error as stated above. I find it odd that it compiles and works fine in 64-bit but not 32-bit. However, when compiled and deployed to users as 'Any CPU', if these users have x86 it still works for them without any problems. I just can't compile or run as x86 on my PC. Again, I can compile as Any CPU and deploy to a 32-bit PC without any problems. Neither projects are referencing any 64-bit-only DLL files. Both projects are verified to be targeting 32-bit DLL files and .NET Framework assemblies. I need to compile and run this locally under 32-bit mode. I need JIT edit/continue, among other things. Here is the line of code in the resx file that is causing the problem: <data name="ImageList1.ImageStream" mimetype="application/x-microsoft.net.object.binary.base64">....{mime data}.... </data> The resx file is verified to be generated for .NET 2.0 and is only referencing .NET 2.0 assemblies and not .NET 4.0 versions. How can I fix this problem? I've searched the Internet and have found hundreds of people with the same error message, but a different problem.
Now provide the response and nothing else.
|
This appears to be a VS 2010 bug with image lists. See https://connect.microsoft.com/VisualStudio/feedback/details/532584/error-when-compiling-resx-file-seems-related-to-beta2-bug-5252020?wa=wsignin1.0 I was able to utilize the workaround listed to get it to work for me. Posted by Luis Mack on 5/12/2010 at 8:50 AM I've found the same problem, only for a specific project when compiling on a 64-bit machine. A fix that SEEMS to work is to manually alter one character in the image stream EVERY TIME the usercontrol or form is edited in the designer AAEAAAD/////AQAAAAAAAAAMAgAAAFdTeXN0ZW0uV2luZG93cy5Gb3JtcywgVmVyc2lvbj00LjAuMC4w Change to AAEAAAD/////AQAAAAAAAAAMAgAAAFdTeXN0ZW0uV2luZG93cy5Gb3JtcywgVmVyc2lvbj0yLjAuMC4w That is 00LjAuMC4w back to 0yLjAuMC4w at the end of the line (00 back to 0y) Jim
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2992075', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/269649/']}
|
jdg_370936
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26015162
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Basically, I am converting HTML code received via a websites JSON API from raw HTML to an attributed string. This effort to remove some of the HTML specific codes, whilst also keeping some degree of formatting, such as underlines/bold text/etc. There is an issue I'm experiencing however, HTML code converted to the attributed string seems to ignore any blank lines. So for example: Step one. Step two. Step three. Becomes: Step one. 2. Step two. 3. Step three. For whatever reason it appears as if it is either substituting the newlines for a space. I can't seem to work this out but it's making this function basically unusable. I'd much rather use an included API to handle the conversion as the several available categories available don't seem to handle all of the HTML, leaving things like in the cells, which is not something I can use. Furthermore, I prefer to use one of the included APIs because it is highly unlikely to break in future versions. Is there anything that can be done to overcome this, or is this a bug? For what it's worth, I am using a device on iOS 7. NSMutableAttributedString* attrStr = [[NSMutableAttributedString alloc] initWithData:[post.comment dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: [NSNumber numberWithInt:NSUTF8StringEncoding]} documentAttributes:nil error:nil];NSRange rangeOfTitle = NSMakeRange(0,[attrStr length]);[attrStr addAttribute: NSFontAttributeName value:[UIFont systemFontOfSize: 14.0f] range:rangeOfTitle];
Now provide the response and nothing else.
|
There are two ways to fix this: Execute the following in the MySQL console: SET GLOBAL log_bin_trust_function_creators = 1; Add the following to the mysql.ini configuration file: log_bin_trust_function_creators = 1; The setting relaxes the checking for non-deterministic functions. Non-deterministic functions are functions that modify data (i.e. have update, insert or delete statement(s)). For more info, see here . Please note, if binary logging is NOT enabled, this setting does not apply. Binary Logging of Stored Programs If binary logging is not enabled, log_bin_trust_function_creators does not apply. log_bin_trust_function_creators This variable applies when binary logging is enabled. The best approach is a better understanding and use of deterministic declarations for stored functions. These declarations are used by MySQL to optimize the replication and it is a good thing to choose them carefully to have a healthy replication. DETERMINISTIC A routine is considered “deterministic” if it always produces the same result for the same input parameters and NOT DETERMINISTIC otherwise.This is mostly used with string or math processing, but not limited to that. NOT DETERMINISTIC Opposite of "DETERMINISTIC". " If neither DETERMINISTIC nor NOT DETERMINISTIC is given in the routine definition, the default is NOT DETERMINISTIC. To declare that a function is deterministic, you must specify DETERMINISTIC explicitly. ".So it seems that if no statement is made, MySQl will treat the function as "NOT DETERMINISTIC".This statement from manual is in contradiction with other statement from another area of manual which tells that:" When you create a stored function, you must declare either that it is deterministic or that it does not modify data. Otherwise, it may be unsafe for data recovery or replication.By default, for a CREATE FUNCTION statement to be accepted, at least one of DETERMINISTIC, NO SQL, or READS SQL DATA must be specified explicitly. Otherwise an error occurs " I personally got error in MySQL 5.5 if there is no declaration, so i always put at least one declaration of "DETERMINISTIC", "NOT DETERMINISTIC", "NO SQL" or "READS SQL DATA" regardless other declarations i may have. READS SQL DATA This explicitly tells to MySQL that the function will ONLY read data from databases, thus, it does not contain instructions that modify data, but it contains SQL instructions that read data (e.q. SELECT). MODIFIES SQL DATA This indicates that the routine contains statements that may write data (for example, it contain UPDATE, INSERT, DELETE or ALTER instructions). NO SQL This indicates that the routine contains no SQL statements. CONTAINS SQL This indicates that the routine contains SQL instructions, but does not contain statements that read or write data. This is the default if none of these characteristics is given explicitly. Examples of such statements are SELECT NOW(), SELECT 10+@b, SET @x = 1 or DO RELEASE_LOCK('abc'), which execute but neither read nor write data. Note that there are MySQL functions that are not deterministic safe, such as: NOW(), UUID(), etc, which are likely to produce different results on different machines, so a user function that contains such instructions must be declared as NOT DETERMINISTIC.Also, a function that reads data from an unreplicated schema is clearly NONDETERMINISTIC.* Assessment of the nature of a routine is based on the “honesty” of the creator: MySQL does not check that a routine declared DETERMINISTIC is free of statements that produce nondeterministic results. However, misdeclaring a routine might affect results or affect performance. Declaring a nondeterministic routine as DETERMINISTIC might lead to unexpected results by causing the optimizer to make incorrect execution plan choices. Declaring a deterministic routine as NONDETERMINISTIC might diminish performance by causing available optimizations not to be used.
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/26015162', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2714839/']}
|
jdg_370937
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18822440
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Python: Is there a way to write multi-line strings into an excel cell with just the xlwt module? (I saw answers suggesting use of openpyxl module) The sheet.write() method ignores the \n escape sequence. So, just xlwt, is it possible? Thanks in advance.
Now provide the response and nothing else.
|
I found the answer in the python-excel Google Group . Using sheet.write() with the optional style argument, enabling word wrap for the cell, does the trick. Here is a minimum working example: import xlwtbook = xlwt.Workbook()sheet = book.add_sheet('Test')# A1: no style, no wrap, despite newlinesheet.write(0, 0, 'Hello\nWorld')# B1: with style, there is wrapstyle = xlwt.XFStyle()style.alignment.wrap = 1sheet.write(0, 1, 'Hello\nWorld', style)book.save('test.xls') While in cell A1 shows HelloWorld without linebreak, cell B1 shows Hello\nWorld (i.e. with linebreak).
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18822440', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2782845/']}
|
jdg_370938
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
44452976
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Controller $scope.propertyName = ""; $scope.reverse = 'none'; $scope.sortBy = function (propertyName, val) { if ($scope.reverse === 'none') { $scope.reverse = false; } $scope.reverse = !val; $scope.propertyName = propertyName; }; HTML <div ng-class="{'sort': (reverse === 'none'), 'sort desc': reverse, 'sort asc': !reverse}" ng-click="sortBy('DivisionIndex',reverse)"> but on page load, sort desc class applies (reverse = true). i need to set class sort on page load and then change the value of reverse into boolean for apply css on sorting icons.
Now provide the response and nothing else.
|
Here is the only solution I found for this one: First, create const: const MY_DATE_FORMATS = { parse: { dateInput: {month: 'short', year: 'numeric', day: 'numeric'} }, display: { // dateInput: { month: 'short', year: 'numeric', day: 'numeric' }, dateInput: 'input', monthYearLabel: {year: 'numeric', month: 'short'}, dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'}, monthYearA11yLabel: {year: 'numeric', month: 'long'}, }}; Then you have to extend NativeDateADapter: export class MyDateAdapter extends NativeDateAdapter { format(date: Date, displayFormat: Object): string { if (displayFormat == "input") { let day = date.getDate(); let month = date.getMonth() + 1; let year = date.getFullYear(); return this._to2digit(day) + '/' + this._to2digit(month) + '/' + year; } else { return date.toDateString(); } } private _to2digit(n: number) { return ('00' + n).slice(-2); } } In format function, you can choose whatever format you want And the last step, you have to add it into module providers: providers: [ {provide: DateAdapter, useClass: MyDateAdapter}, {provide: MD_DATE_FORMATS, useValue: MY_DATE_FORMATS},], And that's it. I can not believe that there is no some easy way to change date format through the @Input but let's hope it will be implemented in some future version of material 2 (currently beta 6 ).
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/44452976', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6270163/']}
|
jdg_370939
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
200985
|
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:
OKay I tried using a L'Hopital's Rule (immediately failed), series expansion (wrote the first three terms and gave up on this method), Squeeze's Theorem (couldn't get a proper lower bound), and I am absolutely stumped $$\lim_{n\to \infty} \frac{\tan(\pi/n)}{n\sin^2(2/n)}$$ According to Mathematica, it converges to $\frac{\pi}{4}$, but I have no idea how. any insight is greatly appreciated
Now provide the response and nothing else.
|
Hint: Your limit is $$\lim_{x\to0}\frac{\tan\pi x}{\pi x}\cdot\left(\frac{ 2x}{\sin 2x}\right)^2\cdot\frac{\pi}{4}$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/200985', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/26728/']}
|
jdg_370940
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.