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 | 18106327 |
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 argparse.ArgumentParser() in my script, I would like to display the pydoc description of my script as part of the '--help' option of the argparse. One possibly solution can be to use the formatter_class or the description attribute of ArgumentParser to configure the displaying of help. But in this case, we need to use the 'pydoc' command internally to fetch the description. Do we have some other ways (possibly elegant) to do it?
Now provide the response and nothing else.
| You can retrieve the docstring of your script from the __doc__ global. To add it to your script's help, you can set the description argument of the parser. """My python scriptScript to process a file"""p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)p.add_argument('foo', help="Name of file to process")p.parse_args() Then the help will look like: $ python tmp.py --helpusage: tmp.py [-h] fooMy python scriptScript to process a filepositional arguments: foo Name of file to processoptional arguments: -h, --help show this help message and exit You can use the epilog keyword argument instead of description to move the docstring to the end of the help, instead of immediately following the usage string. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18106327', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/830526/']} | jdg_73641 |
stackexchange | llm_judgeable_groundtruth_similarity | 13197756 |
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 point of this question is to illustrate that Java is not working as I expected. How would you expect the following code to behave? public class SynchTester { private static SynchTester synchTester; public synchronized static SynchTester getSynchTester(){ if(synchTester==null){ synchTester = new SynchTester(); } return synchTester; } private SynchTester() { SynchTester myTester = getSynchTester(); } public static void main(String[] args) { SynchTester tester = SynchTester.getSynchTester(); }} I would expect it to hang with a deadlock waiting on the recursion to complete, but instead it throws StackOverflow. Evidently synchronized does not block access to the same thread. Is this a bug?
Now provide the response and nothing else.
| In Java, synchronized locks are reentrant . Recall that a thread cannot acquire a lock owned by another thread. But a thread can acquire a lock that it already owns . Allowing a thread to acquire the same lock more than once enables reentrant synchronization. This describes a situation where synchronized code, directly or indirectly, invokes a method that also contains synchronized code, and both sets of code use the same lock. Without reentrant synchronization, synchronized code would have to take many additional precautions to avoid having a thread cause itself to block. Source: see bottom of this page | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13197756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/967330/']} | jdg_73642 |
stackexchange | llm_judgeable_groundtruth_similarity | 1550007 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been working with Microsoft's Unity IOC container. There are a bunch of overloads for the RegisterType() method all looking similar to IUnityContainer RegisterType(Type t, params InjectionMember[] injectionMembers); I'm wondering when the injectionMembers parameters are for? I couldn't find any documentation for the them (even though they're in every overload) and none of the sample code I looked at use them. Am I missing something here? Are they not commonly used or did I just miss the examples?
Now provide the response and nothing else.
| The overload with the InjectionMember array is used, when you do not provide a configuration file that Unity tells how to create an instance of the given type or if you want to create an instance by another way than defined in the configuration file. The overloads are used, when you want to configure an unity container without a configuration file. An InjectionMember can be a constructor, property or method call. The following code, taken from the Unity help, shows how to use InjectionMembers through the fluent interface of the container. IUnityContainer myContainer = new UnityContainer();myContainer.Configure<InjectedMembers>() .ConfigureInjectionFor<MyObject>( new InjectionConstructor(12, "Hello Unity!"), new InjectionProperty("MyStringProperty", "SomeText")); The following XML configuration is equivalent to the code above. <type type="MyObject" mapTo="MyObject" name="MyObject"> <typeConfig extensionType="Microsoft.Practices.Unity.Configuration.TypeInjectionElement, Microsoft.Practices.Unity.Configuration"> <constructor> <param name="someInt" parameterType="int"> <value value="12"/> </param> <param name="someText" parameterType="string"> <value value="Hello Unity!"/> </param> </constructor> <property name="MyStringProperty" propertyType="string"> <value value="SomeText"/> </property> </typeConfig> </type> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1550007', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9045/']} | jdg_73643 |
stackexchange | llm_judgeable_groundtruth_similarity | 1288806 |
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 ActionLink, that calls my public ActionResult, and I would like it to return back to the page that it was called from, but how?
Now provide the response and nothing else.
| There are a couple of tricks that you can use for this. The simplest is ... return Redirect(HttpContext.Request.UrlReferrer.AbsoluteUri); AbsoluteUri may not give you the exact path you are looking for, but UrlReferrer should have the imformation you are looking for. Redirect returns a subclass of ActionResult so it is a valid return value. Another idea is to base the redirect location off of stored values. This is useful when you are going to make multiple requests before you want to redirect, such as when you validate a form and show validation issues on the first response. Another situation will be when the referrer is not a local site. In either case, your referrer won't be what you want it to and you will need to retrieve the correct location from somewhere else. Specific implementations include using a hidden input field on your form, session state, pulling a descriminator value from your route data, or even just a more constant value like HttpContext.Request.ApplicationPath. Good luck. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1288806', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/58309/']} | jdg_73644 |
stackexchange | llm_judgeable_groundtruth_similarity | 9593097 |
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 set each character in a string to an integer? This is just the first thing I have to do in order to write a hash function. I have to set each character in a string to an integer so that I can sum their values. Please help! It it something like this?? int hashCode(string s){ int Sum = 0; for(int i=0; i<strlen(s); i++) { Sum += (int)s[i]; } return Sum;}
Now provide the response and nothing else.
| Yes -- in C and C++, char is just a small integer type (typically with a range from -128 to +127). When you do math on it, it'll normally be converted to int automatically, so you don't even need your cast. As an aside, you really don't want to use strlen(s) inside the stopping condition for your for-loop. At least with most compilers, this will force it to re-evaluated strlen(s) every iteration, so your linear algorithm just became quadratic instead. size_t len = strlen(s);for (int i=0; i<len; i++) Sum += s[i]; Or, if s is actually a std::string , as the parameter type suggests: for (int i=0; i<s.size(); i++) Sum += s[i]; As yet one more possibility: Sum = std::accumulate(s.begin(), s.end(), 0); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9593097', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/742895/']} | jdg_73645 |
stackexchange | llm_judgeable_groundtruth_similarity | 7973224 |
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 convert Varchar to Int in sql server 2008. i have following code when i tried to run it wont allowed me to convert Varchar to Int. Select Cast([Column1] as INT) Column1 is of Varchar(21) NOT NULL type and i wanted to convert it into Int.actually i am trying to insert Column1 into another table having Field as INT.can someone please help me to convert this ?
Now provide the response and nothing else.
| Spaces will not be a problem for cast , however characters like TAB , CR or LF will appear as spaces, will not be trimmed by LTRIM or RTRIM , and will be a problem. For example try the following: declare @v1 varchar(21) = '66', @v2 varchar(21) = ' 66 ', @v3 varchar(21) = '66' + char(13) + char(10), @v4 varchar(21) = char(9) + '66'select cast(@v1 as int) -- okselect cast(@v2 as int) -- okselect cast(@v3 as int) -- errorselect cast(@v4 as int) -- error Check your input for these characters and if you find them, use REPLACE to clean up your data. Per your comment, you can use REPLACE as part of your cast : select cast(replace(replace(@v3, char(13), ''), char(10), '') as int) If this is something that will be happening often, it would be better to clean up the data and modify the way the table is populated to remove the CR and LF before it is entered. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7973224', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1004164/']} | jdg_73646 |
stackexchange | llm_judgeable_groundtruth_similarity | 126099 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How do take this limit: $$ \lim_{n\to\infty} \frac{\sqrt{n}}{\log(n)}$$ I have a feeling that it is infinity, but I'm not sure how to prove it. Should I use L'Hopitals Rule?
Now provide the response and nothing else.
| Let $n = e^x$. Note that as $n \rightarrow \infty$, we also have $x \rightarrow \infty$. Hence, $$\lim_{n \rightarrow \infty} \frac{\sqrt{n}}{\log(n)} = \lim_{x \rightarrow \infty} \frac{\exp(x/2)}{x}$$Note that $\displaystyle \exp(y) > \frac{y^2}{2}$, $\forall y > 0$ (Why?). Hence, we have that $$\lim_{n \rightarrow \infty} \frac{\sqrt{n}}{\log(n)} = \lim_{x \rightarrow \infty} \frac{\exp(x/2)}{x} \geq \lim_{x \rightarrow \infty} \frac{\frac{x^2}{8}}{x} = \lim_{x \rightarrow \infty} \frac{x}{8} = \infty$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/126099', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/23152/']} | jdg_73647 |
stackexchange | llm_judgeable_groundtruth_similarity | 582901 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I don't understand why the probability density in the double slit experiment in the case of both slits opened, has a minimum corresponding to the maximum of intensity. Shouldn't $P_{12}$ have the same trend as intensity? Intensity patterns in the double-slit experiment (a)Photon intensity $I_1$ on the screen with slit-1 only opened (b) Photon intensity I_2 with slit2 only opened (c) Interference pattern when both slits were opened d) probability distribution $P_{12}$ of photons when both the slits were opened and when the film was replaced by an array of photon detectors. The manual says Probability distribution P_12 of photons when both the slits were opened and when the film was replaced by an array of photon detectors
Now provide the response and nothing else.
| You can Taylor-expand it just like you would a polynomial. Given the definition of the exponential function as a Taylor series, $$ e^{ax} = 1 + ax + \frac{(ax)^2}{2!} + \frac{(ax)^3}{3!} + \cdots,$$ you can generalize it to operators. Accordingly, the exponentiation of an operator, say the Hamiltonian $\hat{H},$ can be written as an infinite series of operators: $$ e^{\hat{H}} = \mathbb{I} + \hat{H} + \frac{\hat{H}^2}{2!} + \frac{\hat{H}^3}{3!} + \cdots$$ where the first operator on the right-hand-side is the identity operator: $\mathbb{I}: \mathbb{I} \psi = \psi.$ Of course, the choice of the operator is arbitrary, and as far as I know, it does not need to be Hermitian or unitary. In Quantum Mechanics, exponentiated operators serve the role of generators of motion in time or in a Hilbert space. For instance, the momentum operator $\hat{p}$ exponentiated as $e^{- i \, \textbf{x} \cdot \hat{p}/\hbar}$ represents a translation in position when applied to a wavefunction $\psi(x).$ | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/582901', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/219477/']} | jdg_73648 |
stackexchange | llm_judgeable_groundtruth_similarity | 21747685 |
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 Symfony 2, which is the best way to create a link to delete a record? I can define a route to /entity/delete accepting only a DELETE method, but I don't know how to create a DELETE link from a template. The same goes for creating PUT links. So, what do you do? Accept GET petition to delete a record? Is there any way to create a DELETE link?
Now provide the response and nothing else.
| Anchors can fire only GET requests. And since GET requests can be cached and in some future (when you implement serious caching) might not reach your app code at all, it's a bad practice to use GET for changing anything that modifies state of your App. Here is what I do in my projects. With these two, you will be able to just do the following in your templates: <a href="{{ path('my_entity_destroy') }}" {{ delete_link(myEntity) }}>Delete</a> How it works Assuming your entity delete path is: /my_entity , methods: [DELETE] Principle is really simple. delete_link extension method will create data-attribute on anchor, so compiled anchor will look like this: <a href="/my_entity" data-delete-link="3964">Delete</a> Then, when somebody clicks on that link, javascript will catch that click, create a form and fire a DELETE request with id provided in data-delete-link attribute. What makes it work Here is what makes it possible, a LinkHelper Twig extension: <?phpnamespace Me\MyBundle\Twig;class LinkHelperExtension extends \Twig_Extension{ public function getFunctions() { return [ new \Twig_SimpleFunction('delete_link', [$this, 'fnDeleteLink'], ['is_safe' => ['all']]), ]; } public function fnDeleteLink($target) { if (is_object($target)) { $target = $target->getId(); } return "data-delete-link='$target'"; } public function getName() { return 'link_helper'; }} And I a JavaScript in my base template: $(function () { var createForm = function (action, data) { var $form = $('<form action="' + action + '" method="POST"></form>'); for (input in data) { if (data.hasOwnProperty(input)) { $form.append('<input name="' + input + '" value="' + data[input] + '">'); } } return $form; }; $(document).on('click', 'a[data-delete-link]', function (e) { e.preventDefault(); var $this = $(this); var $form = createForm($this.attr('href'), { id: $this.attr('data-delete-link'), _method: 'DELETE' }).hide(); $('body').append($form); // Firefox requires form to be on the page to allow submission $form.submit(); });}); Limitations It only works for entities that have primary key named id . However, you can pretty easy modify this to suit your needs and support composite primary keys etc. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21747685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/787008/']} | jdg_73649 |
stackexchange | llm_judgeable_groundtruth_similarity | 24906304 |
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 get multiple user request to hold run or kill the jobs running in our autosys server I want to crete a script which will take input as joobname and what send event they want as input parameter and then trigger the respective job as per requirement . Can it be done.Please help
Now provide the response and nothing else.
| @echo off ping -t localhost|find /v ""|cmd /q /v:on /c "for /l %%a in (0) do (set "data="&set /p "data="&if defined data echo(!time! !data!)" note : code to be used inside a batch file. To use from command line replace %%a with %a Start the ping, force a correct line buffered output ( find /v ), and start a cmd process with delayed expansion enabled that will do an infinite loop reading the piped data that will be echoed to console prefixed with the current time. 2015-01-08 edited : In faster/newer machines/os versions there is a synchronization problem in previous code, making the set /p read a line while the ping command is still writting it and the result are line cuts. @echo off ping -t localhost|cmd /q /v /c "(pause&pause)>nul & for /l %%a in () do (set /p "data=" && echo(!time! !data!)&ping -n 2 localhost>nul" Two aditional pause commands are included at the start of the subshell (only one can be used, but as pause consumes a input character, a CRLF pair is broken and a line with a LF is readed) to wait for input data, and a ping -n 2 localhost is included to wait a second for each read in the inner loop. The result is a more stable behaviour and less CPU usage. NOTE: The inner ping can be replaced with a pause , but then the first character of each readed line is consumed by the pause and not retrieved by the set /p | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/24906304', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3867974/']} | jdg_73650 |
stackexchange | llm_judgeable_groundtruth_similarity | 32802766 |
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 access my router from within my component and it is undefined. Here is my router : React.render( <Provider store={store}> {() => <Router> <Route path="/" component={LoginContainer} /> </Router> } </Provider>, document.getElementById('app')); Here is the container: class LoginContainer extends React.Component { constructor() { super(); } static propTypes = { handleLogin: PropTypes.func.isRequired } static contextTypes = { router: React.PropTypes.object } handleLogin() { this.props.dispatch(Actions.login(null, null, this.context.router)); } render() { return ( <Login auth={this.props} handleLogin={this.handleLogin} /> ); }}function mapStateToProps(state) { return { stuff: [] }}export default connect(mapStateToProps)(LoginContainer); And finally the component: import React, { PropTypes } from 'react';class Login extends React.Component { static propType = { handleLogin: PropTypes.func.isRequired } static contextTypes = { router: React.PropTypes.object } render() { return ( <div className="flex-container-center"> <form> <div className="form-group"> <button type="button" onClick={this.props.handleLogin}>Log in</button> </div> </form> </div> ); }}module.exports = Login; When I click on the login button, it hits the handleLogin in the container. In my handleLogin , my this value is undefined . I have tried to bind this to the function in the constructor , but it still is undefined . Also, when I put a breakpoint in my render function, I have a this.context.router , but it is undefined . How do I get my this correct in my handleLogin and how to I make sure that I have my router on the context and it is not undefined ?
Now provide the response and nothing else.
| The best way to keep up with changes is to look through the Releases page. In React Router versions that are > 1.0.0-beta3 and < 2.0.0-rc2 , there is no context.router . Instead, you need to look for context.history . If you use versions <= 1.0.0-beta3 or >= 2.0.0-rc2 , the context.router is there. In short, what happened is it was removed in favor of history but then the maintainters decided it’s best to hide the History library API behind the router, so they brough back the router context in 2.0 RC2 and onward. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32802766', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/968801/']} | jdg_73651 |
stackexchange | llm_judgeable_groundtruth_similarity | 496775 |
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:
Sorry for what might seem like a really simple question. I came across a LED bulb that has the following specs: It is rated for: 120VAC (which I assume is just because the wall voltage in the US is 120VAC @ 60Hz) 14W power 14mA current However, I don't know how they calculated 14W if according to the power law equation: P = I * V I should get something like 16.8W = .14A * 120V So my question is, where does the 14W come from if the power equation is 16.8W ? Thanks in advance!
Now provide the response and nothing else.
| The power factor is not 1.00 in most electronics, particularly inexpensive low-power electronics, so the product of current and voltage (VA) will, in general, be higher than the real power (W) drawn. As well, those numbers may be maximums and not nominal so you can't necessarily depend on them to be consistent. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/496775', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/251096/']} | jdg_73652 |
stackexchange | llm_judgeable_groundtruth_similarity | 1341983 |
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 want to evaluate $$\int \dfrac{\cos \theta \, \mathrm{d}\theta}{ \sqrt{2 - 9 \sin^2 \theta}}$$ but I can't seem to get the answer, my working is as below:
Now provide the response and nothing else.
| Hint$$\int\dfrac{\cos{\theta}}{\sqrt{2-9\sin^2{\theta}}}d\theta=\int\dfrac{d\sin{\theta}}{\sqrt{2-9\sin^2{\theta}}}$$and$$\int\dfrac{1}{\sqrt{2-9t^2}}dt=\dfrac{1}{\sqrt{2}}\cdot\int\dfrac{1}{\sqrt{1-\left(\frac{3}{\sqrt{2}}t\right)^2}}dt=\dfrac{1}{3}\cdot\int\dfrac{1}{\sqrt{1-\left(\frac{3}{\sqrt{2}}t\right)^2}}d\left(\dfrac{3}{\sqrt{2}}t\right)$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1341983', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/165121/']} | jdg_73653 |
stackexchange | llm_judgeable_groundtruth_similarity | 3236575 |
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 there a simple closed expression for the following sum? $$\sum_{i=0}^{\lfloor\frac n2\rfloor}{n\choose i}{n-i\choose i}$$ I can see that this is the constant term in $\big(\frac 1x+1+x\big)^n$ . But this is no closer to a simple close expression I am seeking.
Now provide the response and nothing else.
| We use the coefficient of operator $[z^i]$ to denote the coefficient of $z^i$ of a series. This way we can write for instance \begin{align*}[z^i](1+z)^n=\binom{n}{i}\tag{1}\end{align*} We obtain \begin{align*}\color{blue}{\sum_{i=0}^{\left\lfloor \frac{n}{2}\right\rfloor}}&\color{blue}{\binom{n}{i}\binom{n-i}{i}}\tag{2}\\&=\sum_{i=0}^{n}\binom{n}{i}[z^i](1+z)^{n-i}\tag{3}\\&=[z^0](1+z)^n\sum_{i=0}^{n}\binom{n}{i}\left(\frac{1}{z(1+z)}\right)^i\tag{4}\\&=[z^0](1+z)^n\left(1+\frac{1}{z(1+z)}\right)^{n}\tag{5}\\&\,\,\color{blue}{=[z^{n}](1+z+z^2)^n}\tag{6}\end{align*} Comment: In (3) we apply the coefficient of operator according to (1). We also set the upper limit to $n$ without changing anything, since $\binom{n-i}{i}=0$ if $i>\left\lfloor\frac{n}{2}\right\rfloor$ . In (4) we use the rule $[z^{p-q}]A(z)=[z^p]z^qA(z)$ . In (5) we apply the binomial theorem. In (6) we do some simplifications and use again the rule as in (3). We observe the binomial sum (2) represents essentially central trinomial coefficients \begin{align*}[z^n](1+z+z^2)^n\end{align*} for which there is no closed form available. Notes from the experts: D.E. Knuth gives in Concrete Mathematics , Appendix A 7.56 the following representation of a more general expression \begin{align*}[z^n](a+bz+cz^2)^n=[z^n]\frac{1}{\sqrt{1-2bz+(b^2-4ac)z^2}}\end{align*} He states that according to the paper Hypergeometric Solutions of Linear Recurrences with Polynomial Coeffcients by Marko Petkovšek there exists a closed form (more precisely: a closed form solution as a finite sum of hypergeometric terms) if and only if $$\color{blue}{abc(b^2-4ac)=0}$$ In case of central trinomial coefficients we have $a=b=c=1$ . Since then the expression $abc(b^2-4ac)=-3\ne 0$ there is no such closed form in particular for the central trinomial coefficients. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3236575', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/64809/']} | jdg_73654 |
stackexchange | llm_judgeable_groundtruth_similarity | 216450 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've always programmed in procedural languages and currently I'm moving towards object orientation. The main problem I've faced is that I can't see a way to practice object orientation in an effective way. I'll explain my point. When I've learned PHP and C it was pretty easy to practice: it was just matter of choosing something and thinking about an algorithm for that thing. In PHP for example, it was matter os sitting down and thinking: "well, just to practice, let me build one application with an administration area where people can add products". This was pretty easy, it was matter of thinking of an algorithm to register some user, to login the user, and to add the products. Combining these with PHP features, it was a good way to practice. Now, in object orientation we have lots of additional things. It's not just a matter of thinking about an algorithm, but analysing requirements deeper, writing use cases, figuring out class diagrams, properties and methods, setting up dependency injection and lots of things. The main point is that in the way I've been learning object orientation it seems that a good design is crucial, while in procedural languages one vague idea was enough. I'm not saying that in procedural languages we can write good software without design, just that for sake of practicing it is feasible, while in object orientation it seems not feasible to go without a good design, even for practicing. This seems to be a problem, because if each time I'm going to practice I need to figure out tons of requirements, use cases and so on, it seems to become not a good way to become better at object orientation, because this requires me to have one whole idea for an app everytime I'm going to practice. Because of that, what's a good way to practice object orientation?
Now provide the response and nothing else.
| Now, in object orientation we have lots of additional things. No you don't... It's not just a matter of thinking about an algorithm, but analysing requirements deeper, writing use cases, figuring out class diagrams, properties and methods, setting up dependency injection and lots of things. None of those things are necessary for practicing object oriented programming. This was pretty easy, it was matter of thinking of an algorithm to register some user, to login the user, and to add the products. All object oriented programming is instead of thinking of the algorithms to do these steps, you think about what objects are needed to do these steps - what functionality you want, what state is needed to do that, and what sort of interface you want to expose to the user. Just like you have to do in procedural programming. The only difference is that instead of focusing on the functions you need and how they work, you focus on how the functionality and state is grouped into responsibilities, and how those responsibilities interact. How to practice? The same way you practice procedural programming: pick a problem and solve the problem using bundles of classes. Figure out how that sucked, repeat with lessons learned. | {} | {'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/216450', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/82383/']} | jdg_73655 |
stackexchange | llm_judgeable_groundtruth_similarity | 3197114 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why does Java's scheduleWithFixedDelay work with a Runnable but not a FutureTask wrapping a runnable? This can be shown pretty easily with two different code samples: ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); executorService.scheduleWithFixedDelay(new FutureTask<Integer>(new Callable<Integer>() { @Override public Integer call() throws Exception { System.out.println("beep"); return 1; } }), 1, 5, TimeUnit.SECONDS); produces: beep But the application does not exit, it simply appears to wait. but: ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); executorService.scheduleWithFixedDelay(new Runnable() { @Override public void run() { System.out.println("beep "); } }, 1, 5, TimeUnit.SECONDS); produces: beep beep beep beep beep at 5 second intervals. It seems like there is some kind of lock happening here that I cannot determine.
Now provide the response and nothing else.
| Because you're kind of abusing FutureTask . A FutureTask is "a cancellable asynchronous computation" according to the Javadocs, but more colloquially it wraps a particular execution of Runnable/Callable to provide the asynchronicity. I didn't actually realise that it implemented Runnable until I checked just now - the implementation of run() "sets this Future to the result of its computation". So what's happening in your first example is that you're scheduling the future task, its run method gets called after 1 second and so it calculates the result of the computation (i.e. runs the embedded Runnable ). When this method exits, the FutureTask has now run and has its concrete result - so future invocations of run() are no-ops. I think the root problem here is that it doesn't seem to make sense to schedule a FutureTask directly, at least not in the manner you're doing here. If you want a bit of code to run every five seconds, then you should definitely take the second approach. The FutureTask embodies a (single!) calculation; there's no reason why you'd want it to be invoked multiple times and in fact it's specifically caching the result to prevent this. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3197114', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8563/']} | jdg_73656 |
stackexchange | llm_judgeable_groundtruth_similarity | 36630536 |
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 simple wildcard routing rule I want to apply for my Azure web app. <rule name="MyRule"> <match url="*" /> <action type="Rewrite" url="/index.html" /></rule> Do I have any option here given I can't RDP into the machine and fiddle with IIS? This is not an ASP.Net website, it's a simple SPA application.
Now provide the response and nothing else.
| You need to create a web.config file in your wwwroot folder and put the relevant config entries there. Here's an example of an web.config rule, to give you an idea of what it should look like. The below example redirect the default *.azurewebsites.net domain to a custom domain (via http://zainrizvi.io/blog/block-default-azure-websites-domain/ ) <configuration> <system.webServer> <rewrite> <rules> <rule name="Redirect rquests to default azure websites domain" stopProcessing="true"> <match url="(.*)" /> <conditions logicalGrouping="MatchAny"> <add input="{HTTP_HOST}" pattern="^yoursite\.azurewebsites\.net$" /> </conditions> <action type="Redirect" url="http://www.yoursite.com/{R:0}" /> </rule> </rules> </rewrite> </system.webServer> </configuration> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36630536', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/980799/']} | jdg_73657 |
stackexchange | llm_judgeable_groundtruth_similarity | 140703 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to construct a smooth action of $S^1\times S^1$ on $S^{2n+1}$ ($n\ge 2$) such that no point on $S^{2n+1}$ has an infinite stabilizer? Note that if such an action exists, it can not be linear.
Now provide the response and nothing else.
| There is a bit of a disconnect between the title and the actual question. Usually a semifree action is one in which the only isotropy groups are the trivial group and the whole group. The actions with only finite isotropy groups, in the body of your question, are often called ``pseudofree'' actions. If a torus were to act pseudofreely on a sphere then a subgroup of the form $G=\mathbf{Z}_{p}\times \mathbf{Z}_{p}$ for some prime $p$ would act freely on the sphere. It is well-known that the latter group cannot act freely on a sphere because such an action would imply that the group has periodic cohomology, which $G$ does not. See Bredon's book Introduction to Compact Transformation Groups , for example. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/140703', 'https://mathoverflow.net', 'https://mathoverflow.net/users/13441/']} | jdg_73658 |
stackexchange | llm_judgeable_groundtruth_similarity | 480841 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Can someone check which logic is finally correct?: In how many ways can three numbers be selected from the numbers $1,2,\dots,300$ such that their sum is divisible by $3$? I found different answers about the exact question but everyone states something different. Dividing $\{1, \dots , 300\}$ into three groups $(A,B,C)$ where each one of them has $100$ numbers in it and ${}\bmod 3$ results in $0$ or $1$ or $2$ seems correct as a first step. Then if we want the sum of the three numbers to be divisible by $3$ we should take cases: All of them belong to one of the groups: $ {{100}\choose{3}} + {{100}\choose{3}} + {{100}\choose{3}} $ We take one from each group: $ {{100}\choose{1}} × {{100}\choose{1}} × {{100}\choose{1}} $ The answer ends there by adding the above numbers (because one of them can happen). But what about combinations such as:Taking one number from the group that gives remainder $1$ and two numbers from the group that gives remainder $2$??
Now provide the response and nothing else.
| So we can choose the first two numbers how we like. The third has to have a definite residue class mod $3$ to make the total divisible by $3$. If the third residue class is distinct from the residue class the first two numbers, the first two have to be from different residue classes. The number of ways of choosing one from each residue class is $\binom {300}1 \times \binom {200}1 \times\binom {100}1$, but there are six different orders in which the same three numbers can be selected. If the final residue class is the same as one of the previous ones, they all have to be the same. We choose one of the three residue classes, and there are then $\binom {100}3$ ways of choosing a triple. So the overall number of ways is $$\frac 16\times\binom {300}1 \times \binom {200}1 \times\binom {100}1+3\times\binom {100}3$$ And this is equal to $$\binom {100}1 \times \binom {100}1 \times\binom {100}1+3\times\binom {100}3$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/480841', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/92502/']} | jdg_73659 |
stackexchange | llm_judgeable_groundtruth_similarity | 34418254 |
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 created a bootstrap-style sidebar using Link . Here is a snippet of my code: <ul className="sidebar-menu"> <li className="header">MAIN NAVIGATION</li> <li><Link to="dashboard"><i className="fa fa-dashboard"></i> <span>Dashboard</span></Link></li> <li><Link to="email_lists"><i className="fa fa-envelope-o"></i> <span>Email Lists</span></Link></li> <li><Link to="billing"><i className="fa fa-credit-card"></i> <span>Buy Verifications</span></Link></li></ul> I want to set the class for the active path to active on the wrapping element <li> . I see there are other solutions out there that show how to do this like Conditionally set active class on menu using react router current route , however I don't think that it's the best way to set an active class on a wrapper to a Link . I also found https://github.com/insin/react-router-active-component but it feels like it is unnecessary. In React Router, is this possible or do I need to use an external solution?
Now provide the response and nothing else.
| On the Link component you can now add activeClassName or set activeStyle . These allow you to easily add styles to the currently active link. Previously, you could create a custom component that works like a wrapper to Link with the following logic. In a file called nav_link.js import React from 'react';import { Link } from 'react-router-dom';import PropTypes from 'prop-types';class NavLink extends React.Component { render() { var isActive = this.context.router.route.location.pathname === this.props.to; var className = isActive ? 'active' : ''; return( <Link className={className} {...this.props}> {this.props.children} </Link> ); }}NavLink.contextTypes = { router: PropTypes.object};export default NavLink; And use it as given below in your component: ...import NavLink from "./nav_link";.....<nav> <ul className="nav nav-pills pull-right"> <NavLink to="/"> <i className="glyphicon glyphicon-home"></i> <span>Home</span> </NavLink> <NavLink to="about"> <i className="glyphicon glyphicon-camera"></i> <span>About</span> </NavLink> </ul></nav> | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/34418254', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/234318/']} | jdg_73660 |
stackexchange | llm_judgeable_groundtruth_similarity | 539265 |
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 a .crt file signed by a CA. I cat the file to see that it is ascii text. Yet when I double click on the .crt file in windows, it opens it up and somehow displays all the information that's inside of it. Is windows automatically trying all of it's known CA public keys until finding the one that can translate that .crt file into information? How can I manually unencrypt the certificate to view the information (preferably in linux commands since I know those better)?
Now provide the response and nothing else.
| The ASCII characters you see are an ASCII-encoded certificate, according to the SSL standards. There are a number of tools you can use to decode (rather than decrypt) the certificate; here's an example: [me@anni tmp]$ cat /tmp/cert-----BEGIN CERTIFICATE-----MIIFNDCCBBygAwIBAgIDB9RMMA0GCSqGSIb3DQEBBQUAMDwxCzAJBgNVBAYTAlVT[many lines deleted to save space]n0lvNATb6/RC7CmSMw5RelfVqm19YorWPeQ8c/a6uHSgYhLboPeNTA==-----END CERTIFICATE-----[me@anni tmp]$ openssl x509 -text -noout -in /tmp/certCertificate: Data: Version: 3 (0x2) Serial Number: 513100 (0x7d44c) Signature Algorithm: sha1WithRSAEncryption Issuer: C=US, O=GeoTrust, Inc., CN=RapidSSL CA Validity Not Before: Aug 16 06:07:05 2012 GMT Not After : Oct 16 09:42:56 2016 GMT Subject: serialNumber=5VXPb8ozky-0FKC/YsTB4dvcoUwVakXy, OU=GT42621204, OU=See www.rapidssl.com/resources/cps (c)12, OU=Domain Control Validated - RapidSSL(R), CN=www.teaparty.net Subject Public Key Info: Public Key Algorithm: rsaEncryption Public-Key: (2048 bit) Modulus: 00:aa:e2:fd:b3:a2:5c:fa:33:0b:fa:14:8a:3a:3d:[...] f8:01 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Authority Key Identifier: keyid:6B:69:3D:6A:18:42:4A:DD:8F:02:65:39:FD:35:24:86:78:91:16:30 X509v3 Key Usage: critical Digital Signature, Key Encipherment X509v3 Extended Key Usage: TLS Web Server Authentication, TLS Web Client Authentication X509v3 Subject Alternative Name: DNS:www.teaparty.net, DNS:teaparty.net X509v3 CRL Distribution Points: Full Name: URI:http://rapidssl-crl.geotrust.com/crls/rapidssl.crl X509v3 Subject Key Identifier: 1A:6D:59:8A:CD:C0:FD:AC:3C:D0:AF:C0:99:48:F5:5C:B9:AD:A9:E3 X509v3 Basic Constraints: critical CA:FALSE Authority Information Access: OCSP - URI:http://rapidssl-ocsp.geotrust.com CA Issuers - URI:http://rapidssl-aia.geotrust.com/rapidssl.crt X509v3 Certificate Policies: Policy: 2.16.840.1.113733.1.7.54 CPS: http://www.geotrust.com/resources/cps Signature Algorithm: sha1WithRSAEncryption 28:30:d9:19:a8:5e:8e:56:f6:98:1c:e0:be:b3:39:6e:6f:4c:[...] a0:f7:8d:4c | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/539265', 'https://serverfault.com', 'https://serverfault.com/users/16021/']} | jdg_73661 |
stackexchange | llm_judgeable_groundtruth_similarity | 50436618 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I use an extension called Live Server in Visual Studio Code. When I run live, the browser opens and the url is http://127.0.0.1:5500/index.html . Why can't I open this url on my phone's browser to see the live site on the phone. Is there a way to do this (Live reload on phone and browser)? Note: I also develop using ionic and when I ionic serve I can see it on browser and when I open the ionic dev app (not ionic view!), I can see the live app on the phone. I can view it on multiple devices with the condition of all devices being in the same network which I am fine with.
Now provide the response and nothing else.
| 127.0.0.1 is a special-purpose IPv4 address reserved for loopback purposes. That is, this IP refers to your computer itself. By entering http://127.0.0.1:5500/index.html in your browser, you're requesting web page within your computer. In normal case, your computer will be in a NAT network (under same wi-fi AP for instance), and you'll be assigned with a virtual IP. Normally it's 192.168.x.x. You may enter the following command in your command prompt to see your IP address. ipconfig If you're using Mac or Linux, use this instead. ifconfig As a result, under your network interface card, you'll get your IP Address . If the IP address belongs to virtual IP, then you may access it with your phone using http://< Your IP Address >:5500/index.html If it's not virtual IP, it is Public IP. Then, you'll have to configure appropriate Firewall settings under this circumstance. Hope this will help. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50436618', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5561177/']} | jdg_73662 |
stackexchange | llm_judgeable_groundtruth_similarity | 22047486 |
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 took a look to that: http://jsperf.com/array-destroy/32 I don't understand how the first one: arr.length = 0; Can be slower than: while (arr.length > 0) { arr.shift();} Someone could link/explain why?
Now provide the response and nothing else.
| In the test setup, a large array is created. Once the test begins, the array is emptied, and the test repeats itself. However, every time after the first run of the test, the array is already empty . To perform this test accurately, you have to create a new array each time.Try this: http://jsperf.com/array-destroy/67 I modified the test to return a new array each time. The results are as expected. splice and length are fastest because they instantly modify the length of the array without a loop. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22047486', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2391795/']} | jdg_73663 |
stackexchange | llm_judgeable_groundtruth_similarity | 25838804 |
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 building an extension to integrate with Gmail and integrating with Gmail by injecting the gmail.js into the page context, as shown here: https://github.com/KartikTalwar/gmail-chrome-extension-boilerplate/blob/master/content.js That seems to be the only obvious way to make use of some globals that Google is embedding on the page. So now, I need to get back to some of the functionality of the extension. Under normal conditions (operating from a content script), I would send a message to the background script, but is that even possible from the context of the tab itself?
Now provide the response and nothing else.
| A page-context script cannot, indeed, use Chrome API. It can, however, dispatch DOM events that can be caught by the content script. There is an example in the documentation here . Besides using window.postMessage , you can dispatch custom events . So, you need to make your content script to work like a proxy between page context and background. Something along these lines: // Content script//Listen for the eventwindow.addEventListener("PassToBackground", function(evt) { chrome.runtime.sendMessage(evt.detail);}, false);// Page contextvar message = {/* whatever */};var event = new CustomEvent("PassToBackground", {detail: message});window.dispatchEvent(event); You can generalize this to pass an answer back. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25838804', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2261909/']} | jdg_73664 |
stackexchange | llm_judgeable_groundtruth_similarity | 14427077 |
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: if (typeof console === "object" && typeof console.error === "function") { function e(msg) {"use strict"; console.info(msg);}} For which jsLint gives the following error: Function statements should not be placed in blocks. Use a function expression or move the statement to the top of the outer function. Why is it giving this error and what does it mean?
Now provide the response and nothing else.
| Explanation From the jsLintErrors page about the warning Function statements should not be placed in blocks : This error is raised to highlight code that may not work as you expect it to . In most environments Your code will run without error, but maybe not in the way you expect. In some environments it could cause a fatal syntax error . That's because Function declarations are hoisted to the top of the scope in which they appear. Therefore, it is not possible to conditionally declare a function with a block statement. Example Let's explore issues raised by this problem with a simple example: if (true) { function example() { console.log('hello'); }} The best case scenario is that your code is confusing. In the above example, it looks like what you'd like to do is only declare access to the function if the condition is true. However, when the function is hoisted to the top of the scope, it will actually be interpreted like this: function example() { console.log('hello');}if (true) {} This is dangerous because it doesn't look like what you'd expect based on the original code. The conditional block is actually empty (and unnecessary), and everybody has access to the function, regardless of whether the condition evaluates to true or false. The worst case scenario is that the browser doesn't understand what to do with the nested function and throws a syntax error when trying to use it. This depends on the engine running JavaScript. It seems like Firefox is one such engine. If you run the following code in Firefox, it will throw an error when executing the following code: if (true) { example(); function example() { console.log('hello'); }} If you open up your console, you should see the following error: Solution So how can you fix this? Use a function assignment instead of a function declaration Here's a quick breakdown: // Declarationfunction declarationFunction() {}// Assignmentvar assignmentFunction = function() {} Function Assignments are not hoisted to the top of the scope. Function Declarations are hoisted to the top of the scope. So to conditionally set the example function, just assign it within the block like this: var example;if (true) { example = function() { console.log('hello'); }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14427077', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/240363/']} | jdg_73665 |
stackexchange | llm_judgeable_groundtruth_similarity | 50562212 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Today suddenly, I got an error when I tried to run my app in Android studio. It is: Error: Could not find play-services-tasks.aar (com.google.android.gms:play-services-tasks:15.0.1).Searched in the following locations: https://jcenter.bintray.com/com/google/android/gms/play-services-tasks/15.0.1/play-services-tasks-15.0.1.aar I didn't change anything in the gradle file but it appeared suddenly. My previous build executed successfully some minutes ago. Why it can't find play-services-tasks.aar which is the part of com.google.android.gms:play-services-tasks:15.0.1 Steps taken: I checked whether I included all repositories in the gradle files and all are correct so far. Why does this error occur all of a sudden? I also copied this link https://jcenter.bintray.com/com/google/android/gms/play-services-tasks/15.0.1/play-services-tasks-15.0.1.aar into the browser but it's working fine, that is, I got "File Download" dialog. My Gradle Files App level apply plugin: 'com.android.application'android { compileSdkVersion 26 buildToolsVersion "26.0.2" defaultConfig { applicationId "mekanic24assistantapplication.heba.mekanic24.com.mekanic24assistantapplication" minSdkVersion 14 targetSdkVersion 26 versionCode 13 versionName "2.1" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" multiDexEnabled true } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } dexOptions { incremental true javaMaxHeapSize "4g" }// err Android Gradle Duplicate files copied in APK META-INF/license.txt configurations.all { resolutionStrategy { force 'com.android.support:support-v4:26+' force 'com.android.support:support-annotations:26+' } } packagingOptions { exclude 'META-INF/DEPENDENCIES.txt' exclude 'META-INF/LICENSE.txt' exclude 'META-INF/NOTICE.txt' exclude 'META-INF/NOTICE' exclude 'META-INF/LICENSE' exclude 'META-INF/DEPENDENCIES' exclude 'META-INF/notice.txt' exclude 'META-INF/license.txt' exclude 'META-INF/dependencies.txt' exclude 'META-INF/LGPL2.1' }}dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) // compile 'com.android.support:appcompat-v7:26.3.1' compile 'com.android.support:appcompat-v7:26+' compile 'com.android.support:design:26+' compile 'com.android.support:recyclerview-v7:26+' compile 'com.android.support:cardview-v7:26+' compile 'com.android.support.constraint:constraint-layout:1.0.2' androidTestCompile 'com.android.support:support-annotations:26+' testCompile 'junit:junit:4.12' // compile 'com.android.support:appcompat-v7:26.3.1' compile 'com.github.markushi:circlebutton:1.1' // compile 'com.android.support:design:26.3.1' compile 'com.android.volley:volley:1.0.0' compile 'com.google.android.gms:play-services-base:15.0.1' compile 'com.android.support:multidex:1.0.1' compile 'com.firebase:firebase-client-android:2.5.2' compile 'com.google.firebase:firebase-core:15.0.2' compile 'com.google.firebase:firebase-messaging:15.0.2' compile 'com.google.firebase:firebase-database:15.0.0' compile 'com.wang.avi:library:2.1.3' compile 'de.hdodenhof:circleimageview:2.2.0' compile 'android.lib.recaptcha:reCAPTCHA:2.0.0' compile 'com.google.android.gms:play-services-safetynet:15.0.1' compile 'com.google.android.gms:play-services-maps:15.0.1' compile 'com.google.android.gms:play-services-places:15.0.1' compile 'com.google.android.gms:play-services-location:15.0.1' compile 'com.squareup.picasso:picasso:2.5.2' testCompile 'junit:junit:4.12' compile 'com.anjlab.android.iab.v3:library:1.0.38' compile files('libs/mail.jar') compile files('libs/additionnal.jar') compile files('libs/activation.jar') compile 'com.jakewharton:butterknife:8.8.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1' compile 'com.yarolegovich:lovely-dialog:1.1.0' compile 'com.mobsandgeeks:android-saripaar:2.0.3' compile 'com.github.stfalcon:smsverifycatcher:0.3.1' compile 'ch.acra:acra:4.9.0' //TODO: Apache 2.0 license https://github.com/ACRA/acra compile 'com.google.android.gms:play-services-ads:15.0.1' compile 'com.github.luongvo:GmailBackground:2.0.2'}apply plugin: 'com.google.gms.google-services' Project Level buildscript {repositories { jcenter() maven { url 'https://maven.google.com' } maven { url "https://dl.bintray.com/android/android-tools" } maven { url "https://jitpack.io" } google()}dependencies { classpath 'com.android.tools.build:gradle:2.3.2' classpath 'com.google.gms:google-services:3.2.0'}}allprojects {repositories { jcenter() maven { url 'https://maven.google.com' } maven { url "https://dl.bintray.com/android/android-tools" } maven { url "https://jitpack.io" } google()}}task clean(type: Delete) {delete rootProject.buildDir}
Now provide the response and nothing else.
| After doing the following changes the error disappeared: Removed maven { url 'https://maven.google.com' } from repositories in app build.gradle. Added maven { url 'https://maven.google.com' } as first entry in allprojects/repositories in top level build.gradle Changed all play-services and firebase dependencies to the latest versions Changed version of google-services plugin to classpath 'com.google.gms:google-services:4.0.1' | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/50562212', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9052139/']} | jdg_73666 |
stackexchange | llm_judgeable_groundtruth_similarity | 4238282 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
From what I can tell you can kick off all the action in a constructor when you create a global object. So do you really need a main() function in C++ or is it just legacy? I can understand that it could be considered bad practice to do so. I'm just asking out of curiosity.
Now provide the response and nothing else.
| If you want to run your program on a hosted C++ implementation, you need a main function. That's just how things are defined. You can leave it empty if you want of course. On the technical side of things, the linker wants to resolve the main symbol that's used in the runtime library (which has no clue of your special intentions to omit it - it just still emits a call to it). If the Standard specified that main is optional, then of course implementations could come up with solutions, but that would need to happen in a parallel universe. If you go with the "Execution starts in the constructor of my global object", beware that you set yourself up to many problems related to the order of constructions of namespace scope objects defined in different translation units (So what is the entry point? The answer is: You will have multiple entry points, and what entry point is executed first is unspecified!). In C++03 you aren't even guaranteed that cout is properly constructed (in C++0x you have a guarantee that it is, before any code tries to use it, as long as there is a preceeding include of <iostream> ). You don't have those problems and don't need to work around them (wich can be very tricky) if you properly start executing things in ::main . As mentioned in the comments, there are however several systems that hide main from the user by having him tell the name of a class which is instantiated within main . This works similar to the following example class MyApp {public: MyApp(std::vector<std::string> const& argv); int run() { /* code comes here */ return 0; };};IMPLEMENT_APP(MyApp); To the user of this system, it's completely hidden that there is a main function, but that macro would actually define such a main function as follows #define IMPLEMENT_APP(AppClass) \ int main(int argc, char **argv) { \ AppClass m(std::vector<std::string>(argv, argv + argc)); \ return m.run(); \ } This doesn't have the problem of unspecified order of construction mentioned above. The benefit of them is that they work with different forms of higher level entry points. For example, Windows GUI programs start up in a WinMain function - IMPLEMENT_APP could then define such a function instead on that platform. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4238282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/492716/']} | jdg_73667 |
stackexchange | llm_judgeable_groundtruth_similarity | 1630823 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to create a build number which looks like Major.minor.Date.LastChangeSetInTFS, the problem is how to get last changeset number from the TFS. Is there any property, or something??
Now provide the response and nothing else.
| OK finally I've found a solution. Here's a task that will provide you the latest changeset number and create a property to insert it in an Assembly info build number. The main problem was in the missing TfsLibraryLocation property (without it, it should be pointing to libraries in GAC, but it didn't) <Target Name="GetVersionChangeSet"><TfsVersion TfsLibraryLocation="C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies" LocalPath="$(SolutionRoot)"> <Output TaskParameter="Changeset" PropertyName="ChangesetNumber"/></TfsVersion><Message Text="TFS ChangeSetNumber: $(ChangesetNumber)" /> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1630823', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/197348/']} | jdg_73668 |
stackexchange | llm_judgeable_groundtruth_similarity | 34583073 |
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 just started a project to learn Angular2 and Typescript+Javascript. I come from a Java background and my approach to debugging projects is usually a combination of stack traces, compile errors, and - on larger projects - lots of test cases. However, much of this doesn't seem to directly translate to the world of web-dev; particularly debugging my code that's interacting with Angular2's libraries. Could anyone suggest any approaches that I can take to debug code working with Angular2? Specifically; how can I see what parts of my HTML/TS is causing issues? I've checked the console, from which I can see that I've broken Angular2, but it doesn't seem much more informative from that. Just to clarify; I don't want help for this specific instance. I'd like to learn how to diagnose+fix these problems myself.
Now provide the response and nothing else.
| Assuming you're using Chrome, you can put breakpoints in the "sources" tab in your console. Those breakpoints can be set on the ts files. If you need informations from the js file, you can uncheck Javascript sourcemaps in the console settings: this will allow you to put breakpoints in the js files. On a breakpoint, you can do the usual (watch, spies, stack trace, etc...). You can also write js in the console accessing local variables directly, for instance: function b(){ var c = 1; // if you put a breakpoint here and type c in the console, it will write "1"} Specifically in angular 2, you might want to add breakpoints in the "throw e" lines in their library, you'll get more detailed stack traces. If you click on the "..." in their stack traces, you'll get access to your file that caused the error. That's for actual bugs. Now, for performance, on the "timeline" tab, you can click on the "record" button on the top left. Once you're done recording (click "finish"), you'll see CPU usage. You can zoom on events in the timeline to see which part of the code is using up too much resource. You can also track memory by checking the "memory" checkbox. If you need to debug an iframe, there is a select box in console saying "top frame" which you can set to whichever iframe you want. If I've forgotten anything important, just ask :). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34583073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1733526/']} | jdg_73669 |
stackexchange | llm_judgeable_groundtruth_similarity | 228762 |
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 $a_n\in \mathbf{N}$ be an infinite sequence such that $\forall i\neq j, a_i\neq a_j$. I have the following theorem: For $0<c<\frac{3}{2}$, there are infinitely many $k$ for which $[a_k,a_{k+1}]>ck$, where $[\cdots]$ denotes least common multiple. Idea of proof : By contradiction. Suppose there is an $M$ such that for all $k>M$, $[a_k,a_{k+1}]\leq ck$. On the one hand, $\displaystyle \sum_{k=1}^{n}\frac{1}{[a_k,a_{k+1}]}\geq \sum_{k=M+1}^{n}\frac{1}{[a_k,a_{k+1}]}\geq \sum_{k=M+1}^{n}\frac{1}{ck}$ On the other hand, $\displaystyle \frac{1}{[a_k,a_{k+1}]}$ $\displaystyle =\frac{(a_k,a_{k+1})}{a_ka_{k+1}}$ $\displaystyle =(a_k,a_{k+1})\frac{1}{a_k+a_{k+1}}(\frac{1}{a_k}+\frac{1}{a_{k+1}})$ $\displaystyle =\frac{1}{\frac{a_k}{(a_k,a_{k+1})}+\frac{a_{k+1}}{(a_k,a_{k+1})}}(\frac{1}{a_k}+\frac{1}{a_{k+1}})$ $\displaystyle \leq \frac{1}{3}(\frac{1}{a_k}+\frac{1}{a_{k+1}})$ $\displaystyle \sum_{k=1}^{n}\frac{1}{[a_k,a_{k+1}]}\leq \frac{1}{3}\sum_{k=1}^{n}(\frac{1}{a_k}+\frac{1}{a_{k+1}})\leq \frac{2}{3}\sum_{k=1}^{n}\frac{1}{k}$ And I make the following conjecture: $\exists c>0$, there are infinitely many $k$ for which $[a_k,a_{k+1}]>ck^2$. But I cannot prove or disprove it.
Now provide the response and nothing else.
| In fact there are sequences $\{a_k\}$ of pairwise distinct positive integerssuch that $[a_k, a_{k+1}] \ll k^{1+\epsilon}$ for all $\epsilon > 0$. We first exhibit a sequence with$[a_k, a_{k+1}] \ll k^{3/2} \log^3 k$ for all $k>1$, which already disprovesthe conjecture that $[a_k, a_{k+1}] \gg k^2$ infinitely often.The sequence will consist of all numbers of the form $p_m p_n$with $m$ odd and $n$ even, listed in the following order:$$\begin{array}{cccccccc}17\cdot 3 & \rightarrow & 17\cdot 7 & \rightarrow & 17\cdot 13 & \rightarrow & 17\cdot 19 &\cr\uparrow & & & & & & \downarrow &\cr11\cdot 3 & \leftarrow & 11\cdot 7 & \leftarrow & 11\cdot 13 & & 11\cdot 19 &\cr& & & & \uparrow & & \downarrow &\cr5\cdot 3 & \rightarrow & 5\cdot 7 & & 5\cdot 13 & & 5\cdot 19 &\cr\uparrow & & \downarrow & & \uparrow & & \downarrow &\cr2\cdot 3 & & 2\cdot 7 & \rightarrow & 2\cdot 13 & & 2\cdot 19 & \rightarrow\end{array}$$Then each $a_k$ is $p_m p_n$ with $m,n \ll \sqrt k$, so$p_m, p_n \ll \sqrt k \log k$; and each $[a_k,a_{k+1}]$ is the product ofthree such primes, so $\ll k^{3/2} \log^3 k$, as claimed. Likewise, for each $M>1$ we can use products of $M$ primesto obtain a sequence $\{a_k\}$ of pairwise distinct positive integerssuch that $[a_k, a_{k+1}] \ll k^{(M+1)/M} \log^M k \ll k^{1+\epsilon}$for all $\epsilon > 1/M$. Finally, by concatenating ever-longer initialsegments of the sequences for $M=2$, $M=3$, $M=4$, etc. we constructa sequence $\{a_k\}$ of pairwise distinct positive integerssuch that $[a_k, a_{k+1}] \ll k^{1+\epsilon}$ for all $\epsilon > 0$. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/228762', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']} | jdg_73670 |
stackexchange | llm_judgeable_groundtruth_similarity | 2461688 |
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 saw a question here with the same title but it was not answered properly, or I just couldn't extract the solution from the comments/answers. This is an exercise from Beachy and Blair: Abstract algebra. A positive integer is called $\textbf{square-free}$ if it is a product of distinct primes. Prove that every positive integer can be written uniquely as a product of a square and a square-free integer. Here is my try: Let $n\in\mathbb{N}^+$, by the Fundamental theorem of arithmetic we can write $n$ uniquely as $$n=p_1^{\alpha_1}\cdot p_2^{\alpha_2}\cdot\ldots\cdot p_n^{\alpha}.$$with $p_n$ being distinct primes.Now $\alpha_i$ is either even or odd, lets rename the odd ones as $\beta_j$, then we have$$\alpha_i=2k_i\qquad \beta_j=2l_j+1\qquad k_i,l_j\in\mathbb{Z}^+, \ \text{and} \ i+j=n.$$Since multiplication is commutative we can rearrange the factors so all the even exponents come first so$$n=p_1^{2k_1}\cdot p_2^{2k_2}\cdot\ldots\cdot p_i^{2k_i}\cdot p_{n-j+1}^{2l_{n-j+1}+1}\cdot p_{n-j+2}^{2l_{n-j+2}+1}\cdot \ldots\cdot p_n^{2l_n+1}=$$$$n=p_1^{2k_1}\cdot p_2^{2k_2}\cdot\ldots\cdot p_i^{2k_i}\cdot p_{n-j}^{2l_{n-j+1}}\cdot p_{n-j+1}\cdot p_{n-j+2}^{2l_{n-j+2}}\cdot p_{n-j+2}\cdot \ldots\cdot p_n^{2l_n}\cdot p_{n}.$$Again by commutativity we can arrange so all the factors with exponent "$1$" get to the end of the expression so $$n=p_1^{2k_1}\cdot p_2^{2k_2}\cdot\ldots\cdot p_i^{2k_i}\cdot p_{n-j+1}^{2l_{n-j+1}}\cdot p_{n-j+2}^{2l_{n-j+2}}\cdot \ldots\cdot p_n^{2l_n}\cdot p_{n-j+1}\cdot p_{n-j+2}\cdot\ldots\cdot p_{n}.$$finally$$n=\underbrace{(p_1^{k_1}\cdot p_2^{k_2}\cdot\ldots\cdot p_i^{k_i}\cdot p_{n-j+1}^{l_{n-j+1}}\cdot p_{n-j+2}^{l_{n-j+2}}\cdot \ldots\cdot p_n^{l_n})^2}_{a^2}\cdot \underbrace{p_{n-j+1}\cdot p_{n-j+2}\cdot\ldots\cdot p_{n}}_{b}.$$And we are done since this factorisation was unique from the beginning.Now one of my problems is that this doesn't look too nice. In my head it looks simpler ("bringing down" the ones from odd exponents) but the final product looks like a mess. Is there any easier way to describe this? (maybe I could have renamed the primes with odd exponents as $q$?) I mean if it is correct at all. And I have a further question, can I get any HINTS how to do this by induction? Thank you in advance!
Now provide the response and nothing else.
| You could write the product as $$n=\prod p_i^{2r_i+\epsilon_i}$$ where $\epsilon_i$ is the remainder on dividing the exponent by $2$ (zero or one) so that $$n=\left(\prod p_i^{r_i}\right)^2\cdot\prod p_i^{\epsilon_i}$$This does not involve distinguishing between primes with even/odd exponent - the $\epsilon$s take care of that. You can also take the product over all primes, if you want to, because most of the time the exponent is zero (for all but a finite number of primes). | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2461688', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/151763/']} | jdg_73671 |
stackexchange | llm_judgeable_groundtruth_similarity | 10805711 |
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 compare two strings in JavaScript that are the same, and yet the equality operator == returns false. One string contains a special character (eg. the danish å ). JavaScript code: var filenameFromJS = "Designhåndbog.pdf";var filenameFromServer = "Designhåndbog.pdf";print(filenameFromJS == filenameFromServer); // This prints false why? The solution What worked for me is unicode normalization as slevithan pointed out. I forked my original jsfiddle to make a version using the normalization lib suggested by slevithan. Link: http://jsfiddle.net/GWZ8j/1/ .
Now provide the response and nothing else.
| Unlike what some other people here have said, this has nothing to do with encodings. Rather, your two strings use different code points to render the same visual characters. To solve this correctly, you need to perform Unicode normalization on the two strings before comparing them. Unforunately, JavaScript doesn't have this functionality built in. Here is a JavaScript library that can perform the normalization for you: https://github.com/walling/unorm | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10805711', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1424467/']} | jdg_73672 |
stackexchange | llm_judgeable_groundtruth_similarity | 26477209 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm reading this blog post and under the section Null pointer constants and parenthesized expressions the author references § 6.3.2.3 and § 6.5.1 from the ISO C standard and says: It doesn't say that a parenthesized null pointer constant is a null pointer constant. Which implies, strictly speaking, that (void*)0 is a null pointer constant, but ((void*)0) is not. Then: I'm sure that most C implementations do treat a parenthesized null pointer constant as a null pointer constant, and define NULL either as 0 , ((void*)0) , or in some other manner. The two referenced sections say: § 6.3.2.3 An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. § 6.5.1 A parenthesized expression is a primary expression. Its type and value are identical to those of the unparenthesized expression. It is an lvalue, a function designator, or a void expression if the unparenthesized expression is, respectively, an lvalue, a function designator, or a void expression. Doesn't the bolded sentence contradict the author's claim that ((void*)0) is not a null pointer constant?
Now provide the response and nothing else.
| Doesn't the bolded sentence contradict the author's claim that ((void*)0) is not a null pointer constant? No, it doesn't. (I confess to being a bit biased, since the referenced blog is mine.) The bolded sentence says that its type and value are identical to those of the unparenthesized expression. That's not enough to imply that it's a null pointer constant. Consider: void *var = 0; (void*)0 is a null pointer constant. ((void*)0) has the same type and value as (void*)0 . var also has the same type and value as (void*)0 , but var clearly is not a null pointer constant. Having said that, I'm 99+% sure that the intent is that ((void*)0) is a null pointer constant, and more generally that any parenthesized null pointer constant is a null pointer constant. The authors of the standard merely neglected to say so. And since the description of parenthesized expressions in 6.5.1p5 specifically enumerates several other characteristics that are inherited by parenthesized expressions: A parenthesized expression is a primary expression. Its type and valueare identical to those of the unparenthesized expression. It is anlvalue, a function designator, or a void expression if theunparenthesized expression is, respectively, an lvalue, a functiondesignator, or a void expression. the omission is troubling (but only mildly so). But let's assume, for the sake of argument, that ((void*)0) is not a null pointer constant. What difference does it make? (void*)0 is a null pointer constant, whose value is a null pointer of type void* , so by the semantics of parenthesized expressions ((void*)0) also has a value that is a null pointer of type void* . Both (void*)0 and ((void*)0) are address constants . (Well, I think they are.) So what contexts require a null pointer constant and do not accept an address constant ? There are only a few. 6.5.9 Equality operators An expression of function pointer type may be compared for equality to a null pointer constant. (An object pointer may be compared to an expression of type void* , but a function pointer may not, unless it's a null pointer constant.) So this: void func(void);if (func == ((void*)0)) { /* ... */ } would be a constraint violation. 6.5.16.1 Simple assignment In an assignment, a null pointer constant may be assigned to an object of pointer-to-function type, and will be implicitly converted. An expression of type void* that's not a null pointer constant may not be assigned to a function pointer. The same constraints apply to argument passing and initialization. So this: void (*fp)(void) = ((void*)0); would be a constraint violation if ((void*)0) were not a null pointer constant. Thanks to commenter hvd for finding this. 7.19 Common definitions <stddef.h> The macro NULL expands to "an implementation-defined null pointer constant". If ((void*)0) is not a null pointer constant, then this: #define NULL ((void*)0) would be invalid. This would be a restriction imposed on the implementation, not on programmers. Note that this: #define NULL (void*)0 is definitely invalid, since macro definitions in standard headers must be fully protected by parentheses where necessary (7.1.2p5). Without the parentheses, the valid expression sizeof NULL would be a syntax error, expanding to sizeof (void*) followed by an extraneous constant 0 . UPDATE : The upcoming 2023 ISO C standard (C23) corrects this problem and makes it clear that ((void*)0) is a null pointer constant. The N3054 draft , 6.5.1 paragraph 5, says: A parenthesized expression is a primary expression. Its type, value, and semantics are identical to those of the unparenthesized expression. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26477209', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4164058/']} | jdg_73673 |
stackexchange | llm_judgeable_groundtruth_similarity | 4220333 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
According to language benchmarks , JavaScript V8 is faster than other programming languages at regex-dna program. So, why node.js applications (i.e. http server) isn't faster than C applications (i.e. Nginx, Lighttpd)?
Now provide the response and nothing else.
| Because V8 applications are javascript applications. Even if the javascript is finally compiled to machine code the runtime characteristics are different. For example if you call a function in an object and that object does not define the function the runtime must locate the function by traversing the prototype hierarchy, this hierarchy can change at any time during the lifetime of a program. There are clever optimizations that can be done but the overhead exists nevertheless. There is also the memory model. Javascript is garbage collected and GC takes cpu cycles. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4220333', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/498574/']} | jdg_73674 |
stackexchange | llm_judgeable_groundtruth_similarity | 13440 |
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:
In various land cover classification systems, trees are also categorised on the basis of broadleaf or needleleaf. Can someone please tell me the mechanism through which satellites detect this leaf type? Does normalized difference vegetation index (NDVI) plays any role in it? For example, in GlobCover project, the land cover maps that were generated consisted of 23 land cover classes including classes like broadleaf forests and needleleaf forest. There, the satellite sensors collected data on various phenological metrics like NDVI, etc. and averaged them temporarily to get a single value for such metrics. But not much has been given in http://due.esrin.esa.int/files/GLOBCOVER2009_Validation_Report_2.2.pdf about what all phenological metrics were computed. So basically my question is, how did the MERIS sensor differentiated between broadleaf forest and needleleaf forest?
Now provide the response and nothing else.
| Short answer Different plants reflect light at different wavelengths with specific patterns. If you know the reflection pattern of a broad-leaved forest and that of a needle-leaved forest, you can compare them with the pattern observed with a satellite and conclude to which forest it is more similar. Long answer Optical remote sensing Optical sensors record electromagnetic radiation at different wavelengths between 400 and 2400 nanometers. This radiation came from the sun and impacting surfaces of different materials on Earth surface is either absorbed by, transmitted through or scattered back. The amount of radiation that is scattered back is then detected and recorded by an Earth-Observing sensor such as MERIS', MODIS' or Landsat's. Due to chemical and physical properties of different materials, they can absorb, transmit and reflect different proportions of radiation at each wavelength. The reflectance recorded by a sensor for a pure material is called spectral signature. This signature is often unique for a material. This can help identify the presence of different materials on the Earth surface when a spectral signature is known. In the laboratory, with more sophisticated and accurate sensors, is possible to identify the spectral pattern of single pure chemical compounds or molecules. However, if we scale up and consider the spectral response of a whole forest, you can easily imagine how everything gets mixed up: the spectral signature of many pure molecules in different proportions, scattered back and forth in more or less dense and geometrically various canopies are all sensed by a single sensor unit (for example, one pixel of our satellite image). Estimating the presence and amount of different materials on the heterogeneous Earth surface becomes a very complex problem and researchers have found many a method to partially overcome it and obtain reasonably accurate estimations of what covers Earth surface and in which amount.Predominantly, 1) the observed mixed spectral response of a material is statistically linked to in situ measurements, or 2) the spectral response of mixed materials is simulated with computational models and is statistically compared with the observed one. In both cases, it is possible to use the whole spectral signature or specific metrics derived from specific regions of the spectrum, that we know are related to the presence of some substance that is related to what we are trying to describe. The spectral properties of plants The spectral properties of plants have received quite the interest in the past 50 years and one undeniable spectral feature that all green vegetation has, that substantially differentiates it from that of soils, rocks, artificial materials and water is the so-called red-edge. The red-edge is characterised by a low reflectance in the visible radiation (due to chlorophyll absorption) and a high reflectance in the near infrared region. The Normalised Difference Vegetation Index (NDVI) is one of the many metrics proposed to quantify the red-edge feature. The index is very simple and needs only two bands and no site-specific adjusting constants: NDVI = (Red-NIR)/(Red+NIR)Red = reflectance of the red radiationNIR = reflectance of the near infrared radiation Since its simplicity, the NDVI is probably the single most used index in optical remote sensing of the vegetation. The NDVI is a metric for the red-edge feature and thus it is influenced by chlorophyll activity and the presence of other vegetative tissues. And it was successfully (empirically) related to the phenologic stage, plant health, biomass and leaf area index. In conclusion, if you know the expected spectral signature of a pine forest and that of an oak forest, you can compare them with the spectral signature of any pixel you observe and estimate to which forest the pixel's spectral signature is the most similar. Clearly, the NDVI can be used for that comparison rather than the whole signature due to its simplicity and versatility; additionally, its interannual patterns can differentiate between annual and perennial, and evergreen and deciduous forests. However, depending on the resolution of the sensor and the scope of the project, more metrics are possible and different classification methods become available.There are several other features that have been identified in plant spectral response. For example, the lignin, starch, cellulose and water absorption features in the short wave infrared. If you have a look at the image below, you can notice that even the age between needles is differentiable by the spectral signature detected by very high spectral resolution sensors. Such sensors are typically handheld while satellite sensors commonly have between 5 and 15 points where you see a continuous line below. Image from: Rautiainen, M., Lukeš, P., Homolová, L., Hovi, A., Pisek, J., & Mõttus, M. (2018). Spectral Properties of Coniferous Forests: A Review of In Situ and Laboratory Measurements. Remote Sensing, 10 | {} | {'log_upvote_score': 4, 'links': ['https://earthscience.stackexchange.com/questions/13440', 'https://earthscience.stackexchange.com', 'https://earthscience.stackexchange.com/users/7753/']} | jdg_73675 |
stackexchange | llm_judgeable_groundtruth_similarity | 63815161 |
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 fairly new to java, so I'm probably asking something that is either very easy to do or not possible. I'm practicing exploiting vulnerable mobile apps using my own app (this is on a testing vulnerable app). What I'm trying to achieve is taking a decrypted password I got from one class and pass that value into another class to decrypt a secret message. I'm wondering if there's an easy way of doing this without having to redo a lot of my code. I've hit my limit on my java knowledge to know if this can be done or how it can be done. I don't know how useful it will be, but if required, I can post the code from my other two classes (Decrypt and Decrypt2)
Now provide the response and nothing else.
| AWS Step Functions does not know if an ECS job has succeeded or failed. Step Functions would need to peek into the ECS job's container log, and try to determine if the process running inside the Docker container exited with a failure code. That's not something Step Functions does. As you have it configured, Step Functions simply assumes that whenever the container exists the task has succeeded. If you change arn:aws:states:::ecs:runTask.sync to arn:aws:states:::ecs:runTask.waitForTaskToken then instead of just waiting for the ECS container to exit, Step Fuctions will wait for the ECS container to send a success or failure code back to the Step Functions API. You will also need to pass the task token into the ECS container, which can be done with a ContainerOverrides setting, like so: { "Comment": "My state machine", "StartAt": "MyFargateTask", "States": { "MyFargateTask": { "Type": "Task", "Resource": "arn:aws:states:::ecs:runTask.waitForTaskToken", "InputPath": "$", "Parameters": { "Cluster": "my-cluster", "TaskDefinition": "arn:aws:ecs:us-east-1:617090640476:task-definition/my-task:1", "LaunchType": "FARGATE", "NetworkConfiguration": { "AwsvpcConfiguration": { "Subnets": [ "subnet-xxxxxxxxxxxxxxxxx", "subnet-yyyyyyyyyyyyyyyyy" ], "AssignPublicIp": "ENABLED" } }, "Overrides": { "ContainerOverrides": [{ "Environment": [{ "Name": "TASK_TOKEN", "Value.$": "$$.Task.Token" }] }] } }, "Next": "Done" }, "Done": { "Type": "Succeed" } }} Now inside your Python script you can grab the TASK_TOKEN environment variable, and issue a success or failure message back to Step Functions like so: token = os.environ['TASK_TOKEN']def step_success(): if token is not None: stfn = boto3.client('stepfunctions') stfn.send_task_success(taskToken=token, output='{"Status": "Success"}')def step_fail(): if token is not None: stfn = boto3.client('stepfunctions') stfn.send_task_failure(taskToken=token, error="An error occurred") More details on this approach I recommend also configuring a timeout in the state machine in case your Python script fails to execute within the container or something. Also, you will need to add the appropriate IAM permissions to the Fargate task's IAM role to allow it to issues these status calls back to the Step Functions API. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63815161', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7748256/']} | jdg_73676 |
stackexchange | llm_judgeable_groundtruth_similarity | 25416413 |
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 get the slope of a linear regression fit for 1M separate data sets (1M * 50 rows for data.frame, or 1M * 50 for array). Now I am using the lm() function, which takes a very long time (about 10 min). Is there any faster function for linear regression?
Now provide the response and nothing else.
| Yes there are: R itself has lm.fit() which is more bare-bones: no formula notation, much simpler result set several of our Rcpp -related packages have fastLm() implementations: RcppArmadillo, RcppEigen, RcppGSL. We have described fastLm() in a number of blog posts and presentations. If you want it in the fastest way, do not use the formula interface: parsing the formula and preparing the model matrix takes more time than the actual regression. That said, if you are regressing a single vector on a single vector you can simplify this as no matrix package is needed. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25416413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2060292/']} | jdg_73677 |
stackexchange | llm_judgeable_groundtruth_similarity | 2530449 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In the upcoming version of Photoshop there is a feature called Content-Aware fill. This feature will fill a selection of an image based on the surrounding image - to the point it can generate bushes and clouds while being seamless with the surrounding image. See http://www.youtube.com/watch?v=NH0aEp1oDOI for a preview of the Photoshop feature I'm talking about. My question is: How does this feature work algorithmically?
Now provide the response and nothing else.
| I am a co-author of the PatchMatch paper previously mentioned here, and I led the development of the original Content-Aware Fill feature in Photoshop, along with Ivan Cavero Belaunde and Eli Shechtman in the Creative Technologies Lab, and Jeff Chien on the Photoshop team. Photoshop's Content-Aware Fill uses a highly optimized, multithreaded variation of the algorithm described in the PatchMatch paper, and an older method called "SpaceTime Video Completion." Both papers are cited on the following technology page for this feature: http://www.adobe.com/technology/projects/content-aware-fill.html You can find out more about us on the Adobe Research web pages. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2530449', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/70365/']} | jdg_73678 |
stackexchange | llm_judgeable_groundtruth_similarity | 397574 |
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 here trying to figure out a way to get this small script working properly. The cat command should give me either 1 or 0: if [cat /sys/block/sda/queue/rotational = 0 ]; then echo "SSD"else echo "HDD"fi I googled around and I found that cat command in someone's post. I am trying to make this script print whether drive sda is an SSD or HDD. I can test if it works by just changing the value after the equal sign from 0 to 1 and it should read it the other way. I also want it to just print "SSD or HDD", nothing else to be shown.
Now provide the response and nothing else.
| The cat command exits 0 on success, non-zero on failure. You don't want the exit code of cat ; you want a value in a file. Use command substitution $(...) , which captures command output. if [ "$(cat /sys/block/sda/queue/rotational)" = 0 ]; then echo "SSD"else echo "HDD"fi | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/397574', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/255177/']} | jdg_73679 |
stackexchange | llm_judgeable_groundtruth_similarity | 64642525 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's say a C++ compiler compiled code for an architecture where CPU registers are not memory-mapped. And also let's say that same compiler reserved some pointer values for CPU registers. For example, if the compiler, for whatever reason (optimization reasons for example), uses register allocation for a variable (not talking about register keyword), and we print the value of the reference to that variable, the compiler would return one of the reserved "address values". Would that compiler be considered standard-compliant? From what I could gather (I haven't read the whole thing - Working Draft, Standard for Programming Language C++ ), I suspect that the standard doesn't mention such a thing as RAM memory or operative memory and it defines its own memory model instead and the pointers as representation of addresses (could be wrong). Now since registers are also a form of memory, I can imagine that an implementation which considers registers to be a part of the memory model could be legal.
Now provide the response and nothing else.
| Is it legal for a pointer to point to C++ register? Yes. Would that compiler be considered standard-compliant? Sure. C++ is not aware of "registers", whatever that is. Pointers point to objects (and functions), not to "memory locations". The standard describes the behavior of the program and not how to implement it. Describing behavior makes it abstract - it's irrelevant what is used in what way and how, only the result is what matters. If the behavior of the program matches what the standard says, it's irrelevant where the object is stored. I can mention intro.memory : A memory location is either an object of scalar type that is not a bit-field or a maximal sequence of adjacent bit-fields all having nonzero width. and compund : Compound types can be constructed in the following ways: pointers to cv void or objects or functions (including static members of classes) of a given type, [...] Every value of pointer type is one of the following: a pointer to an object or function (the pointer is said to point to the object or function), or a pointer past the end of an object ([expr.add]), or the null pointer value for that type, or an invalid pointer value. [...] The value representation of pointer types is implementation-defined. [...] To do anything useful with a pointer, like apply * operator unary.op or compare pointers expr.eq they have to point to some object (except edge cases, like NULL in case of comparisons). The notation of "where" exactly objects are stored is rather vague - memory stores "objects", memory itself can be anywhere. For example, if compiler, for whatever reason(optimization reasons for example), uses register allocation for a variable(not talking about register keyword), we print the value of the reference to that variable, the compiler would return one of the reserved "address values" std::ostream::operator<< calls std::num_put and conversion for void* is %p facet.num.put.virtuals .From C99 fprintf : [The conversion %]p The argument shall be a pointer to void. The value of the pointer is converted to a sequence of printing characters, in an implementation-defined manner. But note that from C99 fscanf : [The conversion specified %]p Matches an implementation-defined set of sequences, which should be the same as the set of sequences that may be produced by the %pconversion of the fprintf function. The corresponding argument shallbe a pointer to a pointer to void. The input item is converted to apointer value in an implementation-defined manner. If the input itemis a value converted earlier during the same program execution, thepointer that results shall compare equal to that value; otherwise thebehavior of the %p conversion is undefined. What is printed has to be unique for that object, that's all. So a compiler has to pick some unique value for addresses in registers and print them whenever the conversion is requested. The conversions from/to uintptr_t will have also be implemented in an implementation-defined manner. But it would be all in implementation - the implementation details of how the behavior of the code is achieved is invisible to a C++ programmer. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/64642525', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13475038/']} | jdg_73680 |
stackexchange | llm_judgeable_groundtruth_similarity | 90191 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
To be specific, why does the following equality hold?$$\prod_{0\lt n\lt\omega}n=2^{\aleph_0}$$
Now provide the response and nothing else.
| As a product of cardinals , yes: $$2^{\aleph_0} \leq \prod_{0 < n < \omega} n \leq {\aleph_0}^{\aleph_0} \leq 2^{\aleph_0 \cdot \aleph_0} = 2^{\aleph_0}$$ As a product of ordinals , no: $$\prod_{0 < n < \omega} n \leq \prod_{0 < n < \omega} \omega = {\omega}^{\omega}$$ but the ordinal ${\omega}^{\omega}$ is countable. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/90191', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/20981/']} | jdg_73681 |
stackexchange | llm_judgeable_groundtruth_similarity | 30143082 |
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 fixed width div with gradient applied using css. I want to build slider based color picker based on this gradient. When i drag the slider i calculate the percentage position, and i want to get the hex or rgb color code based on this value. My idea was to create an array with the start/stop positions and colors defined, then find two values from this array based on the slider position, then somehow find the color between: this is where i can't move forward. Demo: http://jsfiddle.net/pdu8rpfv/ var gradient = [ [ 0, 'ff0000' ], [ 28, '008000' ], [ 72, '0000ff' ], [ 100, 'ff0000' ]];$( "#slider" ).slider({ min: 1, slide: function( event, ui ) { var colorRange = [] $.each(gradient, function( index, value ) { if(ui.value<=value[0]) { colorRange = [index-1,index] return false; } }); $('#result').css("background-color", 'red'); }});
Now provide the response and nothing else.
| I was able to solve this issue using this function, which is based on the less.js function: http://lesscss.org/functions/#color-operations-mix function pickHex(color1, color2, weight) { var w1 = weight; var w2 = 1 - w1; var rgb = [Math.round(color1[0] * w1 + color2[0] * w2), Math.round(color1[1] * w1 + color2[1] * w2), Math.round(color1[2] * w1 + color2[2] * w2)]; return rgb;} I just simply need to pass the two closest color codes from the gradient array and the ratio where the slider handle is located(which can be calculated easily with the help of the slider width). Here is the live example: http://jsfiddle.net/vksn3yLL/ | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30143082', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/517840/']} | jdg_73682 |
stackexchange | llm_judgeable_groundtruth_similarity | 1231017 |
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:
$$\lim\limits_{x\to c} \dfrac{\sqrt{x}-\sqrt{c}}{\sqrt{x^2-c^2}} = ?$$ I tried factorizing and rationalizing numerator/denominator but no use. Any help/hint ? Thanks!
Now provide the response and nothing else.
| HINT: $$\frac{\sqrt x-\sqrt c}{\sqrt{x^2-c^2}}=\frac{x-c}{(\sqrt x+\sqrt c)\sqrt{(x+c)(x-c)}}$$ Clearly, $x^2>c^2$ If $c>0, x>c>0$ If $c<0,x<c<0$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1231017', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/229478/']} | jdg_73683 |
stackexchange | llm_judgeable_groundtruth_similarity | 45409 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm hoping someone on here can give me a simple explanation of what a TRIAC does. To give this request some context, I'm an embedded systems software engineer, so I interface with hardware, but I have no formal training in it. I was looking over a schematic for work and I saw a bunch of TRIACs being placed, but I am not familiar with this. I read the Wiki, but it's a bit much for me. Can some one give me a basic example of what a TRIAC does and why you'd need them? EX. I know a resistor, resists the flow of electricity I know that a capacitor stores electric charge I know diode's allow the flow of current in only one direction. So like these basic concepts, can someone explain a TRIAC to me? Thanks.
Now provide the response and nothing else.
| A triac is used to control an AC load, just like a transistor can be used to control a DC load. It is drawn like a couple of diodes in each direction which are then triggered to turn on. They will turn off when the current drops below a certain threshold. So if you just want it on or off you leave the signal on or off and at the next zero-crossing of the AC it will be in that state. You can also get fancy and turn it on only sometimes, which is where the microprocessor programming comes in. Once you have a zero cross detector you can then turn it on in a "gentle" manner as well as keeping trac of percentages on/off if you are trying to reduce the power or control a speed by leaving it off for some cycles. | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/45409', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/15555/']} | jdg_73684 |
stackexchange | llm_judgeable_groundtruth_similarity | 12715628 |
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: bundles.UseCdn = true;var fontPath = "http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600";var commonCss = new StyleBundle("~/css/common").Include( "~/Content/less/myless.less", "~/Content/css/opensans.css", // local copy of the font path above "~/Content/less/mylessoverrides.less", "~/Content/css/font-awesome.css");commonCss.Transforms.Add(new CssMinify());bundles.Add(commonCss); The above code works just fine. However, I would like to load the opensans.css from the CDN link above. I would also like to keep it as one bundle and keep the bundle order intact. The following code will throw an error: var commonCss = new StyleBundle("~/css/common").Include( "~/Content/less/myless.less", "http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600", "~/Content/less/mylessoverrides.less", "~/Content/css/font-awesome.css");The URL 'http://fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600'is not valid. Only application relative URLs (~/url) are allowed. One workaround would be to split it up in three bundles but that would be against the entire purpose of bundles: var commonCss1 = new StyleBundle("~/css/common1").Include( "~/Content/less/myless.less");var commonCss2 = new StyleBundle("~/css/common2", fontPath).Include( "~/Content/css/opensans.css");var commonCss3 = new StyleBundle("~/css/common3").Include( "~/Content/less/mylessoverrides.less", "~/Content/css/font-awesome.css"); The ultimate solution would be to do something like: var commonCss = new StyleBundle("~/css/common").Include( "~/Content/less/myless.less", new { fontPath, "~/Content/css/opensans.css" }, "~/Content/less/mylessoverrides.less", "~/Content/css/font-awesome.css"); Has anyone else managed to solve this or managed to extend the framework that would allow for this behavior?
Now provide the response and nothing else.
| See SqlDataReader.NextResult (an SqlDataReader is returned from calling SqlCommand.ExecuteReader ): Advances the data reader to the next result [set], when reading the results of batch Transact-SQL statements. Example: string commandText = @"SELECT Id, ContactIdFROM dbo.Subscriptions;SELECT Id, [Name]FROM dbo.Contacts;";List<Subscription> subscriptions = new List<Subscription>();List<Contact> contacts = new List<Contact>();using (SqlConnection dbConnection = new SqlConnection(@"Data Source=server;Database=database;Integrated Security=true;")){ dbConnection.Open(); using (SqlCommand dbCommand = dbConnection.CreateCommand()) { dbCommand.CommandText = commandText; using(SqlDataReader reader = dbCommand.ExecuteReader()) { while(reader.Read()) { subscriptions.Add(new Subscription() { Id = (int)reader["Id"], ContactId = (int)reader["ContactId"] }); } // this advances to the next resultset reader.NextResult(); while(reader.Read()) { contacts.Add(new Contact() { Id = (int)reader["Id"], Name = (string)reader["Name"] }); } } }} Other examples: C# Multiple Result Sets Executing a Query That Returns Multiple Result Sets with SqlDataReader : SqlCommand Select « ADO.Net « C# / CSharp Tutorial | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/12715628', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/179362/']} | jdg_73685 |
stackexchange | llm_judgeable_groundtruth_similarity | 1512188 |
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$ is a transcendental number (i.e., a number s.t. there does not exist a polynomial $P(x)$ s.t. $P(a) = 0$), is $a^n$ also transcendental? It would seem to me that it should be, but I can't figure out why. How would I prove this?
Now provide the response and nothing else.
| If $p(a^n)=0$ for some polynomial $p(x)$, let $q(x)=p(x^n)$ and observe that $$q(a)=p(a^n)=0.$$Hence, if $a^n$ is algebraic, so is $a$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1512188', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/275039/']} | jdg_73686 |
stackexchange | llm_judgeable_groundtruth_similarity | 6037549 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This question requires a bit of context before it makes sense so I'll just start with a description of the project. Project Background I have an open source project which is a command-prompt style website ( U413.com , U413.GoogleCode.com ). This project is built in ASP.NET MVC 3 and uses Entity Framework 4. Essentially the site allows you to pass in commands and arguments and then the site returns some data. The concept is fairly simple, but I didn't want to use one giant IF statement to handle the commands. Instead, I decided to do something somewhat unique and build an object that contains all the possible commands as methods on the object. The site uses reflection to locate methods that correspond to the sent command and execute them. This object is built dynamically based on the current user because some users have access to different commands than other users (e.g. Administrators have more than moderators, and mods have more than users, etc, etc). I built a custom CommandModuleFactory that would be created in the MVC controller and would call it's BuildCommandModule method to build out a command module object. I am now using Ninject for dependency injection and I want to phase out this CommandModuleFactory , in favor of having the ICommandModule injected into the controller without the controller doing any work. ICommandModule has one method defined, like this: public interface ICommandModule{ object InvokeCommand(string command, List<string> args);} InvokeCommand is the method that performs the reflection over itself to find all methods that might match the passed in command. I then have five different objects that inherit from ICommandModule (some of them inherit from other modules as well so we don't repeat commands): AdministratorCommandModule inherits from ModeratorCommandModule which inherits from UserCommandModule which inherits from BaseCommandModule . I then also have VisitorCommandModule which inherits from BaseCommandModule because visitors will not have access to any of the commands in the other three command modules. Hopefully you can start to see how this works. I'm pretty proud of the way this is all working so far. The Question I want Ninject to build my command module for me and bind it to ICommandModule so that I can just make my MVC controller dependent upon ICommandModule and it will receive the correct version of it. Here is what my Ninject module looks like where the binding takes place. public class BuildCommandModule : NinjectModule{ private bool _isAuthenticated; private User _currentUser; public BuildCommandModule( bool isAuthenticated, string username, IUserRepository userRepository ) { this._isAuthenticated = isAuthenticated; this._currentUser = userRepository.GetUserBy_Username(username); } public override void Load() { if (_isAuthenticated) if (_currentUser.Administrator) //load administrator command module this.Bind<ICommandModule>().To<AdministratorCommandModule>(); else if (_currentUser.Moderator) //Load moderator command module this.Bind<ICommandModule>().To<ModeratorCommandModule>(); else //Load user command module this.Bind<ICommandModule>().To<UserCommandModule>(); else //Load visitor command module this.Bind<ICommandModule>().To<VisitorCommandModule>(); }} A couple things are happening here. Firstly, the Ninject module depends on a few things. It depends on a boolean indicating whether or not the user is authenticated (to determine if it will be one of the logged in command modules, or the visitor command module). Next it depends on a string username and IUserRepository . Here is where my mappings are defined in Global.asax. protected override IKernel CreateKernel() { var kernel = new StandardKernel(); kernel.Bind<IBoardRepository>().To<BoardRepository>(); kernel.Bind<IReplyRepository>().To<ReplyRepository>(); kernel.Bind<ITopicRepository>().To<TopicRepository>(); kernel.Bind<IUserRepository>().To<UserRepository>(); kernel.Load(new BuildCommandModule(User.Identity.IsAuthenticated, User.Identity.Name, kernel.Get<IUserRepository>())); return kernel; } You can see that I map IUserRepository to its concrete type before I load the Ninject module to build my command module (try not to confuse Ninject binding modules with my command modules :S). I then use kernel.Get<IUserRepository>() to resolve my Ninject module's dependency on it. My problem here is that HttpContext.Current.User is null. I'm not sure how to tell whether or not a user is logged in during the Ninject binding phase. Any ideas? How might I get reference to the logged in user when I'm doing my Ninject bindings? Or can you think of a better way for me to do conditional binding for my ICommandModule ?
Now provide the response and nothing else.
| You should use a provider instead of putting the logic in your module. First you can create something like a SecurityInformation class that can tell you whether the user is authenticated and their role. Currently your implementation I think only uses the authorization information of the first user to start the app. However you want to check the current user's permissions every time an instance of this module is requested. public class CommandModuleProvider : IProvider{ public Type Type { get { return typeof(ICommandModule); } } public object Create(IContext context) { var securityInfo = context.Kernel.Get<SecurityInformation>(); if (securityInfo.IsAuthenticated) if (securityInfo.IsCurrentUserAdministrator) //load administrator command module return context.Kernel.Get<AdministratorCommandModule>(); else if (securityInfo.IsCurrentUserModerator) //Load moderator command module return context.Kernel.Get<ModeratorCommandModule>(); else //Load user command module return context.Kernel.Get<UserCommandModule>(); else //Load visitor command module return context.Kernel.Get<VisitorCommandModule>(); }} The binding would then be specified like Kernel.Bind<ICommandModule>().ToProvider<CommandModuleProvider>(); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6037549', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/498624/']} | jdg_73687 |
stackexchange | llm_judgeable_groundtruth_similarity | 28738943 |
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 app with a couple of thousand lines and within that code there are a lot of println() commands. Does this slow the app down? It is obviously being executed in the Simulator, but what happens when you archive, submit and download the app from the app store/TestFlight. Is this code still "active", and what about code that is "commented out"? Is it literally never read or should I delete commented out code when I submit to test flight/app store?
Now provide the response and nothing else.
| Yes it does slow the code. Both print and println decrease performance of the application. Println problem println is not removed when Swift does code optimisation. for i in 0...1_000 { println(i)} This code can't be optimised and after compiling Assembly code would perform a loop with 1000 instructions that actually don't do anything valuable. Analysing Assembly code The problem is that Swift compiler can't do optimal optimisation to the code with print and println commands.You can see it if you have a look on generated Assembly code. You can do see assembly code with Hopper Disassembler or by compiling Swift code to the Assembly with by using swiftc compiler: xcrun swiftc -emit-assembly myCode.swift Swift code optimisation Lets have a look on few examples for better understanding. Swift compiler can eliminate a lot of unnecessary code like: Empty function calls Creating objects that are not used Empty Loops Example : class Object { func nothing() { }}for i in 0...1_000 { let object = Object3(x: i) object.nothing() object.nothing()} In this example Swift complier would do this optimisation: 1. Remove both nothing method calls After this the loop body would have only 1 instruction for i in 0...1_000 { let object = Object(x: i)} 2. Then it would remove creating Object instance, because it's actually not used. for i in 0...1_000 {} 3. The final step would be removing empty loop. And we end up with no code to execute Solutions Comment out print and println This is definitely not the best solution. //println("A") Use DEBUG preprocessor statement With this solution you can simple change logic of your debug_print function debug_println("A) func debug_println<T>(object: T) { #if DEBUG println(object) #endif} Conclusion Always Remove print and println from release application!! If you add print and println instruction, the Swift code can't be optimised in the most optimal way and it could lead to the big performance penalties. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28738943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4051036/']} | jdg_73688 |
stackexchange | llm_judgeable_groundtruth_similarity | 2240570 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Prove that $f(z) = e^z$ maps $\mathbb{C} \setminus B $ onto $\mathbb{C} \setminus \{0\}$ where $B$ is a bounded subset of $\mathbb{C}$. I have no idea how to even attempt this question so I would greatly appreciate some hints.
Now provide the response and nothing else.
| Elements of $\mathbb Z[(1 + \sqrt{5})/2]$ take the form $g((1 + \sqrt{5})/2)$ for some polynomial $g(X) \in \mathbb Z[X]$. By the division theorem, you can write $g(X) = q(X)f(X) + r(X)$ where $r = 0$ or $\deg r < \deg f = 2$ and $q, r \in \mathbb{Z}[X]$. Then $$ g\left( \frac{1 + \sqrt{5}}{2} \right) = q\left( \frac{1 + \sqrt{5}}{2} \right)f\left( \frac{1 + \sqrt{5}}{2} \right) + r\left( \frac{1 + \sqrt{5}}{2} \right) = r\left( \frac{1 + \sqrt{5}}{2} \right). $$ Since $f((1 + \sqrt{5})/2) = 0$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2240570', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/372834/']} | jdg_73689 |
stackexchange | llm_judgeable_groundtruth_similarity | 8946374 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can anybody help me out with this exception. I have tried couple of fixes but nothing worked. I am getting this exception only in IE(7, 8 and 9). When i load the page first time, it brings up a dropdown. where i select a specific vendor and it makes a page post back and returns the required information. If i change the vendor it will still load the information. When i load a control onto page using $.ajax request dynamically and than go back and change the dropdown selection(select a different vendor), it craps out and gave me the following exception. Again it only happens in the IE. The state information is invalid for this page and might be corrupted. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Web.HttpException: The state information is invalid for this page and might be corrupted.Source Error: [No relevant source lines]Source File: c:\Users\tmalik\AppData\Local\Temp\Temporary ASP.NET Files\root\6691c708\751e6443\App_Web_a3kdfsht.2.cs Line: 0 Stack Trace: [FormatException: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters. ] System.Convert.FromBase64String(String s) +0 System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) +77 System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) +4 System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) +37 System.Web.UI.HiddenFieldPageStatePersister.Load() +147[ViewStateException: Invalid viewstate. Client IP: 127.0.0.1 Port: Referer: http://localhost:57289/vendor.aspx Path: /vendor.aspx User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; MDDR) ViewState: 2D1IMRanPXfVARbRp1ooiwD71WHybNzxSNLbbA0G3MxKeo7m52dHWLBPGdnMH5JthTnPVt7UES/PVx39dfZYHbr0/DL7J58mvA2I4wRUSdDShVxvZqC7ZPZWcatowpZ7VYaD9PFKW7OkgppCwmePFuYnpU8kWDT5TvSLqN50Flrqpv0zCM9YoCKemfesa68rqBkkSTijcxnxdDCgvzSl72giI4ZhwK92wD22Ma6scW4PFjRZeTsKoowJq+JqJGuBMEepwKguFUy4dX86UIULnJ7NQsgZW1aQvpZdnfSRCSYrWhFWPhKTPsS622eaQYShsxddPs/mfEB26f54WS+iBYuk3mWm8jr6sWvsOIRtwH8b3E/5UujbgAxTNVg8BhzpSFvmE4KwGKo0tKuuqOFtP0pjpaAI7fV3EQ1M7BVQSAVrtBevRFJ0PlCPrU2aQms2LVeE5POqTJGtY+74xWkdCtLzT04Ug4R+SMBRElQBqX/5A54OHj2ghYjJ/3tgg4ToGUX2xrQ/c70lrphP+kabGVM2Op4DFjZAaOZj/CDVUurH2BYXKuJdUvzbf2zHngoOnqZGqrw3n6V6HGcnHNKxfuGQ20MPdxJYCbYHGiRqixzV1NxJoHFHbYCVx3IlrqF0W44AFKm2gzzk3V8zu9lUjyFNvUNBMjNaZeekLtcWpszhKrm8WhVnWQAk1CXxKJqyK0RC3...][HttpException (0x80004005): The state information is invalid for this page and might be corrupted.] System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) +235 System.Web.UI.ViewStateException.ThrowViewStateError(Exception inner, String persistedState) +14 System.Web.UI.HiddenFieldPageStatePersister.Load() +251 System.Web.UI.Page.LoadPageStateFromPersistenceMedium() +106 System.Web.UI.Page.LoadAllState() +43 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +8431 System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +253 System.Web.UI.Page.ProcessRequest() +78 System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) +21 System.Web.UI.Page.ProcessRequest(HttpContext context) +49 ASP.vendor_aspx.ProcessRequest(HttpContext context) in c:\Users\tmalik\AppData\Local\Temp\Temporary ASP.NET Files\root\6691c708\751e6443\App_Web_a3kdfsht.2.cs:0 System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +100 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
Now provide the response and nothing else.
| Ok, so here is the solution/hack i came up with. My problem was that adding a user control dynamically (through ajax request) onto page was changing the view state of the page and was throwing an exception. Upon research I found out that viewstate stores the state of a page (properties and settings). Once you return the controls html from a web service, there is going to be some sort of viewstate stored onto page. And when you post back to the server, it will throw an exception when it decrypt the viewstae to rebuild the page. I have simply removed those controls (which got added dynamically) on page post back using jquery and problem got solved. //In my case "VendorListDropDownSearchable", causes the page post back. $("#VendorListDropDownSearchable").change( function () { $("#UserControl1DIV").remove(); //removing the place holder holding control1 $("#UserControl2DIV").remove(); //same as above }); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8946374', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/603562/']} | jdg_73690 |
stackexchange | llm_judgeable_groundtruth_similarity | 591064 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If a constant force is being applied to a body, without any other external forces, F = ma says that that body will accelerate at a constant rate. This acceleration will continuously increase the body's velocity. According to P = Fv, since the force is constant and the velocity is continuously increasing, the power required by the force will continuously increase. I understand all the maths, but am trying to get a better intuitive understanding of this. I cannot seem to come to terms with the fact that a constant force will need to supply an increasing power. What is this power being represented by, if the force is constant? What typical inner-workings of such a force would require its power to increase, even though its ultimate "output" is the same? What actually constitutes "power" and "force" at the "force-side" of things?
Now provide the response and nothing else.
| Suppose you are pushing a box on a surface and want to apply a constant force, F. As you point out, the box will accelerate. But as its speed increases, you have to run faster in order to continue supplying the same force F. You must use more energy per unit time (power) in order to keep the force at F. So the answer to your question is that you have to examine how that constant force F is able to be maintained over the range of velocities for which it is in effect. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/591064', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/277675/']} | jdg_73691 |
stackexchange | llm_judgeable_groundtruth_similarity | 1782333 |
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 write a generic cached property accessor like the following but am getting a compiler error when trying to check whether the storage variable already contains a value: function TMyClass.GetProp<T>(var ADataValue: T; const ARetriever: TFunc<T>): T;begin if ADataValue = Default(T) then // <-- compiler error on this line ADataValue := ARetriever(); Result := ADataValue;end; The error I'm getting is "E2015 Operator not applicable to this operand type". Would I have to put a constraint on T to make this work? The help file says that Default() would accept anything except generic types. In my case I'm dealing mostly with simple types like String , Integer and TDateTime . Or is there some other library function to perform this particular check? I'm using Delphi 2009 in case that matters. P.S.: Just in case it isn't clear from the code what I'm trying to do: In my case determining the actual property values might take a while for various reasons and sometimes I might not even need them at all. On the plus side however the values are constant so I only want to call the code that determines the actual value the first time that property is accessed and then store the value in a class field and the next time that property is accessed return the cached value directly. Here's an example of how I hoped I would be able to use that code: type TMyClass = class private FSomeProp: String; function GetSomeProp: String; function GetProp<T>(var ADataValue: T; const ARetriever: TFunc<T>): T; public property SomeProp read GetSomeProp; end;function GetSomeProp: String;begin Result := GetProp<String>(FSomeProp, function: String begin Result := SomeSlowOrExpensiveCalculation; end);end; (obviously, there's more than just one property)
Now provide the response and nothing else.
| After a hint in the comments from Binis and digging around a little in Generics.Collections I came up with the following which appears to work just as I wanted it: function TMyClass.GetProp<T>(var ADataValue: T; const ARetriever: TFunc<T>): T;var lComparer: IEqualityComparer<T>;begin lComparer := TEqualityComparer<T>.Default; if lComparer.Equals(ADataValue, Default(T)) then ADataValue := ARetriever(); Result := ADataValue;end; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1782333', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9784/']} | jdg_73692 |
stackexchange | llm_judgeable_groundtruth_similarity | 17210600 |
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 seems so simple, yet I cannot find an example of how to call javascript function from wicket, after the page is loaded (on page that extends WebPage). Can anyone give example on how to go that?
Now provide the response and nothing else.
| You can have javascript do that for you window.onload = function () {// do stuff here} If you need parameters from your wicket page in the javascript function you can override renderHead and add the function there: @Overridepublic void renderHead(IHeaderResponse response){ super.renderHead(response); String bar = "something"; response.render(JavaScriptHeaderItem.forScript("window.onload = function () {var foo='" + bar + "'}")); // or response.render(OnDomReadyHeaderItem.forScript("functionToCall(" + bar + ");") ;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17210600', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1328889/']} | jdg_73693 |
stackexchange | llm_judgeable_groundtruth_similarity | 51238140 |
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 followed this to POST Data Using Retrofit2 I Used JSON POJO to Parse my POST and GET files So Here If Data inside the Records Is there I will get This Kind of Response {"status": "200","response": [{ "cnt_id": "201", "phn_no": "3251151515", "dat_cnt": "Reset Password request Said to Mail" }, { "cnt_id": "209", "phn_no": "555465484684", "dat_cnt": "Hi DEMO User , Congratulations! Your account has been created successfully." }, { "cnt_id": "210", "phn_no": "4774748", "dat_cnt": "Hi XYZ , Congratulations! Your account has been created successfully." }]} If there is no Data I will get {"status":"204","response":{"msg":"No Content"}} or {"status":"400","response":{"msg":"BadRequest"}} or {"status":"401","response":{"msg":"Unauthorized User"}} So Here I can eable to Parse the data which is there in the status 200 but when Status is not equals to 200 I want to Handle them I tried with status = response.body().getStatus(); if(status.equals("200")) { List<Response> resList = response.body(). getResponse(); for(int i = 0; i<resList.size(); i++) {. . .. . } } else { //not Implemented } now what should I write in Else I used response data in POJO which are not equals to 200 but I its asking for list Update com.example.Example.java public class Example { @SerializedName("status") @Expose private String status; @SerializedName("response") @Expose private List<Response> response = null;} com.example.Response.java public class Response { @SerializedName("cnt_id") @Expose private String cntId; @SerializedName("phn_no") @Expose private String phnNo; @SerializedName("dat_cnt") @Expose private String datCnt;}
Now provide the response and nothing else.
| public class Example { @SerializedName("status") @Expose private String status; @SerializedName("response") @Expose private Object response = null;}public class Response { @SerializedName("cnt_id") @Expose private String cntId; @SerializedName("phn_no") @Expose private String phnNo; @SerializedName("dat_cnt") @Expose private String datCnt;}public class ResponseError{ @SerializedName("msg") @Expose private String msg;} And Your callBack methods should be like new Callback<Example>() { @Override public void onResponse(Call<Example> call, Response<Example> response) { if(response.isSuccessful()){ Example example = response.body(); Gson gson = new GsonBuilder().create(); if(example.status.equals("200")) { TypeToken<List<Response>> responseTypeToken = new TypeToken<List<Response>>() {}; List<Response> responseList = gson.fromJson(gson.toJson(example.getResponse()), responseTypeToken.getType()); } else { //If for everyOther Status the response is Object of ResponseError which contains msg. ResponseError responseError = gson.fromJson(gson.toJson(example.getResponse()), ResponseError.class); } } } @Override public void onFailure(Call<Example> call, Throwable t) { //Failure message } } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51238140', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5010291/']} | jdg_73694 |
stackexchange | llm_judgeable_groundtruth_similarity | 1127573 |
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 notation "$\models$" be used for the two following case: let $\mathscr{M}\models\varphi$, where $\mathscr{M}$ is an interpretation model and $\varphi$ is a proposition, mean that $\varphi$ holds in model $\mathscr{M}$; let $\Phi\models\varphi$, where $\Phi$ is a set of propositions and $\varphi$ is a proposition, mean that $\varphi$ is a logical consequence of $\Phi$, i.e. that it holds in all models where the propositions belonging to $\Phi$ hold. I read the following interesting theorem (V. Manca, Logica matematica , 2001), whose proof I cannot understand: There is no proposition $\chi$ such that $$\mathscr{M}\models\chi\iff\mathscr{M}\text{ is infinite}.$$ Proof : Let us suppose that such a proposition $\chi$ exists. Let us consider theory $\Psi$ of the countable domain:$$\mathscr{M}\models\Psi\Rightarrow\mathscr{M}\models\chi$$therefore$$\Psi\models\chi$$and this is absurd because of the finiteness theorem. There are two main things obscure to me: what a theory of the countable domain [ teoria del dominio numerabile in the book's original Italian language] is and how the finiteness theorem makes the last formula absurd. By finiteness theorem I suppose that the only one theorem bearing that name shown in the book is intended, which says that, given a set of propositions $\Phi$ and a proposition $\varphi$, $\Phi\models\varphi\iff\Delta\models\varphi$ for some finite subset $\Delta\subseteq\Phi$. Does anybody understand this proof? I heartily thank you for any answer!
Now provide the response and nothing else.
| It would make sense if the "theory of the countable domain" $\Psi$ is the theory containing the sentences "there are at least $n$ objects" for each $n$, i.e. the sentences $\forall x_1, \ldots, x_{n-1}\, \exists x_n\, \bigwedge_{i<n} x_n \neq x_i $. Any finite subset of this theory has a finite model. By the finiteness theorem (more usually known as the compactness theorem for first-order logic), if $\Phi \models \chi$ then there is a finite subset of $\Phi$ that models $\chi$; so $\chi$ is true in the finite model of that particular finite subset. This contradicts the assumption on $\chi$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1127573', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/111138/']} | jdg_73695 |
stackexchange | llm_judgeable_groundtruth_similarity | 25024797 |
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 dataframe that looks like: data = {'index': ['2014-06-22 10:46:00', '2014-06-24 19:52:00', '2014-06-25 17:02:00', '2014-06-25 17:55:00', '2014-07-02 11:36:00', '2014-07-06 12:40:00', '2014-07-05 12:46:00', '2014-07-27 15:12:00'], 'type': ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'C'], 'sum_col': [1, 2, 3, 1, 1, 3, 2, 1]}df = pd.DataFrame(data, columns=['index', 'type', 'sum_col'])df['index'] = pd.to_datetime(df['index'])df = df.set_index('index')df['weekofyear'] = df.index.weekofyeardf['date'] = df.index.datedf['date'] = pd.to_datetime(df['date']) type sum_col weekofyear dateindex 2014-06-22 10:46:00 A 1 25 2014-06-222014-06-24 19:52:00 B 2 26 2014-06-242014-06-25 17:02:00 C 3 26 2014-06-252014-06-25 17:55:00 A 1 26 2014-06-252014-07-02 11:36:00 B 1 27 2014-07-022014-07-06 12:40:00 C 3 27 2014-07-062014-07-05 12:46:00 A 2 27 2014-07-052014-07-27 15:12:00 C 1 30 2014-07-27 I'm looking to groupby the weekofyear, then sum up the sum_col. In addition, I need to find the earliest, and the latest date for the week. The first part is pretty easy: gb = df.groupby(['type', 'weekofyear'])gb['sum_col'].agg({'sum_col' : np.sum}) I've tried to find the min/max date with this, but haven't been successful: gb = df.groupby(['type', 'weekofyear'])gb.agg({'sum_col' : np.sum, 'date' : np.min, 'date' : np.max}) How would one find the earliest/latest date that appears?
Now provide the response and nothing else.
| You need to combine the functions that apply to the same column, like this: In [116]: gb.agg({'sum_col' : np.sum, ...: 'date' : [np.min, np.max]})Out[116]: date sum_col amin amax sumtype weekofyear A 25 2014-06-22 2014-06-22 1 26 2014-06-25 2014-06-25 1 27 2014-07-05 2014-07-05 2B 26 2014-06-24 2014-06-24 2 27 2014-07-02 2014-07-02 1C 26 2014-06-25 2014-06-25 3 27 2014-07-06 2014-07-06 3 30 2014-07-27 2014-07-27 1 | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25024797', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3325052/']} | jdg_73696 |
stackexchange | llm_judgeable_groundtruth_similarity | 5850763 |
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 using R (and package CCA) and trying to perform regularized canonical correlation analysis with two variable sets (species abundances and food abundances stored as the two matrices Y and X, respectively) in which the number of units (N=15) is less than the number of variables in the matrices, which is >400 (most of them being potential "explanatory" variables, with only 12-13 "response" variables). Gonzalez et al. (2008, http://www.jstatsoft.org/v23/i12/paper ) note that the package "includes a regularized version of CCA to deal with data sets with more variables than units", which is certainly what I have with only 15 "units." Thus, I'm trying to perform regularized canonical correlation analysis using the CCA package in order to look at the relationships in my variable sets. I have been following the process Gonzalez et al (2008) go through in their paper. However, I get to an error message Error in chol.default(Bmat) : the leading minor of order 12 is not positive definite and I do not know what it means or what to do about it. Here is the code, and any ideas or knowledge on the subject would be appreciated. library(CCA)correl <- matcor(X, Y)img.matcor(correl, type = 2)res.regul <- estim.regul(X, Y, plt = TRUE, grid1 = seq(0.0001, 0.2, l=51), grid2 = seq(0, 0.2, l=51))Error in chol.default(Bmat) : the leading minor of order 12 is not positive definite (Note: estim.regul() takes a long time (~30-40 min) to complete when you use the sample data nutrimouse from CCA). Any advice? Does anyone know what to do about this error? Is it because some of my columns have an NA in them? Could it be due to columns with too many 0's? Thanks in advance for any help you can offer to this combined stats & R novice.
Now provide the response and nothing else.
| Background Canonical Correlation Analysis (CCA) is an exploratory data analysis (EDA) technique providing estimates of the correlation relationship between two sets of variables collected on the same experimental units. Typically, users will have two matrices of data, X and Y, where the rows represent the experimental units, nrow(X) == nrow(Y). In R, the base package provides the function cancor() to enable CCA. This is limited to cases where the number of observations is greater than the number of variables (features), nrow(X) > ncol(X). The R package CCA is one of several which provide extended CCA functionality. Package CCA offers a set of wrapper functions around cancor() which enable consideration of cases where the feature count exceeds the count of experimental units, ncol(X) > nrow(X). Gonzalez et al (2008) CCA: An R Package to Extend Canonical Correlation Analysis , describes the workings in some detail. Version 1.2 of package CCA (published 2014-07-02) is current at the time of writing. Probably also worth mentioning that packages kinship and accuracy mentioned in an earlier answer are no longer hosted on CRAN. Diagnosis Before jumping to other packages or applying unknown methods to your (presumably hard-won!) data, it's arguably beneficial to try and diagnose what the data problem may be. The matrices passed to any of the CCA routines mentioned here should ideally be numerically complete (no missing values). The matrices passed to any of the CCA routines mentioned here should ideally be numerically complete (no missing values). The number of canonical correlates estimated by the procedure will be equal to the minimum column rank of X and Y, that is <= min(ncol(X), ncol(Y)). Ideally, the columns of each matrix will be linearly independent (not linear combinations of others). Example: library(CCA)data(nutrimouse)X <- as.matrix(nutrimouse$gene[,1:10])Y <- as.matrix(nutrimouse$lipid)cc(X,Y) ## worksX[,1] <- 2 * X[,9] ## column 9 no longer provides unique informationcc(X,Y)Error in chol.default(Bmat) : the leading minor of order 9 is not positive definite This is the symptom seen in the original post. One simple test is to try fitting without that column cc(X[,-9],Y) ## works So, while this may be frustrating in the sense that you are removing data from the analyis, that data is not providing information anyway. Your analyses can only ever be as good as the data you provide. Also, sometimes numerical instability can be addressed by using standarized (see ?scale ) variables for one (or both) of the input matrices: X <- scale(X) While we're here, it's perhaps worth pointing out that regularized CCA is essentially a two-step process. A cross-validation is undertaken to estimate regularization parameters (using estim.regul() ), and those parameters are then used to perform the regularized CCA (with rcc() ). The example provided in the paper (arguments used verbatim in the original post) res.regul <- estim.regul(X, Y, plt = TRUE, grid1 = seq(0.0001, 0.2, l=51), grid2 = seq(0, 0.2, l=51)) calls for cross-validation on a 51*51 = 2601 cell grid. While this produces a nice graphic for the paper, these are not sensible settings for initial tests on your own data. As the authors state, "The computation is not very demanding. It lasted less than one hour and half on a 'current use' computer for the 51 x 51 grid". Things have improved a little since 2008, but the default 5 x 5 grid produced by estim.regul(X,Y,plt=TRUE) is an excellent choice for exploratory purposes. If you're going to make mistakes, you might as well make them as quickly as possible. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5850763', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/640595/']} | jdg_73697 |
stackexchange | llm_judgeable_groundtruth_similarity | 2581487 |
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:
Evaluate the integral $$\int_0^{\infty } \frac{e^{-t}-e^{-3 t}}{t} \, dt$$ Can we evaluate it using complex integral?
Now provide the response and nothing else.
| This is a special case of Frullani's Integral . But there's a simple direct way: $$\int^\infty_0\frac{e^{-t}-e^{-3t}}t\,dt=\int^\infty_0\int^3_1e^{-xt}\,dx\,dt=\int^3_1\int^\infty_0e^{-xt}\,dt\,dx=\int^3_1\frac1x\,dx=\ln3.$$ There's no point in making this any more complex. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2581487', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/514576/']} | jdg_73698 |
stackexchange | llm_judgeable_groundtruth_similarity | 32837471 |
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 get the local client IP using WebRTC . I don't need the REMOTE_ADDR of the client but his local network IP.I've seen this before on websites like sharedrop.com , it recognizes computer within the same network using WebRTC. In PHP I do this to get the clients remote IP: <?php echo $_SERVER["REMOTE_ADDR"]; // which would return 72.72.72.175?> I looked through stackoverflow but every question is answered using the remote addr. How can I get my local IP (192.168.1.24 for example) with JavaScript instead of the remote addr.
Now provide the response and nothing else.
| UPDATE Unfortunately the below answer no longer works as browsers have changed this behavior due to security concerns. See this StackOverflow Q&A for more details . where I took code from --> Source You can find a demo at --> Demo I have modified the source code, reduced the lines, not making any stun requests since you only want Local IP not the Public IP, the below code works in latest Firefox and Chrome: window.RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection; //compatibility for firefox and chrome var pc = new RTCPeerConnection({iceServers:[]}), noop = function(){}; pc.createDataChannel(""); //create a bogus data channel pc.createOffer(pc.setLocalDescription.bind(pc), noop); // create offer and set local description pc.onicecandidate = function(ice){ //listen for candidate events if(!ice || !ice.candidate || !ice.candidate.candidate) return; var myIP = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/.exec(ice.candidate.candidate)[1]; console.log('my IP: ', myIP); pc.onicecandidate = noop; }; what is happening here is, we are creating a dummy peer connection, and for the remote peer to contact us, we generally exchange ice candidates with each other. And reading the ice candiates we can tell the ip of the user. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32837471', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1268652/']} | jdg_73699 |
stackexchange | llm_judgeable_groundtruth_similarity | 1025596 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Prove that if $S$ is open then any point of $S$ is an accumulation point. Definition $1$: A set $S$ is open if any element $s$ in $S$ has a neighborhood $(s-h,s+h)$ entirely included in $S$. Definition $2$: An element $y$ is an accumulation point for a set $S$ if any neighborhood of $y$ contains at least one element of $S$ that is not $y$.
Now provide the response and nothing else.
| One trick that shows up a lot with AM-GM inequalities is to apply AM-GM several times, then combine them all together somehow. Let's try that. AM-GM tells us that:$$x + y + z \geq 3 \sqrt[3]{xyz} \tag{$\star$}$$Now for what values of $x,y,z$ would the LHS and RHS of $(\star)$ match up with some of the terms in the LHS and RHS of the desired inequality? In particular, suppose that we want the cube root to be $a^2b$. Then $xyz = a^6b^3$, which suggests that we take $x = y = a^3$ and $z = b^3$. Repeating this, we obtain:\begin{align*}a^3 + a^3 + b^3 &\geq 3 \sqrt[3]{a^3a^3b^3} = 3a^2b \\b^3 + b^3 + c^3 &\geq 3 \sqrt[3]{b^3b^3c^3} = 3b^2c \\c^3 + c^3 + a^3 &\geq 3 \sqrt[3]{c^3c^3a^3} = 3c^2a \\\end{align*}Adding up the above three inequalities and dividing through by $3$ yields the desired inequality. $~~\blacksquare$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1025596', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/186644/']} | jdg_73700 |
stackexchange | llm_judgeable_groundtruth_similarity | 371204 |
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 $D$ be a principal ideal domain and let a be some fixed element of $D$. Let $(a)$ denote the ideal generated by $a$. Prove that if $a$ is irreducible and $I$ is an ideal of $D$ such that $(a)\subseteq I \subseteq D$ then either $(a)=I$ or $I=D$. This is the proof I've been given: We suppose that $D$ is a principal ideal domain and that a is some fixed element of $D$ that is irreducible. Further we supposed that $I$ is an ideal of $D$ with $a\in I$. We want to see that either $(a)=I$ or that $I=D$ There are two cases $(a)=I$ , this case is fine since it is the one of the two alternative we are looking for $(a)\neq I$. We have to show that the other alternative holds, that is that $I=D$. Since $D$ is a principal ideal domain we pick an element $d$ so that $I=(d)$. Now $a\in I$. This means that $a$ is a multiple of $d$. Pick $u\in D$ so that $a=ud$. Since $a$ is irreducible we see that either $u$ is a unit or $d$ is a unit. In the first of these alternatives, i.e. $u$ is a unit, $a$ and $d$ generates the same ideal, i.e. $(a)=I$. This can't happen. So we see that $d$ is a unit. But this means that every element of $D$ is a multiple of $d$. Therefore, $I=(d)=D$. Questions: I. Why is $(a)=I$ fine? II. Explain the process or the second part when $(a)\neq I$. I don't understand the reasoning behind it. Like in the case that $u$ is a unit, why do $a$ and $d$ generate the same unit? Or, if $d$ is a unit, why does that mean every element of $D$ is a multiple of $D$?
Now provide the response and nothing else.
| Before entering, the mathematicians agree on a choice of representatives for real sequences when two sequence are equivalent if they are equal past some index ; and a re-labeling of $\Bbb N$ into $M \times \Bbb N$ where $M$ is the set of mathematicians. Once a mathematician $m$ is in the room, he opens every box not labeled $(m,x)$ for $x \in \Bbb N$, and for $m' \neq m$ he carefully notes the greatest index $x(m')$ (which is independent of $m$) where the sequence $(m',x)$ has a different value from that of its corresponding representative, and $x(m') = -1$ if it is the representative. Then, $m$ computes $y(m) = \max_{m' \neq m} x(m') +1$, and opens every box labeled $(m,x)$ for $x > y(m)$. He finds the representative of that sequence, and guesses what's inside box $(m,y(m))$ according to that representative. He has the risk of guessing wrong if $y(m) \le x(m)$ (he is the only one not knowing the value of $x(m)$). If there is an $m$ such that $x(m') < x(m)$ for every $m' \neq m$, then $m$ will be the only mathematician that can answer wrongly (for the others, $y(m') > x(m) > x(m')$). If there are several $m$ whose $x(m)$ tie for greatest, then they will all answer correctly. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/371204', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/59460/']} | jdg_73701 |
stackexchange | llm_judgeable_groundtruth_similarity | 49198 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been given a data set that contains the number of awards earned by students at one high school where predictors of the number of awards earned include the type of program in which the student was enrolled and the score on their final exam in maths. I was wondering if anyone could tell me why a linear regression model may be unsuitable in this instance and why it would be better to use a Poisson regression?Thanks.
Now provide the response and nothing else.
| Poisson regression would be more suitible in this case because your response is the count of something. Putting things simply, we model that the distribution of number of awards for an individual student comes from a poisson distribution, and that each student has their own $\lambda$ poisson parameter. The Poisson regression then relates this parameter to the explanatory variables, rather than the count. The reason this is better than normal linear regression is to do with the errors. If our model is correct, and each student has their own $\lambda$, then for a given $\lambda$ we would expect a poisson distribution of counts around it - i.e. an asymmetric distribution. This means unusually high values are not as surprising as unusually low. Normal linear regression assumes normal errors around the mean, and hence equally weights them. This says that if a student has an expected number of awards of 1, it is just as likely for them to receive -2 awards as for them to receive 3 awards: this is clearly nonsense and what poisson is built to address. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/49198', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/20428/']} | jdg_73702 |
stackexchange | llm_judgeable_groundtruth_similarity | 512808 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The relation of being locally isometric for Riemannian manifolds is reflexive and transitive. Is it symmetric? Can you give me an example?
Now provide the response and nothing else.
| This depends on the precise definition of the relation "$M$ and $N$ are locally isometric". For the first two definitions that sprang to my mind, the answer is "no." If one defines "$M$ and $N$ are locally isometric if there exists a local isometry $f:M\to N$", then the relation is not symmetric. Consider, say, a closed complete hyperbolic manifold $M$. In particular, the projection map $\mathbb{H}^n\to M$ is a local isometry, but there is no local isometry $M\to \mathbb{H}^n$, for there is not even a local diffeomorphism $M\to\mathbb{H}^n$ (choose a reference point $r\in\mathbb{H}^n$ and consider $df$ at a point $p\in M$ where $d(f(p),r)$ is maximized). (This argument works for any closed complete Riemannian manifold with infinite-diameter universal cover.) If one defines "$M$ and $N$ are locally isometric if for any $m\in M$ there exists an $n\in N$ and neighborhoods $U_p\ni p$, $U_q\ni q$ such that $U_p$ is isometric to $U_q$", then the relation is also not symmetric. Daniel Fischer provides a counterexample in the comments. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/512808', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/78806/']} | jdg_73703 |
stackexchange | llm_judgeable_groundtruth_similarity | 12029524 |
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 change my website over from the default /year/month/day/post_title permalinks, to a simple /post_title/ link, however, when changing it, all of my older links are broken. I've read a site on how to do it on Apache with .htaccess, but need some help on figuring out how to make it work with nginx's location instead of mod_rewrite. This is the site that details how to do it on Apache http://www.rickbeckman.org/how-to-update-your-wordpress-permalinks-without-causing-link-rot/ And I tried using this htaccess to nginx converter http://winginx.com/htaccess however, the regex is probably causing a problem and I get this error when starting nginx [emerg]: unknown directive "4}/[0-9]" in /usr/local/nginx/sites-enabled/website.com:19 And this is my configuration file server { listen 80; server_name website.com; rewrite ^/(.*) http://www.website.com/$1 permanent; } server { listen 80; server_name www.website.com; error_log /home/user/public_html/website.com/log/error.log; client_max_body_size 10M; client_body_buffer_size 128k; location / { root /home/user/public_html/website.com/public/; index index.php index.html; try_files $uri $uri/ /index.php; } location ~ ^/[0-9]{4}/[0-9]{2}/[0-9]{2}/([a-z0-9\-/]+) { rewrite ^(.*)$ http://website.com/$1 permanent; } # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 location ~ \.php$ { fastcgi_read_timeout 120; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include /usr/local/nginx/conf/fastcgi_params; fastcgi_param SCRIPT_FILENAME /home/user/public_html/website.com/public/$fastcgi_script_name; } } Would anyone know how to fix it? Thanks.
Now provide the response and nothing else.
| Yes, the problem is with encoding. When you wait for the whole transfer to finish body is coerced to a string by default. You can tell request to give you a Buffer instead by setting the encoding option to null : var fileUrl = "http://twitter.github.com/bootstrap/assets/bootstrap.zip";var output = "bootstrap.zip";request({url: fileUrl, encoding: null}, function(err, resp, body) { if(err) throw err; fs.writeFile(output, body, function(err) { console.log("file written!"); });}); Another more elegant solution is to use pipe() to point the response to a file writable stream: request('http://twitter.github.com/bootstrap/assets/bootstrap.zip') .pipe(fs.createWriteStream('bootstrap.zip')) .on('close', function () { console.log('File written!'); }); A one liner always wins :) pipe() returns the destination stream (the WriteStream in this case), so you can listen to its close event to get notified when the file was written. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12029524', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1610417/']} | jdg_73704 |
stackexchange | llm_judgeable_groundtruth_similarity | 10939807 |
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 extending an existing library (lets call it Lib ) that I cannot modify directly. Is there any way to make some methods from Lib private so that they cannot be accessed outside of subclasses? For example if I have: class A extends Lib { def fun(i: int) = someLibFunction(i) //someLibFunction is inherited from Lib} how can I make someLibFunction private in A, despite it being public/protected in Lib?
Now provide the response and nothing else.
| This would break the basic foundation of object-oriented programming - that you can use subclass everywhere where super class was expected (polymorphism). If it was allowed to narrow down the visibility of a method (e.g. from public to private ) client code receiving an instance of Lib would not be allowed to receive A extends Lib . Client code expects someLibFunction() to be accessible and subclass cannot change that contract. That being said neither Scala nor any object-oriented language is allowed to narrow down the visibility of any method when subclassing. Note that widening the visibility (e.g. from protected to public is perfectly possible). In other words you are not extending an existing API (library). You are creating a completely different API (library) that has a different contract. Final example: you have a Vehicle class that has a capacity() and can drive() . Car can extend Vehicle by adding some new capabilities like refuel() . But Container cannot extend Vehicle and hide driving capability. Container can contain Vehicle (or vice-versa), also Container and Vehicle might have common parent like CanHoldCargo . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10939807', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/735168/']} | jdg_73705 |
stackexchange | llm_judgeable_groundtruth_similarity | 18626126 |
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 following observation arose as I was following this question about char[] and char* differences. #include <iostream>typedef char ar[];typedef char* pr;void f2(ar x, pr y){ std::cout << std::is_same<decltype(x), decltype(y)>::value << '\n'; std::cout << std::is_same<ar, pr>::value << '\n';}int main(){ char data[] = "data"; char *ptr = data; f2(data,ptr); return 0;} Output ( on Apple LLVM version 4.2 (clang-425.0.28) ) 10 Why do these report as different types, but not different decltype() s ? My suspicion is they are in fact different types due to their typedef declarations, but then why are variables reported as the same type?
Now provide the response and nothing else.
| In C++, as in C, a parameter that's declared to be of array type is adjusted (at compile time) to be of pointer type, specifically a pointer to the array's element type. This happens whether the array type is specified directly or via a typedef (remember that a typedef doesn't create a new type, just an alias for an existing type). So this: typedef char ar[];typedef char* pr;void f2(ar x, pr y){ // ...} really means: void f2(char* x, char* y){ // ...} Another rule, also shared by C and C++, is that an expression of array type is, in most but not all contexts, implicitly converted to a pointer to the first element of the array object. Which means that if you define an array object: char arr[10]; you can use the name of that object as an argument to a function that takes a char* parameter (which loses the bounds information). In C, the cases where this implicit conversion doesn't happen are: When the array expression is the operand of sizeof ( sizeof arr yields the size of the array, not the size of a pointer); When the array expression is the operand of unary & ( &arr is a pointer-to-array, not a pointer-to-pointer); and When the array expression is a string literal used to initialize an object of array type ( char s[] = "hello"; initializes s as an array, not as a pointer). None of these cases (or the other cases that occur in C++) appear in your program, so your call: f2(data,ptr); passes two pointer values of type char* to f2 . Inside f2 , the parameter objects x and y are both of type char* , so std::is_same<decltype(x), decltype(y)>::value is true. But the types ar and pr are distinct. ar is an incomplete array type char[] , and pr is the pointer type char* . Which explains your program's output. The weirdness happens because the parameter x , which you defined with the array type ar , is really of type char* , which is the same type as pr . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18626126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1322972/']} | jdg_73706 |
stackexchange | llm_judgeable_groundtruth_similarity | 576708 |
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:
Does there exist a continuous function such that f(x) is rational for every irrational x, and f(x) is irrational for every rational x?I can think of examples where this would be true, but I'm having a lot of trouble with the continuity.
Now provide the response and nothing else.
| There is no such a function. Your hypothesis imply that the image of $f$ is countable which is impossible for any non-constant continuous function from $\mathbb R$ into $\mathbb R$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/576708', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/110592/']} | jdg_73707 |
stackexchange | llm_judgeable_groundtruth_similarity | 326061 |
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 $\mathbf G$ be a connected reductive group over $\mathbb R$ , and let $G = \mathbf G(\mathbb R)$ . Then $G$ is not necessarily connected as a Lie group, e.g. $\mathbf G = \operatorname{GL}_n$ . Does $G$ have finitely many connected components? I heard it's true when $\mathbf G$ is semisimple, by a theorem of Cartan.
Now provide the response and nothing else.
| For every $\mathbb{R}$ -scheme $X$ of finite type, $\pi_0(X(\mathbb{R}))$ is finite. This follows e.g. from Theorem 2.3.6 in Bochnak, Coste, Roy, Real Algebraic Geometry (basic structure theorem for semi-algebraic sets). | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/326061', 'https://mathoverflow.net', 'https://mathoverflow.net/users/38145/']} | jdg_73708 |
stackexchange | llm_judgeable_groundtruth_similarity | 12255554 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to get it so that 1.7.0 comes after 1.7.0.rc0 but before 1.8.0, as it should if you were sorting versions. I thought the whole point of LooseVersion was that it handled the sorting and comparison of this kind of thing correctly. >>> from distutils.version import LooseVersion>>> versions = ["1.7.0", "1.7.0.rc0", "1.8.0"]>>> lv = [LooseVersion(v) for v in versions]>>> sorted(lv, reverse=True)[LooseVersion ('1.8.0'), LooseVersion ('1.7.0.rc0'), LooseVersion ('1.7.0')]
Now provide the response and nothing else.
| MAJOR EDIT: old answer was too unpythonic. Here are two prettier solutions. So, I currently see about three ways of achieving the wished ordering, releases candidates "rc" before actual releases. my old, imperative-style ordering use "b" instead of "rc" in order to use StrictVersion , from the same package extend the Version class to add support for arbitrary tags and tag ordering 1. Old, imperative-style ordering from distutils.version import LooseVersionversions = ["1.7.0", "1.7.0.rc0", "1.8.0"]lv = [LooseVersion(v) for v in versions]lv.sort()sorted_rc = [v.vstring for v in lv]import rep = re.compile('rc\\d+$')i = 0# skip the first RCswhile i + 1 < len(sorted_rc): m = p.search(sorted_rc[i]) if m: i += 1 else: breakwhile i + 1 < len(sorted_rc): tmp = sorted_rc[i] m = p.search(sorted_rc[i+1]) if m and sorted_rc[i+1].startswith(tmp): sorted_rc[i] = sorted_rc[i+1] sorted_rc[i+1] = tmp i += 1 with this I get: ['1.7.0rc0', '1.7.0', '1.11.0'] 2. Use "b" instead of "rc" The package distutils.version also has another class, StrictVersion which does the job, if your 1.7.0.rc0 is allowed to be written as 1.7.0a0 or 1.7.0b0 noting alpha or beta releases. That is: from distutils.version import StrictVersionversions = ["1.7.0", "1.7.0b0", "1.11.0"]sorted(versions, key=StrictVersion) This gives: ['1.7.0b0', '1.7.0', '1.11.0'] Translation from one form to another can be done using the re module. 3. Extend the Version class The obvious problem of the previous solution is the lack of flexibility of StrictVersion . Altering the version_re class attribute to use rc instead of a or b , even if it accepts 1.7.1rc0 , still prints it as 1.7.1r0 (as of python 2.7.3). We can get it right by implementing our own custom version class. This can be done like this, with some unit tests to ensure correctness at least in some cases: #!/usr/bin/python# file: version2.pyfrom distutils import versionimport reimport [email protected]_orderingclass NumberedVersion(version.Version): """ A more flexible implementation of distutils.version.StrictVersion This implementation allows to specify: - an arbitrary number of version numbers: not only '1.2.3' , but also '1.2.3.4.5' - the separator between version numbers: '1-2-3' is allowed when '-' is specified as separator - an arbitrary ordering of pre-release tags: 1.1alpha3 < 1.1beta2 < 1.1rc1 < 1.1 when ["alpha", "beta", "rc"] is specified as pre-release tag list """ def __init__(self, vstring=None, sep='.', prerel_tags=('a', 'b')): version.Version.__init__(self) # super() is better here, but Version is an old-style class self.sep = sep self.prerel_tags = dict(zip(prerel_tags, xrange(len(prerel_tags)))) self.version_re = self._compile_pattern(sep, self.prerel_tags.keys()) self.sep_re = re.compile(re.escape(sep)) if vstring: self.parse(vstring) _re_prerel_tag = 'rel_tag' _re_prerel_num = 'tag_num' def _compile_pattern(self, sep, prerel_tags): sep = re.escape(sep) tags = '|'.join(re.escape(tag) for tag in prerel_tags) if tags: release_re = '(?:(?P<{tn}>{tags})(?P<{nn}>\d+))?'\ .format(tags=tags, tn=self._re_prerel_tag, nn=self._re_prerel_num) else: release_re = '' return re.compile(r'^(\d+)(?:{sep}(\d+))*{rel}$'\ .format(sep=sep, rel=release_re)) def parse(self, vstring): m = self.version_re.match(vstring) if not m: raise ValueError("invalid version number '{}'".format(vstring)) tag = m.group(self._re_prerel_tag) tag_num = m.group(self._re_prerel_num) if tag is not None and tag_num is not None: self.prerelease = (tag, int(tag_num)) vnum_string = vstring[:-(len(tag) + len(tag_num))] else: self.prerelease = None vnum_string = vstring self.version = tuple(map(int, self.sep_re.split(vnum_string))) def __repr__(self): return "{cls} ('{vstring}', '{sep}', {prerel_tags})"\ .format(cls=self.__class__.__name__, vstring=str(self), sep=self.sep, prerel_tags = list(self.prerel_tags.keys())) def __str__(self): s = self.sep.join(map(str,self.version)) if self.prerelease: return s + "{}{}".format(*self.prerelease) else: return s def __lt__(self, other): """ Fails when the separator is not the same or when the pre-release tags are not the same or do not respect the same order. """ # TODO deal with trailing zeroes: e.g. "1.2.0" == "1.2" if self.prerel_tags != other.prerel_tags or self.sep != other.sep: raise ValueError("Unable to compare: instances have different" " structures") if self.version == other.version and self.prerelease is not None and\ other.prerelease is not None: tag_index = self.prerel_tags[self.prerelease[0]] other_index = self.prerel_tags[other.prerelease[0]] if tag_index == other_index: return self.prerelease[1] < other.prerelease[1] return tag_index < other_index elif self.version == other.version: return self.prerelease is not None and other.prerelease is None return self.version < other.version def __eq__(self, other): tag_index = self.prerel_tags[self.prerelease[0]] other_index = other.prerel_tags[other.prerelease[0]] return self.prerel_tags == other.prerel_tags and self.sep == other.sep\ and self.version == other.version and tag_index == other_index and\ self.prerelease[1] == other.prerelease[1]import unittestclass TestNumberedVersion(unittest.TestCase): def setUp(self): self.v = NumberedVersion() def test_compile_pattern(self): p = self.v._compile_pattern('.', ['a', 'b']) tests = {'1.2.3': True, '1a0': True, '1': True, '1.2.3.4a5': True, 'b': False, '1c0': False, ' 1': False, '': False} for test, result in tests.iteritems(): self.assertEqual(result, p.match(test) is not None, \ "test: {} result: {}".format(test, result)) def test_parse(self): tests = {"1.2.3.4a5": ((1, 2, 3, 4), ('a', 5))} for test, result in tests.iteritems(): self.v.parse(test) self.assertEqual(result, (self.v.version, self.v.prerelease)) def test_str(self): tests = (('1.2.3',), ('10-2-42rc12', '-', ['rc'])) for t in tests: self.assertEqual(t[0], str(NumberedVersion(*t))) def test_repr(self): v = NumberedVersion('1,2,3rc4', ',', ['lol', 'rc']) expected = "NumberedVersion ('1,2,3rc4', ',', ['lol', 'rc'])" self.assertEqual(expected, repr(v)) def test_order(self): test = ["1.7.0", "1.7.0rc0", "1.11.0"] expected = ['1.7.0rc0', '1.7.0', '1.11.0'] versions = [NumberedVersion(v, '.', ['rc']) for v in test] self.assertEqual(expected, list(map(str,sorted(versions))))if __name__ == '__main__': unittest.main() So, it can be used like this: import version2versions = ["1.7.0", "1.7.0rc2", "1.7.0rc1", "1.7.1", "1.11.0"]sorted(versions, key=lambda v: version2.NumberedVersion(v, '.', ['rc'])) output: ['1.7.0rc1', '1.7.0rc2', '1.7.0', '1.7.1', '1.11.0'] So, in conclusion, use python's included batteries or roll out your own. About this implementation: it could be improved by dealing with the trailing zeroes in the releases, and memoize the compilation of the regular expressions. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12255554', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/216314/']} | jdg_73709 |
stackexchange | llm_judgeable_groundtruth_similarity | 543350 |
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 $k$ be an algebraically closed field. Nullstellensatz states that the maximal ideals of the polynomial ring $R=k[X_1,\dots,X_n]$ are precisely those of the form $\langle X_1-a_1,\dots,X_n-a_n\rangle$, with $(a_1,\dots,a_n)\in k^n$. What if we are working with infinitely many variables, say $\{X_i\}_{i\in I}$, being $I$ an infinite set? Again, the ideals of the form $\bigl\langle\{X_i-a_i: i\in I\}\bigr\rangle$, with $(a_i)_{i\in I}\subseteq k$ are maximal (even if $k$ is not algebraically closed), but what about the converse?
Now provide the response and nothing else.
| Let $k$ be a field and let $K$ be an extension of $k$ of degree larger than $1$. Let $R=k[X_i, i\in K]$ be a polynomial ring with one variable per element of $K$. There is a $k$-linear ring homomorphism $\phi:R\to K$ which maps $X_i$ to $i$ for all $i\in K$, and it is surjective. It follows that the kernel of $\phi$ is maximal. Clearly, it is not of the form you mentioned: indeed, the quotient of $R$ by all ideals of that form is $1$-dimensional as a $k$-algebra. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/543350', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/52816/']} | jdg_73710 |
stackexchange | llm_judgeable_groundtruth_similarity | 5858250 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So, I'm trying to initialize a DatagramSocket in a constructor, and I want this field to be final , but my compiler (i.e. Eclipse) is giving me the following error: The blank final field datagramSocket may not have been initialized This is understandable. Here's a code snippet: public class Foo { private final int DEFAULT_UDPLISTENPORT = 49400; private final DatagramSocket datagramSocket; public Foo() { synchronized(this) { try { datagramSocket = new DatagramSocket(DEFAULT_UDPLISTENPORT); } catch (SocketException e) { // Log error logger.error("Trouble opening UDP port: ", e); } } } } Now, I know there's a way to bypass this, but it requires me to create a temporary variable. Here's a code snippet: public class Foo { private final int DEFAULT_UDPLISTENPORT = 49400; private final DatagramSocket datagramSocket; public Foo() { synchronized(this) { DatagramSocket tempSocket = null; try { tempSocket = new DatagramSocket(DEFAULT_UDPLISTENPORT); } catch (SocketException e) { // Log error logger.error("Trouble opening UDP port: ", e); } datagramSocket = tempSocket; } } } So, I suppose my question is: is there a more elegant way of doing this, or is this something that I'll just have to live with if I want that field to be final ? EDIT: For those of you who are interested, here's the solution I came up with from your recommendations: public class Foo{ private static final Foo INSTANCE; static { try { INSTANCE = new Foo(); } catch (SocketException e) { throw new ExceptionInInitializerError(e); } } private final int DEFAULT_UDPLISTENPORT = 49400; private final DatagramSocket datagramSocket; public Foo() throws SocketException { synchronized (this) { datagramSocket = new DatagramSocket(DEFAULT_UDPLISTENPORT); } } public static Foo getInstance() { return INSTANCE; }} Please, let me know if this is correct, or if you have any other suggestions. I appreciate the help!
Now provide the response and nothing else.
| Yes, after catching SocketException wrap it in runtime exception and rethrow it. Since your variable is final and you have encountered error during object initialization, your object is probably in incorrect state and you are guaranteed that it will remain as such. Logging the exception isn't probably enough for exception handling and hiding SocketException hides the fact that the object is invalid and allows you to continue, risking NullPointerException or others. If you really want to create such a faulty object, your suggestion is fine, just use another method: public Foo() { synchronized(this) { datagramSocket = createSocket(); } }private DatagramSocket createSocket() { try { return new DatagramSocket(DEFAULT_UDPLISTENPORT); } catch (SocketException e) { logger.error("Trouble opening UDP port: ", e); return null; //I beg you, don't return null here... } } As for returning null : consider subclassing DatagramSocket and creating: NoOpDatagramSocket NullDatagramSocket BrokenDatagramSocket MemoryDatagramSocket ...you get the idea :-) P.S.: Why the synchronized ? P.S.2: The comment // Log error right before logger.error() isn't adding much value, don't you think? | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5858250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/584862/']} | jdg_73711 |
stackexchange | llm_judgeable_groundtruth_similarity | 488163 |
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 want to understand the definition of the determinant of a $n\times n$ real matrix $A$ as the signed volume of the image of the unit cube $C'$ under the linear transformation given by $A$, i.e. $x\to Ax$. However I am failing to make sense of the words signed volume . What will be the precise definition of this? Will it be the $\int\int...\int dx_1dx_2\cdots dx_n$ over the image $C'$. I think this is an overcomplicated way to define the signed volume. Can someone suggest another way? Thanks
Now provide the response and nothing else.
| This is something traditional linear algebra doesn't handle really well because it's designed to handle only vectors, scalars, and linear maps (sometimes represented by matrices) that act on vectors. The reason you're having so much trouble understanding what a "signed volume" could be is simple: signed volumes don't belong as algebraic elements in the same vector space you're used to dealing with, so it's unclear what kind of objects these are and how to describe them. One solution to this problem is to use the geometric algebra . The geometric algebra has as part of it a wedge product of vectors that produces not another vector, but something called a 2-vector, or a bivector . This would be written $$C = a \wedge b$$ where $C$ is a 2-vector and $a$, $b$ are vectors. The space of 2-vectors is in itself a vector space. 2-vectors can be added and subtracted or multiplied by scalars. Geometric interpretation is critical here. Think of ordinary vectors ("1-vectors") as weighted directions . Each vector (except the 0 vector) has an associated unit vector (a "direction") and a unit magnitude (a "weight"). Importantly, two vectors that are scalar multiples of each other could be said to have the same direction but different weights. Another way to think about it is to say that each unit vector represents a 1d subspace through $\mathbb R^n$. In the geometric algebra, the vector space of 2-vectors also has unit-2-vectors. We interpret the unit-2-vectors as planes . Thus, 2-vectors are weighted planes . Each 2-vector represents an planar (or two-dimensional) subspace of $\mathbb R^n$. A 2-vector and a 1-vector can be wedged to form a 3-vector, and this is interpreted as a "weighted" or "oriented volume". In $\mathbb R^3$, this is a vector space consisting of a single unit 3-vector and all its scalar multiples. Again, I refer to the idea that each unit $k$-vector represents a subspace. In this case, the unit 3-vector represents a subspace of $\mathbb R^3$ that is, well, $\mathbb R^3$ itself. When we're in $\mathbb R^n$ instead, the 3-vector represents 3d subspace, but there are many such subspaces that aren't scalar multiples of each other. However, the $n$-vector has the same quality of all $n$-vectors being scalar multiples of one another, making it suitable to describe a generalized notion of volume. Now, perhaps the real question is, what is the difference between a unit 3-vector and its additive inverse? That is, what does it mean for a subspace to be "oriented"? To answer this question, I return to the case of 1-vectors, or ordinary vectors. A vector $v$ and its additive inverse $-v$ could be thought to point in opposite directions. This is easy to visualize, and shouldn't give you any problems. Still, I want to point out that there is some notion of orientation already present even in this case. Instead of merely saying $v$ and $-v$ are scalar multiples of each other, we can say that $v$ represents a 1d subspace one particular way, and $-v$ represents the same subspace but oriented in an opposite way. (Any given subspace usually only admits two orientations in this manner.) What about a 2-vector? Usually, when we talk about planes, we cheat and talk about those planes' normal vectors instead, so in some ways, people are already familiar with the idea of oriented planes. Still, it helps to imagine this intrinsically, without talking about normals. I usually imagine a sheet of paper with a counterclockwise spiral on it. The spiral defines the orientation of the sheet. Another sheet of paper that describes the same subspace could instead have spirals going clockwise. (Clockwise and counterclockwise: again, only two orientations.) What about a 3-vector, the "oriented volume" as it were? This is usually done using hands. You've heard of the right-hand rule, I'm sure. You can choose a 3-vector built from a set of basis vectors according to the right-hand rule, or you can choose one built from a "left-hand rule." The two represent the same subspace (all of $\mathbb R^3$), but they are nevertheless additive inverses in this system, and we have already identified such inverses for the last two cases as denoting opposite orientations. (Right and left-hand rules. Again, only two orientations for a given subspace.) In a general $\mathbb R^n$, there are many more such $k$-vectors, but the $n$-vector always has the quality of describing the subspace that is the whole space itself. So far, I've shown how subspaces can be represented algebraically using the geometric algebra (as well as the exterior algebra). They can also be using matrices whose kernels are those subspace, but those matrices do not capture the important idea of orientation . Under the geometric and exterior algebras, algebraic elements describing subspaces also carry information about those subspaces' orientations. Each subspace has only two orientations. Now let's talk about linear algebra and the action of linear operators ("square matrices") on $k$-vectors. There is a natural extension of a linear operator to act on these oriented subspaces. This is, in GA parlance, called "outermorphism" (after the wedge also being called an "outer" product). Define the action of a linear map $\underline T$ on a 2-vector $C = a \wedge b)$ as $$\underline T(C) = \underline T(a \wedge b) \equiv \underline T(a) \wedge \underline T(b)$$ That's fancy math for "$\underline T$ acts on each individual vector and then the two images are wedged". This gives a meaningful way to talk about "matrices" acting on 2-vectors. (It's for this reason that GA users seldom talk about "matrices." The matrix expression is actually different when we talk about $\underline T$ acting on the space of 2-vectors. Having to compute new matrices for each kind of $k$-vector that might be acted upon is clumsy, and the algebra usually allows for more compact expressions of reflections, rotations, and other common operations.) As you might expect, this extends to n-vectors also. Let $i = a_1 \wedge a_2 \wedge \ldots \wedge a_n$ be an $n$-vector, so that $$\underline T(i) \equiv \underline T(a_1) \wedge \underline T(a_2) \wedge \ldots \wedge \underline T(a_n)$$ Remember, all n-vectors in $n$ dimensions are multiples of the unit n-vector. Or, we can just as easily say all n-vectors are multiples of $i$. So we can write $$\underline T(i) = \alpha i$$ for some scalar $\alpha$. $\alpha$ is the determinant . All the determinant is really saying is that any $n$-vector that is put into this linear operator comes out as a scalar multiple of itself. It could be reversed in orientation. It could be scaled up or down by some factor. The determinant is just an eigenvalue. The "eigenvector" is not a vector but a n-vector. In summary, I have described how geometric algebra can represent subspaces in some vector space with generalized vectors called $k$-vectors. I've shown how such objects are built. I've shown that these objects have orientation associated with them. I have also described how linear operators can be made to act on these $k$-vectors as a natural, logical extension of how they act on ordinary vectors. The determinant of a linear operator is then just an eigenvalue, with "eigenvector" being the (unit) $n$-vector of the space. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/488163', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/10575/']} | jdg_73712 |
stackexchange | llm_judgeable_groundtruth_similarity | 40849152 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
List<String> checkLength(List<String> input) { if (input.length > 6) { var tempOutput = input; while (tempOutput.length > 6) { var difference = (tempOutput.length/6).round() + 1; for (int i = 0; i < tempOutput.length - 1; i + difference) { tempOutput.removeAt(i); //Removing the value from the list } } return tempOutput; //Return Updated list } else { return input; }} I am trying to delete something out of a temporary list. Why does it not work? I do not see how it is fixed, in other problems I have solved, I used a similar approach and it worked (Even identical nearly) Please note I am kind of new to Dart, so please forgive me this sort of question, but I couldn't figure out the solution. Find the Code available in the Dart Link Code in Dart
Now provide the response and nothing else.
| You can ensure that tempOutput is not a fixed-length list by initializing it as var tempOutput = new List<String>.from(input); thereby declaring tempOutput to be a mutable copy of input . FYI it also looks like you have another bug in your program since you are doing i + difference in your for-loop update step but I think you want i += difference . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40849152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6815822/']} | jdg_73713 |
stackexchange | llm_judgeable_groundtruth_similarity | 413438 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
The quantum set-up has many settings, so let's fix some definitions. I will be taking the Hilbert space approach with a minor modification that I will make explicit. We begin with a Hilbert space $\mathcal{H}$ , and let $\mathcal{L}(\mathcal{H})$ be the set of all of its projection operators to (closed, I guess? I will be focusing on the finite dimensional case anyway.) subspaces. In that case we define a quantum probability measure as any function $p:\mathcal{L}(\mathcal{H})\rightarrow \mathbb{R}$ satisfying: $\forall P\in\mathcal{L}(\mathcal{H}) \,\, p(P)\geq 0$ . $p(I)=1$ . For every countable set of mutually orthogonal projections $\{P_i\}_i$ we have additivity: $$p(\sum_i P_i)=\sum_ip(P_i).$$ Technical Note: The content of Gleason's Theorem is that if $dim(\mathcal{H})\geq 3$ then quantum probability measures are in 1-1 correspondence with so-called density operators. In most textbooks one would find the density operator as the definition of a "state". I feel that the density operator approach is much less intuitive, so I will go ahead and treat the non-equivalence between the two approaches in low dimension as a not-very-important oddity, and take the probability measure approach as primary. An observable, the quantum version of a random variable, is a choice of a an orthogonal decomposition of $\mathcal{H}$ as $\oplus_{i\in I}\mathcal{H}_i$ , and a choice of a real number for each $i\in I$ . (Usually in the literature it is said that it is a compact self-dual operator; those are of course equivalent by the spectral theorem. Sometimes is it assumed to be non-bounded, but that's crazy and I can't wrap my head around that so I'm not going to try right now.) I will focus on low dimensions to try to understand what all this means. 2 Dimensions Let $A$ and $B$ be observables, and let $A$ be $diag(a,b)$ in the orthonormal basis $u_1, u_2$ and $B$ be $diag(c,d)$ in the orthonormal basis $v_1, v_2$ . If $span(u_1)=span(v_1)$ then $span(u_2)=span(v_2)$ , and $p(P_{span(u_1)})=p(P_{span(v_1)})$ and $p(P_{span(u_2)})=p(P_{span(v_2)})$ . If $span(u_1)\neq span(v_1),span(v_2)$ , then you can choose $p$ so that $p(P_{span(u_1)})$ be anything you want, and $p(P_{span(v_1)})$ be anything you want. So essentially, the totality of the situations you can describe are classical. Either $A$ and $B$ are two independent coin flips with whatever Bernoulli parameter you want (and the Bernoulli parameter of one says nothing about the other), or it's a single coin flip that determines the value for both $A$ and $B$ . 3 Dimensions It seems to me, therefore, that if there is any hope to describe something non-classical it would be if the eigendecomposition of $A$ has a summand that intersects a summand of the eigendecomposition of $B$ non-trivially. To give an example, let's say that the standard basis is an eigenbasis for $A$ , and that the eigenbasis for $B$ is $u_1, u_2, e_3$ , where $span(u_1,u_2)=span(e_1,e_2)$ . It seems to me that the 3rd property of quantum probability measures only applies to determine that $p(P_{span(u_1)})+p(P_{span(u_2)})=p(P_{span(u_1,u_2)})=p(P_{span(v_1,v_2)})=p(P_{span(v_1)})+p(P_{span(v_2)})$ . In other words, I can describe this situation thusly. Flip a coin, it's heads with probability $p(P_{span(e_3)})$ . If heads, great. If tails, flip two more coins; one with Bernoulli parameter $p(P_{span(u_1)})$ and the other with Bernoulli parameter $p(P_{span(v_1)})$ . This can be described classically. The possible situations are: 1st coin heads (with probability $p(Proj_{span(e_3)})$ ) 1st coin tails; 2nd coin heads; 3rd coin heads (with probability $p(Proj_{span(u_1)})p(Proj_{span(v_1)})$ ) 1st coin tails; 2nd coin heads; 3rd coin tails (with probability $p(Proj_{span(u_1)})(1-p(Proj_{span(v_1)}))$ ) 1st coin tails; 2nd coin tails; 3rd coin heads (with probability $(1-p(Proj_{span(u_1)}))p(Proj_{span(v_1)})$ ) 1st coin tails; 2nd coin tails; 3rd coin tails (with probability $(1-p(Proj_{span(u_1)}))(1-p(Proj_{span(v_1)}))$ ) Main Question Given the definitions above and the examples I have presented: in what sense is quantum probability more expressive than classical probability? Am I misunderstanding something? And how does all of this relate to Bell's Theorem if at all?
Now provide the response and nothing else.
| No direct answer. Only "hidden variables in quantum logic" (NO physics needed). Quite long; subdivisions hopefully help. Disclaimer This expands what I said about hidden variables in (more general) lectures in Bologna, 2010 My study of this subject goes back to 1992 - 1993 with two later complements: 1998, approximations of arbitrary theories with theories admitting noncontextual hidden variables; 2010, (nonexistence of) noncontextual embedding in von Neumann's modular quantum logic. So I have almost no idea about how quantum logicians look at this subject now. You might consider (the already posted answer and): Svozil , Dalla Chiara & Giuntini or the Handbook of Quantum Logic and Quantum Structures . Philosophers might look at this But above all the writings of Rédei , because they go back directly to von Neumann, including specific difficulties of noncommutative probability. General setting for a quantum logic : $L$ structured by a partial binary operation $\oplus$ (commutative, associative, with 0). Examples: $L(H)$ (closed subspaces of an Hilbert space, with sum of orthogonal subspaces). Boolean algebras (with disjoint union). Self-adjoint idempotents ( projections : $e^2=e=e^*$ ) in a ring with involution ( $e\oplus f=e+f$ when $ef=0=fe$ ), the real interval $[0,1]$ with ordinary sum. In all examples above the natural pre-order ( $x\geq y$ iff $\exists z:x=y\oplus z$ ) is a partial order since $x\oplus y=x\Rightarrow y=0$ . Even more the $z$ in $x=y\oplus z$ is unique when it exists; one writes $z=x\ominus y$ ( orthocomplement of $y$ in $x\geq y$ , or relative negation; $1\ominus x$ is the orthocomplement $x^\perp$ , or negation, of $x$ ). $x\perp y$ means " $x\oplus y$ exists" ( orthogonality relation; mutually exclusive propositions : one is contained in the negation of the other). Homomorphisms $f$ preserve $\oplus$ ( $x\oplus y=z\Rightarrow f(x)\oplus f(y)=f(z)$ ); states (a.k.a. probability measures ) are homomorphisms with values in the real interval $[0,1]$ with ordinary sum. $\sigma$ -homomorphisms preserve joins (for the partial order) of increasing sequences, i.e. preserve countable $\oplus$ (countable additivity). Complete additivity means preservation ofall existing joins of directed families, hence of all existing (even uncountable) $\oplus$ . My preference is for finite additivity: the "no-go" theorems are stronger (not even an embedding preserving finite $\oplus$ ). Except the real interval, the above examples satisfy $x\perp x\Rightarrow x=0$ ( orthoalgebras ; "partial boolean algebras" are essentially the same thing for our purposes). Orthoalgebras where $\leq$ is a lattice order are the same thing as orthomodular lattices Gleason's theorem (1957) The original version was for the logic of "type I factors" (real or complex): The only countably additive probability measures on $L(H)$ for a separable Hilbert spaces $H$ are the well known ones (induced by bounded linear operators with trace 1). Extension to the non-separable cases: in the natural way, requiring complete additivity.(These are the normal states, which then are exactly the classical mixture i.e. $\sigma$ -convex combination of normal pure states, which in turn are exactly the vectorial ones) in the set theoretic way: assume only countable additivity but also that there are no uncountable real-valued measurable cardinals, or that the dimension of the Hilbert space is less than the first of such cardinals.This really reduces to the natural case above. All this is quite standard and spelled out in many books, two examples: G. Kalmbach, Measures and Hilbert lattices (1986) ; A. Dvurecenskij, Gleason's Theorem and its Applications (1993) Desired generalization: the (completely) additive probability measures on the orthoalgebra of projections uniquely extend to (normal) states on thealgebra of observables. In this form the theorem has been generalized to (real or complex) W $^*$ -algebras with no abelian (type I $_1$ , boolean logic) or type I $_2$ (subdirect product of "spin factors", see below) components.A very good exposition (as anything I have seen from this author) is:S. Maeda, Probability measures on projections in von Neumann algebras, Reviews in Mathematical Physics 1 (1990), 235-290. Then it was also extended to the Jordan setting (JBW algebras), to states that need not be normal (finitely additive probability measures) on AW $^*$ algebras and their Jordan generalization, to signed, complex and more general measures, and so on. One example ,but Google Scholar can give the idea of how much work was done on the subject. When the theorem applies, one has a equivalence (extending von Neumann's one) between the orthoalgebra of projections, the Jordan ring of self adjoint operators, the enveloping associative ring with involution (if the Jordan ring has no exceptional component), the "effect algebra", and still other structures. This consequence of the theorem is possibly more important than the application to the hidden variables problem. How does Gleason's theorem rule out noncontextual hidden variables? The subject of hidden variables became formal part of mathematical quantum logic (as opposed to other kinds of formalizations) with N. Zierler and M. Schlessinger, Duke J. 32, 251 (1965) A non-contextual hidden variable theory for a logic $L$ is a $\oplus$ preserving embedding of $L$ in a boolean algebra $B$ . Since the beginning it was observed that the existence of an embedding as above is the same thing a as the existence of a "full" set $S$ of two-valued states (0 and 1, true and false) on $L$ ( full : many inequivalent definitions that became equivalent when each $s\in S$ is two-valued. One: if $\forall s\in S,s(x)+s(y)=s(z)$ then $x\oplus y=z$ ). This follows from the fact that the compact convex set of finitely additive states on a Boolean algebra has as extreme points exactly the two-valued measures. In general the pure states on $L$ are defined as the extremepoints of the convex set of states. Two valued states are always pure, not conversely. For the countably additive case one uses embeddings in $\sigma$ -algebras of sets, not more general countably complete boolean algebras.(There are some with no countably additive measures at all: "open subsets of the real line modulo meager sets"; this is essentially the same as the classical example of a commutative AW $^*$ -algebra which cannot be W $^*$ ).The correct abstract setting is that of measure algebras, see Fremlin's free volumes about measure theory Gleason's theorem excludes existence of two-valued states for $L(H)$ when $H$ has dimension at least three (or for the more general cases noted above), hence even the weakest kindof noncontextual hidden variables (with finite additivity) cannot exist. Side note: "modular" noncontextual hidden variables. Besides embeddings of a general $L$ in a distributive case (the noncontextual hidden variable problem above), one can consider orthoalgebra embedding of a general $L$ in a modular $L_f$ associated to a finite von Neumann algebra. For $L(H)$ of infinite dimension(and the other cases with a properly infinite component where Gleason's theorem has been generalized) this is not possible, even in the weakest sense of finitely additive embeddings. This is not explicitly noted in the literature, but follows easily for example from S. Pulmannova and A. Dvurechnskij, Sum logics, vector-valued measures and representations, Ann. H. Poincare A 53 (1990), 83 - 95 Cor. 3.3 pag. 91 implies that $\sigma$ -additive faithful representation of a non-modular $L$ (associated to a W $^*$ -algebra with no type I $_2$ component) into such a modular $L_f$ cannot exist since it must preserve also the lattice operations. To treat finitely additive faithful representations of $L(H)$ (for a infinite dimensional Hilbert space) in a modular $L_f$ , apply the above to finite dimensional initial intervals of $L(H)$ : these restrictions are $\sigma$ -additive, hence lattice representations; in particular they preserve equidimensionality (by its lattice definition). Hence a infinite orthogonal sequence of atoms in $L(H)$ must go to an infinite orthogonal sequence of nonzero and equidimensional elements, which cannot exist in a $L_f$ with a (separating set of) finite dimension function. Finally, such a $L(H)$ is a sublogic of any non-finite $L$ , since by (Loomis - Maeda) dimension theory one finds a homogeneous sequence of nonzero elements. So impossibility of modular embeddings for $L(H)$ assure the same for $L$ . This "modular no go theorem" shows that, in the same way as one cannot reduce the current quantumtheories to classical theories (but see below), one cannot reduce them to the particular (finite, modular) case that von Neumann wanted. Now look at the cases not covered by Gleason's theorem. The "abelian" part is the one which already has classical (boolean) logic, so nothing more has to be said for this question. Now the remaining I $_2$ part. It is not classical, but (unique among the W $^*$ algebras and and similar cases) it has non-contextual hidden variables. The so called "spin factors" (the matrix $2\times 2$ rings over the real, complex, quaternionic $*$ -ring, or the more general Jordan structures) have as logic $L$ a length 2 lattice: to an antichain of incomparable "points" one adds the bottom 0 and the top 1. This isa projective line , here moreover with orthocomplementation, i.e. a partition of the set of points in subsets of unordered pairs (one the orthocomplement of the other). The general type I $_2$ is subdirect product of these projective ortho-lines, so it suffices to see a boolean embedding for projective lines with orthocomplementation. Even more generally, for later use: noncontextual hidden variables exist for horizontal sums of boolean algebras . For a family $\{B_i\}_i$ of boolean algebras (or orthoalgebras), their horizontal sum is the following structure: the base set is the disjoint union of the $B_i$ , except thatall of the top elements $1_i\in B_i$ are identified (they give the same element $1$ of the horizontal sum), and the same for the bottom elements $0_i$ ; the partial binary operation $\oplus$ is given by the trivial cases( $0\oplus a=a=a\oplus 0$ ) and exactly the following cases: $a\oplus b=c$ iff $a,b,c$ are in the same $B_i$ for one $i$ , and this relation holds in $B_i$ . The horizontal sum of a family of othoalgebras or othomodular lattices is again such. So for boolean algebras $B_i$ one has an orthomodular lattice. Special case: the projective lines with orthocomplementationare exactly such horizontal sums with each $B_i$ being a four element boolean algebra (two nontrivial propositions, one the negation of the other). To see that a horizontal sum of boolean algebras has noncontextual hidden variables, one replaces the horizontal sum with the tensor product of the Boolean algebras (i.e. the topological direct product of their Stone spaces);for the embedding, a nontrivial proposition $a\in B_i$ goes to the proposition $a\otimes(\otimes_{j\neq i}1_j)$ (using Stone spaces $X_j$ of the $B_j$ : a subset $A\subseteq X_i$ goes to $A\times(\prod_{j\neq i}X_j)$ ). [This is the "finitely additive" case; the "countably additive case" ( $\sigma$ -algebras of sets) and the "completely additive case" (measure algebras) are analogue] " Intuitive picture ": if $B_1$ is a logic of propositions referring to something happening in this world, and $B_2$ is instead referring to something happening in a far away galaxy,you take the horizontal sum when you say "I cannot test together something happening here and something happening there" (so the only propositions are the two trivial ones and the onesfor the two cases separately), but you take the boolean tensor product when you say "in principle one can consider also propositions of the form [ $a$ happens here and $b$ happens there] and the boolean algebra they generate". There are two interesting consequences of the above easy noncontextual hidden variable embedding for horizontal sums of boolean algebras. 1 each theory has contextual hidden variables . Take any $L$ (with at least four elements i.e. one non trivial proposition), and a collection of boolean subalgebras $B_i$ that covers $L$ . Three obvious examples of such coverings: (i) the collection of all four element boolean subalgebras (i.e. one takes a nontrivial proposition, its negation, and the two trivial proposition); (ii) the collection of all finite boolean subalgebras; (iii) the collection of all maximal boolean subalgebras. Since already (i) covers $L$ , also the larger collection (ii) covers, and then also (iii) covers(each Boolean subalgebras extends to a maximal one). Since a observable can be identified with its spectral resolution (i.e. the boolean algebra of propositions referring to measurements of that observable, like:is the observed measure in this set of real numbers?), one can consider boolean subalgebras as ideal observables (with two [ideal or real] observables being compatible when there is a ideal observable common extension of both)and having a covering intuitively means that a sufficient set of observables has been singled out. Now replace $L$ with the horizontal sum of the $B_i$ , and then take the non-contextual hidden variable theory as above for the horizontal sum.This gives a " contextual hidden variable theory " for the original $L$ . [When the $B_i$ are the maximal boolean subalgebras of $L$ , this is a reformulation of Gudder's universal contextual hidden variable theory for $L$ .S. P. Gudder, On hidden-variable theories, Journal of Mathematical Physics 11, 431-436 (1970).He considered only the countable additive theory (as it is customary),but nothing changes for the other two points of view. And yes, "universal" means that one has a categorical universal property to abstractly define up a unique isomorphism such a contextual embedding among the other possible ones] What does mean " contextual "? It means that since incompatible observables cannot be tested together, when a proposition $a\in L$ belongs to an (ideal) observable $B_i$ and also to a (different, possibly incompatible) observable $B_j$ ,we "split" $a$ : it is no more a single proposition $a$ , but two distinct propositions $a_i$ (to be treated in the context of the observable $B_i$ ) and $a_j$ . When the $B_i$ are the maximal ideal observables you are splittingeach $a$ in all possible largest ideally experimentable contexts (every experiment tests only a boolean algebra of propositions). NB: this shows that the heart of the matter is a family $\{B_i\}_i$ of Boolean algebras ( $i$ are indexes for the [ideal] observables, $B_i$ is the boolean algebra of propositions about $i$ ),and a set $S$ of states $s$ with a function that maps each pair $(s,i)$ to a (finitely additive, or more) probability measure $s_i$ on $B_i$ . One can start from a $L$ (with states) and obtain the preceding data,or one can start from the observables (with states) and recover $L$ (with states) as explained below. [This is not a equivalence, only an adjoint pair of constructions; one can disregard this not being an equivalence for reasons I have written about more generally elsewhere]. NB: This is for "sharp" quantum logics; for "unsharp" logics (where orthoalgebras are generalized to effect algebras)one uses MV-algebras in place of Boolean algebras. 2 any "theory" with at most a continuum of propositions can be arbitrarily approximated with theories admitting noncontextual hidden variables. Note: in 1999 I found that in Austria some work was done (possibly by Svozil?), which for one side I considered very related to what follows, and for the other side it is completely different in method: much less general (the starting $L$ was inside a Hilbert space) but much more concrete; I cannot find it now. The approximation of $L$ , if I remember correctly, it was not by changing the states but by moving elements of $L$ inside the Hilbert space. The conclusion was much weaker, but interesting for the concreteness of the construction. Here a theory is a pair of sets (the set $L$ of propositions and the set $S$ of states) with the function $(s,x)\in S\times L\mapsto s(x)\in[0,1]$ that gives the probability $s(x)$ that the proposition $x$ turns out to be true when the experimental test is performed with the system in the state $s$ . The natural topology for the approximation of theories is the one of pointwise convergence in the set of such functions of two variables sincewe can practically perform only a finite amount of experiments. One usually identifies propositions $x,y$ that the states cannot separate ( $\forall s,s(x)=s(y)$ ) and dually one identifies states $s,s'$ that give the same results on propositions ( $\forall x,s(x)=s'(x)$ ).One can always add (if not already present) the two trivial propositions "always false" $0_L$ ( $\forall s,s(0_L)=0$ ) and "always true" $1_L$ ( $\forall s,s(1_L)=1$ ).One has a natural orthoalgebra structure on the set of (identified as above) propositions, defined by: $x\oplus y=z$ iff $\forall s,s(x)+s(y)=s(z)$ . There might be other compatible orthoalgebra structures(i.e. structures that make every $s$ a finitely additive probability measure), but this is the minimal (and natural) orthoalgebra structure on $L$ compatible with the states. [And yes, in the usual caseslike the ones where Gleason applies this"intrinsic logic orthoalgebra structure" on $L$ defined by the usually chosen set of states coincides with the usually taken orthoalgebra structure on $L$ ]. Now use this: the real numbers have a Hamel basis $\{h_i\}_i$ (of continuum cardinality) as vector space over the rationals; one takes (as always possible) the number $1$ as member of such a basis. Partition the set of nontrivial propositions using pairs (a proposition and its negation).To each pair $\{x,x^\perp\}$ associate injectively a $h_i\neq 1$ , and note that the rational multiples of $h_i$ can approximate arbitrarily well each $s(x),s(x^\perp)=1-s(x)$ . Taking such modifications ofthe probability function on $S\times L$ (the ones that for each pair $x,x^\perp$ the states take only values in the rational multiples of the corresponding $h_i$ ) one sees that the associated intrinsic logic is a horizontal sum of four element boolean algebras (i.e. a projective line with orthogonality), without changing identifications (as above) in the sets $L$ or $S$ ; using density of the rationals in the reals one sees thatthe family of such modifications arbitrarily approximates, for pointwise convergence, the initially given probability function. Conclusion : no finite set of experiments can ever rule out the possibility that physical reality is modeled by a intrinsic logic $L$ which is a orthocomplemented projective line,hence a theory with non-contextual hidden variables. The Bohm theory in 1952 was the first explicitly with this kind of $L$ . It was for someone a surprise because von Neumann's non go theorem rules out "non contextual hidden variables" also for bidimensional Hilbert spaces, but by assuming additivity not only on propositions but also for observables, and sums of non compatible observables are not covered with above definition of noncontextual hidden variables.So the Mackey problem was raised and Gleason's solutionruled out noncontextual hidden variables in dimension at least three using a really minimal and hopefully un-objectionable hypothesis. So it is mathematically proved that there is no way to convince a philosopher who wants noncontextual hidden variable theories "whatever it takes". On the other hand, the practical problem of finding a useful hidden variable theory (of Bohm type, i.e. starting from projective ortholines) is not solved by the above approximation procedure(absolutely ideal and using the axiom of choice; Hamel bases are not there in Soloway / Shelah models of ZF + DC). So quantum mechanics is done the way it is done simply because it gives good predictionof experimental results. Yes, you can prove that in principle you can use only classical-like theories, but NO, nothing will change practically used physical theoriesuntil someone gives a way to make experimental predictions at least as easily an accurately as the present method, whatever philosophical difficulties it might have. Return now to the noncontextual non-go theorem (for the $L$ where Gleason applies) to concretize it using finite substructures of $L$ . Kochen - Specker where the first (1967) to construct a finite sub-ortholattice $L$ (of a $L(H)$ for a finite dimensional Hilbert space $H$ ) where non-contextual hidden variables are impossible(even more, there are no two-valued probability measures on $L$ ). Better finite $L$ were found later (starting with A. Peres, Two simple proofs of the Kochen - Specker theorem, Journal of Physics A24, L175-L178 (1991) and then others, Google Scholar should find them). Along these lines, a finite $L$ like that and hypothetical two valued states on $L$ are also used in the "free will theorem" which for most people is quite possibly a better introduction to this subject. The smallest dimension of $H$ for such an $L$ is at least three, and in fact a three dimensional example is known. But the known four dimensional examples are better for the following reasons: they are easier to construct / describe, and they can be linked to the 1935 "EPR paradox" and the 1966 Bell's inequalities Four is the dimension of the tensor product of two to dimensional Hilbert spaces; that tensor product describes a system with two components (say, two particles completely determined,for the specific purposes of the experiment, by their spin. This is the reason for the name "spin factors"). Two ways (horizontal sum and boolean tensor product) were given aboveto describe a composite system (the boolean product only when the components have a boolean logic embedding); the Hilbert tensor space productis the orthodox way to go if the two components have orthodox quantum mechanical description (please disregard fermions and bosons, symmetric and anti-symmetric part of the tensor product), and we again want a orthodox description for the composite system (again, disregard the non unicity of C $^*$ tensor products in general: here we have two finite dimensional Hilbert spaces and hence no such problem: only an algebraic tensor product). Suppose that we are mainly interested in propositions $x$ that refer to a single subsystem, and that we are only interested in states $s$ which are "decomposable" (its representing vectors are decomposable $v_1\otimes v_2$ with $v_i\in H_i$ ). There are more states: the pure states are identified with the proportionality classes of its vectors; the vectors in a tensor product are the sums of decomposable vectors, but not all such vectors are decomposable, hence: there are states which are superposition of two decomposable states but are not decomposable. A decomposable state is naturally recovered by its restriction to both subsystems separately. How naturally? analogously to the recovering of a product of two probability measures on boolean algebras by the two component measures [note: probabilistic independence is natural reducibility to a direct product]; so here we are treating only the states of the composite system that are as decomposable as possible in the two components,disregarding the more complicated propositions and states that depend upon the "superpositions" available in quantum mechanics, and the propositions that are generated by logical operationson the propositions of the two subsystems). Abstracting form the specific case of the tensor product: one considers only some of the states and some of the propositions, in such a way that certain pairs (or larger sets) of propositionsto be considered are compatible (meaning that are contained in a boolean subalgebra in $L$ ) and other pairs (or larger sets) of propositions, even if not compatible in $L$ ,are to be treated as compatible because the chosen $s$ treats them independently. In that setting it is possible to derive certain inequalities relating linear combinations of $s(p(x,y,\dots))$ ( $s$ a state as above; $p$ a ortholattice polynomial in the propositions $x,y,\dots$ as above) involving an arbitrary but fixed $s$ , and various ortholattice polynomials.These are the famous Bell's inequalities (either essentially the original ones, or generalizations). If we consider all $s$ and all $x,y,\dots$ (instead of the more restricted one as above) we can derive other inequalities, less stringent than Bell's inequalities. In 1992 I saw a derivation of these inequalities in this setting,but now I cannot find it. However, pag. 4 of https://arxiv.org/abs/quant-ph/0207062 resembles what I remember to have read at the times.A summary, to see a concrete form of a Bell inequality: Fix a state $s$ . Define the distance (relative to $s$ ) of two propositions $A,B$ as $d(A, B) = s(A \vee B) - s(A \wedge B)$ . In the boolean setting this is the usual $s$ -measure of $(A\cup B)\setminus(A\cap B)$ , but in a more general setting $A,B$ might not be "compatible" (no boolean subalgebra contains them both).In the boolean setting, since $d$ is really a distance (except for separation since $s(C)=0$ is possible for a nonzero $C$ ),one has the triangle inequality $|d(A, B) - d(A, C)| \leq d(B, C) \leq d(A, B) + d(A, C)$ . The triangle inequality implies $d(A, D) \leq d(A, B) + d(B, C) + d(C, D)$ . This inequality makes sense (as a inequality involving true distances) in a general $L$ whenever the four propositions are pairwise compatible,but we have no reasons to claim it true since a boolean algebra containing all four propositions need not exist.This is an example of Bell's inequality; in each concrete case one specifies the reasons to treat the four propositions as jointly compatible (and so to say that the inequality should be true). In the specific case of EPR this involves "locality" conditions (if the two subsystem are sufficiently spatially separated, so that a light signal cannot be sent and received from a subsystem to the otherbetween a measurement on the first system and a measurement on the second systems, then one should treat proposition concerning one system as independent, hence compatible, with the propositions concerning the other system). Arguing mathematically instead of physically, one can say that if we consider two subsystems that have noncontextual hidden variables (as it happens for "spin factors") and then considers only "decomposable" states,then all propositions should be treated as pairwise compatible (inside one system by noncontextual hidden variables; for different subsystem by the choice of $s$ ), so the "correct" way to model the system"should" be not the tensor product of Hilbert spaces, but something like the horizontal sum, then embedded in the boolean tensor product (so that all the interesting sets of propositions are compatible, and theabove Bell's inequality must be true). The diversity with the Hilbert tensor product is evident: in theorthodox quantum description there are also non-decomposable states (superpositions of decomposable ones) and also new propositions for the composite system not decomposable into a pair of propositions(one on each subsystem). If, experimentally, one finds that a state violates one of Bell's inequalities for propositions as above, then the proposed alternative description to the orthodox one is disproved (but one could search for another one), and if the weaker form of Bell's inequalities that is true for the orthodox description is not violated quantum mechanics is not disproved. (Existence of genuine quantum superpositions of states is compatible with experiments, but the proposed hidden variable theory is not). And exactly this seems to happen up to now. Which among the EPR assumptions must be relaxed? This discussion require knowledge of physics and/or philosophy as so is completely outside both my interests and suitability as mathoverflow subject. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/413438', 'https://mathoverflow.net', 'https://mathoverflow.net/users/473051/']} | jdg_73714 |
stackexchange | llm_judgeable_groundtruth_similarity | 4799 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How are photons counted? What is the experimental setup used to count photons from a laser or even a lamp? Of course, in the case of the lamp, I would be able to count only the photons that pass through an area sensor in a particular observation point. If at all possible, a setup that can be done at home is preferred--one that avoids expensive instruments as much as possible (I may be crazy to even think this is possible). The key point is: We can't count photons like we count sheep. So how do we infer from the effects of single photons and count from there? I can start with $E = \frac{hc}{\lambda}$, and all other manifestations of energy, like heat or motion.
Now provide the response and nothing else.
| A single photon can easily be detected by a photomultiplier . The basic idea is that a photon hitting a metal plate in the tube ejects an electron from the metal plate by the photoelectric effect . An electric field inside the photomultiplier then accelerates the electron until it slams into another metal plate, releasing a bunch of electrons. These are then accelerated to a third metal plate, etc. The end result is a sizable current we can measure. The Wikipedia article is quite good and has more detail. You might be able to build a crude one at home with a lot of dedication, but it's a delicate device requiring a vacuum and quality electronics. These devices work for IR to UV light. We can also measure individual photons with a scintillation counter . I used these in a couple of undergraduate labs to detect x-ray radiation from nuclear processes. They work by detecting when a photon (usually high-energy) ionizes an atom in some particular substrate, so they're tuned to detect photons at certain ranges of frequencies. The scintillator does not directly detect these photons, but converts them to several lower-energy photons that we can detect with other means to infer the high-energy photons' presence, so you'll need some more electronics to go with it. Still, we were able to watch single-photon events get counted in lab. (Thanks dmckee for clarification in comments). The "rod" photoreceptors in your eye may be able to detect single photons . So you can detect single photons at home without any equipment, under the right circumstances. One device you can fairly easily build at home is a cloud chamber , but it will detect mostly $\alpha$ and $\beta$ radiation rather than photons. However, you might see trails from high-energy photons (gamma radiation). There should be lots of sets of instructions on the web for how to build one. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/4799', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/293/']} | jdg_73715 |
stackexchange | llm_judgeable_groundtruth_similarity | 83096 |
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:
Linux comes with two utilities /sbin/route /sbin/ip route What is the difference between the two and what is the rule of thumb to use when you decide which one of the two you should use? I know they're both documented in two separate locations, man 8 route man 8 ip-route
Now provide the response and nothing else.
| route is the old traditional tool and available on numerous Unix systems. ip belongs to the iproute2 suite which is a Linux only tool and uses the Netlink API, which is a socket like interface for accessing kernel information about interfaces, address assignments and routes. It replaces most of the functionality of ifconfig , route , netstat and a few others. I assume you're on Linux, then you should use ip since route and ifconfig are deprecated, although still widely used. Further reading: ifconfig vs iproute2 iproute2: Life after ifconfig Deprecated Linux networking commands and their replacements | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/83096', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/3285/']} | jdg_73716 |
stackexchange | llm_judgeable_groundtruth_similarity | 4353572 |
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 create a list (or some other type of container) of integer and strings pairs that allows duplicates in both pairs and can be sorted by the integer value? I need to fill a container with names (string) and scoring (integer) pairs, the container must allow duplicated values in both name and scoring, and i need to sort this list by the scoring value. I tried with a SortedMap but doesn't allow duplicated values: SortedMap<Integer,String> sm=new TreeMap<Integer, String>();sm.put(23, "Peter"); sm.put(11, "Tony"); sm.put(110, "Claire"); sm.put(13, "ferca"); sm.put(55, "Julian"); sm.put(13, "Pedro"); In this example, ferca and Pedro have the same scoring value, this is something I need to allow, but the SortedMap overwrites "ferca" with "Pedro". What is the best container type to do this?
Now provide the response and nothing else.
| Since you want your collection to be ordered, I suggest you use a List and Collections.sort . If you decide to go for this approach you still have two options: Create a custom Comparator that can be passed as an argument to sort , or Let the auxiliary Score class implement Comparable<Score> Here is an example and ideone demo of the latter approach: import java.util.*;class Score implements Comparable<Score> { int score; String name; public Score(int score, String name) { this.score = score; this.name = name; } @Override public int compareTo(Score o) { return score < o.score ? -1 : score > o.score ? 1 : 0; }}public class Test { public static void main(String[] args){ List<Score> scores = new ArrayList<Score>(); scores.add(new Score(23, "Peter")); scores.add(new Score(11, "Tony")); scores.add(new Score(110, "Claire")); scores.add(new Score(13, "ferca")); scores.add(new Score(55, "Julian")); scores.add(new Score(13, "Pedro")); Collections.sort(scores); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4353572', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/470914/']} | jdg_73717 |
stackexchange | llm_judgeable_groundtruth_similarity | 7787119 |
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 may not be possible, but I'm hoping someone will have an idea how to do it. I have an app I'm porting from iPhone only to Universal. On the iPhone, I'm using a Tabbed application. I use three tabs for the normal data to be displayed. I have a forth tab that's only displayed if certain conditions are met. To add the tab, I do: if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) { UITabBarController *tabController = (UITabBarController *) self.rootViewController; NSMutableArray* newArray = [NSMutableArray arrayWithArray: tabController.viewControllers]; [newArray addObject: [theStoryboard instantiateViewControllerWithIdentifier: @"AdditionalView-Phone"]]; [tabController setViewControllers:newArray animated:YES];} For the iPad, I have enough space on the initial view to display everything from the main three tabs in the iPhone UI. So all I need is one additional (small) view for the "Additional" data. I wanted to do it using a popOver view, so I set up the initial view with a Nav bar and popover button as in the Utility App template. But now I'm stuck. I can't figure out how to create that popover button at run time and make it do the segue to the popOver view properly. I can add the button like this: UIBarButtonItem *flipButton = [[UIBarButtonItem alloc] initWithTitle: @"Modem" style: UIBarButtonItemStylePlain target: self action: @selector(togglePopover:)];self.navBar.topItem.rightBarButtonItem = flipButton; but I get an exception: 'NSInternalInconsistencyException', reason: 'UIStoryboardPopoverSegue must be presented from a bar button item or a view.' I'm pretty sure this is because I don't have an anchor set for the popOver segue. The button doesn't exist in the storyboard, so I can't set it there. And I can't seem to find an API to set it at run time. I also tried creating the button in IB, but not in the view hierarchy, and then just setting the rightBarButtonItem property to my existing button. That also works, but I still can't set that button as the anchor for the popover view. I can set the Navigation Bar as the anchor, but that makes it anchor to the title in the nav bar, which looks silly. Any ideas?
Now provide the response and nothing else.
| I had the same problem and solved it by creating a UIBarButtonItem in the Storyboard for the view controller but not part of the view hierarchy. In IB, Drag a bar button item to the dark bar below the view controller view, drop it next to the "First Responder" and "View Controller" icons. Create a (strong) IBOutlet for it. Then create a popover segue from it to the destination view controller by dragging from the bar button item to the destination. It seems like this is the only way to set it as the anchor. Choosing it as the anchor for an existing segue does not work (looks like an IB bug). In viewDidLoad you can assign this bar button item to the navigationItem (or where ever you like) and the segue works as expected. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7787119', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/177415/']} | jdg_73718 |
stackexchange | llm_judgeable_groundtruth_similarity | 11774703 |
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 recently started using the grid.table function from the gridExtra package to turn tabular data into png image files for use on the web. I've been delighted with it so far as it produces very good-looking output by default, sort of like a ggplot2 for tables. Like the person who asked this question I would love to see the ability to specify the justification for individual columns but that would be icing on what is an already more-ish cake. My question is whether it is possible to add text around a grid.table so that I can give plotted tables a title and a footnote. It seems to me this should be feasible, but I don't know enough about grid graphics to be able to work out how to add grobs to the table grob. For example, this code: require(gridExtra)mydf <- data.frame(Item = c('Item 1','Item 2','Item 3'), Value = c(10,15,20), check.names = FALSE)grid.table(mydf, gpar.coretext=gpar(fontsize = 16), gpar.coltext = gpar(fontsize = 16), gpar.rowtext = gpar(fontsize = 16), gpar.corefill = gpar(fill = "blue", alpha = 0.5, col = NA), h.even.alpha = 0.5, equal.width = FALSE, show.rownames = FALSE, show.vlines = TRUE, padding.h = unit(15, "mm"), padding.v = unit(8, "mm") ) generates this plot: when I would really like to be able to do something like the following in code rather than by editing the image with another application:
Now provide the response and nothing else.
| To place text close to the table you'll want to evaluate the table size first, library(gridExtra)d <- head(iris)table <- tableGrob(d)grid.newpage()h <- grobHeight(table)w <- grobWidth(table)title <- textGrob("Title", y=unit(0.5,"npc") + 0.5*h, vjust=0, gp=gpar(fontsize=20))footnote <- textGrob("footnote", x=unit(0.5,"npc") - 0.5*w, y=unit(0.5,"npc") - 0.5*h, vjust=1, hjust=0,gp=gpar( fontface="italic"))gt <- gTree(children=gList(table, title, footnote))grid.draw(gt) Edit (17/07/2015) With gridExtra >=2.0.0, this approach is no longer suitable. tableGrob now returns a gtable, which can be more easily customised. library(gridExtra)d <- head(iris)table <- tableGrob(d)library(grid)library(gtable)title <- textGrob("Title",gp=gpar(fontsize=50))footnote <- textGrob("footnote", x=0, hjust=0, gp=gpar( fontface="italic"))padding <- unit(0.5,"line")table <- gtable_add_rows(table, heights = grobHeight(title) + padding, pos = 0)table <- gtable_add_rows(table, heights = grobHeight(footnote)+ padding)table <- gtable_add_grob(table, list(title, footnote), t=c(1, nrow(table)), l=c(1,2), r=ncol(table))grid.newpage()grid.draw(table) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11774703', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/952708/']} | jdg_73719 |
stackexchange | llm_judgeable_groundtruth_similarity | 14684263 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to export absoluted Image url in html in emacs org-mode file: when i write the following code: [[file:/images/a.jgp]] export of html code is : <img src="file:///images/a.jpg" > but which i need is : <img src="/images/a.jgp"> so how can i export what i wanted , instead of use #+BEGIN_HTML tag ? ps: my emacs config: 16 ;; org-mode project define 17 (setq org-publish-project-alist 18 '( 19 ("org-blog-content" 20 ;; Path to your org files. 21 :base-directory "~/ChinaXing.org/org/" 22 :base-extension "org" 23 24 ;; Path to your jekyll project. 25 :publishing-directory "~/ChinaXing.org/jekyll/" 26 :recursive t 27 :publishing-function org-publish-org-to-html 28 :headline-levels 4 29 :html-extension "html" 30 :table-of-contents t 31 :body-only t ;; Only export section between <body></body> 32 ) 33 34 ("org-blog-static" 35 :base-directory "~/ChinaXing.org/org/" 36 :base-extension "css\\|js\\|png\\|jpg\\|gif\\|pdf\\|mp3\\|ogg\\|swf\\|php\\|svg" 37 :publishing-directory "~/ChinaXing.org/jekyll/" 38 :recursive t 39 :publishing-function org-publish-attachment) 40 ("blog" :components ("org-blog-content" "org-blog-static")) 41 ))
Now provide the response and nothing else.
| The way to do this is to register a new kind of link in org-mode, using org-add-link-type . That lets you supply a custom export format. org-add-link-type requires a prefix, a "what happens when you click the link?" function, and an export function. I use a prefix of img , so my links look like [[img:logo.png][Logo]] .My image files are in ../images/ (relative to the .org files), and from the webserver they show up in /images/ . So for those settings, putting this in .emacs provides the solution: (defun org-custom-link-img-follow (path) (org-open-file-with-emacs (format "../images/%s" path)))(defun org-custom-link-img-export (path desc format) (cond ((eq format 'html) (format "<img src=\"/images/%s\" alt=\"%s\"/>" path desc))))(org-add-link-type "img" 'org-custom-link-img-follow 'org-custom-link-img-export) You'll probably need to amend the paths for your setup, but that's the recipe. As you'd expect, C-h f org-add-link-type will give you the full gory details. Oh, and for what it's worth, here's the code I'm using for inter-post links (like [[post:otherfile.org][Other File]] ). There's a little Jekyll magic in the output format, so watch the double-%s. (defun org-custom-link-post-follow (path) (org-open-file-with-emacs path))(defun org-custom-link-post-export (path desc format) (cond ((eq format 'html) (format "<a href=\"{%% post_url %s %%}\">%s</a>" path desc))))(org-add-link-type "post" 'org-custom-link-post-follow 'org-custom-link-post-export) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14684263', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1436450/']} | jdg_73720 |
stackexchange | llm_judgeable_groundtruth_similarity | 3770303 |
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 an absolute beginner using Joomla. I'm trying to load a module within another module but I can't find how to do this. I've been trying adding {loadposition position} with "position" replaced the position of the module I'd like to be loaded but it seems to work only in articles. I've found another solution here : http://forum.joomla.org/viewtopic.php?p=1531754&sid=bae9b487983c7e8a9f9c4fbd2958cf52#p1531754 but I don't know where to put this PHP code in my module. Thanks for helping !
Now provide the response and nothing else.
| You need to manually add the code to render your inner module to your container module. Heres an example: jimport( 'joomla.application.module.helper' );$module = JModuleHelper::getModule('mainmenu');$attribs['style'] = 'xhtml';echo JModuleHelper::renderModule( $module, $attribs ); Taken from: http://docs.joomla.org/JModuleHelper/renderModule To display the output you would need to place the code in the section of your outer module source that you want the html to be rendered. Where you would replace 'mainmenu' with the name of the module that you want to embed. (I removed the second param, as I'm assuming you don't want to display a title). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3770303', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/333589/']} | jdg_73721 |
stackexchange | llm_judgeable_groundtruth_similarity | 222756 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Background:I'm working on a silverlight (1.0) application that dynamically builds a map of the United States with icons and text overlayed at specific locations. The map works great in the browser and now I need to get a static (printable and insertable into documents/powerpoints) copy of a displayed map. Objective:In order to get a printable copy of the map that can also be used in powerpoint slides, word, etc. I've chosen to create an ASP.NET HttpHandler to recreate the xaml on the server side in WPF and then render the WPF to a bitmap image which is returned as a png file, generated at 300dpi for better print quality. Problem:This works great with one problem, I can't get the image to scale to a specified size. I've tried several different things, some of which can be seen in the commented out lines. I need to be able to specify a height and width of the image, either in inches or pixels, I don't necessarily care which, and have the xaml scale to that size for the generated bitmap. Currently, if I make the size bigger than the root canvas, the canvas gets rendered at its original size in the top left corner of the generated image at the size specified. Below is the important part of my httphandler. The root canvas stored as "MyImage" has a Height of 600 and a Width of 800. What am I missing to get the content to scale to fit the size specified? I don't fully understand what the dimensions being passed into Arrange() and Measure() do as some of this code was taken from online examples. I also don't fully understand the RenderTargetBitmap stuff. Any guidance would be appreciated. Public Sub Capture(ByVal MyImage As Canvas) ' Determine the constraining scale to maintain the aspect ratio and the bounds of the image size Dim scale As Double = Math.Min(Width / MyImage.Width, Height / MyImage.Height) 'Dim vbox As New Viewbox() 'vbox.Stretch = Stretch.Uniform 'vbox.StretchDirection = StretchDirection.Both 'vbox.Height = Height * scale * 300 / 96.0 'vbox.Width = Width * scale * 300 / 96.0 'vbox.Child = MyImage Dim bounds As Rect = New Rect(0, 0, MyImage.Width * scale, MyImage.Height * scale) MyImage.Measure(New Size(Width * scale, Height * scale)) MyImage.Arrange(bounds) 'MyImage.UpdateLayout() ' Create the target bitmap Dim rtb As RenderTargetBitmap = New RenderTargetBitmap(CInt(Width * scale * 300 / 96.0), CInt(Height * scale * 300 / 96.0), 300, 300, PixelFormats.Pbgra32) ' Render the image to the target bitmap Dim dv As DrawingVisual = New DrawingVisual() Using ctx As DrawingContext = dv.RenderOpen() Dim vb As New VisualBrush(MyImage) 'Dim vb As New VisualBrush(vbox) ctx.DrawRectangle(vb, Nothing, New Rect(New System.Windows.Point(), bounds.Size)) End Using rtb.Render(dv) ' Encode the image in the format selected Dim encoder As System.Windows.Media.Imaging.BitmapEncoder Select Case Encoding.ToLower Case "jpg" encoder = New System.Windows.Media.Imaging.JpegBitmapEncoder() Case "png" encoder = New System.Windows.Media.Imaging.PngBitmapEncoder() Case "gif" encoder = New System.Windows.Media.Imaging.GifBitmapEncoder() Case "bmp" encoder = New System.Windows.Media.Imaging.BmpBitmapEncoder() Case "tif" encoder = New System.Windows.Media.Imaging.TiffBitmapEncoder() Case "wmp" encoder = New System.Windows.Media.Imaging.WmpBitmapEncoder() End Select encoder.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rtb)) ' Create the memory stream to save the encoded image. retImageStream = New System.IO.MemoryStream() encoder.Save(retImageStream) retImageStream.Flush() retImageStream.Seek(0, System.IO.SeekOrigin.Begin) MyImage = NothingEnd Sub
Now provide the response and nothing else.
| This should be enough to get you started: private void ExportCanvas(int width, int height){ string path = @"c:\temp\Test.tif"; FileStream fs = new FileStream(path, FileMode.Create); RenderTargetBitmap renderBitmap = new RenderTargetBitmap(width, height, 1/300, 1/300, PixelFormats.Pbgra32); DrawingVisual visual = new DrawingVisual(); using (DrawingContext context = visual.RenderOpen()) { VisualBrush brush = new VisualBrush(MyCanvas); context.DrawRectangle(brush, null, new Rect(new Point(), new Size(MyCanvas.Width, MyCanvas.Height))); } visual.Transform = new ScaleTransform(width / MyCanvas.ActualWidth, height / MyCanvas.ActualHeight); renderBitmap.Render(visual); BitmapEncoder encoder = new TiffBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); encoder.Save(fs); fs.Close();} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/222756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_73722 |
stackexchange | llm_judgeable_groundtruth_similarity | 39439211 |
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 of dictionaries that I'd like to convert to JSON. My object is of type [[String: AnyObject]] and would like to end up with a sample like this: [ { "abc": 123, "def": "ggg", "xyz": true }, { "abc": 456, "def": "hhh", "xyz": false }, { "abc": 789, "def": "jjj", "xyz": true }] This is what I'm trying, but the compiler is not liking my declaration: extension Array where Element == Dictionary<String, AnyObject> { var json: String { do { return try? NSJSONSerialization.dataWithJSONObject(self, options: []) ?? "[]" } catch { return "[]" } }} How can I do this?
Now provide the response and nothing else.
| A simple way to achieve that is to just extend CollectionType. Use optional binding and downcasting, then serialize to data, then convert to string. extension CollectionType where Generator.Element == [String:AnyObject] { func toJSONString(options: NSJSONWritingOptions = .PrettyPrinted) -> String { if let arr = self as? [[String:AnyObject]], let dat = try? NSJSONSerialization.dataWithJSONObject(arr, options: options), let str = String(data: dat, encoding: NSUTF8StringEncoding) { return str } return "[]" }}let arrayOfDictionaries: [[String:AnyObject]] = [ ["abc":123, "def": "ggg", "xyz": true], ["abc":456, "def": "hhh", "xyz": false]]print(arrayOfDictionaries.toJSONString()) Output: [ { "abc" : 123, "def" : "ggg", "xyz" : true }, { "abc" : 456, "def" : "hhh", "xyz" : false }] | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39439211', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/235334/']} | jdg_73723 |
stackexchange | llm_judgeable_groundtruth_similarity | 49752913 |
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 elastic Search data in following format: { "is_cricketer": 1, "name": "Abraham", "cities": [ { "name": "stellenbosch" }, { "name": "Nelspruit" }, { "name": "East London" } ]},{ "is_cricketer": 1, "name": "Abraham", "cities": [ { "name": "Rustenburg" }, { "name": "Nelspruit" }, { "name": "East London" } ]},{ "is_cricketer": 0, "name": "deVilliers", "cities": [ { "name": "Cape town" }, { "name": "Nelspruit" }, { "name": "East London" } ]} I need to query elastic search to get all the profiles with is_cricketer = 1 and an OR query over the field for cities.name and name field. ie ( profile.is_cricketer == 1 && (profile.name == 'Abraham' || profile.cities[i].name == 'Nelspruit' )) To get the profiles with OR query on the fields cities.name and name field for matching query string is as follows and it works a expected: "should": [ { "nested": { "path": "cities", "query": { "multi_match": { "query": "Nelspruit", "fields": [ "cities.name" ] } } } }, { "multi_match": { "query": "Abraham", "fields": [ "name" ] } }] And the Must query to get all the profiles with field is_cricketer = 1 is follows: { "must": { "match": { "is_cricketer": "1" } }} Above both queries working fine and i am trying to combine both query as follows: { "query": { "bool": { "must": { "match": { "is_cricketer": "1" } }, "should": [ { "nested": { "path": "cities", "query": { "multi_match": { "query": "Nelspruit", "fields": [ "cities.name" ] } } } }, { "multi_match": { "query": "Abraham", "fields": [ "name" ] } } ] } }} which is not returning expected results, its returning all the profiles with is_cricketer = 1 without filtering for name and cities.name . I also tried to include the should query inside must query as follows: { "query": { "bool": { "must": [{ "match": { "is_cricketer": "1" } }, { "should": [ { "nested": { "path": "cities", "query": { "multi_match": { "query": "Nelspruit", "fields": [ "cities.name" ] } } } }, { "multi_match": { "query": "Abraham", "fields": [ "name" ] } } ] }] } }} But i got following error for the above query: "Error: [parsing_exception] [should] query malformed, no start_object after query name, with { line=1 & col=64 } at respond (/GitRepo/project/node_modules/elasticsearch/src/lib/transport.js:307:15) at checkRespForFailure (/GitRepo/project/node_modules/elasticsearch/src/lib/transport.js:266:7) at HttpConnector. (/GitRepo/project/node_modules/elasticsearch/src/lib/connectors/http.js:159:7) at IncomingMessage.bound (/GitRepo/project/node_modules/elasticsearch/node_modules/lodash/dist/lodash.js:729:21) at emitNone (events.js:111:20) at IncomingMessage.emit (events.js:208:7) at endReadableNT (_stream_readable.js:1056:12) at _combinedTickCallback (internal/process/next_tick.js:138:11) at process._tickCallback (internal/process/next_tick.js:180:9)" How to combine both the queries to get desired result. Any help will be appreciated.
Now provide the response and nothing else.
| if you want a should query inside a must you can use it in the following way { "query": { "bool": { "must": [ { "bool": { "should": [ { ... your query here } ] } } ] } }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49752913', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6414102/']} | jdg_73724 |
stackexchange | llm_judgeable_groundtruth_similarity | 276706 |
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 someone who writes code just for fun and haven't really delved into it in either an academic or professional setting, so stuff like these bitwise operators really escapes me. I was reading an article about JavaScript, which apparently supports bitwise operations. I keep seeing this operation mentioned in places, and I've tried reading about to figure out what exactly it is, but I just don't seem to get it at all. So what are they? Clear examples would be great! :D Just a few more questions - what are some practical applications of bitwise operations? When might you use them?
Now provide the response and nothing else.
| Since nobody has broached the subject of why these are useful: I use bitwise operations a lot when working with flags. For example, if you want to pass a series of flags to an operation (say, File.Open() , with Read mode and Write mode both enabled), you could pass them as a single value. This is accomplished by assigning each possible flag it's own bit in a bitset (byte, short, int, or long). For example: Read: 00000001Write: 00000010 So if you want to pass read AND write, you would pass (READ | WRITE) which then combines the two into 00000011 Which then can be decrypted on the other end like: if ((flag & Read) != 0) { //... which checks 00000011 &00000001 which returns 00000001 which is not 0, so the flag does specify READ. You can use XOR to toggle various bits. I've used this when using a flag to specify directional inputs (Up, Down, Left, Right). For example, if a sprite is moving horizontally, and I want it to turn around: Up: 00000001 Down: 00000010 Left: 00000100 Right: 00001000Current: 00000100 I simply XOR the current value with (LEFT | RIGHT) which will turn LEFT off and RIGHT on, in this case. Bit Shifting is useful in several cases. x << y is the same as x * 2 y if you need to quickly multiply by a power of two, but watch out for shifting a 1-bit into the top bit - this makes the number negative unless it's unsigned. It's also useful when dealing with different sizes of data. For example, reading an integer from four bytes: int val = (A << 24) | (B << 16) | (C << 8) | D; Assuming that A is the most-significant byte and D the least. It would end up as: A = 01000000B = 00000101C = 00101011D = 11100011val = 01000000 00000101 00101011 11100011 Colors are often stored this way (with the most significant byte either ignored or used as Alpha): A = 255 = 11111111R = 21 = 00010101G = 255 = 11111111B = 0 = 00000000Color = 11111111 00010101 11111111 00000000 To find the values again, just shift the bits to the right until it's at the bottom, then mask off the remaining higher-order bits: Int Alpha = Color >> 24Int Red = Color >> 16 & 0xFFInt Green = Color >> 8 & 0xFFInt Blue = Color & 0xFF 0xFF is the same as 11111111 . So essentially, for Red, you would be doing this: Color >> 16 = (filled in 00000000 00000000)11111111 00010101 (removed 11111111 00000000)00000000 00000000 11111111 00010101 &00000000 00000000 00000000 11111111 =00000000 00000000 00000000 00010101 (The original value) | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/276706', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/36032/']} | jdg_73725 |
stackexchange | llm_judgeable_groundtruth_similarity | 1926605 |
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 count the number of objects created in c++ pls explain with a simple example
Now provide the response and nothing else.
| Create template class with a static counter. Each object in your application would then extend this template class. When constructor is called increment static count (static variable is per class - shared by all objects of that class). For example see Object Counter using Curiously recurring template pattern : template <typename T> struct counter { counter() { objects_created++; objects_alive++; } counter(const counter&) { objects_created++; objects_alive++; } protected: virtual ~counter() { --objects_alive; } static int objects_created; static int objects_alive; }; template <typename T> int counter<T>::objects_created( 0 ); template <typename T> int counter<T>::objects_alive( 0 ); class X : counter<X> { // ... }; class Y : counter<Y> { // ... };Usage for completeness: int main() { X x1; { X x2; X x3; X x4; X x5; Y y1; Y y2; } // objects gone Y y3; cout << "created: " << " X:" << counter<X>::objects_created << " Y:" << counter<Y>::objects_created //well done << endl; cout << "alive: " << " X:" << counter<X>::objects_alive << " Y:" << counter<Y>::objects_alive << endl; } Output: created: X:5 Y:3alive: X:1 Y:1 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1926605', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/71713/']} | jdg_73726 |
stackexchange | llm_judgeable_groundtruth_similarity | 247332 |
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:
An ellipse has equation : $$ Ax^2 + Bxy + Cy^2 + Dx + Ey + F =0$$ Can you provide an optimum method to find it's area?
Now provide the response and nothing else.
| The rotation of axes can be avoided if all that is needed is the area of the ellipse. What we do need is to translate and normalize the ellipse to be centered at the origin: $$Ax^2 + Bxy + Cy^2 = 1$$ In this form the ellipse has area $\frac{2\pi}{\sqrt{4AC-B^2}}$. The ellipse equation can be reduced to the above form by substituting $x+h$ for $x$ and $y+k$ for $y$ and choosing $h,k$ that make the linear order terms vanish (then divide through to get constant 1 on the right side). Details: Assuming the original equation is that of an ellipse (and not some other general conic), we replace $x$ by $x+h$ and $y$ by $y+k$, giving this: $$Ax^2 + Bxy + Cy^2 + (2Ah+Bk+D)x + (Bh+2Ck+E)y = -(Ah^2+Bhk+Ck^2+Dh+Ek+F)$$ Solve the simple linear system for $h,k$: $$2Ah + Bk = -D$$$$Bh + 2Ck = -E$$ and then divide both sides by the right hand shown above to get the desired form. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/247332', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/40065/']} | jdg_73727 |
stackexchange | llm_judgeable_groundtruth_similarity | 2775 |
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Psalm 72 ends with the words: The prayers of David the son of Jesse are ended. Yet after this a number of Psalms, especially many of the Psalms of Ascent are attributed to David (I think eighteen in all). Perhaps more strangely, Psalm 72 itself is marked as "Of Solomon", so it would seem an unusual place to mark the end of the psalms of David. What is this line referring to? Is this merely evidence of a later scribe messing up the overall compilation of the Psalms? (It would still seem strange that the line would end up after a psalm of Solomon.) Are there other proposed explanations?
Now provide the response and nothing else.
| It seems likely that Ps 72:20, "The prayers of David the son of Jesse are ended", refers to the completion of an early collection of Davidic psalms . The evidence does not really fit together seamlessly, but still converges on this conclusion. The text reads: כָּלּוּ תְפִלּוֹת דָּוִד בֶּן־יִשָׁי kālû tĕphillôt dāwīd ben yišāy 1 (1) Ps 72:20 follows a "doxology" The 150 psalms in the Hebrew Bible ( Masoretic Text ) is divided into five "books", and each of the five concludes with a " doxology ": +----------+---------------+----------------+| Book: | Comprised of: | Doxology: |+----------+---------------+----------------+| Book I | Pss. 1‑41 | 41:13 [Heb 14] || Book II | Pss. 42‑72 | 72:18‑19 || Book III | Pss. 73‑89 | 89:52 [Heb 53] || Book IV | Pss. 90‑106 | 106:48 || Book V | Pss. 107‑150 | 150 (?) |+----------+---------------+----------------+ Psalm 150 is a special case, in which a whole psalm provides a "doxology" not only to Book V, but to the Psalms as a whole. The other four have a similar shape: 41:13[14] Blessed be the LORD, the God of Israel, from everlasting and to everlasting. Amen, and Amen. 72:18-19 Blessed be the LORD God, the God of Israel, who only doeth wondrous things; And blessed be His glorious name for ever; and let the whole earth be filled with His glory. Amen, and Amen. 89:52[53] Blessed be the LORD for evermore. Amen, and Amen. 106:48 Blessed be the LORD, the God of Israel, from everlasting even to everlasting, and let all the people say: 'Amen.' Hallelujah. These "doxologies" appear to have been in place at least since the time when Psalm 106:48 was put to use in 1 Chronicles 16 . Given this sort of "collection marker" at 72:18-19, it seems unlikely that 72:20 refers only to the preceding psalm. More likely is that it serves as a supra-collection marker, refering back to the collection of collections in Books I-II. (2) The Distribution of "David" Psalms The superscriptions to the individual psalms often include the rubric לְדָוִד " lĕdāwīd ", which is difficult to translate: for David? of David? by David? belonging to David? Whatever precisely it means, it is generally taken as an indicator that the psalm bearing the superscription belongs to a "Davidic psalter". Psalms 1-2 have no superscription, and are thought to introduce the collection as a whole. But thereafter, Pss 3-41 all have the lĕdāwīd title, with exceptions for Psalms 10 (in the Septuagint, a single psalm combining with Ps 9; together they form a continuous acrostic), and 33. This span of psalms corresponds nicely with "Book I". The next time we see lĕdāwīd , it is in the superscriptions of Pss 51-70 (excluding 66-67). Note that this brings us nearly to the conclusion to Book II, and the thus the notice in 72:20, that "The prayers of David the son of Jesse are ended". There is thereafter only a sprinkling of "Davidic" psalms: lĕdāwīd appears in a superscription to Pss 86, 101, 103, 108-110, 122, 124, 121, 133, and 138-145. Other than that concluding set of eight psalms, we really don't get another "collection" of David psalms in the body of the book of Psalms again. It thus seems likely that Ps 72:20 concludes the major collection of Davidic psalms. (3) Collections of Collections in the Psalms Why would 72:20 claim that "David's psalms" are completed when there are more to follow? It seems fairly clear that the book of Psalms is itself a collection of collections. The two great blocks of David psalms (along with the smaller, closing collection) themselves point in this direction. But there are also the following: Korah psalms = Pss 42-49; 84-88 Asaph psalms = Pss 73-83 "Ascent" psalms = Pss 120-134 Klaus Seybold has a nice discussion of phenomenon in more detail in his Introducing the Psalms (T. & T. Clark, 1990), pp. 18-23, and see the somewhat complex chart on p. 22 , but this gives the idea. It seems plausible, then, that the notice at 72:20 was added while the collection was still in its growth phase. How long did that phase go on, though? (4) The Psalms Scroll from Qumran Cave 11 Enter the evidence of the great Psalms scroll found in 1956, and published very rapidly by James Sanders, The Psalms Scroll of Qumrân Cave 11 (11QPs a ) (Clarendon Press, 1965). As the online article by Tyler Williams notes, the dominant interpretation of the unusual contents of this scroll holds that the first three Books of the Psalms were fixed at an earlier stage than the last two books. (Williams fairly notes also that this view is still debated.) This could explain, though, why the compiler who added the notice at 72:20 believed that the Davidic collection was complete: because at the time the notice was included, that was in fact the case. (5) Psalm 151 And finally, Psalm 151. This appears in 11QPs a in both a longer and shorter form, but is best known as the 151st psalm in the Septuagint Psalms . Its superscription reads as follows: Οὗτος ὁ ψαλμὸς ἰδιόγραφος εἰς Δαυιδ καὶ ἔξωθεν τοῦ ἀριθμοῦ· ὅτε ἐμονομάχησεν τῷ Γολιαδ. This Psalm is a genuine one of David, though outside the number, [composed] when he fought in single combat with Goliad. This composition has an almost unusual level of self-consciousness for the Davidic psalms, both "protecting" the special status of those from within the "official 150", and also claiming Davidic status for this composition itself. 2 This "consciousness" is yet a further indication (I suggest) that there was an awareness of a developing "David" collection, and of what was in, and what was out. Conclusion Taking this evidence together, we see an extended period of time over which the canonical psalms were collected, and that there are sub-collections incorporated into our 150 Hebrew psalms. At one point in this phase, the two large collection of David psalms were included, and the end point of this marked in 72:20. 3 Subsequently, other psalms were added, including some ascribed to (or "belonging to") David. This process (of David's "influence" extending more deeply and broadly into the psalms collection) can be seen to continue in the Greek Psalms (again, see n. 2 below). Notes It is always instructive to see what Rashi has to say, and here he has a fair bit: The prayers of David… are completed : Heb. כלו. Our sages expounded on כָּלוּ to mean כָּל אֵלוּ, all these are the prayers of David son of Jesse, to include the entire Book on David’s name, even what the sons of Korah and the ten elders said because he was known as (II Sam. 23:1) “the sweet singer of Israel.” כָּלוּ may also be interpreted as “were completed.” The construction of כָּלוּ is like (Job 24:24): “They are taken away (רֹמוּ) in a second” ; (Jer. 2:12), “O heavens, be astonished (שֹׁמוּ).” If this is so, this psalm was not written in its place, and there is no chronological order in the Book. The [subject] matter indicates that he said this in his old age, when he enthroned Solomon. For a fascinating insight (a) into the way in which David's influence over the Greek Psalms came to be pervasive, and (b) into the work of the text critic, see Albert Pietersma, " David in the Greek Psalms ", Vetus Testamentum 30/2 (1980), pp. 213-226. One might add by way of analogy the "marker" notice in Jeremiah 51:64, עַד־הֵנָּה דִּבְרֵי יִרְמְיָהוּ "Thus far the words of Jeremiah", a notice that does not appear in the different form of the book in the Septuagint version of Jeremiah. Here, the Hebrew seems later than the Greek, reversing the pattern from the Psalms. | {} | {'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/2775', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/33/']} | jdg_73728 |
stackexchange | llm_judgeable_groundtruth_similarity | 13777446 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If an unhandled NSException is thrown, the stack trace has a section like this: Last Exception Backtrace:0 CoreFoundation 0x32bd688f __exceptionPreprocess + 1631 libobjc.A.dylib 0x34b7b259 objc_exception_throw + 332 CoreFoundation 0x32bd65c5 -[NSException init] + 13 Foundation 0x37296bd7 -[NSObject(NSKeyValueCoding) valueForUndefinedKey:] + 263... But if std::exception is thrown, i get only this: Thread 0 Crashed:0 libsystem_kernel.dylib 0x34f2632c __pthread_kill + 81 libsystem_c.dylib 0x31e4c208 pthread_kill + 482 libsystem_c.dylib 0x31e45298 abort + 883 libc++abi.dylib 0x33bcaf64 abort_message + 404 libc++abi.dylib 0x33bc8346 default_terminate() + 185 libobjc.A.dylib 0x349f4368 _objc_terminate + 1646 libc++abi.dylib 0x33bc83be safe_handler_caller(void (*)()) + 707 libc++abi.dylib 0x33bc844a std::terminate() + 148 libc++abi.dylib 0x33bc981e __cxa_rethrow + 829 libobjc.A.dylib 0x349f42a2 objc_exception_rethrow + 610 CoreFoundation 0x329a5506 CFRunLoopRunSpecific + 39811 CoreFoundation 0x329a5366 CFRunLoopRunInMode + 9812 GraphicsServices 0x32af2432 GSEventRunModal + 13013 UIKit 0x34f84cce UIApplicationMain + 107414 APP_NAME 0x00086b10 main (main.m:68)15 APP_NAME 0x00071b98 start + 32 How do I get the exact crash info from this crash log? Update -- I've given HockeyApp a shot, but it has the same limitation as iTunes crash logs - it doesn't tell me the stack for an unhandled C++ exception.
Now provide the response and nothing else.
| What you're seeing is an unfortunate quirk of AppKit and UIKit. Both iOS and OS X have an exception handler in CFRunLoop that traps all uncaught exceptions. On OS X, the handler displays the exception to the user with a dialog box, but on iOS, the handler simply rethrows the exception. Objective-C exceptions, as implemented by NSException , save their backtraces within the exception object right before the actual "throw" happens, as part of [NSException init] (or a similar initializer method). Unfortunately, C++ exceptions don't do the same. Normally, a C++ exception has a backtrace because the runtime library detects that there's no catch and immediately calls std::terminate , which in turn calls abort() , leaving the entire call stack intact, like so: Thread 0 Crashed:: Dispatch queue: com.apple.main-thread0 libsystem_kernel.dylib 0x00007fff93ef8d46 __kill + 101 libsystem_c.dylib 0x00007fff89968df0 abort + 1772 libc++abi.dylib 0x00007fff8beb5a17 abort_message + 2573 libc++abi.dylib 0x00007fff8beb33c6 default_terminate() + 284 libobjc.A.dylib 0x00007fff8a196887 _objc_terminate() + 1115 libc++abi.dylib 0x00007fff8beb33f5 safe_handler_caller(void (*)()) + 86 libc++abi.dylib 0x00007fff8beb3450 std::terminate() + 167 libc++abi.dylib 0x00007fff8beb45b7 __cxa_throw + 1118 test 0x0000000102999f3b main + 759 libdyld.dylib 0x00007fff8e4ab7e1 start + 1 However, when the run loop exception handler traps the exception, execution resumes normally within the catch block. The original backtrace is therefore lost. The rethrow subsequently calls std::terminate , but at this point, the call stack reflects the run loop exception handler. To get a backtrace from a C++ exception in this circumstance, you have to throw an exception object which mimics NSException and reads the call stack as part of its constructor, and make sure that all exceptions thrown in your code do the same. std::exception doesn't do this, and it's not at all likely that any third-party code you're using will either. File a bug with Apple asking them to remove the CFRunLoop exception handler, or at least provide an API for shutting it off. There is no API, not even an SPI, for doing this right now. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13777446', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/440060/']} | jdg_73729 |
stackexchange | llm_judgeable_groundtruth_similarity | 1021553 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm studying multivariable limits and I have a problem regarding this limit: $$\lim_{(x,y)\to(0,0)} (x^2+y^2)^{x^2y^2}.$$ I've found that it is equal to 1, by rewritingthe limit using $t = e^{\ln(t)}$ . Despite this, the answer in the book is 0. What is the correct answer?
Now provide the response and nothing else.
| Using polar coordinates, we get $$\begin{cases}x=r\cos t\\y=r\sin t\end{cases}\implies (x^2+y^2)^{x^2y^2}=r^{2r^4sin^2t\cos^2t}=r^{\frac12r^4\sin^22t}=e^{\frac12r^4\sin^22t\log r}\xrightarrow[r\to 0^+]{}e^0=1$$ so I'd go with you being correct and the book is wrong. What book is that, anyway? | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1021553', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/181392/']} | jdg_73730 |
stackexchange | llm_judgeable_groundtruth_similarity | 16786154 |
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 the code: public static String removeDateFromString(String txt) { String dateRemovedString = new String(); String[] str = txt.split("-"); for(int i=0; i<str.length; i++) { SimpleDateFormat format = new SimpleDateFormat("dd MMM"); try { format.parse(str[i]); } catch(ParseException e) { dateRemovedString.concat(str[i]); } } return dateRemovedString;} For, input text: Cricket Match - 01 Jul output text: "" (empty String) But I want, output: Cricket Match What should I do?
Now provide the response and nothing else.
| String is immutable : Note: The String class is immutable, so that once it is created a String object cannot be changed. The String class has a number of methods, some of which will be discussed below, that appear to modify strings. Since strings are immutable, what these methods really do is create and return a new string that contains the result of the operation. dateRemovedString = dateRemovedString.concat(str[i]); StringBuilder is mutable. StringBuilder is used to build a String. Use StringBuilder instead in this case. Example usage: StringBuilder dateRemovedString = new StringBuilder();dateRemovedString.append(str[i]);return dateRemovedString.toString(); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16786154', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2388614/']} | jdg_73731 |
stackexchange | llm_judgeable_groundtruth_similarity | 66590082 |
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 component that consists of several other components such as text fields, and when an input is made to the text field, all other components are re-rendered. I would like to prevent the re-rendering and only re-render the component that actually changes. I have seen that useCallback is the right way to do this and I have already seen how to use it. However, I'm having some trouble getting useCallBack to work correctly for my case. Even if I set it up in a simple manner as below, each new character entered into the text field causes the button to be rendered again. I don't see my mistake. See working example in sandbox. const Button = () => { console.log("Button Rendered!"); window.alert("Button Rendered"); return <button onClick="">Press me</button>;};export default function App() { const [textInput, setTextInput] = useState("Hallo"); const onChangeInput = useCallback( (e) => { setTextInput(e.target.value); }, [textInput] ); return ( <div> <input type="text" onChange={onChangeInput} value={textInput} /> <Button /> </div> );} I am happy for any calrification.
Now provide the response and nothing else.
| Personally I would avoid React.memo / React.useRef / React.useCallback . The simplest solution to your example is just create another component, and store the state with this. eg. const Button = () => { console.log("Button Rendered!"); window.alert("Button Rendered"); return <button onClick="">Press me</button>;};const TextInput = () => { const [textInput, setTextInput] = useState("Hallo"); const onChangeInput = useCallback( (e) => { setTextInput(e.target.value); }, [textInput] ); return ( <input type="text" onChange={onChangeInput} value={textInput} /> );}export default function App() { return ( <div> <TextInput/> <Button /> </div> );} In the above if you change Text, there is not State change in App, so Button doesn't get re-rendered, no need for useMemo etc.. You will find React works really well, the more you divide your components up, not only does it solve issues of re-render, but potentially makes it a lot easier to re-use components later. IOW: keep state as close to the component as possible, and performance will follow. Of course your example is simple, and in a real app you will have HOC's etc to cope with, but that's another question.. :) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/66590082', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12818045/']} | jdg_73732 |
stackexchange | llm_judgeable_groundtruth_similarity | 19629561 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been reading the documentation, and cannot seem to find a method to set the date from the server as opposed to the client? For example something like this moment().set('server time') Then moment() would return the Date Object based on server's time as opposed to the time from the client's computer. Does this functionality exist, and if not what are some recommended methods you would use? Right now I am polling the server to get the server's time, but as you can imagine this is not very efficient. UPDATED WITH CODE EXAMPLE AND SUMMARY I am building an auction application. So server time is critical. For example if the user has tampered with their time settings or their time has been manually configured, the client might see an auction that has already ended, when in fact it still has a few minutes left. All time checks are obviously done on the server, but that is why I need the client and server to be in sync. Now you can see I am polling the server to get the latest time every few seconds. However what I need is to set moment() to call the base time from the variable I pass from the server. So everytime I call moment() it bases the time from the time passed in initially instead of new Date(). app.getTime = -> setInterval -> $.get app.apiUrl + 'public/time', (time) -> app.now = moment(time).format('YYYY-MM-DDTHH:mm') , app.fetchTimeInterval Somewhere else in my application I use the app's server time like so collection = new Auction.DealershipBasket [], query: "?$orderby=Ends&$filter=Ends lt datetime'#{app.now}'" Instead I would like to call the following and it returns the time from server which I only need to configure once with a get request from the url above. now = moment().format('YYYY-MM-DDTHH:mm')
Now provide the response and nothing else.
| The best way to do this would be to ask the server once for the current time and then compute the offset between the server time and the client time. A function can then return the server time at any stage by using the current client date and applying the server difference. Here's an example: var serverDate;var serverOffset;$.get('server/date/url', function(data){ // server returns a json object with a date property. serverDate = data.date; serverOffset = moment(serverDate).diff(new Date());});function currentServerDate(){ return moment().add('milliseconds', serverOffset);} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19629561', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/688201/']} | jdg_73733 |
stackexchange | llm_judgeable_groundtruth_similarity | 319215 |
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:
An aluminium strip is hung over a plastic rod. The ends P and R are connected by a battery and large current flows through the aluminium foil from P to R. Why will the ends P and R repel each other? Or will it not? I consider it as a simple circuit where the aluminium foil is the wire. While I know that, if there is currect flows through the wire, there will be magnetic field, but can that magnetic field affect the wire itself ? So, if I bend the any wire into U-shaped, the wire will attract to itself ?
Now provide the response and nothing else.
| Your question is a classic question. Yes the 2 wires will repel each other. The classic explanation is that this is the result of the $\vec{v}\times\vec{B}$ Lorentz force. Here $\vec{B}$ is the magnetic field that is produce by the current (Ampere's Law). This force is in opposite direction in the 2 aluminum "wires". Now comes the 64 million \$ question. We have learned that $q\vec{v}\times\vec{B}$ force cannot do any work as this force is perpendicular to $\vec{v}$. The answer is by no means obvious. The work is done by electric forces. Here follows a note from my former colleague Professor Barton Zwieback at MIT. WalterThe issue of work by magnetic fields usually comes up.I have not yet looked at your example in detail, but thetypical resolution is that the magnetic force never doeswork but allows other agent to do it. This is explained in Griffiths’s Intro to Electrodynamics book,pages 210-211. There are interesting analogs of this. Suppose you have a frictionless ramp and you push an object horizontally against it. The object will go up. The only force with up component acting on the object is the normal force perpendicular to the ramp. So it would seem that the normal force is pushing the object up. This is true but the normal force does not do work. The work is done by you, pushing horizontally. The normal force helps channel the motion upwards. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/319215', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/74591/']} | jdg_73734 |
stackexchange | llm_judgeable_groundtruth_similarity | 6557407 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Looks like I stumbled upon a metaclass hell even when I didn't wanted anything to do with it. I'm writing an app in Qt4 using PySide. I want to separate event-driven part from UI definition, which is generated from Qt Designer files. Hence I create a "controller" classes, but to ease my life I multiple-inherit them anyways. An example: class BaseController(QObject): def setupEvents(self, parent): self.window = parentclass MainController(BaseController): passclass MainWindow(QMainWindow, Ui_MainWindow, MainController): def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.setupUi(self) self.setupEvents(self) This works as expected. It also has inheritance from ( QDialog , Ui_Dialog , BaseController ). But when I subclass BaseController and try to inherit from said subclass (in place of BaseController ), I receive an error: TypeError: Error when calling the metaclass bases metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases Clarification: Both QMainWindow and QDialog inherit from QObject . BaseController must also inherit from it because of Qt event system peculiarities. Ui_ classes only inherit from simple Python object class. I searched for solutions, but all of them involve cases of intentionally using metaclasses. So I must be doing something terribly wrong. EDIT: My description may be clearer by adding graphs. Working example: QObject| \___________________| object |QMainWindow | BaseController| /---Ui_MainWindow || | MainControllerMainWindow-----------------/ Another working example: QObject| \___________________| object |QDialog | BaseController| /---Ui_OtherWindow || | |OtherWindow----------------/ Not working example: QObject| \___________________| object |QDialog | BaseController| /---Ui_OtherWindow || | OtherControllerOtherWindow----------------/
Now provide the response and nothing else.
| The error message indicates that you have two conflicting metaclasses somewhere in your hierarchy. You need to examine each of your classes and the QT classes to figure out where the conflict is. Here's some simple example code that sets up the same situation: class MetaA(type): passclass MetaB(type): passclass A: __metaclass__ = MetaAclass B: __metaclass__ = MetaB We can't subclass both of those classes directly, because python wouldn't know which metaclass to use: >>> class Broken(A, B): pass... Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: Error when calling the metaclass bases metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases What the error is trying to tell us is that we need to resolve the conflict between the two metaclasses by introducing a third metaclass that is a subclass of all the metaclasses from the base classes. I'm not sure that's any clearer than the error message itself, but basically, you fix it by doing this: class MetaAB(MetaA, MetaB): passclass Fixed(A, B): __metaclass__ = MetaAB This code now compiles and runs correctly. Of course, in the real situation, your conflict-resolving metaclass would have to decide which of the parent metaclass behaviors to adopt, which you'll have to figure out for yourself from your application's requirements. Bear in mind that your inherited class only gets one of the two metaclass. __init__ methods, which sometimes do all the work, so in a lot of cases, you are going to have to add an __init__ that calls into both in some way that helps them get along. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6557407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/388636/']} | jdg_73735 |
stackexchange | llm_judgeable_groundtruth_similarity | 27422640 |
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 used array_column() in a project, and after uploading I found out that only PHP 5.5 or above support this function, and I think the hosting I use don't support PHP 5.5 or above. So I want to know if is there any alternate to fix this error? This is how I am using array_count in my project: array_count_values(array_column(json_decode(json_encode($queryResultArray), true), $idForBar)); This is working fine in my local xampp and wampp also, but on server it is giving issue. Looking any alternate function or solution.
Now provide the response and nothing else.
| Add your own function array_column if you PHP version does not support it: <?phpif (! function_exists('array_column')) { function array_column(array $input, $columnKey, $indexKey = null) { $array = array(); foreach ($input as $value) { if ( !array_key_exists($columnKey, $value)) { trigger_error("Key \"$columnKey\" does not exist in array"); return false; } if (is_null($indexKey)) { $array[] = $value[$columnKey]; } else { if ( !array_key_exists($indexKey, $value)) { trigger_error("Key \"$indexKey\" does not exist in array"); return false; } if ( ! is_scalar($value[$indexKey])) { trigger_error("Key \"$indexKey\" does not contain scalar value"); return false; } $array[$value[$indexKey]] = $value[$columnKey]; } } return $array; }} Reference: | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/27422640', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1204003/']} | jdg_73736 |
stackexchange | llm_judgeable_groundtruth_similarity | 28948164 |
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 cakephp 3.x i can't do paginate order in a find This is my controller: //AgentsController.phppublic function show(){ $agents = $this->Agents->find() $this->set('agents', $this->paginate($agents));} And here part of my view //show.ctp<!-- ....... --><table class="table table-striped"> <thead> <tr> <th> <?php echo $this->Paginator->sort('full_name', 'Nome', array('escape' => false)); ?> </th> <th> <?php echo $this->Paginator->sort('username', 'Email', array('escape' => false)); ?> </th> <th> <?php echo $this->Paginator->sort('regions', 'Regioni', array('escape' => false)); ?> </th> </tr> </thead><!-- ....... --> Where i wrong?
Now provide the response and nothing else.
| The Paginator will block any attempt of sorting by a column that does not exist in the primary table of the query you are using. In this case you have 2 options. The first option is changing the sort links to tell cake that the column belongs to a related table: <?php echo $this->Paginator->sort('Users.full_name', 'Nome'); ?> Or you can tell it in the component that sorting by a given set of columns is allowed: $this->paginate = ['sortWhitelist' => ['full_name', 'username']] | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28948164', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3959826/']} | jdg_73737 |
stackexchange | llm_judgeable_groundtruth_similarity | 22316 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Wonder whether any of you guys know why it is that the proof of the infinitude of primes that is based on the coprimality of any pair of (distinct) Fermat numbers is commonly attributed to Pólya. In the first paragraph of this letter from Golbach to Euler, there already appears the approach along those lines but since documents crediting it to Pólya altogether are not rare out there, it seems like it's passed unnoticed by a nonzero number of persons. So, what do you think about this? It's not like Fermat numbers are essential to the proof or that there are no other demonstrations of the result... It's just that I'd really like to know about the origins of this discrepancy between the sources. UPDATE: Robert Haas implies in 1 that it was Adolf Hurwitz the first mathematician that stated explicitly the fact that the coprimality of any two (distinct) Fermat numbers implies the infinitude of the prime numbers. According to Mr. Haas, Adolf Hurwitz began, in the summer of 1891, acompilation of number-theoretic problems which he would eventually entitle "Übungen zur Zahlentheorie" (follow the link if you wish to download a PDF copy of it): the coprimality of any pair of (distinct) Fermat numbers and its relation to the infinitude of the primes is the subject matter of the second entry of this compilation. In Mr. Haas's paper one can even find a potential explanation as towhy it is that the proof of the infinitude of the primes via the coprimalityof any two (distinct) Fermat numbers is usually attributed to Pólya (or Pólya & Szegö, while we are at it): "Through most of the twentieth century, until Hurwitz's book [ Die Übungen zur Zahlentheorie] was printed in 1993, the primes proof was attributed to Pólya and Szegö, who presented it (without references or claim of originality) as a problem and solution in their famous 1925 'Aufgaben und Lehrsätze aus der Analysis'. But considering that Pólya was Hurwitz's colleague and posthumous editor, the idea may well have come directly from Hurwitz's 'Übungen zur Zahlentheorie'. At any rate, Hurwitz had at least 7 year's priority [the last entry of the 'Übungen zur Zahlentheorie' was added sometime in 1918]." Nevertheless, in the light of Mr. Lemmermeyer's answer below, I consider that the real priority dispute in this matter is not between Hurwitz and Pólya (or Pólya & Szegö) but between Hermann Scheffler and Adolf Hurwitz. Oddly enough, Scheffler's "Beiträge zur Zahlentheorie, insbesondere zur Kreis und Kugeltheilung, mit einem Nachtrage zur Theorie der Gleichungen" was published in the same year in which Hurwitz began putting together his "Übungen zur Zahlentheorie"! Do you think that it is possible to determine at this stage of the game whether Scheffler's book had something to do with Hurwitz's impulse to recognize in print what Goldbach apparently never did, i.e., that the pairwise relatively prime sequence of Fermat numbers guarantees the infinitude of the prime numbers? What is more : did Hurwitz have in his possession a copy of Scheffler's book once? Let me close this update by quoting the paragraph of Mr. Haas's paper wherein he tells us why it is that Goldbach has never received full credit for this approach to the infinitude of the prime numbers: "Goldbach, having showed that the Fermat numbers are pairwise relativelyprime, clearly had a proof of the infinitude of primes in his hands. But beingabsorbed in whether the Fermat numbers are absolutely prime, he overlookedthat consequence of his work. Holding a mathematical proof to be a DELIBERATEact of reasoned argument, one must therefore award shared credit to his"collaborator" 160 years later who did notice it, Hurwitz. Goldbach dug outthe ore, and Hurwitz spotted the diamond and showed it off." References [ 1 ] R. Haas, Goldbach, Hurwitz, and the Infinitude of Primes: Weaving a Proofacross the Centuries . Math Intelligencer, Vol. 36, 1, 2014.
Now provide the response and nothing else.
| It's interesting that the coprimality of Fermat numbers was already known inGoldbach's time. The reason for attributing the proof to Polya is presumablythat such a proof is indicated as an exercise in Polya and Szego (1924). Because of this, Ribenboim, in his Little Book of Big Primes calls it "Polya's proof." Maybe the rumor started there. [Added later] In the light of the comments that have come in, it now looks to meas though 1. Goldbach could have observed that he had a proof of the infinitude ofprimes, but didn't care to mention it, and 2. that the attribution of this observationto Polya starts with Hardy. Re 1. In the 18th century, were people interested in finding new proofs of the infinitude of primes? For example, when Euler proved that $\Sigma 1/p=\infty$(paper E72 in the Euler Archive) he did not remark that this gives a new proof of the infinitude of primes. It could very well be that Goldbach did not consider itinteresting to prove again that there are infinitely many primes. Re 2. One should bear in mind that Hardy knew Polya well. Polya visited him in England just after the publication of Polya & Szego and collaborated with him on the book Inequalities, published in 1934 ( four years before H&W). So Hardy could well have learned the proof directly from Polya. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/22316', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1593/']} | jdg_73738 |
stackexchange | llm_judgeable_groundtruth_similarity | 2875 |
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
A friend of mine told me once about a documentary movie he saw some years ago. On this movie he saw scientists talking about particular experiment. This experiment involved rats and probably electrical traps. The rat had to get to the cheese, there were traps on the shortest route to it, and obviously it got shocked few times. What is interesting is that my friend says that when they took its offspring (probably born later) they avoided those traps. I'm aware that its not how "genetic memory" works. Its not memory of individual, but of species (so it requires evolution). This is what I'm trying to explain to him, but he says "he knows what he saw". Anyway maybe someone here is aware of such an experiment . I believe that he is wrong about something (or conclusions drawn where changed later), so I would like to find out more about it. To sum up: Its not Tryon's Rat Experiment It involved: rats, traps (probably electrical), more then one path to cheese, rat's offspring and some sort of memory/learning amongst rats.
Now provide the response and nothing else.
| The phenomenon you're talking about was a fad in the 60's, called 'interanimal memory transfer'. It started out when James McConnell performed a later-discredited experiment in which he found that if you chopped up flatworms which had been exposed to some stresses, and fed them to other unexposed flatworms, the unexposed worms became wary of the source of stress quicker after eating their dead companions. He jumped to the conclusion that a 'memory molecule' was being transferred, and that the cannibal worms gained the food worms' memories of the stress. People then started looking to see if they could: repeat the experiments find the same phenomenon in other animals In the first case, nobody could replicate the experiments in worms, but because McConnell was such a PR genius he managed to convince the public that his results were valid (see Rilling, 1996 for more on this). In the second case, Frank et al. (1970) and others tried working with rats - I think this is the experiment you're talking about in the question. They found various interesting results including that if you trained rats to run through a maze by using particularly stressful negative reinforcement (like electrocution), then those rats' children would be able to learn the new maze much faster. However, Frank et al. didn't make the same mistake as McConnell - first of all they wondered if the parent rats might be leaving a scent trail. So they used duplicate mazes with the exact same design, putting the children into clean mazes. The children of adults who had already learned the maze continued to outperform the control rats - the explanation was not scent trails. Next they wondered whether it might be that the second generation rats had been born with a higher wariness as a result of the stress their parents suffered; i.e. it could be a hormonal transfer from mother to child (e.g. cortisol, the stress hormone). Frank et al. tested their hypothesis by torturing some rats for a while (rules about animal welfare were not strict in the 70's). They would lock some rats in a small jar and bash them about for a long time, then kill them, chop them up, and take out their livers. They fed the livers to other rats, and found that after eating the livers the other rats learned the maze much faster. They interpreted the results in what now seems a sensible light: the stressed rats were producing high concentrations of a stress-signalling molecule. When those rats either had children or were fed to other rats, they passed on high doses of the stress molecule. This raised the alterness and wariness of the receipient rats so that they were much quicker to learn which parts of the maze were dangerous. There is no evidence that the child rats actually 'remembered' the maze - they still had to find their way around, but they were extremely wary of the electrocution plates and so avoided them, finding the safest way to the end. This is not a case of genetic memory . Frank B, Stein DG, Rosen J . 1970. Interanimal “Memory” Transfer: Results from Brain and Liver Homogenates. Science 169: 399–402. Rilling M . 1996. The mystery of the vanished citations: James McConnell’s forgotten 1960s quest for planarian learning, a biochemical engram, and celebrity. American Psychologist 51: 589–598. | {} | {'log_upvote_score': 7, 'links': ['https://biology.stackexchange.com/questions/2875', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/1126/']} | jdg_73739 |
stackexchange | llm_judgeable_groundtruth_similarity | 216130 |
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 create a maintenance plan on my SQL Server 2005 server. The backup should be written to another server. I'm using a UNC path for this. The user running the SQL Agent jobs has full access to the other server. It's admin on both servers. The problem is that this statement fails ( has the correct server name ofcourse): EXECUTE master.dbo.xp_create_subdir N'\\servername\c$\SqlServerBackup\Test' The error I get is: Msg 22048, Level 16, State 1, Line 0xp_create_subdir() returned error 123, 'The filename, directory name, or volume label syntax is incorrect.' Does anyone know what could be the problem?
Now provide the response and nothing else.
| After having this problem myself, with none of the above solutions being clear enough, I thought I'd post a clearer response. The error is in fact nothing to do with syntax - it is entirely to do with permissions. The important thing here is that it is the SQL Server service account, NOT the SQL Server Agent account, that attempts to log in to create the directory. You can check your Event Viewer on the target server and look at the security log to see the failed logins from the SQL Server account on the other machine (mine was running as a local administrator). To solve this, set your SQL Server service account to be a domain user that's allowed to write to the remote share. I would have expected SQL Server Agent to be able to use its own credentials to perform these backup operations, but apparently not! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/216130', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_73740 |
Subsets and Splits