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 | 1784136 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
#include <stdio.h>#include <signal.h>void ALARMhandler(int sig){ signal(SIGALRM, SIG_IGN); /* ignore this signal */ printf("Hello"); signal(SIGALRM, ALARMhandler); /* reinstall the handler */}int main(int argc, char *argv[]){ alarm(2); /* set alarm clock */ while (1) ; printf("All done");} I expect the program to print "hello" after 2 seconds, but instead the output is "zsh: alarm ./a.out" Any idea what is going on?
Now provide the response and nothing else.
| You're forgetting to set the alarm handler initially. Change the start of main() like: int main(int argc, char *argv[]){ signal(SIGALRM, ALARMhandler); ... Also, the signal handler will probably print nothing. That's because the C library caches output until it sees an end of line. So: void ALARMhandler(int sig){ signal(SIGALRM, SIG_IGN); /* ignore this signal */ printf("Hello\n"); signal(SIGALRM, ALARMhandler); /* reinstall the handler */} For a real-world program, printing from a signal handler is not very safe. A signal handler should do as little as it can, preferably only setting a flag here or there. And the flag should be declared volatile . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1784136', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/217133/']} | jdg_73541 |
stackexchange | llm_judgeable_groundtruth_similarity | 237599 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a question from Lang's Algebra (chapter twenty ex 6d). I think the vagueness confuses me as I am not even sure where to start If $H$ is a normal subgroup of $G$, we have the cohomology groups $H^i (H,A)$. The question asks to describe how we can get an operation of $G$ on the cohomology function $H_G$ "by conjugation" and functorality. Any advice or direction on what this operation would be or how to look for it would be greatly appreciated.
Now provide the response and nothing else.
| Let $C^i(H,A)$ be the group of $i$-cochains, i.e., functions $H^i\rightarrow A$, which define the complex that computes the cohomology $H^i(H,A)$. For $g\in G$, you have the automorphism $\varphi_g:h\mapsto ghg^{-1}:H\rightarrow H$ because $H$ is normal in $G$, and you also have the abelian group automorphism $\psi_g:a\mapsto g^{-1}a:A\rightarrow A$, which is not usually $G$-equivariant, but is compatible with $\varphi_g$ in the sense that $\psi_g(\varphi_g(h)a)=h\psi_g(a)$. These maps give rise to maps $f\mapsto\psi_g\circ f\circ\varphi_g^i:C^i(H,A)\rightarrow C^i(H,A)$ which are compatible with the coboundary maps (here $\varphi_g^i:H^i\rightarrow H^i$ is the $i$-fold product of the map $\varphi_g$ with itself). So these maps descend to maps on cohomology $g^*:H^i(H,A)\rightarrow H^i(H,A)$ for all $i$. Then you get an action of $G$ on $H^i(H,A)$ by $g\cdot\kappa:=g^*(\kappa)$ (I may have the signs switched for a left action, i.e., you might need $\varphi_{g^{-1}}$ and $\psi_{g^{-1}}$ instead, but that works the same way). For example, on $H^0(H,A)=A^H$, this action is just given by $a\mapsto g^{-1}a$, so in particular, $H$ acts trivially on $H^0(H,A)$. Using an inductive argument with long exact sequences, it can be shown that $H$ acts trivially on $H^i(H,A)$ for all $i$, so you really have an action of $G/H$ on $H^i(H,A)$. This is important for defining the Hochschild-Serre spectral sequence $H^p(G/H,H^q(H,A))\Rightarrow H^{p+q}(G,A)$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/237599', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/45150/']} | jdg_73542 |
stackexchange | llm_judgeable_groundtruth_similarity | 29672213 |
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 URL of pages that register ServiceWorker in ServiceWorker scope? main.js console.log(window.location.pathname); // /usernavigator.serviceWorker.register('/app/sw.js',{scope : '/user'}).then(function(){ console.log('Service Worker initialised');}).catch(function(er){ console.log('er.message);}); sw.js console.log(self.location.pathname); // /sw.js// How can I get the `/user` URI?
Now provide the response and nothing else.
| Within a service worker, self.registration.scope will give you the associated scope. This is available in Chrome 42+ (which just became the stable release), so it should be safe to use. I think you might also be asking about how to get the a reference to all of the active pages that a service worker controls, too? If that's the case, the answer is to use self.clients.matchAll() (also available in Chrome 42+), which will return a (potentially empty) array of WindowClient objects, corresponding to each open, controlled page. WindowClient exposes a url property with the corresponding URL. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29672213', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3247703/']} | jdg_73543 |
stackexchange | llm_judgeable_groundtruth_similarity | 413107 |
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 trying to control the back-light of a TC1602A-09T 16X2 Character LCD by using an output pin on a Teensy 3.2 microcontroller. This is the circuit I have at the moment: The LED- pin would be connected to the backlight ground pin of the LCD and it would be pulled to ground via a signal from the teensy microcontroller. R1 limits the current into the base of the NPN transistor while R2 will pull the base to ground when the backlight should be off. My question is about R3 . I put R3 into the circuit so that the LED- pin on the LCD would not be floating when Q1 is turned off. Is this necessary to do? Is there any harm in just leaving the pin floating? Regardless of whether or not R3 is necessary in this particular application, I was trying to determine what the best value of R3 should be such that the power dissipated through it when Q1 is on would be at a minimum. Using the data I obtained from LTspice I created this graph: LTspice clearly shows that the higher the resistance value, the lower the power dissipated in the resistor. If this is the case, is there any reason not to choose the highest value resistor that one can get in order to minimize power consumption? Are there any other considerations when choosing a pull-up resistor that help in determining the correct value of the resistor?
Now provide the response and nothing else.
| Since they're labeled TF , it's safe to state they're t hermal f uses. Therefor, since inductance is likely irrelevant, you could replace them with through-hole fuses of the correct value. The current value depends on copper layer thickness , but for 1 oz. Cu, 0.4 mm would be about 1.5 A and 0.6 mm ~2.5 A... but it would be better to find out what the actual current ratings are. N.B. Since that 0.4 mm trace is thoroughly fried, first fix the issue that burned it out . The fuse has a purpose, and it likely prevented further damage or even a fire, so don't just bypass it. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/413107', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/161029/']} | jdg_73544 |
stackexchange | llm_judgeable_groundtruth_similarity | 12276243 |
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 activity which loads a data list from the server using loader callbacks. I have to list out the data into a fragment which extends SherlockListFragment i tried to commit the fragment using Fragment newFragment = CategoryFragment.newInstance(mStackLevel,categoryList);FragmentTransaction ft = getSupportFragmentManager().beginTransaction();ft.add(R.id.simple_fragment, newFragment).commit(); in onLoadFinished and it gives an IllegalStateException saying java.lang.IllegalStateException: Can not perform this action inside of onLoadFinished I have referred the example in actionbar sherlock, but those examples have loaders within the fragments and not the activity. Can anybody help me with this o that I can fix it without calling the loader from the fragment!
Now provide the response and nothing else.
| Atlast, I have found a solution to this problem. Create a handle setting an empty message and call that handler onLoadFinished(). The code is similar to this. @Overridepublic void onLoadFinished(Loader<List<Station>> arg0, List<Station> arg1) { // do other actions handler.sendEmptyMessage(2);} In the handler, private Handler handler = new Handler() { // handler for commiting fragment after data is loaded @Override public void handleMessage(Message msg) { if(msg.what == 2) { Log.d(TAG, "onload finished : handler called. setting the fragment."); // commit the fragment } }}; The number of fragments depend on the requirement. This method can be mainly used in case of stackFragments, where all fragments have different related functions. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12276243', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1237656/']} | jdg_73545 |
stackexchange | llm_judgeable_groundtruth_similarity | 24798382 |
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 a playbook I got the following code: ---- hosts: db vars: postgresql_ext_install_contrib: yes postgresql_pg_hba_passwd_hosts: ['10.129.181.241/32']... I would like to replace the value of postgresql_pg_hba_passwd_hosts with all of my webservers private ips . I understand I can get the values like this in a template : {% for host in groups['web'] %} {{ hostvars[host]['ansible_eth1']['ipv4']['address'] }}{% endfor %} What is the simplest/easiest way to assign the result of this loop to a variable in a playbook ? Or is there a better way to collect this information in the first place? Should I put this loop in a template? Additional challenge: I'd have to add /32 to every entry.
Now provide the response and nothing else.
| You can assign a list to variable by set_fact and ansible filter plugin . Put custom filter plugin to filter_plugins directory like this: (ansible top directory)site.ymlhostsfilter_plugins/ to_group_vars.py to_group_vars.py convert hostvars into list that selected by group. from ansible import errors, runnerimport jsondef to_group_vars(host_vars, groups, target = 'all'): if type(host_vars) != runner.HostVars: raise errors.AnsibleFilterError("|failed expects a HostVars") if type(groups) != dict: raise errors.AnsibleFilterError("|failed expects a Dictionary") data = [] for host in groups[target]: data.append(host_vars[host]) return dataclass FilterModule (object): def filters(self): return {"to_group_vars": to_group_vars} Use like this: ---- hosts: all tasks: - set_fact: web_ips: "{{hostvars|to_group_vars(groups, 'web')|map(attribute='ansible_eth0.ipv4.address')|list }}" - debug: msg: "web ip is {{item}}/32" with_items: web_ips | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24798382', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1137547/']} | jdg_73546 |
stackexchange | llm_judgeable_groundtruth_similarity | 20292680 |
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 question, because I can't figure it out and I can't find it anywhere (maybe the wrong search-words I don't know..). I have the following: Array( [0] => Array ( [Factuurnummer] => 50 [Omschrijving] => Thing 1 ) [1] => Array ( [Factuurnummer] => 50 [Omschrijving] => Thing 2 ) [2] => Array ( [Factuurnummer] => 51 [Omschrijving] => Thing 2 ) [3] => Array ( [Factuurnummer] => 51 [Omschrijving] => Thing 3 ) [4] => Array ( [Factuurnummer] => 51 [Omschrijving] => Thing 4 )) Now when I use a foreach to print it all in a table I get 5 rows, but I only want 2, based on the same 'Factuurnummer'. So 1 row with 'Factuurnummer'=50 and 'Omschrijving'=Thing 1, Thing 2 and another row with 'Factuurnummer'=51 and 'Omschrijving'=Thing 2, Thing 3, Thing 4. I've read something about array_intersect, but I don't know if that will help in this case. The nicest would be if the value from 'Omschrijving' based on same 'Factuurnummer' would be separated with a comma (like my little example). Hope I was clear enough and someone could help me in the right direction!
Now provide the response and nothing else.
| In Angular 1.1.3 or newer you can use the following: <div ng-repeat="user in users | filter:{'id': 1}:true"> {'id': 1} says to only compare with the field id . That gets you: simon, 1archie, 14 :true says "exact match" resulting in: simon, 1 Here's that working: http://jsfiddle.net/AM95H/ To filter against a list of values , if you have the list in a scope variable, I'd add a custom filter to your JS file: $scope.filterValues = [1,8];$scope.myFilter = function(value) { return ($scope.filterValues.indexOf(value.id) !== -1);}; Used like this: <div ng-repeat="user in users | filter: myFilter"> To filter against a parameter list we'll create our own filter. In this case we'll get called once with all the input values to test rather than once per value. So the first parameter we'll receive is the array of input values (users in your case) and the second parameter will be the parameter we pass in ([1,8]). We'll then create an output array and add (push) any items in the input stream that match one of the filterValues . And return the output array. myApp.filter('myFilter', function () { return function(inputs,filterValues) { var output = []; angular.forEach(inputs, function (input) { if (filterValues.indexOf(input.id) !== -1) output.push(input); }); return output; };}); And use it like this: <div ng-repeat="user in users | myFilter:[1,8]"> Here's an example of this: http://jsfiddle.net/AM95H/2/ | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/20292680', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3050534/']} | jdg_73547 |
stackexchange | llm_judgeable_groundtruth_similarity | 9320819 |
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 select all input elements except input type="submit/reset/button I have tried to make a selector like this: inputSelector = 'input:not(input[type=button], input[type=submit], input[type=reset]), textarea, select'; But this does not work, because the submit buttons always make into the final selection. Any idea what's wrong with the above. Thanks!
Now provide the response and nothing else.
| Try modifying your selector to chain .not(...) like: var inputs = $('input, textarea, select') .not(':input[type=button], :input[type=submit], :input[type=reset]');$(inputs).each(function() { console.log(this.type);}); This makes it (arguably) easier to read, and should work how you expect. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9320819', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/536768/']} | jdg_73548 |
stackexchange | llm_judgeable_groundtruth_similarity | 1692366 |
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 use telnet to google mail server on linux. I want to send mail using SMTP. But it is not able to do so. I am using this command. telnet alt4.gmail-smtp-in.l.google.com 25 But it says Trying 209.85.220.19... After some time, it gives time out. Does anyone knows how to do it?
Now provide the response and nothing else.
| It connects for me too. I think the most likely reason is that your ISP is blocking your external access to port 25. This is a common and sensible thing to do because SMTP from end-user PCs is a significant source of spam. You may be able to talk your provider into opening the port up for you, or you can use a proxy server out on the 'net, or you can use a different service, such as SSMTP (?) which connects over a secure channel using a different port. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1692366', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/169210/']} | jdg_73549 |
stackexchange | llm_judgeable_groundtruth_similarity | 12080170 |
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 experimenting with some Android functions. Right now, I'm trying to get the rotation angle of the device, so when I show a happy face bitmap on a canvas, it always looks "straight". All I would need for this, is to get the x-axis rotation angle (I guess) but I can't find how to achieve it. Hope you can help me. Thank you.
Now provide the response and nothing else.
| Found a better answer! (Thanks to forgivegod for helping me starting this!) ORIENTATION is now deprecated and uses to many resources. Plus, it works with reference to the magnetic north, which gives not the pure rotation of the device, but actually always points to the north. By using ACCELEROMETER, one can calculate the rotation angle of the device with values [0] and [1] this way: public void onSensorChanged(SensorEvent event) { // TODO Auto-generated method stub if (event.sensor != mSensor) return; aX= event.values[0]; aY= event.values[1]; //aZ= event.values[2]; angle = Math.atan2(aX, aY)/(Math.PI/180); } Maybe this can help someone else in the future. Thanks a lot! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12080170', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_73550 |
stackexchange | llm_judgeable_groundtruth_similarity | 48249 |
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
This is somewhat of a meta-cstheory question, and is more historical in nature. What are some good examples of problems for which the literature followed the develpment below: The original algorithms, despite being hopelessly intractable (e.g. exponential or high-degree polynomial), were considered breakthroughs at the time by the TCS community; Since then, extremely efficient (e.g. provably linear or sublinear, maybe sub-quadratic) algorithms have been developed and are used in practice. So, 1) precludes algorithms which have inefficient solutions (e.g. brute-force), but also have efficient solutions. The idea is that these are problems that were initially considered so difficult that even inefficient algorithms were considered a breakthrough by the research community. 2) is meant exclude problems that have shown incremental progress, even if those incremental developments are/were considered theoretically significant (e.g. exponential to high-degree polynomial). In other words, have we gone from problems that were considered theoretical curiosities to practical, usable algorithms that are widely adopted in practice?
Now provide the response and nothing else.
| Computing a generating set of invariants (sometimes called the computational problem of "Noether's Normalization Lemma") for the action of $SL_3$ on an $n$ -dimensional vector space $V$ . (You can also talk about $SL_m$ , but it's just a little cleaner to state the results when $m=3$ .) Went from non-constructive proof of finiteness, to computable, to EXPSPACE, to nearly-polynomial, over the course of over a century. As discussed in GCT V : Hilbert originally proved that the invariant ring $\mathbb{C}[V]^{SL_3}$ was finitely generated non-constructively . After Gordan's criticism, Hilbert [1893] gave an algorithm, showing (in modern language) that a finite generating set can be computed in finitely many steps (so, the problem became computable). Degree bounds proved nearly a century later by Popov and then Derksen combined with Gröbner basis puts it into $\mathsf{EXPSPACE}$ . In GCT V , Mulmuley put this problem into time $n^{O(\log \log n)}$ . | {} | {'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/48249', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/61161/']} | jdg_73551 |
stackexchange | llm_judgeable_groundtruth_similarity | 321668 |
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:
The Euler-Lagrange equation for particles is given by $$ \frac{d}{dt}\frac{\partial L}{\partial \dot{q}} = \frac{\partial L}{\partial q},\tag{1}$$ and for fields it is $$ \partial_{\mu} \frac{\partial \mathcal{L}}{\partial (\partial_{\mu}\phi)} = \frac{\partial \mathcal{L}}{\partial \phi}.\tag{2} $$ Comparing the two equations, the first one has a total time derivative $\frac{d}{dt}$ but the other one appears to have partial derivatives $\partial_{\mu}$ . These derivatives come from integration by parts in the derivation of the EL equation. I was wondering why the field version has partial derivatives and the particle version has total derivatives? I have also seen for the specific example (in Quantum Field Theory for the gifted amateur ) of 1 dimensional waves on a string, the corresponding Euler-Lagrange equation is $$ \frac{d}{dt} \frac{\partial \mathcal{L}}{\partial \left(\frac{d\phi}{dt}\right)} + \frac{d}{dx} \frac{\partial \mathcal{L}}{\partial \left(\frac{d\phi}{dx}\right)} = \frac{\partial \mathcal{L}}{\partial \phi}, \tag{3}$$ which uses total derivatives, so I am a bit confused.
Now provide the response and nothing else.
| No, one of the partial derivative symbol $\partial_{\mu}$ in OP's equation (2) is not correct if it is supposed to mean partial derivatives. The correct Euler-Lagrange (EL) equations read $$ \tag{2'} 0~\approx~\frac{\delta S}{\delta \phi^{\alpha}}~=~\frac{\partial {\cal L}}{\partial \phi^{\alpha}} - \sum_{\mu} \color{Red}{\frac{ d}{dx^{\mu}}} \frac{\partial {\cal L}}{\partial (\partial_{\mu}\phi^{\alpha})} + \ldots,$$where the $\approx$ symbol means equality modulo eoms, and the ellipsis $\ldots$ denotes possible higher derivative terms. Here$$ \color{Red}{\frac{ d}{dx^{\mu}}}~=~ \frac{\partial }{\partial x^{\mu}}+\sum_{\alpha}(\partial_{\mu}\phi^{\alpha})\frac{\partial }{\partial \phi^{\alpha}} + \sum_{\alpha, \nu} (\partial_{\mu}\partial_{\nu}\phi^{\alpha})\frac{\partial }{\partial (\partial_{\nu}\phi^{\alpha})} + \ldots $$is the $\color{Red}{\text{total spacetime derivative}}$ rather than a partial spacetime derivative. See also this and this related Phys.SE posts. Let us mention for completeness that the other appearance of the partial derivative symbol $\partial_{\mu}$ in OP's equation (2) is correct. It may be replaced with a total spacetime derivative $\color{Red}{d_{\mu}}$, since $\partial_{\mu}\phi\equiv\color{Red}{d_{\mu}}\phi$ by definition, cf. OP's eq. (3). | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/321668', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/263243/']} | jdg_73552 |
stackexchange | llm_judgeable_groundtruth_similarity | 9321794 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Pretty simple idea, but I'm not sure how to do this. I'd like to be able to style it as one div (if possible). How can I create an octagonal div ?
Now provide the response and nothing else.
| The CSS used in this link is this: #octagon { width: 100px; height: 100px; background: red; position: relative;}#octagon:before { content: ""; position: absolute; top: 0; left: 0; border-bottom: 29px solid red; border-left: 29px solid #eee; border-right: 29px solid #eee; width: 42px; height: 0;}#octagon:after { content: ""; position: absolute; bottom: 0; left: 0; border-top: 29px solid red; border-left: 29px solid #eee; border-right: 29px solid #eee; width: 42px; height: 0;} It is constructed from the div element itself which is given a rectangular shape. Using the :before and :after pseudo classes, content is added to create two trapeziums that complete the octagon. Cleverly this keeps the actual tag count at just one by using the funkier bits of CSS. The origins of this technique can be found here . Here is a quick demo . The blue part is the :before CSS and the green the :after CSS. And even better, here is a demo that allows transparent backgrounds! (thank you @GGG). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9321794', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/666564/']} | jdg_73553 |
stackexchange | llm_judgeable_groundtruth_similarity | 44124376 |
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 manual on the Dataset class in Tensorflow, it shows how to shuffle the data and how to batch it. However, it's not apparent how one can shuffle the data each epoch . I've tried the below, but the data is given in exactly the same order the second epoch as in the first. Does anybody know how to shuffle between epochs using a Dataset? n_epochs = 2batch_size = 3data = tf.contrib.data.Dataset.range(12)data = data.repeat(n_epochs)data = data.batch(batch_size)next_batch = data.make_one_shot_iterator().get_next()sess = tf.Session()for _ in range(4): print(sess.run(next_batch))print("new epoch")data = data.shuffle(12)for _ in range(4): print(sess.run(next_batch))
Now provide the response and nothing else.
| My environment: Python 3.6, TensorFlow 1.4. TensorFlow has added Dataset into tf.data . You should be cautious with the position of data.shuffle . In your code, the epochs of data has been put into the dataset 's buffer before your shuffle . Here is two usable examples to shuffle dataset. shuffle all elements # shuffle all elementsimport tensorflow as tfn_epochs = 2batch_size = 3buffer_size = 5dataset = tf.data.Dataset.range(12)dataset = dataset.shuffle(buffer_size=buffer_size)dataset = dataset.batch(batch_size)dataset = dataset.repeat(n_epochs)iterator = dataset.make_one_shot_iterator()next_batch = iterator.get_next()sess = tf.Session()print("epoch 1")for _ in range(4): print(sess.run(next_batch))print("epoch 2")for _ in range(4): print(sess.run(next_batch)) OUTPUT: epoch 1[1 4 5][3 0 7][6 9 8][10 2 11]epoch 2[2 0 6][1 7 4][5 3 8][11 9 10] shuffle between batches, not shuffle in a batch # shuffle between batches, not shuffle in a batchimport tensorflow as tfn_epochs = 2batch_size = 3buffer_size = 5dataset = tf.data.Dataset.range(12)dataset = dataset.batch(batch_size)dataset = dataset.repeat(n_epochs)dataset = dataset.shuffle(buffer_size=buffer_size)iterator = dataset.make_one_shot_iterator()next_batch = iterator.get_next()sess = tf.Session()print("epoch 1")for _ in range(4): print(sess.run(next_batch))print("epoch 2")for _ in range(4): print(sess.run(next_batch)) OUTPUT: epoch 1[0 1 2][6 7 8][3 4 5][6 7 8]epoch 2[3 4 5][0 1 2][ 9 10 11][ 9 10 11] | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44124376', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4880003/']} | jdg_73554 |
stackexchange | llm_judgeable_groundtruth_similarity | 39888758 |
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 calculate the time from now (i.e. Date()) till the next 5pm. If the current time is 3pm, the output will be 02:00:00. (in HH:MM:SS) If the current time is 6pm, the output will be 23:00:00. (until the next 5pm!) How do I do that in Swift 3? Thanks.
Now provide the response and nothing else.
| You can use Calendar.nextDate to find the Date of the coming 5pm. let now = Date()let calendar = Calendar.currentlet components = DateComponents(calendar: calendar, hour: 17) // <- 17:00 = 5pmlet next5pm = calendar.nextDate(after: now, matching: components, matchingPolicy: .nextTime)! then, just compute the different between next5pm and now using dateComponents(_:from:to:) . let diff = calendar.dateComponents([.hour, .minute, .second], from: now, to: next5pm)print(diff)// Example outputs:// hour: 2 minute: 21 second: 39 isLeapMonth: false // hour: 23 minute: 20 second: 10 isLeapMonth: false | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39888758', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4076956/']} | jdg_73555 |
stackexchange | llm_judgeable_groundtruth_similarity | 8211965 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to add some kind of library, or maven plugin, or 'something' to combine and compress my javascript and css source files. However, I think this is pretty difficult to do unobtrusively with Java. The Rails people have pretty much solved this problem... it uses the unjoined/uncompressed files for development and then it compresses everything during production. It does this unobtrusively as you don't have to change your html headers or anything like that - it works for both testing and production. This is more or less what I want. Does it even exist in the Java space? The last thing I want is to comment and uncomment lines of freemarker/html code for development and production - I want everything to be the same. Ideally, I'd want to be able to leave Tomcat running and code my javascript and css, and see my changes instantly - no delays or hickups. I also don't want to have to manually run a command to generate the new javascript every time I make a change... or even have some daemon constantly update it (because then it might not be instantaneous when I'm testing). At the same time, if I'm going to package up my war for production, I want it to use the joined and compressed files instead. Is this even possible? If so, what tool should I be looking at? I know there are quite a few that do some of this, but they've fallen short on the "unobtrusive" aspect. Thanks
Now provide the response and nothing else.
| A solution that has worked for me is using the maven-minify-plugin (groupId is com.samaxes.maven ) but only when building for production. Use a build property to specify if you are in development mode or not. Link to plugin You can then have something like this (I don't know freemarker so I am just pasting some JSP code but I am sure it can easily be converted): <c:choose> <c:when test="${developmentMode}"> <link rel="stylesheet" type="text/css" href="<c:url value="/css/custom1.css"/>"/> <link rel="stylesheet" type="text/css" href="<c:url value="/css/custom2.css"/>"/> <link rel="stylesheet" type="text/css" href="<c:url value="/css/another1.css"/>"/> <link rel="stylesheet" type="text/css" href="<c:url value="/css/another2.css"/>"/> <script type="text/javascript" src="<c:url value="/js/mylibrary.js"/>"></script> <script type="text/javascript" src="<c:url value="/js/more.js"/>"></script> <script type="text/javascript" src="<c:url value="/js/util.js"/>"></script> <script type="text/javascript" src="<c:url value="/js/whatever.js"/>"></script> <script type="text/javascript" src="<c:url value="/js/more.js"/>"></script> </c:when> <c:otherwise> <link rel="stylesheet" type="text/css" href="<c:url value="/css/minified.css"/>"/> <script type="text/javascript" src="<c:url value="/js/minified.js"/>"></script> </c:otherwise></c:choose> This way non-minified/combined JS/css is used while in development and the minified css only used when building for production. EDIT: As requested here is the code to expose Spring-defined beans on the ServletContext: <bean class="org.springframework.web.context.support.ServletContextAttributeExporter"> <property name="attributes"> <map> <!-- Obviously this can be changed to read from properties file --> <entry key="developmentMode" value="false" /> </map> </property></bean> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8211965', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/331439/']} | jdg_73556 |
stackexchange | llm_judgeable_groundtruth_similarity | 24744294 |
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 understand why one version of this code compiles, and one version does not. {-# LANGUAGE RankNTypes, FlexibleContexts #-}module Foo whereimport Data.Vector.Generic.Mutable as Mimport Data.Vector.Generic as Vimport Control.Monad.STimport Control.Monad.Primitivedata DimFun v m r = DimFun {dim::Int, func :: v (PrimState m) r -> m ()}runFun1 :: (Vector v r, MVector (Mutable v) r) => (forall m . (PrimMonad m) => DimFun (Mutable v) m r) -> v r -> v rrunFun1 (DimFun dim t) x | V.length x == dim = runST $ do y <- thaw x t y unsafeFreeze yrunFun2 :: (Vector v r, MVector (Mutable v) r) => (forall m . (PrimMonad m) => DimFun (Mutable v) m r) -> v r -> v rrunFun2 t x = runST $ do y <- thaw x evalFun t y unsafeFreeze yevalFun :: (PrimMonad m, MVector v r) => DimFun v m r -> v (PrimState m) r -> m ()evalFun (DimFun dim f) y | dim == M.length y = f y runFun2 compiles fine (GHC-7.8.2), but runFun1 results in errors: Could not deduce (PrimMonad m0) arising from a patternfrom the context (Vector v r, MVector (Mutable v) r) bound by the type signature for tfb :: (Vector v r, MVector (Mutable v) r) => (forall (m :: * -> *). PrimMonad m => TensorFunc m r) -> v r -> v r at Testing/Foo.hs:(26,8)-(28,15)The type variable ‘m0’ is ambiguousNote: there are several potential instances: instance PrimMonad IO -- Defined in ‘Control.Monad.Primitive’ instance PrimMonad (ST s) -- Defined in ‘Control.Monad.Primitive’In the pattern: TensorFunc _ fIn an equation for ‘tfb’: tfb (TensorFunc _ f) x = runST $ do { y <- thaw x; f y; unsafeFreeze y }Couldn't match type ‘m0’ with ‘ST s’ because type variable ‘s’ would escape its scopeThis (rigid, skolem) type variable is bound by a type expected by the context: ST s (v r) at Testing/Foo.hs:(29,26)-(32,18)Expected type: ST s () Actual type: m0 ()Relevant bindings include y :: Mutable v s r (bound at Testing/Foo.hs:30:3) f :: forall (v :: * -> * -> *). MVector v r => v (PrimState m0) r -> m0 () (bound at Testing/Foo.hs:29:19)In a stmt of a 'do' block: f yIn the second argument of ‘($)’, namely ‘do { y <- thaw x; f y; unsafeFreeze y }’Could not deduce (s ~ PrimState m0)from the context (Vector v r, MVector (Mutable v) r) bound by the type signature for tfb :: (Vector v r, MVector (Mutable v) r) => (forall (m :: * -> *). PrimMonad m => TensorFunc m r) -> v r -> v r at Testing/Foo.hs:(26,8)-(28,15) ‘s’ is a rigid type variable bound by a type expected by the context: ST s (v r) at Testing/Foo.hs:29:26Expected type: Mutable v (PrimState m0) r Actual type: Mutable v s rRelevant bindings include y :: Mutable v s r (bound at Testing/Foo.hs:30:3) f :: forall (v :: * -> * -> *). MVector v r => v (PrimState m0) r -> m0 () (bound at Testing/Foo.hs:29:19)In the first argument of ‘f’, namely ‘y’In a stmt of a 'do' block: f y I'm pretty sure the rank-2 type is to blame, possibly caused by a monomorphism restriction. However, as suggested in a previous question of mine, I enabled -XNoMonomorphismRestriction , but got the same error. What is the difference between these seemingly identical code snippets?
Now provide the response and nothing else.
| I think that having a rough mental model of the type-level plumbing involved here is essential, so I'm going go talk about "implicit things" in a bit more detail, and scrutinize your problem only after that. Readers only interested in the direct solution to the question may skip to the "Pattern matching on polymorhpic values" subsection and the end. 1. Implicit function arguments Type arguments GHC compiles Haskell to a small intermediate language called Core, which is essentially a rank-n polymorphic typed lambda calculus called System F (plus some extensions). Below I am going use Haskell alongside a notation somewhat resembling Core; I hope it's not overly confusing. In Core, polymorphic functions are functions which take types as additional arguments, and arguments further down the line can refer to those types or have those types: -- in Haskellconst :: forall (a :: *) (b :: *). a -> b -> aconst x y = x-- in pseudo-Coreconst' :: (a :: *) -> (b :: *) -> a -> b -> aconst' a b x y = x This means that we must also supply type arguments to these functions whenever we want to use them. In Haskell type inference usually figures out the type arguments and supplies them automatically, but if we look at the Core output (for example, see this introduction for how to do that), type arguments and applications are visible everywhere. Building a mental model of this makes figuring out higher-rank code a whole lot easier: -- Haskellpoly :: (forall a. a -> a) -> b -> (Int, b)poly f x = (f 0, f x)-- pseudo-Corepoly' :: (b :: *) -> ((a :: *) -> a -> a) -> b -> (Int, b)poly' b f x = (f Int 0, f b x) And it makes clear why some things don't typecheck: wrong :: (a -> a) -> (Int, Bool)wrong f = (f 0, f True)wrong' :: (a :: *) -> (a -> a) -> (Int, Bool)wrong' a f = (f ?, f ?) -- f takes an "a", not Int or Bool. Class constraint arguments -- Haskellshow :: forall a. Show a => a -> Stringshow x = show x-- pseudo-Coreshow' :: (a :: *) -> Show a -> a -> Stringshow' a (ShowDict showa) x = showa x What is ShowDict and Show a here? ShowDict is just a Haskell record containing a show instance, and GHC generates such records for each instance of a class. Show a is just the type of this instance record: -- We translate classes to a record type:class Show a where show :: a -> stringdata Show a = ShowDict (show :: a -> String)-- And translate instances to concrete records of the class type:instance Show () where show () = "()"showUnit :: Show ()showUnit = ShowDict (\() -> "()") For example, whenever we want to apply show , the compiler has to search the scope in order to find a suitable type argument and an instance dictionary for that type. Note that while instances are always top level, quite often in polymorphic functions the instances are passed in as arguments : data Foo = Foo-- instance Show Foo where show _ = "Foo"showFoo :: Show FooshowFoo = ShowDict (\_ -> "Foo")-- The compiler fills in an instance from top levelfooStr :: StringfooStr = show' Foo showFoo Foo polyShow :: (Show a, Show b) => a -> b -> StringpolyShow a b = show a ++ show b-- Here we get the instances as arguments (also, note how (++) also takes an extra-- type argument, since (++) :: forall a. [a] -> [a] -> [a])polyShow' :: (a :: *) -> (b :: *) -> Show a -> Show b -> a -> b -> StringpolyShow' a b (ShowDict showa) (ShowDict showb) a b -> (++) Char (showa a) (showb b) Pattern matching on polymorphic values In Haskell, pattern matching on functions doesn't make sense. Polymorphic values can be also viewed as functions, but we can pattern match on them, just like in OP's erroneous runfun1 example. However, all the implicit arguments must be inferable in the scope, or else the mere act of pattern matching is a type error: import Data.Monoid-- it's a type error even if we don't use "a" or "n".-- foo :: (forall a. Monoid a => (a, Int)) -> Int-- foo (a, n) = 0 foo :: ((a :: *) -> Monoid a -> (a, Int)) -> Intfoo f = ? -- What are we going to apply f to? In other words, by pattern matching on a polymorphic value, we assert that all implicit arguments have been already applied . In the case of foo here, although there isn't a syntax for type application in Haskell, we can sprinkle around type annotations: {-# LANGUAGE ScopedTypeVariables, RankNTypes #-}foo :: (forall a. Monoid a => (a, Int)) -> Intfoo x = case (x :: (String, Int)) of (_, n) -> n-- or alternativelyfoo ((_ :: String), n) = n Again, pseudo-Core makes the situation clearer: foo :: ((a :: *) -> Monoid a -> (a, Int)) -> Intfoo f = case f String monoidString of (_ , n) -> n Here monoidString is some available Monoid instance of String . 2. Implicit data fields Implicit data fields usually correspond to the notion of "existential types" in Haskell. In a sense, they are dual to implicit function arguments with respect to term obligations: When we construct functions, the implicit arguments are available in the function body. When we apply functions, we have extra obligations to fulfill. When we construct data with implicit fields, we must supply those extra fields. When we pattern match on data, the implicit fields also come into scope. Standard example: {-# LANGUAGE GADTs #-}data Showy where Showy :: forall a. Show a => a -> Showy-- pseudo-Coredata Showy where Showy :: (a :: *) -> Show a -> a -> Showy-- when constructing "Showy", "Show a" must be also available:someShowy :: ShowysomeShowy = Showy (300 :: Int)-- in pseudo-CoresomeShowy' = Showy Int showInt 300 -- When pattern matching on "Showy", we get an instance in scope tooshowShowy :: Showy -> StringshowShowy (Showy x) = show x showShowy' :: Showy -> StringshowShowy' (Showy a showa x) = showa x 3. Taking a look at OP's example We have the function runFun1 :: (Vector v r, MVector (Mutable v) r) => (forall m . (PrimMonad m) => DimFun (Mutable v) m r) -> v r -> v rrunFun1 dfun@(DimFun dim t) x | V.length x == dim = runST $ do y <- thaw x t y unsafeFreeze y Remember that pattern matching on polymorphic values asserts that all implicit arguments are available in the scope. Except that here, at the point of pattern matching there is no m at all in scope, let alone a PrimMonad instance for it. With GHC 7.8.x it's is good practice to use type holes liberally: runFun1 :: (Vector v r, MVector (Mutable v) r) => (forall m . (PrimMonad m) => DimFun (Mutable v) m r) -> v r -> v rrunFun1 (DimFun dim t) x | V.length x == dim = _ Now GHC will duly display the type of the hole, and also the types of the variables in the context. We can see that t has type Mutable v (PrimState m0) r -> m0 () , and we also see that m0 is not listed as bound anywhere. Indeed, it is a notorious "ambiguous" type variable conjured up by GHC as a placeholder. So, why don't we try manually supplying the arguments, just as in the prior example with the Monoid instance? We know that we will use t inside an ST action, so we can try fixing m as ST s and GHC automatically applies the PrimMonad instance for us: runFun1 :: forall v r. (Vector v r, MVector (Mutable v) r) => (forall m . (PrimMonad m) => DimFun (Mutable v) m r) -> v r -> v rrunFun1 (DimFun dim (t :: Mutable v s r -> ST s ())) x | V.length x == dim = runST $ do y <- thaw x t y unsafeFreeze y ... except it doesn't work and we get the error "Couldn't match type ‘s’ with ‘s1’ because type variable ‘s1’ would escape its scope" . It turns out - comes as no surprise - that we've forgotten about yet another implicit argument. Recall the type of runST : runST :: (forall s. ST s a) -> a We can imagine that runST takes a function of type ((s :: PrimState ST) -> ST s a) , and then our code looks like this: runST $ \s -> do y <- thaw x -- y :: Mutable v s r t y -- error: "t" takes a "Mutable v s r" with a different "s". unsafeFreeze y The s in t 's argument type is silently introduced at the outermost scope: runFun1 :: forall v s r. ... And thus the two s -es are distinct. A possible solution is to pattern match on the DimFun argument inside the ST action. There, the correct s is in scope, and GHC can supply ST s as m : runFun1 :: forall v r. (Vector v r, MVector (Mutable v) r) => (forall m . PrimMonad m => DimFun (Mutable v) m r) -> v r -> v rrunFun1 dimfun x = runST $ do y <- thaw x case dimfun of DimFun dim t | dim == M.length y -> t y unsafeFreeze y With some parameters made explicit: runST $ \s -> do y <- thaw x case dimfun (ST s) primMonadST of DimFun dim t | dim == M.length y -> t y unsafeFreeze y As an exercise, let's convert all of the function to pseudo-Core (but let's not desugar the do syntax, because that would be way too ugly): -- the full types of the functions involved, for referencethaw :: forall m v a. (PrimMonad m, V.Vector v a) => v a -> m (V.Mutable v (PrimState m) a)runST :: forall a. (forall s. ST s a) -> aunsafeFreeze :: forall m v a. (PrimMonad m, Vector v a) => Mutable v (PrimState m) a -> v a M.length :: forall v s a. MVector v s a -> Int(==) :: forall a. Eq a => a -> a -> BoolrunFun1 :: (v :: * -> *) -> (r :: *) -> Vector v r -> MVector (Mutable v) r -> ((m :: (* -> *)) -> PrimMonad m -> DimFun (Mutable v) m r) -> v r -> v rrunFun1 v r vecInstance mvecInstance dimfun x = runST r $ \s -> do y <- thaw (ST s) v r primMonadST vecInstance x case dimFun (ST s) primMonadST of DimFun dim t | (==) Int eqInt dim (M.length v s r y) -> t y unsafeFreeze (ST s) v r primMonadST vecInstance y That was a mouthful. Now we are well-equipped to explain why runFun2 worked: runFun2 :: (Vector v r, MVector (Mutable v) r) => (forall m . (PrimMonad m) => DimFun (Mutable v) m r) -> v r -> v rrunFun2 t x = runST $ do y <- thaw x evalFun t y unsafeFreeze yevalFun :: (PrimMonad m, MVector v r) => DimFun v m r -> v (PrimState m) r -> m ()evalFun (DimFun dim f) y | dim == M.length y = f y evalFun is just a polymorphic function that gets called in the right place (we ultimately pattern match on t in the right place), where the correct ST s is available as the m argument. As a type system gets more sophisticated, pattern matching becomes a progressively more serious affair, with far-reaching consequences and non-trivial requirements. At the end of the spectrum you find full-dependent languages and proof assistants such as Agda, Idris or Coq, where pattern matching on a piece of data can mean accepting an arbitrary logical proposition as true in a certain branch of your program. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24744294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/925978/']} | jdg_73557 |
stackexchange | llm_judgeable_groundtruth_similarity | 185510 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to do something like this? var pattern = /some regex segment/ + /* comment here */ /another segment/; Or do I have to use new RegExp() syntax and concatenate a string? I'd prefer to use the literal as the code is both more self-evident and concise.
Now provide the response and nothing else.
| Here is how to create a regular expression without using the regular expression literal syntax. This lets you do arbitary string manipulation before it becomes a regular expression object: var segment_part = "some bit of the regexp";var pattern = new RegExp("some regex segment" + /*comment here */ segment_part + /* that was defined just now */ "another segment"); If you have two regular expression literals, you can in fact concatenate them using this technique: var regex1 = /foo/g;var regex2 = /bar/y;var flags = (regex1.flags + regex2.flags).split("").sort().join("").replace(/(.)(?=.*\1)/g, "");var regex3 = new RegExp(expression_one.source + expression_two.source, flags);// regex3 is now /foobar/gy It's just more wordy than just having expression one and two being literal strings instead of literal regular expressions. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/185510', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17964/']} | jdg_73558 |
stackexchange | llm_judgeable_groundtruth_similarity | 1676753 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What are the differences between using SqlDataAdapter vs SqlDataReader for getting data from a DB? I am specifically looking into their Pros and Cons as well as their speed and memory performances. Thanks
Now provide the response and nothing else.
| DataReader: Needs the connection held open until you are finished (don't forget to close it!). Can typically only be iterated over once Is not as useful for updating back to the database On the other hand, it: Only has one record in memory at a time rather than an entire result set (this can be HUGE ) Is about as fast as you can get for that one iteration Allows you start processing results sooner (once the first record is available). For some query types this can also be a very big deal. DataAdapter/DataSet Lets you close the connection as soon it's done loading data, and may even close it for you automatically All of the results are available in memory You can iterate over it as many times as you need, or even look up a specific record by index Has some built-in faculties for updating back to the database At the cost of: Much higher memory use You wait until all the data is loaded before using any of it So really it depends on what you're doing, but I tend to prefer a DataReader until I need something that's only supported by a dataset. SqlDataReader is perfect for the common data access case of binding to a read-only grid. For more info, see the official Microsoft documentation . | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1676753', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/180700/']} | jdg_73559 |
stackexchange | llm_judgeable_groundtruth_similarity | 86441 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Given a finite group $G$, and a finite category $\mathcal{C}$, one can define the action of $G$ on $\mathcal{C}$ as a functor $A_{\mathcal{C}}\colon G\to\mathbf{Cat}$, which takes the single object of $G$ (regarded as a category) to $\mathcal{C}$. Moreover, one can define the quotient $\mathcal{C}/G$ to be the colimit of $A_{\mathcal{C}}$.There is an explicit construction of the category $\mathcal{C}/G$: let's denote the orbit of an element $a$ by $Ga$. The object set of $\mathcal{C}/G$ is simply given by the orbits of the elements of $\mathcal{C}^{(0)}$.To construct the set of morphism ${\mathcal{C}/G}^{(1)}$, one defines a relation $\leftrightarrow$ on $\mathcal{C}^{(1)}$ by saying $f\leftrightarrow g$ iff there is are decompositions $f = f_1\circ\...\circ f_n$ and $g=g_1\circ\...\circ g_n$, such that $G f_i = G g_i$ for all $i=1,...,n$.This relation is clearly symmetric and reflexive. It is however, not transitive. So one defines $\sim$ to be the transitive closure of $\leftrightarrow$ and sets $\mathcal{C}/G^{(1)} := \mathcal{C}^{(1)}/\sim$.My problem is that even though I can imagine why transitivity fails (i.e. given 3 morphisms $f,g,h$, one might find decompostions such that $f\sim g$ and $g\sim h$, but no decompositions such that $f\sim h$), I can't find an explicit example to demonstrate that case. P.S.: As far as I know this might very well work too without the restrictions to finite groups and categories. But I haven't thought this through yet. So I restricted my question to the finite case.
Now provide the response and nothing else.
| This question has been bugging me since it was posted, in part because I keep thinking you should have a homotopy action and should take the homotopy quotient. But anyway.... whew! I have an example which demonstrates why the relation is not transitive. The example consists of a category C with four objects $x,y, y'$, and $z$. The group in question is the cyclic group of order two $G = \mathbb{Z}/2 \mathbb{Z}$ and the action on C fixes the objects identically. The category C is almost a free category. Here are the generating morphisms: morphisms $a_i$ for $i = 0,1$ which go from $x$ to $y$, morphisms $a_i'$ for $i = 0,1$ which go from $x$ to $y'$, morphisms $b_i$ for $i = 0,1$ which go from $y$ to $z$, and morphisms $b_i'$ for $i = 0,1$ which go from $y'$ to $z$. The effect of $k \in G$ on $a_i$, $a_i'$, $b_i$, or $b'_i$ is to send $i$ to $i+k$ mod 2. There are two relations which we impose to define this category: $ b_0 a_0 = b_0' a_0'$, and $ b_1 a_1 = b_1' a_1'$. Notice that this pair of identifications is compatible with the group action. This means there are exactly six morphisms from x to z. Now all of them are equivalent under the relation generated by $\leftrightarrow$, but this relation is not transitive. For example we have: $$b_1 a_0 \leftrightarrow b_1 a_1 = b_1' a_1' \leftrightarrow b_1' a_0'$$ but there is no direct relation between $b_1 a_0$ and $b_1' a_0'$. A similar construction works with G any group with the index $i \in G$ given by group elements. In this case the quotient category, as you defined it, is the `free walking commutative square'. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/86441', 'https://mathoverflow.net', 'https://mathoverflow.net/users/20356/']} | jdg_73560 |
stackexchange | llm_judgeable_groundtruth_similarity | 12216802 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have created my tables with a column (type: timestamp with timezone) and set its default value to now() ( current_timestamp() ). I run a series of inserts in separate statements in a single function and I noticed all the timestamps are equal down to the (ms), is the function value somehow cached and shared for the entire function call or transaction?
Now provide the response and nothing else.
| That is expected and documented behaviour: From the manual: Since these functions return the start time of the current transaction, their values do not change during the transaction. This is considered a feature: the intent is to allow a single transaction to have a consistent notion of the "current" time, so that multiple modifications within the same transaction bear the same time stamp. If you want something that changes each time you run a statement, you need to use statement_timestamp() or even clock_timestamp() (again see the description in the manual) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12216802', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/852001/']} | jdg_73561 |
stackexchange | llm_judgeable_groundtruth_similarity | 17435995 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
As I'm using the Emacs Org mode as a research log, sometime I want to keep track of something via screenshot images, and I definitely don't want to save them. So I'm wondering is there any way to insert those figures into my org mode file, like with word coping them from clipboard?
Now provide the response and nothing else.
| The exact functionality you want isn't currently implemented, but I would be skeptical of saving lots of images into a research log if your opinion is that you "definitely don't want to save them." Anyways, the functionality you desire has been expressed in the org-mode mailing list a couple of times in recent years - check http://comments.gmane.org/gmane.emacs.orgmode/33770 http://www.mail-archive.com/[email protected]/msg50862.html The first link includes some code to launch a screenshot utility (via ImageMagick) to [uniquely] save the file and insert an inline link in your org-mode buffer. As stated in that thread, the code was improved upon and added to org-mode hacks page - which has lots of useful gems: http://orgmode.org/worg/org-hacks.html (defun my-org-screenshot () "Take a screenshot into a time stamped unique-named file in thesame directory as the org-buffer and insert a link to this file." (interactive) (setq filename (concat (make-temp-name (concat (buffer-file-name) "_" (format-time-string "%Y%m%d_%H%M%S_")) ) ".png")) (call-process "import" nil nil nil filename) (insert (concat "[[" filename "]]")) (org-display-inline-images)) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17435995', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2472584/']} | jdg_73562 |
stackexchange | llm_judgeable_groundtruth_similarity | 20341355 |
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 where a variable is being initialized with the result of a function call. This function throws so I set up a try-catch to catch the exception. For some reason the exception is still showing up on the screen even after the catch clause runs. #include <iostream>#include <stdexcept>int f() { throw std::invalid_argument("threw"); return 50; }struct S{ S() try : r(f()) { std::cout << "works"; } catch(const std::invalid_argument&) { std::cout << "fails"; } int r;};int main(){ S s;} This code prints "fails" after showing the exception: terminate called after throwing an instance of 'std::invalid_argument'what(): threw Why is the exception still thrown? I have the same code set up in main and it works without fail: int main(){ try { throw std::invalid_argument("blah"); } catch(const std::invalid_argument&) { }} So why does it fail when being used in an initializer list?
Now provide the response and nothing else.
| Constructors with function try blocks (like what you have for S ) automatically rethrow any exceptions caught by the catch block. Consequently, after the catch catches the exception, it rethrows it. This behavior is different from normal catch handlers, which don't do this. I think the rationale is that if construction of a data member or base class fails, the object has failed to construct. The purpose of the catch handler is just to do any extra cleanup before the exception propagates outward. Hope this helps! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20341355', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/701092/']} | jdg_73563 |
stackexchange | llm_judgeable_groundtruth_similarity | 433891 |
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 $Z_1, Z_2, \dots$ be a Poisson point process on $[0, 1]$ with intensity function $1/z$ . What is the distribution of the sum $Z = \sum_{i=1}^\infty Z_i$ ? One can construct $Z_1, Z_2, \dots$ by taking a standard Poisson point process $X_1, X_2, \dots$ on $[0, \infty)$ with intensity $1$ (so the number of points in any interval $I$ is Poisson-distributed with mean $|I|$ ) and setting $Z_i = \exp(-X_i)$ . The sum $Z$ seems to have mean $1$ and variance $1/2$ . Empirical CDF and distribution function below. It looks like $Z$ is uniformly distributed on $[0,1]$ and exponentially distributed above $1$ . Is something like that true?
Now provide the response and nothing else.
| The density function of $Z$ is the Dickman $\rho$ function, normalized (that is, divided by its mass, $e^{\gamma}$ ). This function, $\rho\colon [0,\infty)\to (0,\infty)$ , is defined via $\rho(t)=1$ for $t \in [0,1]$ and $\rho'(t)=-\rho(t-1)/t$ for $t \ge 1$ . Equivalently, $u\rho(u) = \int_{u-1}^{u} \rho(t)dt$ . This already shows $\rho(t) \le 1/\Gamma(t+1)$ , so it decays superexponentially. Its Laplace transform is given by $$\hat{\rho}(s):=\int_{0}^{\infty} e^{-st}\rho(t)dt = e^{\gamma+I(-s)}$$ where $I(s) = \int_{0}^{s} \frac{e^t-1}{t}dt$ (see Theorem III.5.10 in Tenenbaum's book, "Introduction to Analytic and Probabilistic Number Theory"; the same chapter contains a wealth of information on $\rho$ ). Plugging $s=0$ we get that $\int_{0}^{\infty} \rho(t)dt = e^{\gamma}$ , so $\rho(t) e^{-\gamma}$ is indeed a density function. From DRJ's answer, we know that if $f$ is your density function then $$\int_{0}^{\infty} e^{-st} f(t)dt = e^{-\int_{0}^{s} \frac{1-e^{-u}}{u}du}=e^{I(-s)}$$ by change of variables $u=-v$ . Standard uniqueness properties imply $f \equiv \rho e^{-\gamma}$ . This function features prominently in number theory and probability. In number theory $\rho(u)$ arises as the probability that a number $x$ is $x^{1/u}$ -smooth (or friable). Equivalently, the CDF of the random variable $\log P(n)/\log n$ ( $n$ random from $\mathbb{Z}\cap[1,x]$ , $P(n)$ the largest prime factor of $n$ ) tends to $\rho(1/\cdot)$ as $x \to \infty$ . Relatedly, in probability, $\rho(1/\cdot)$ arises as the CDF of the first coordinate of a Poisson-Dirichlet process. In the last examples it arises as a CDF but in your situation it is a density function, so let me give an example where it arises as the latter. It is the density function for the limit of $\sum_{k=1}^{n} k Z_k/n$ , where $Z_k$ are independent Poisson with parameters $1/k$ . This is intuitive if we work with Laplace transforms: $$\mathbb{E} e^{-s \sum_{k=1}^{n} k Z_k/n} = \prod_{i=1}^{n} \mathbb{E} e^{-s kZ_k/n} = \prod_{k=1}^{n} e^{\frac{1}{k}\left( e^{-sk/n}-1\right)} = e^{\sum_{k=1}^{n} \frac{1}{k}(e^{-sk/n}-1)}$$ and the exponent tends to $I(-s)$ with $n$ . This is mentioned in "On strong and almost sure local limit theorems for a probabilistic model of the Dickman distribution" by La Bretèche and Tenenbaum, along with references. A related nice fact: if you condition on $\sum_{k=1}^{n} k Z_k=n$ , then the vector $(Z_1,\ldots,Z_k)$ becomes distributed like $(C_1(\pi_n),\ldots,C_n(\pi_n))$ where $\pi_n$ is a permutation chosen uniformly at random from $S_n$ and $C_i$ is its number of cycles of size $i$ . This appears in the book "Logarithmic Combinatorial Structures" by Arartia, Barbour and Tavaré, specifically equation (1.15) and the discussion on page 26. (It could be that the book includes a discussion of the previous fact as well but I couldn't find it.) | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/433891', 'https://mathoverflow.net', 'https://mathoverflow.net/users/20598/']} | jdg_73564 |
stackexchange | llm_judgeable_groundtruth_similarity | 80681 |
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
This problem usually occurs with servers, but the question itself is about network. When I have a gateway with 10.1.1.1 and an interface with /24 network, the network routes are automatically installed by the os as follows: 0.0.0.0/0 via 10.1.1.1 dev eno1 src 10.1.1.1010.1.1.0/24 dev eno1 And if I have a packet destined to 10.1.1.20 from local, it doesn't send the packet to its gateway 10.1.1.1. Instead, it looks up an arp table for 10.1.1.20 and writes a destination address for 10.1.1.20 in its frame. However, if there's a static host route to 10.1.1.20 with the next hop 10.1.1.1 in the route table (see below), it seems to look up an arp table for 10.1.1.1 and write a destination address for 10.1.1.1 in its frame. 10.1.1.20/32 via 10.1.1.1 dev eno1 src 10.1.1.10 So what's going on here? Why does it look up an arp entry for a destination host when the route table has only network address, but it looks up an arp entry for the next hop when the route table has a host address?
Now provide the response and nothing else.
| Why does it look up an arp entry for a destination host when the route table has only network address, but it looks up an arp entry for the next hop when the route table has a host address? 10.1.1.0/24 dev eno1 10.1.1.20/32 via 10.1.1.1 dev eno1 src 10.1.1.10 Note how the route to 10.1.1.0/24 (the upper one) doesn't have a gateway ("via xxx") set, but the second one does. Having no gateway means the destination must be directly accessible, on the given device ("on-link"). For IPv4 and Ethernet, that means making ARP queries and sending the packets directly to the destination host's Ethernet address. With the gateway set, the final destination is (supposedly) not available directly on the link, so the packets are sent through the gateway. It's the gateway's address that's looked up for ARP queries, and its Ethernet address used as the destination of the frame. This isn't related to host vs. network routes, as you could have a route like this: 10.1.2.0/24 via 10.1.1.99 dev eno1 src 10.1.1.10 i.e. a network route through a gateway. (Similar to the default route you already had there, but anyway.) Similarly you could have an on-link route (without a gw) to a host: 10.1.1.20/32 dev eno1 | {} | {'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/80681', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/43549/']} | jdg_73565 |
stackexchange | llm_judgeable_groundtruth_similarity | 66618136 |
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 define my Service Worker as persistent in my Chrome extension because I'm using the webRequest API to intercept some data passed in a form for a specific request, but I don't know how I can do that. I've tried everything, but my Service Worker keeps unloading. How can I keep it loaded and waiting until the request is intercepted?
Now provide the response and nothing else.
| Service worker (SW) can't be persistent by definition and the browser must forcibly terminate all of SW connections such as network requests or runtime ports after a certain time, which in Chrome is 5 minutes. The inactivity timer when no such requests or ports are open is even shorter: 30 seconds. Chromium team currently considers this behavior intentional and good, however this only applies to extensions that observe infrequent events, so they'll run just a few times a day thus reducing browser memory footprint between the runs e.g. webRequest/webNavigation events with urls filter for a rarely visited site. These extensions can be reworked to maintain the state, example . Such an idyll is unsustainable in many cases. Problem 1: Chrome 106 and older doesn't wake up SW for webRequest events . Although you can try to subscribe to an API like chrome.webNavigation as shown in the other answers, but it helps only with events that occur after the worker starts. Problem 2: the worker is randomly broken after an update . No workaround. Try uninstalling the extension and install it again. Problem 3: SW inactivity timer isn't prolonged for a new chrome API event in an already running background script. It means that when the event occurred in the last milliseconds of the 30-second inactivity timeout your code won't be able to run anything asynchronous reliably. It means that your extension will be perceived as unreliable by the user. Problem 4: worse performance than MV2 in case the extension maintains a socket connection or the state (variables) takes a long time to rebuild or you observe frequent events like these: chrome.tabs.onUpdated/onActivated, chrome.webNavigation if not scoped to a rare url, chrome.webRequest if not scoped to a rare url or type, chrome.runtime.onMessage/onConnect for messages from content script in all tabs. Starting SW for a new event is essentially like opening a new tab. Creating the environment takes ~50ms, running the entire SW script may take 100ms (or even 1000ms depending on the amount of code), reading the state from storage and rebuilding/hydrating it may take 1ms (or 1000ms depending on the complexity of data). Even with an almost empty script it'd be at least 50ms, which is quite a huge overhead to call the event listener, which takes only 1ms. SW may restart hundreds of times a day, because such events are generated in response to user actions that have natural gaps in them e.g. clicked a tab then wrote something, during which the SW is terminated and restarted again for a new event thus wearing down CPU, disk, battery, often introducing a frequent perceivable lag of the extension's reaction. "Persistent" service worker while nativeMessaging host is connected In Chrome 105 and newer the service worker will run as long as it's connected to a nativeMessaging host via chrome.runtime.connectNative . If the host process is terminated due to a crash or user action, the port will be closed, and the SW will terminate as usual. You can guard against it by listening to port's onDisconnect event and call chrome.runtime.connectNative again. "Persistent" service worker while a connectable tab is present Downsides: The need for an open web page tab Broad host permissions (like <all_urls> or *://*/* ) for content scripts which puts most extensions into the slow review queue in the web store. Warning! If you already connect ports, don't use this workaround, use another one for ports below. Warning! Also implement the workaround for sendMessage (below) if you use sendMessage. manifest.json, the relevant part: "permissions": ["scripting"], "host_permissions": ["<all_urls>"], "background": {"service_worker": "bg.js"} background service worker bg.js: const onUpdate = (tabId, info, tab) => /^https?:/.test(info.url) && findTab([tab]);findTab();chrome.runtime.onConnect.addListener(port => { if (port.name === 'keepAlive') { setTimeout(() => port.disconnect(), 250e3); port.onDisconnect.addListener(() => findTab()); }});async function findTab(tabs) { if (chrome.runtime.lastError) { /* tab was closed before setTimeout ran */ } for (const {id: tabId} of tabs || await chrome.tabs.query({url: '*://*/*'})) { try { await chrome.scripting.executeScript({target: {tabId}, func: connect}); chrome.tabs.onUpdated.removeListener(onUpdate); return; } catch (e) {} } chrome.tabs.onUpdated.addListener(onUpdate);}function connect() { chrome.runtime.connect({name: 'keepAlive'}) .onDisconnect.addListener(connect);} all your other extension pages like the popup or options: ;(function connect() { chrome.runtime.connect({name: 'keepAlive'}) .onDisconnect.addListener(connect);})(); If you also use sendMessage In Chrome 99-101 you need to always call sendResponse() in your chrome.runtime.onMessage listener even if you don't need the response. This is a bug in MV3. Also, make sure you do it in less than 5 minutes time, otherwise call sendResponse immediately and send a new message back via chrome.tabs.sendMessage (to the tab) or chrome.runtime.sendMessage (to the popup) after the work is done. If you already use ports e.g. chrome.runtime.connect Warning! If you also connect more ports to the service worker you need to reconnect each one before its 5 minutes elapse e.g. in 295 seconds. This is crucial in Chrome versions before 104, which killed SW regardless of additional connected ports. In Chrome 104 and newer this bug is fixed but you'll still need to reconnect them, because their 5-minute lifetime hasn't changed, so the easiest solution is to reconnect the same way in all versions of Chrome: e.g. every 295 seconds. background script example: chrome.runtime.onConnect.addListener(port => { if (port.name !== 'foo') return; port.onMessage.addListener(onMessage); port.onDisconnect.addListener(deleteTimer); port._timer = setTimeout(forceReconnect, 250e3, port);});function onMessage(msg, port) { console.log('received', msg, 'from', port.sender);}function forceReconnect(port) { deleteTimer(port); port.disconnect();}function deleteTimer(port) { if (port._timer) { clearTimeout(port._timer); delete port._timer; }} client script example e.g. a content script: let port;function connect() { port = chrome.runtime.connect({name: 'foo'}); port.onDisconnect.addListener(connect); port.onMessage.addListener(msg => { console.log('received', msg, 'from bg'); });}connect(); "Forever", via a dedicated tab, while the tab is open Open a new tab with an extension page inside e.g. chrome.tabs.create({url: 'bg.html'}) . It'll have the same abilities as the persistent background page of ManifestV2 but a) it's visible and b) not accessible via chrome.extension.getBackgroundPage (which can be replaced with chrome.extension.getViews ). Downsides: consumes more memory, wastes space in the tab strip, distracts the user, when multiple extensions open such a tab, the downsides snowball and become a real PITA. You can make it a little more bearable for your users by adding info/logs/charts/dashboard to the page and also add a beforeunload listener to prevent the tab from being accidentally closed. Caution regarding persistence You still need to save/restore the state (variables) because there's no such thing as a persistent service worker and those workarounds have limits as described above, so the worker can terminate. You can maintain the state in a storage, example . Note that you shouldn't make your worker persistent just to simplify state/variable management. Do it only to restore the performance worsened by restarting the worker in case your state is very expensive to rebuild or if you hook into frequent events listed in the beginning of this answer. Future of ManifestV3 Let's hope Chromium will provide an API to control this behavior without the need to resort to such dirty hacks and pathetic workarounds. Meanwhile describe your use case in crbug.com/1152255 if it isn't already described there to help Chromium team become aware of the established fact that many extensions may need a persistent background script for an arbitrary duration of time and that at least one such extension may be installed by the majority of extension users. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/66618136', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15318375/']} | jdg_73566 |
stackexchange | llm_judgeable_groundtruth_similarity | 15265295 |
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 viewed the source code of __libc_init_array from http://newlib.sourcearchive.com/documentation/1.18.0/init_8c-source.html . But I don't quite understand what this function does. I know that these symbols /* These magic symbols are provided by the linker. */extern void (*__preinit_array_start []) (void) __attribute__((weak));extern void (*__preinit_array_end []) (void) __attribute__((weak));extern void (*__init_array_start []) (void) __attribute__((weak));extern void (*__init_array_end []) (void) __attribute__((weak));extern void (*__fini_array_start []) (void) __attribute__((weak));extern void (*__fini_array_end []) (void) __attribute__((weak)); is defined in the linker script. Part of the linker script may look like: .preinit_array : { PROVIDE_HIDDEN (__preinit_array_start = .); KEEP (*(.preinit_array*)) PROVIDE_HIDDEN (__preinit_array_end = .); } >FLASH .init_array : { PROVIDE_HIDDEN (__init_array_start = .); KEEP (*(SORT(.init_array.*))) KEEP (*(.init_array*)) PROVIDE_HIDDEN (__init_array_end = .); } >FLASH ... and then I searched with the key "init_array" in the docs of ELF-v1.1, gcc 4.7.2, ld, and codesourcery(I'm using codesourcery g++ lite) only to get nothing. Where can I find the specification of these symbols?
Now provide the response and nothing else.
| These symbols are related to the C / C++ constructor and destructor startup and tear down code that is called before / after main() . Sections named .init , .ctors , .preinit_array , and .init_array are to do with initialization of C/C++ objects, and sections .fini , .fini_array , and .dtors are for tear down. The start and end symbols define the beginning and end of code sections related to such operations and might be referenced from other parts of the runtime support code. The .preinit_array and .init_array sections contain arrays of pointers to functions that will be called on initialization. The .fini_array is an array of functions that will be called on destruction. Presumably the start and end labels are used to walk these lists. A good example of code that uses these symbols is to be found here libc source for initfini.c . You can see that on startup, __libc_init_array() is called and this first calls all the function pointers in section .preinit_array by referring to the start and end labels. Then it calls the _init() function in the .init section. Lastly it calls all the function pointers in section .init_array . After main() is complete the teardown call to __libc_fini_array() causes all the functions in .fini_array to be called, before finally calling _fini() . Note that there seems to be a cut-and-paste bug in this code when it calculates the count of functions to call at teardown. Presumably they were dealing with a real time micro controller OS and never encountered this section. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15265295', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1887273/']} | jdg_73567 |
stackexchange | llm_judgeable_groundtruth_similarity | 5346908 |
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 started messing around with the ASM API for a compiler project I am working on. However, I am finding that the documentation is less than clear for a newcomer in many places and I thought having a good solid example of generating a class that simply prints "Hello, World!" would be a great example to have on here. Currently, I can generate a class with a main() (using the ClassWriter, ClassVisitor and MethodVisitor classes) but I can't seem to work out how to generate main's body. Could anyone give me an example of generating a class file in ASM that: contains a main() creates a local String variable in main() with the value "Hello, World!" prints the variable
Now provide the response and nothing else.
| You can compile a class using java, then get asm to print out the calls it would take to generate an equivalent class, FAQ ASMifierClassVisitor The ASMifierClassVisitor javadocs actually has the hello world code in it, import org.objectweb.asm.*;public class HelloDump implements Opcodes { public static byte[] dump() throws Exception { ClassWriter cw = new ClassWriter(0); FieldVisitor fv; MethodVisitor mv; AnnotationVisitor av0; cw.visit(49, ACC_PUBLIC + ACC_SUPER, "Hello", null, "java/lang/Object", null); cw.visitSource("Hello.java", null); { mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V"); mv.visitInsn(RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); } { mv = cw.visitMethod(ACC_PUBLIC + ACC_STATIC, "main", "([Ljava/lang/String;)V", null, null); mv.visitFieldInsn(GETSTATIC, "java/lang/System", "out", "Ljava/io/PrintStream;"); mv.visitLdcInsn("hello"); mv.visitMethodInsn(INVOKEVIRTUAL, "java/io/PrintStream", "println", "(Ljava/lang/String;)V"); mv.visitInsn(RETURN); mv.visitMaxs(2, 1); mv.visitEnd(); } cw.visitEnd(); return cw.toByteArray(); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5346908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/304674/']} | jdg_73568 |
stackexchange | llm_judgeable_groundtruth_similarity | 224257 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a computer (in fact, a Banana Pi Pro) with a touchscreen which I have configured to emulate the right click via xorg.conf : Section "InputClass" Identifier "Touchscreen" Option "EmulateThirdButton" "1" Option "EmulateThirdButtonTimeout" "750" Option "EmulateThirdButtonThreshold" "30"EndSection This works really well. But sometimes, when I want to use a real mouse, these settings become quite annoying, because long left mouse clicks are converted to right mouse clicks. Also, drag selection becomes imprecise because of 30 pixels threshold. I wonder if it's possible to disable the right click emulation when the mouse is used: Is it possible to modify Xorg configuration at runtime to alter the "InputClass" section? If not, is it possible to apply this section only to one particular input device (the touchscreen)? If the only way is to update xorg.conf and restart the server, what would be the least painful way to do it? Ideally it would be nice to preserve the applicatons which are already running, but I doubt it's possible. Is there a program which does what I want without changing xorg.conf ? Like in this question , where xrandr is used to dynamically configure parameters which are static when configured via xorg.conf .
Now provide the response and nothing else.
| xinput controls input settings. It has the same role for input that xrandr has for the display. Run xinput list to list devices. Each device has a name and a numerical ID. You can use either this name or this ID to list properties of the corresponding device. Device IDs can depend on the order in which the devices are detected, so to target a specific device, use its name. For example, I have a mouse as device 8; here's an excerpt of its properties: $ xinput list-props 8… Evdev Third Button Emulation (280): 0 Evdev Third Button Emulation Timeout (281): 1000 Evdev Third Button Emulation Button (282): 3 Evdev Third Button Emulation Threshold (283): 20… So I can use either of the following commands to turn on third button emulation for this device: xinput set-prop 8 280 1xinput set-prop 8 'Evdev Third Button Emulation' 1 There is a hierarchy of devices, which xinput list represents graphically. Applying a property to a device also applies it to its children. For example, you can apply a property to all pointing devices by applying it to the root pointer Virtual core pointer . | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/224257', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/106927/']} | jdg_73569 |
stackexchange | llm_judgeable_groundtruth_similarity | 9584573 |
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 bind query string parameter that is comma separated value http://localhost/Action?ids=4783,5063,5305 to a controller action expecting a list? public ActionResult Action(List<long> ids){ return View();} Note! ids in the controller action must a list (or something IEnumerable based), so string ids is not accepted as an answer because these parameters are passed to many actions and parsing string to an array would add unwanted noise.
Now provide the response and nothing else.
| Default model binder expects simple type lists to be in the format name=value&name=value2&name=value3 To use builtin binding, you should change your query string to Action?ids=4783&ids=5063&ids=5305 Or create custom model binder. You may take a look at following article (code from there) public class CommaSeparatedValuesModelBinder : DefaultModelBinder{ private static readonly MethodInfo ToArrayMethod = typeof(Enumerable).GetMethod("ToArray"); protected override object GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, System.ComponentModel.PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) { if (propertyDescriptor.PropertyType.GetInterface(typeof(IEnumerable).Name) != null) { var actualValue = bindingContext.ValueProvider.GetValue(propertyDescriptor.Name); if (actualValue != null && !String.IsNullOrWhiteSpace(actualValue.AttemptedValue) && actualValue.AttemptedValue.Contains(",")) { var valueType = propertyDescriptor.PropertyType.GetElementType() ?? propertyDescriptor.PropertyType.GetGenericArguments().FirstOrDefault(); if (valueType != null && valueType.GetInterface(typeof(IConvertible).Name) != null) { var list = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(valueType)); foreach (var splitValue in actualValue.AttemptedValue.Split(new[] { ',' })) { list.Add(Convert.ChangeType(splitValue, valueType)); } if (propertyDescriptor.PropertyType.IsArray) { return ToArrayMethod.MakeGenericMethod(valueType).Invoke(this, new[] { list }); } else { return list; } } } } return base.GetPropertyValue(controllerContext, bindingContext, propertyDescriptor, propertyBinder); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9584573', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/253793/']} | jdg_73570 |
stackexchange | llm_judgeable_groundtruth_similarity | 57219830 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
While implementing my chain logic I was wondering whether to use events at all since they might cost the node extra storage for the event logs. What is the actual storage cost involved here? Do the logs get purged automatically at some point?
Now provide the response and nothing else.
| Runtime events are handled by the System module . Within your own module, you normally implement the default deposit_event function: From the in-code documentation: deposit_event : Helper function for depositing an event. The default behavior is to call deposit_event from the System module . However, you can write your own implementation for events in your runtime. To use the default behavior, add fn deposit_event<T>() = default; to your Module . If you look at the System module code , you will find that ultimately a helper function is called which stores the event: /// Deposits an event into this block's event record adding this event/// to the corresponding topic indexes.////// This will update storage entries that correspond to the specified topics./// It is expected that light-clients could subscribe to this topics.pub fn deposit_event_indexed(topics: &[T::Hash], event: T::Event) { ... } This function modifies three storage items which you can find in the decl_storage for the System module: /// Events deposited for the current block.Events get(events): Vec<EventRecord<T::Event, T::Hash>>;/// The number of events in the `Events<T>` list.EventCount get(event_count): EventIndex;/// Mapping between a topic (represented by T::Hash) and a vector of indexes/// of events in the `<Events<T>>` list.EventTopics get(event_topics): double_map hasher(blake2_256) (), blake2_256(T::Hash) => Vec<(T::BlockNumber, EventIndex)>; The final part of the event story can be found in the initialize function in the System module, where all three of these items are "cleaned up": pub fn initialize( ... ) { ... <Events<T>>::kill(); EventCount::kill(); <EventTopics<T>>::remove_prefix(&());} This initialize function is called in the Executive module at the beginning of every block, before on_initialize is called for any module: fn initialize_block_impl( block_number: &System::BlockNumber, parent_hash: &System::Hash, extrinsics_root: &System::Hash, digest: &Digest<System::Hash>,) { <system::Module<System>>::initialize(block_number, parent_hash, extrinsics_root, digest); <AllModules as OnInitialize<System::BlockNumber>>::on_initialize(*block_number);} In conclusion, the cost of adding a single Event in the runtime is: Running the deposit_event_indexed function. Adding a new item to two vectors in runtime storage. ... which are cleaned up at the beginning of the next block so the storage cost is not compounding. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57219830', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/540128/']} | jdg_73571 |
stackexchange | llm_judgeable_groundtruth_similarity | 161622 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
It's a question (not hw) I bumped into few years back. Couldn't make any real progress with. Maybe you can help? $$\frac{1}{\sqrt{4}+\sqrt{6}+\sqrt{9}}+\frac{1}{\sqrt{9}+\sqrt{12}+\sqrt{16}}+\frac{1}{\sqrt{16}+\sqrt{20}+\sqrt{25}}=?$$ Thanks.
Now provide the response and nothing else.
| The case of cube roots is probably more interesting than square roots; namely, simplifying $$\frac{1}{\sqrt[3]{4}+\sqrt[3]{6}+\sqrt[3]{9}}+\frac{1}{\sqrt[3]{9}+\sqrt[3]{12}+\sqrt[3]{16}}+\frac{1}{\sqrt[3]{16}+\sqrt[3]{20}+\sqrt[3]{25}}. \tag{$\circ$}$$ To evaluate this, as sos440 did in the comments, one notes the structure of the denominators are apparent as $a^2+ab+b^2$, which appears in the factorization in a difference of cubes, $b^3-a^3$. More generally, this sort of homogeneous polynomial results from using the geometric series formula on the common ratio $b/a$, but I digress. It is clear that we have $$\frac{1}{a^2+ab+b^2}=\frac{b~-~a}{b^3-a^3} \tag{$\bullet$}$$ as the individual terms in $(\circ)$, with $b=\sqrt[3]{k+1}$ and $a=\sqrt[3]{k}$, for $k=2,3,4$. The denominators will all simply be $1$, and the three terms (the numerators) subsequently telescope: $$\big(\sqrt[3]3-\sqrt[3]2\big)+\big(\sqrt[3]4-\sqrt[3]3\big)+\big(\sqrt[3]5-\sqrt[3]4\big)=\sqrt[3]5-\sqrt[3]2. \tag{$\square$}$$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/161622', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/22409/']} | jdg_73572 |
stackexchange | llm_judgeable_groundtruth_similarity | 472177 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
How we back up We currently have a file server that is backed up to tape. The backups are incremental which means the files that have changed since the last backup get written to tape. Over time the tape sets get larger and larger. Once they reach a certain size our backup software grooms the sets back down by removing old versions of files. The problem Under that scheme if a file gets deleted from the server by accident we have a limited amount of time to find out and restore it. Otherwise all versions of that file will get groomed out of the backup tapes after enough time. That's not an acceptable risk. Possible solutions? The only solution I see is to stop grooming our tape sets. The sets will continue to grow in size and once they become unwieldy perhaps we just stow them somewhere off-site and start a new set. Am I missing a better solution? Is such an indefinite file retention policy just unreasonable?
Now provide the response and nothing else.
| Backup to tape is great for long term retention, but for recovering from mistakes, we used backup to disk. Depending on your total storage, this can be a cheap way of keeping at least one copy of every file cheaply and quickly. Say you have a total of 4TB of storage to backup. It doesn't cost much to build a 12TB backup volume and backup to there. Then keep your tapes for long term archival, doing full backups and shipping them off site or into a fire proof safe, etc. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/472177', 'https://serverfault.com', 'https://serverfault.com/users/155942/']} | jdg_73573 |
stackexchange | llm_judgeable_groundtruth_similarity | 22590247 |
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 Activity which uses the Android NavigationDrawer .When using only fragment s (as usual), everything works perfect.But now I want to use this drawer on other activities of my app, and for some of them,I don't want the main view to be a fragment . Question The problem is, the onTouchEvent() of the activity itself (and the onItemClickedListener() of a child ListView for that matter) isn't called, because the drawer consumes it.Of course, I want it to be called:) Needless to say, I would hope the answer will be simple (even a XML one), and hopefully not by extending the Drawer class (unless that's what it takes of course). More Info The Activity's main layout is very simple, basically a ListView and the DrawerLayout on top of it (below in XML). The Drawer has one fragment as it's childView (for fragment navigation) and of course, the ListView for the Drawer Items. I've seen many questions regarding (not exactly) similar issues, and the frequent answer was to use onInterceptTouch() , requestDisallowInterceptTouchEvent() on the DrawerLayout , and on the Parent view ( Activity 's main content) and even onTouchEvent() (with False returned) on the ListView of the Drawer. Nothing seems to do the trick. I read this link and it does seem like using Intercept methods somewhere could be the answer. But how? Please let me know if you need any code. But it's a very basic code/layout for this matter. Thanks!
Now provide the response and nothing else.
| Apparently the answer is somewhat easy, although it does make you extend the DrawerLayout and do some thinking, and maybe will result in some strange results (using the LASTexample, I haven't seen any, yet). Anyway, related questions which looking backwards can help understanding the issue (will explain about the first one later on): 1. DrawerLayout prevents call of MainActivity.onTouchEvent() 2. How can I requestDisallowTouchEvents on Android DrawerLayout 3. Set drag margin for Android Navigation Drawer Answer First, please note that I put lots of examples here. If you just want the best one (for me), jump to the last one. Secondly, if someone has enough reputation, please comment on the first link's question and put a link to this answer (it can help that guy). Example 1 Well, basically, just extend Android's DrawerLayout and replace onTouchEvent() to this: @Overridepublic boolean onTouchEvent(MotionEvent arg0) { super.onTouchEvent(arg0); return false;} This solution will do anything except that it won't open the Drawer on slides, only menu clicks and the like. Besides, it forwards clicks so when the Drawer is openfor instance, touching outside of it will NOT close it, but click on whatever is behind (e.g. a ListView). Le'ts try harder... Example 2 Now, let's catch the open OR visible cases, to return true (and consume the action at the Drawer). @Overridepublic boolean onTouchEvent(MotionEvent arg0) { super.onTouchEvent(arg0); if(isDrawerOpen(findViewById(R.id.list_slidermenu)) || isDrawerVisible(findViewById(R.id.list_slidermenu))){ return true; } return false;} This solution is better, as it prevents clicks on behind the Drawer when the drawer is open or even visible (slide starts...). But touch-sliding it still doesn't work. Example 3 Ok, so let's just split cases. Touches (MotionEvent.ACTION_DOWN) inside the Drawer's margin (area that Google desided to slide Drawer when touched at) will result in returning True to consume the action, and others will forward the event (return False). @Overridepublic boolean onTouchEvent(MotionEvent arg0) { super.onTouchEvent(arg0); float edge = 30;//that's for a left drawer obviously. Use <parentWidth - 30> for the right one. View mDrawerListView = findViewById(R.id.drawer_listview); if(isDrawerOpen(mDrawerListView) || isDrawerVisible(mDrawerListView)){ return true; } else if(arg0.getAction() == MotionEvent.ACTION_DOWN && arg0.getX() > edge){ return false; } return true;} Note that I used 30dp. That's what I found to be the margin (although in one of the links it is said to be 20....). Well, the next example would of course be deciding what is, exactly, that edge (see in code above) value is, according to Android. We don't want to use a number that could change or whatever. New Question So now that first link should come handy. It "hacks" the Drawer code to get that Drawer edge/megin number. BUT, it didn't work for me, as those exact Field names could not be found. I run mDrawerLayout.getClass().getField() which returns all the fields, but without any luck finding what we want. Anyone? Last Example - Full Code Ok, looking on example number 3, after understanding what exactly I did, we can make it faster by extending the onFinishInflate() method and save it as a global variablefor this CustomDrawerLayout for later use. We can also put that first 'if' inside the second one to save some more work. OK here goes: View mDrawerListView;...@Overrideprotected void onFinishInflate() { super.onFinishInflate(); mDrawerListView = findViewById(R.id.drawer_listview);}@Overridepublic boolean onTouchEvent(MotionEvent event) { super.onTouchEvent(event); if(event.getX() > 30 && event.getAction() == MotionEvent.ACTION_DOWN){ if(isDrawerOpen(mDrawerListView) || isDrawerVisible(mDrawerListView)){ return true; } else{ return false; } } return true;} That's it for now! Hope it'll helps someone in the future beside myself, hehe.... | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22590247', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2774781/']} | jdg_73574 |
stackexchange | llm_judgeable_groundtruth_similarity | 1320963 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to prove that $45$ is composite using Fermat's Little Theorem. I am given a hint which states: "Find an integer $b$ such that $b^{45} \not \equiv b \pmod{45}$ and explain why this implies that $45$ cannot be prime." If I understand, the reason that finding such a $b$ would be sufficient to show that $45$ is composite is because this would demonstrate the contrapositive of Fermat's Little Theorem insofar as if $a^p \not \equiv a\pmod{p}$ then $p$ is not a prime. I have first tried finding such a $b$ but I'm simply guessing and that doesn't seem like the best approach to this. Any help would be appreciated on how to proceed.
Now provide the response and nothing else.
| Well, to find a satisfactory $b$, we can make use of our knowledge of the decomposition $45=3^2\times 5$. This means if we pick $b=3\times5=15$, then we would have $b^n\equiv0\pmod{45}$ for any $n\ge 2$ (in particular for $n=45$). [Added for clarity] More explicitly, note that $15^2=3^2\times5^2=45\times 5$. Hence if $n\ge2$, then$$15^n\equiv 15^2\times15^{n-2}\equiv 45\times 5\times 15^{n-2}\equiv 0\pmod {45}$$ Perhaps making use of the known factorization is in some sense cheating. In that case, you can just say $15^2=225=5\times 45$, and so $15^2\equiv 0\pmod{45}$, and then use $$15^n\equiv 15^2\times15^{n-2}\equiv 0\times15^{n-2}\equiv0\pmod{45}$$ However, our motivation for looking at the number $15$ does come from us already knowing the factorization of $45$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1320963', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/131029/']} | jdg_73575 |
stackexchange | llm_judgeable_groundtruth_similarity | 522222 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What are the primary differences between LISP and C# with regards to functional programming? In specific, if a LISP programmer was to switch to using C#, what are the features they are most likely to miss?
Now provide the response and nothing else.
| Doing functional programming in C# is technically possible (well, any language that has function pointers or delegates equivalent can be "functional") -- but C# gets very very painful if you try to do much. Off the top of my head, in no particular order: Type inference Only exists for locals now Should apply to pretty much everything The #1 problem I have with C# is this. Particularly when you declare a local function... Func<...> = ouch. Full first class functions Delegates aren't the answer, since they aren't structually equivalent. There's no canonical type to represent a function of a certain type. Ex: What is "increment"? Is it a Func? Is it a Converter? Is it something else? This in turn makes inference more complicated. Automatic generalization Sucks to have to calculate and specify all the generic type parameters and their constraints Better support for immutability Make it trivial to declare simple data types Copy-with-modify type stuff (var x = oldX { SomeField = newVal }) Tuples C# 7 Discriminated unions (sum types) Pattern matching C# 7 Makes tuples and sum types much more valuable Allows more expression-oriented code General monad syntax Makes things like async code much easier to write C# 5 After you've nested 2+ layers of BeginXXX/EndXXX, it gets quite ugly. Easy syntax for function blocks, so you don't end up with closing lines like "});});" Edit: One more: Function composition Right now it's painful to do much of any sort of function composition. Currying, chaining, etc. LINQ doesn't get as hurt here because extension methods take the first parameter like an instance method. C# should emit tail.call too. Not needed, the JIT will add tail calls itself as appropriate. Items in bold have been addressed since this answer was written. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/522222', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/30917/']} | jdg_73576 |
stackexchange | llm_judgeable_groundtruth_similarity | 2832953 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am having a bit of trouble working out when an image has been loaded. I have been told that the following function will work but it isn't doing anything. $("#photos img:first").load(function (){ alert("Image loaded!");}); There are no error's in my code. Everything else in my script works great. My HTML looks like this. <div id="photos"> <img src="../sample1.jpg" style="background-color:#000033" width="1" height="1" alt="Frog!"/> <img src="../sample2.jpg" style="background-color:#999999" width="1" height="1" alt="Zooey!"/></div> Do I have the wrong JQuery function? It should also be noted that the visibility is set to hidden. However even when visible there is no alert. Any ideas?
Now provide the response and nothing else.
| The load event of an image is fired when it's loaded (doh!), and critically, if you don't hook up your handler before it loads, your handler won't get called. Browsers will load resources in parallel, so you can't be sure (even in jQuery's ready event saying the page's DOM is ready) that the image hasn't already been loaded when your code runs. You can use the complete property of the image object to know whether it's already been loaded, so: var firstPhoto = $("#photos img:first");if (firstPhoto[0].complete) { // Already loaded, call the handler directly handler();}else { // Not loaded yet, register the handler firstPhoto.load(handler);}function handler() { alert("Image loaded!");} There may even be a race condition in that, if the browser in question really implements multi-threaded loading where the image load may occur on a different thread than the Javascript thread. Of course, if your selector will match multiple images, you'll need to handle that; your selector looks like it's supposed to match only one, so... Edit This version allows for multiple images, and I think it handles any non-Javascript race conditions (and of course, at present there are no Javascript race conditions; Javascript itself is single-threaded in browsers [unless you use the new web workers stuff]): function onImageReady(selector, handler) { var list; // If given a string, use it as a selector; else use what we're given list = typeof selector === 'string' ? $(selector) : selector; // Hook up each image individually list.each(function(index, element) { if (element.complete) { // Already loaded, fire the handler (asynchronously) setTimeout(function() { fireHandler.call(element); }, 0); // Won't really be 0, but close } else { // Hook up the handler $(element).bind('load', fireHandler); } }); function fireHandler(event) { // Unbind us if we were bound $(this).unbind('load', fireHandler); // Call the handler handler.call(this); }}// Usage:onImageReady("#photos img:first"); A couple of notes: The callback doesn't get the event object; you could modify it to do so if you liked, but of course, there'd be no event in the case where the image is already loaded, so it would be of limited utility. You could probably use one instead of bind and unbind , but I like the clarity and I'm paranoid. :-) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2832953', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/244681/']} | jdg_73577 |
stackexchange | llm_judgeable_groundtruth_similarity | 1155321 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
There is a question (2.4.c) marked ** (to denote "extremely difficult/currently open problem") in Silverman and Tate's Rational Points on Elliptic Curves which I found really interesting and wondered if anyone can shed any more light on the problem for me. Let $p\geq 5$ be a prime and let $C=C_p: y^2 = x^3 + 1$ be the cubic curve over the finite field $\mathbb{F}_p$. Let $M_p = \left\vert C(\mathbb{F}_p)\right\vert$ be the order of the group of rational points of $C$ (this includes the point at infinity). Looking at some small primes I proved that if $p\equiv 2 \pmod 3$ then $M_p = p+1$. The interesting case is when $p\equiv 1 \pmod 3$. I wrote a program which computes $M_p$ where $p\equiv 1\pmod 3$ is prime. We get the following sequence, where the $i$th term is the value of $M_p$ for the $i$th largest prime $p$ of the form $p\equiv 1\pmod 3$, and I have computed here for all $p\leq 1000$: $12, 12, 12, 36, 48, 36, 48, 84, 84, 84, 84, 84, 108, 108, 156, 156, 144, 156, 156, 192, 228, 228, 252, 252, 228, 300, 252, 252, 324, 336, 300, 372, 336, 372, 336, 372, 432, 372, 444, 432, 468, 468, 444, 444, 468, 516, 588, 588, 588, 624, 576, 588, 624, 588, 588, 684, 624, 624, 684, 732, 684, 684, 756, 804, 732, 768, 732, 756, 876, 876, 912, 804, 912, 876, 948, 972, 912, 948, 948, 1008, \dots$ It seems that however many terms you take their GCD is always $12$, and this doesn't change as far as $p\leq 3000$, so I have two questions: Can anyone prove that $M_p$ is always divisible by 12? Since 1992 when the book was published, has anyone found an expression for $M_p$? Any extra information about this sequence (or related topics/papers) is very welcome!
Now provide the response and nothing else.
| The numbers you actually want to look at turn out to be $$a_p = p + 1 - |C(\mathbb{F}_p)|.$$ There is a lot to say about these numbers. The Hasse-Weil bound implies that $|a_p| \le 2 \sqrt{p}$. The Weil conjectures explain why this bound holds: it's because (for all but finitely many $p$) there is a pair of conjugate algebraic numbers $\alpha_p, \overline{\alpha}_p$ of absolute value $\sqrt{p}$ such that $$|C(\mathbb{F}_{p^n})| = p^n + 1 - \alpha_p^n - \overline{\alpha}_p^n$$ for all $n$, which gives $$a_p = \alpha_p + \overline{\alpha}_p.$$ The Sato-Tate conjecture describes the asymptotic distribution of these numbers as $p$ varies. Finally, one way to state the modularity theorem (which was not a theorem when Silverman-Tate was published!) in this case is that there is a modular form $$f(q) = \sum_{n \ge 0} b_n q^n$$ which must be a "normalized cuspidal Hecke eigenform of weight $2$ and level $N$," where $N$ is a positive integer called the conductor of $C$, such that $b_0 = 0$ ("cuspidal"), $b_1 = 1$ ("normalized"), and $$a_p = b_p$$ for all primes $p$ not dividing $N$. So essentially the best you can do as far as finding a formula for the $a_p$ goes is to find a concise description of this modular form. Sage informs me that this curve has conductor $36$ and that there is a unique normalized cusp form of weight $2$ and level $36$, which is necessarily the Hecke eigenform we want. This implies that $y^2 = x^3 + 1$ must in fact be (isogenous to?) the modular curve $X_0(36)$. The $q$-expansion of this modular form begins $$q - 4 q^7 + 2 q^{13} + 8 q^{19} - 5 q^{25} + \dots$$ and according to this paper that I found , it is $\eta (6 \tau)^4$ where $\eta$ is the Dedekind eta function . The $q$-expansion of this modular form, in full, is therefore $$f(q) = q \prod_{n=1}^{\infty} (1 - q^{6n})^4.$$ See also the pentagonal number theorem , which leads to an expression for $a_p = b_p$ in terms of a signed sum over the set of ways $\frac{p - 1}{6}$ can be written as a sum of $4$ pentagonal numbers. Edit: Here is a proof that $|C(\mathbb{F}_p)|$ is divisible by $12$ when $p \equiv 1 \bmod 3$. As Greg Martin says in the comments, this is equivalent to showing that $C(\mathbb{F}_p)$ has full 2-torsion and a 3-torsion point. The 2-torsion points on an elliptic curve in Weierstrass normal form are precisely those of the form $(x_0, 0)$, together with the point at infinity, and hence the number of 2-torsion points is the number of roots of $x^3 + 1$, plus one. Now, if $p \equiv 1 \bmod 6$, then $\mathbb{F}_p^{\times}$ contains an element of order $6$, and hence $\mathbb{F}_p$ has all sixth roots of unity. Since the roots of $x^3 + 1$ are sixth roots of unity, it follows that $x^3 + 1$ has $3$ roots over $\mathbb{F}_p$ in this case, and hence there are $4$ 2-torsion points, as desired. It remains to show that there is also a nontrivial $3$-torsion point. Recall that a point is $3$-torsion iff its tangent line intersects the curve with multiplicity $3$. In fact, the points $(0,\pm 1)$ both have this property: their tangent lines take the form $y = \pm 1, x = t$, and substituting this in gives $t^3 = 0$. So there are always at least $3$ 3-torsion points, as desired. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1155321', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/184547/']} | jdg_73578 |
stackexchange | llm_judgeable_groundtruth_similarity | 2924116 |
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 no idea how to handle this in ColdFusion 9, I have a form being submitted (POST) with element checkboxes, called items[]. When I do a <cfdump var="#form#" /> no-problem, I get all the items shown with the proper names like items[] eg: struct ITEMS[] 13,14 FIELDNAMES ITEMS[] however doing a <cfdump var="#form.items[]#" /> results in an error. How do I access the CF9 field values? Somehow loop through it? I cannot seem to do anything with the array to get the id's out of it? Thoughts? I'm kind of stumped and ColdFusion isn't the easiest language to find examples / references on the net. ;) Is there a correct way to deal with this? I need to get the ID's out of there so I can reference what lines were checked in the form, so I can follow up with an action. Thanks!
Now provide the response and nothing else.
| There's no Form Array’s in ColdFusion. Having '[]' at the end doesn't make it an array. You can access the checkbox values from form scope like this: FORM["ITEMS[]"] Dot notation doesn't work 'cause of the '[]' . See: http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSc3ff6d0ea77859461172e0811cbec22c24-7fb2.html Values from checkboxes are just comma separated values, which is a List in ColdFusion To loop through it, use cfloop list=: <cfoutput> <cfloop index="i" list="#FORM['ITEMS[]']#"> #i# </cfloop></cfoutput> To convert a list to array, use ListToArray() . There are list functions like listGetAt() , but if you're doing lots of random access, it'd be smarter to convert the list into an array first. Thoughts, I'm kindof stumped and coldfusion isn't the easiest language to find examples / references on the net ;) http://help.adobe.com/en_US/ColdFusion/9.0/Developing/index.html http://learncf.com/tutorials http://www.easycfm.com/ http://www.carehart.org/ugtv/ | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2924116', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/158014/']} | jdg_73579 |
stackexchange | llm_judgeable_groundtruth_similarity | 38424619 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is a follow-up question from a previous question on Stackoverflow . I've tried to remove large files from my local git history, but the tool (BFG Repo-Cleaner) suggested in this question states that my private GitHub repository is not a valid git repository. The command I use is: java -jar bfg-1.12.12.jar --strip-blobs-bigger-than 99M https://github.com/name/repo.git Which eventually results in: Aborting : https://github.com/name/repo.git is not a valid Git repository. I couldn't find a solution. Is the tool not compatible with private or https GitHub repositories?How would I use the alternative tool git-filter-branch , to remove all files larger than 99MB from my local git history? The project is about 6MB large and only about 50 commits were made up to now and no other people are working on it.
Now provide the response and nothing else.
| Point to a local copy, not a remote. You have given your GitHub URL to the tool, but the usage section on their site says that you should work from a local copy of your repository: Usage First clone a fresh copy of your repo, using the --mirror flag: $ git clone --mirror git://example.com/some-big-repo.git This is a bare repo, which means your normal files won't be visible, but it is a full copy of the Git database of your repository, and at this point you should make a backup of it to ensure you don't lose anything. Now you can run the BFG to clean your repository up: $ java -jar bfg.jar --strip-blobs-bigger-than 100M some-big-repo.git There is lots of other good content on that page; I recommend you read the entire thing before trying again. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38424619', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5438714/']} | jdg_73580 |
stackexchange | llm_judgeable_groundtruth_similarity | 12833979 |
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 SQL table called 'brands' with the columns id, name, url.In that table I have this data set: 1, Solidfloor, solidfloor;2, Quickstep, quickstep;4, Cleanfloor, cleanfloor;5, Blue Dolphin, blue-dolphin;6, Krono, krono;8, Meister, meister; I'm fetching them all right now and I get a nice array in return, but, I need the index of the arrays to not be an incremented number, but the id of that particular row. I could of course loop through the result set, but is there a cleaner way of doing this?
Now provide the response and nothing else.
| Fetch as assoc For the manual: http://php.net/manual/en/pdostatement.fetchall.php fetch_style Controls the contents of the returned array as documented in PDOStatement::fetch(). Defaults to value of PDO::ATTR_DEFAULT_FETCH_MODE (which defaults to PDO::FETCH_BOTH) To return an array consisting of all values of a single column from the result set, specify PDO::FETCH_COLUMN. You can specify which column you want with the column-index parameter. To fetch only the unique values of a single column from the result set, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_UNIQUE. To return an associative array grouped by the values of a specified column, bitwise-OR PDO::FETCH_COLUMN with PDO::FETCH_GROUP. That last bit is key. It doesn't seem to be completely documented (that I could find), but instead of PDO::FETCH_COLUMN, you can combine PDO::FETCH_ASSOC with PDO::FETCH_GROUP to achieve the desired result: $PDOstmt->fetchAll(PDO::FETCH_ASSOC | PDO::FETCH_GROUP) So, given the above data: $stmt = $PDO_obj->prepare('select * from brands');$stmt->execute();$result = $stmt->fetchAll(PDO::FETCH_ASSOC | PDO::FETCH_GROUP);d($result); Results in: array (6) [ '1' => array (1) [ array (2) [ 'name' => string (10) "Solidfloor" 'url' => string (10) "solidfloor" ] ] '2' => array (1) [ array (2) [ 'name' => string (9) "Quickstep" 'url' => string (9) "quickstep" ] ] '4' => array (1) [ array (2) [ 'name' => string (10) "Cleanfloor" 'url' => string (10) "cleanfloor" ] ] '5' => array (1) [ array (2) [ 'name' => string (12) "Blue Dolphin" 'url' => string (12) "blue-dolphin" ] ] '6' => array (1) [ array (2) [ 'name' => string (5) "Krono" 'url' => string (5) "krono" ] ] '8' => array (1) [ array (2) [ 'name' => string (7) "Meister" 'url' => string (7) "meister" ] ]] ( d() is just a handy debugging function from the kint library, like var_dump() or print_r() ) Note that the column used to index the array will always be the first column in the results, so you can modify your select statement to choose which column you want. And note also that the indexed column will be stripped out of each row's array; to get around that, you can add the column twice to your select statement (i.e., select id, brands.* from brands , etc.). There are more parameters documented here: http://php.net/manual/en/pdostatement.fetch.php , like PDO::FETCH_UNIQUE to make sure that each index is used only once. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12833979', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/811183/']} | jdg_73581 |
stackexchange | llm_judgeable_groundtruth_similarity | 49185304 |
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 are two of the ways to write functions in Clojure: (defn foo [a b] (+ a b))(fn foo [a b] (+ a b)) I can call them like so: In the case of 'defn' (foo 1 2) In the case of 'fn' ((fn foo [a b] (+ a b)) 1 2) 'fn' doesn't seem to insert its optional name into the current scope, where 'defn' seems to do exactly that. Is there any other difference or reason for having two ways of creating functions? Is there a reason we don't just use 'fn' like this: (fn foo [a b] (+ a b))(foo 1 2)
Now provide the response and nothing else.
| defn is basically defined as*: (defmacro defn [name args & body] `(def ~name (fn ~args ~@body))) Or in other words, you could basically write: (defn my-func [a] (stuff a)) As*: (def my-func (fn [a] (stuff a))) Using just fn creates an anonymous function that alone isn't bound to any symbol externally. It must be bound using let or def to be referred to outside of itself. By having defn defined in terms of def and fn , the responsibilies of binding a function to a symbol (as well as all the other complexities that come with it) and handling function behaviour can be separated. When you supply a name for fn , it can't be referred to outside of the function, but it can be used to refer to itself to create a recursive anonymous function: (fn my-func [n] (my-func (inc n)) And, it gives the function a slightly nicer name to show up in stack traces to ease debugging: (defn my-func [] ((fn my-inner-func [] (/ 1 0))))=> #'digital-rain.core/my-func(my-func)java.lang.ArithmeticException: Divide by zero at clojure.lang.Numbers.divide(Numbers.java:158) at clojure.lang.Numbers.divide(Numbers.java:3808) at digital_rain.core$my_func$my_inner_func__2320.invoke(form-init1838550899342340522.clj:2) at digital_rain.core$my_func.invokeStatic(form-init1838550899342340522.clj:2) at digital_rain.core$my_func.invoke(form-init1838550899342340522.clj:1) * These are gross understatements and a tad misleading, but they simplify things. In reality, defn isn't defined using defmacro ; defmacro is actually defined using defn . defn also adds some good stuff like pre/post condition checking, documentation, and other meta information; but that's not as relevant here. I recommend looking over its source for a more in-depth look; although it's pretty convoluted. The fundamental guts of clojure.core can be a little daunting to wrap your head around. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49185304', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/514773/']} | jdg_73582 |
stackexchange | llm_judgeable_groundtruth_similarity | 9191318 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm new to Backbone.js. I have gone through the documentation. My question is where does the controller concept come into picture? In other words, what is a controller in Backbone.js? I heard that the router is the controller. If so, why it is considered as a controller? Can we develop simple basic apps without the Router also? In that case what will be the controller?
Now provide the response and nothing else.
| To clear things a little bit here. A Router is not a Controller, It's a way to define a client-side route map (similar to Rails's routes.rb). This helps routing client-side pages to certain actions/handlers. And that's different from a controller's job which is to provide a bit of orchestration between Models and Views. And there is actually more than one way to do this using Backbone. Quoting from Backbone's documentation : References between Models and Views can be handled several ways. Some people like to have direct pointers, where views correspond 1:1 with models (model.view and view.model). Others prefer to have intermediate "controller" objects that orchestrate the creation and organization of views into a hierarchy. Others still prefer the evented approach, and always fire events instead of calling methods directly. All of these styles work well. This brings three different approaches to accomplish this. The first one is pretty straightforward which is to have the model object included as a property to the view. The second one proposes including a third component that performs this role of orchestration. I believe this can be helpful in quite large and complex applications. For this I encourage you to look at Chaplin , a sample application architecture using Backbone.js. The guys have done a great job in separating things out and also introduced the concept of a Controller into the architecture. The last approach is suggesting using events to mark for actions and mediator to handle these actions. For this I encourage you to look into the mediator and Publish/Subscribe JavaScript patterns. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9191318', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2279170/']} | jdg_73583 |
stackexchange | llm_judgeable_groundtruth_similarity | 20897 |
Below is a question asked on the forum scicomp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I work on geological problems and I use the Finite Element Method. But this question can be applied on other classical mechanical problems. I work on implicit 3D surfaces (which represent the limits between two geological layers aka two media). I have to impose displacement on these surfaces (Dirichlet Condition). The condition that I impose on surfaces are transfered on the surrounding nodes. I make the assumption that I can use the " classical" way to apply Dirichlet Condition (penalty method in my case) on these nodes, that are NOT on the the boundaries. My question is: do you think this assumption is valid? Have you got some references about the subject? As I understand the problem I try to apply Boundary Conditions not on the boundaries... Thank you in advance. Best. EDIT We try to solve this problem:$$ \left\{ \begin{aligned} \sigma_{ij,j} + F_{i} &= 0 & &\text{in the domain $\Omega$}&\\ u_i&= q_{i}& &\text{on the boundary $\Gamma_{q}$}&\\ \sigma_{ij}n_{j} &= h_{i}& &\text{on the boundary $\Gamma_{h}$}&\\ u_i &= b_{i}& &\text{punctually in the domain $\Omega$}&\\ \end{aligned} \right.$$ We run the FEA on a mesh. We basically try to impose Dirichlet Condition on the nodes which are inside the domain $\Omega$ (fourth line). We constrain the displacement value of $u_i$ to $b_i$ for these nodes.
Now provide the response and nothing else.
| The solution of the equation you are looking for is in the space $H^1$ of functions that have one weak derivative, but in 2d and 3d, this does not imply that the solution is in fact continuous. As a consequence, it is not possible to define the value of a solution at individual points, and equally consequentially, it is mathematically not possible to prescribe (boundary) values at individual points. But I suspect that you're not actually interested in prescribing values for the displacement at individual points, but for all points along a line (in 2d) or surface (in 3d), and this is perfectly valid. (Mathematically speaking, this is so because the trace operator is well defined on $H^1$). At the discrete level, this is then equivalent to prescribing the values on all nodes that lie on this line/surface. Conceptually, you can think of this as a crack in your domain that is occupied by an infinitely thin device whose displacement you can manipulate and that attached to the two sides of the crack. | {} | {'log_upvote_score': 4, 'links': ['https://scicomp.stackexchange.com/questions/20897', 'https://scicomp.stackexchange.com', 'https://scicomp.stackexchange.com/users/17731/']} | jdg_73584 |
stackexchange | llm_judgeable_groundtruth_similarity | 634775 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Specifically I am trying to grasp how SQL statements differ from normal C style programming, I can't seem to understand how to do stuff like "for every userid in this table that has another column of data equal to such and such, run this stored procedure" which in programming would be a for loop, how the heck do you do stuff like that? Or like, for each row in tableA that has a contentID of 11, add a new row to tableB containing this data and the userID from the row of tableA found containing contentID of 11... Anyone mind possibly writing a bit on how I should understand SQL statements compared to programming? I feel like I could wield it better if I understood how I was suppose to think about it...
Now provide the response and nothing else.
| They are approaching the world from different points of view. C is about performing actions. SQL is about storing data, and manipulating data. The only "actions" it is good at are pulling and changing data. Think of all your data like a Venn diagram - SQL lets you "look" at any part of that diagram you want. If you want to actually do something to that data, then in C, you might say "Go to every user and perform this action on them", as in //if a customer is late, send them a reminderfor(int i=0;i<USER_COUNT-1;++i){ if(LATE_ON_PAYMENTS=CustomerType(Customers[i])){ SendReminder(Customers[i]); } //if cust is late on their payments} //for ea customer In SQL, you would be able to ASK for the list of users, as in: SELECT *FROM CUSTOMERSWHERE LATE_FLAG = 'Y'; Or you could change data regarding those customers, as in: UPDATE CUSTOMERSSET TRUST_LEVEL = TRUST_LEVEL - 1 --trust a little less when they are lateWHERE LATE_FLAG = 'Y'; Note that this UPDATE could affect any number of rows, but there is no loop... you are simply saying "look up these records, and change them in this way". But if you wanted to send them a reminder, well that's just too bad... you've got to use C or a stored procedure to do that. You really get the best of both worlds when you combine a traditional language with SQL. If you can replace the earlier example in C with this (disclaimer: I know this is bogus code, it's just an example): //if a customer is late, send them a reminder//get all the late customerssqlCommand = 'SELECT CUSTOMER_ID FROM CUSTOMERS WHERE LATE_FLAG = ''Y''';dataSet = GetDataSet(sqlCommand);//now loop through the late customers i just retrieved for(int i=0;i<dataSet.RecordCount - 1;++i){ SendReminder(dataSet[i].Field('CUSTOMER_ID'));} //for ea customer Now the code is more readable, and everyone is pointed at the same data source at runtime.You also avoid the potentially messy code in C that would have been involved in building your list of customers - now it is just a dataset. Just as SQL sucks at doing imperative actions, C sucks at manipulating data sets. Used together, they can easily get data, manipulate it, and perform actions on it. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/634775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/18309/']} | jdg_73585 |
stackexchange | llm_judgeable_groundtruth_similarity | 18726867 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
It's not too hard to demonstrate that strcpy on overlapped source and destination addresses fails on some platforms, either producing incorrect results or trapping (the latter with some negative random offsets on Linux/amd64). I'd instrumented a strcpy wrapper function for our codebase with an debug-build assertions that check for such overlapped copies, and have received a number of internal development requests to weaken this assertion checking so that it only raises an abortion for non-zero overlaps. I've been hesitant to do so, based on my read of the strcpy documentation since I'd assume that equal source and destinations would count as overlapped. Is overlapped defined explicitly in the C++ standard (or C), and does this also include equality? I suspect many vendor strcpy implementations special case this despite the freedom the standard allows to have this be undefined behavior. Are there any platform/hardware combinations where such an equal copy is known to fail?
Now provide the response and nothing else.
| Start by creating a new TextWriter that is capable of writing to a textbox. It only needs to override the Write method that accepts a char , but that would be ungodly inefficient, so it's better to overwrite at least the method with a string. public class ControlWriter : TextWriter{ private Control textbox; public ControlWriter(Control textbox) { this.textbox = textbox; } public override void Write(char value) { textbox.Text += value; } public override void Write(string value) { textbox.Text += value; } public override Encoding Encoding { get { return Encoding.ASCII; } }} In this case I've had it just accept a Control , which could be a Textbox , a Label , or whatever. If you want to change it to just a Label that would be fine. Then just set the console output to a new instance of this writer, pointing to some textbox or label: Console.SetOut(new ControlWriter(textbox1)); If you want the output to be written to the console as well as to the textbox we can use this class to create a writer that will write to several writers: public class MultiTextWriter : TextWriter{ private IEnumerable<TextWriter> writers; public MultiTextWriter(IEnumerable<TextWriter> writers) { this.writers = writers.ToList(); } public MultiTextWriter(params TextWriter[] writers) { this.writers = writers; } public override void Write(char value) { foreach (var writer in writers) writer.Write(value); } public override void Write(string value) { foreach (var writer in writers) writer.Write(value); } public override void Flush() { foreach (var writer in writers) writer.Flush(); } public override void Close() { foreach (var writer in writers) writer.Close(); } public override Encoding Encoding { get { return Encoding.ASCII; } }} Then using this we can do: Console.SetOut(new MultiTextWriter(new ControlWriter(textbox1), Console.Out)); | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18726867', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/189270/']} | jdg_73586 |
stackexchange | llm_judgeable_groundtruth_similarity | 39547858 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
ng-container is mentioned in the official documentation but I'm still trying to understand how it works and what are use cases. It is particularly mentioned in ngPlural and ngSwitch directives. Does <ng-container> do the same thing as <template> or does it depend on whether a directive was written to use one of them? Are <ng-container *ngPluralCase="'=0'">there is nothing</ng-container> and <template [ngPluralCase]="'=0'">there is nothing</template> supposed to be the same? How do we choose one of them? How can <ng-container> be used in a custom directive?
Now provide the response and nothing else.
| Edit : Now it is documented <ng-container> to the rescue The Angular <ng-container> is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM. (...) The <ng-container> is a syntax element recognized by the Angular parser. It's not a directive, component, class, or interface. It's more like the curly braces in a JavaScript if-block: if (someCondition) { statement1; statement2; statement3; } Without those braces, JavaScript would only execute the first statement when you intend to conditionally execute all of them as a single block. The <ng-container> satisfies a similar need in Angular templates. Original answer: According to this pull request : <ng-container> is a logical container that can be used to group nodes but is not rendered in the DOM tree as a node. <ng-container> is rendered as an HTML comment. so this angular template : <div> <ng-container>foo</ng-container><div> will produce this kind of output : <div> <!--template bindings={}-->foo<div> So ng-container is useful when you want to conditionaly append a group of elements (ie using *ngIf="foo" ) in your application but don't want to wrap them with another element . <div> <ng-container *ngIf="true"> <h2>Title</h2> <div>Content</div> </ng-container></div> will then produce : <div> <h2>Title</h2> <div>Content</div></div> | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/39547858', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3731501/']} | jdg_73587 |
stackexchange | llm_judgeable_groundtruth_similarity | 48343387 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I can't completely understand the difference between Type and Value error in Python3x. Why do we get a ValueError when I try float('string') instead of TypeError? shouldn't this give also a TypeError because I am passing a variable of type 'str' to be converted into float? In [169]: float('string')---------------------------------------------------------------------------ValueError Traceback (most recent call last)<ipython-input-169-f894e176bff2> in <module>()----> 1 float('string')ValueError: could not convert string to float: 'string'
Now provide the response and nothing else.
| A Value error is Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value the float function can take a string, ie float('5') , it's just that the value 'string' in float('string') is an inappropriate (non-convertible) string On the other hand, Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError so you would get a TypeError if you tried float(['5']) because a list can never be converted into a float. Cite | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/48343387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9240584/']} | jdg_73588 |
stackexchange | llm_judgeable_groundtruth_similarity | 13022016 |
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 an article on MSDN, it states that the double data type has a range of "-1.79769313486232e308 .. 1.79769313486232e308". Whereas the long data type only has a range of "-9,223,372,036,854,775,808 .. 9,223,372,036,854,775,807". How can a double hold so much more data than a long if they are both 64 bits in size? http://msdn.microsoft.com/en-us/library/cs7y5x0x(v=vs.90).aspx
Now provide the response and nothing else.
| The number of possible doubles, and the number of possible longs is the same, they are just distributed differently*. The longs are uniformly distributed, while the floats are not. You can Read more here . I'd write more, but for some reason the cursor is jumping around all over the place on my phone. Edit: This might actually be more helpful: http://en.wikipedia.org/wiki/Double-precision_floating-point_format#section_1 Edit2: and this is even better: http://blogs.msdn.com/b/dwayneneed/archive/2010/05/07/fun-with-floating-point.aspx * According to that link, it would seem that there are actually more longs, since some doubles are lost due to the way NaNs and other special numbers are represented. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13022016', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1054899/']} | jdg_73589 |
stackexchange | llm_judgeable_groundtruth_similarity | 28715859 |
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 some code that pulls all documents from a collection and puts it onto a webpage. a simplified version looks like this: var mongodb = require("mongodb"), express = require("express"), mongoServer = new mongodb.Server('localhost', 27017), dbConnector = new mongodb.Db('systemMonitor', mongoServer), db;var app = new express();app.get('/drives', function(req, res) { db.collection('driveInfo', function(err, collection) { if (err) throw err; collection.find({}, function(err, documents) { res.send(documents); }); });});dbConnector.open(function(err, opendb) { if (err) throw err; db = opendb; app.listen(80);}); I have a driveInfo collection which contains a long list of documents. Each document contains nested objects. What I would like to do, is whenever someone visits /drives in their browser, to print the entire collection as a json object so that I can grab everything with jquery later (beginnings of an api) However, I get an error saying "TypeError: Converting circular structure to JSON". The error on the page points to this line of code: collection.find({}, function(err, documents) { res.send(documents);}); I'm unsure what the problem is, or where the self-reference is. Am I not querying the collection properly?
Now provide the response and nothing else.
| Not sure what version of the API you are using, but i think that your syntax might be wrong looking at the API spec: http://docs.mongodb.org/manual/reference/method/db.collection.find/ This is the declaration: db.collection.find(<criteria>, <projection>) And you are definitely misusing the projection parameter. Passing a callback like you are doing seems to return the db object in the result, which is causing the circular error during JSON serialization in express. The correct code for the find all operation should be something like: collection.find({}).toArray(function(error, documents) { if (err) throw error; res.send(documents);}); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28715859', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2605604/']} | jdg_73590 |
stackexchange | llm_judgeable_groundtruth_similarity | 11603005 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: C++ delete - It deletes my objects but I can still access the data? Can a local variable's memory be accessed outside its scope? I do not understand what delete really does when I want to free memory allocated with new . In C++ Premiere book it is written: This removes the memory to which ps pointer points; it doesn’t remove the pointer ps itself. You can reuse ps, for example, to point to another new allocation. You should always balance a use of new with a use of delete; otherwise, you can wind up with a memory leak—that is, memory that has been allocated but can no longer be used. If a memory leak grows too large, it can bring a program seeking more memory to a halt. So as I understand delete must delete the value in the memory to which pinter points. But it doesn't. Here's my experiment: int * ipt = new int; // create new pointer-to-intcout << ipt << endl; // 0x200102a0, so pointer ipt points to address 0x200102a0cout << *ipt << endl; // 0, so the value at that address for now is 0. Ok, nothing was assigned*ipt = 1000; // assign a value to that memory addresscout << *pt << endl; // read the new value, it is 1000, okcout << *((int *) 0x200102a0) << endl; // read exactly from the address, 1000 toodelete ipt; // now I do delete and then checkcout << ipt << endl; // 0x200102a0, so still points to 0x200102a0cout << *ipt << endl; // 1000, the value there is the samecout << *((int *) 0x200102a0) << endl; // 1000, also 1000 is the value So what does delete really do?
Now provide the response and nothing else.
| Think of memory as a big warehouse with lots of boxes to put things into. When you call "new", the warehouse staff finds an unused box large enough for your needs, records that box as being owned by you (so it's not given to someone else), and gives you the number of that box so you can put your stuff into it. This number would be the "pointer". Now, when you "delete" that pointer, the reverse happens: the warehouse staff notes that this particular box is available again. Contrary to real warehouse staff they aren't doing anything with the box — so if you look into it after a "delete" you might see your old stuff. Or you might see somebody else’s stuff, if the box was reassigned in the meantime. Technically, you are not allowed to look into your box once you have returned it to the pool, but this is a somewhat weird warehouse with no keys or guards, so you can still do whatever you want. However, it might cause problems with the new owner of the box, so it's expected that you follow the rules. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11603005', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1114926/']} | jdg_73591 |
stackexchange | llm_judgeable_groundtruth_similarity | 27799026 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using a wordpress theme that has it's own framwork which is based upon redux framework I think. I am modifying this theme using a child theme. I want to add to the Theme Options in the backend and I found a function within the files of the parent theme that seems to be exactly what I need: /* * * Custom function for filtering the sections array. Good for child themes to override or add to the sections. * Simply include this function in the child themes functions.php file. * * NOTE: the defined constansts for URLs, and directories will NOT be available at this point in a child theme, * so you must use get_template_directory_uri() if you want to use any of the built in icons * */function add_another_section($sections){ //$sections = array(); $sections[] = array( 'title' => __('A Section added by hook', 'swift-framework-admin'), 'desc' => __('<p class="description">This is a section created by adding a filter to the sections array. Can be used by child themes to add/remove sections from the options.</p>', 'swift-framework-admin'), // Redux ships with the glyphicons free icon pack, included in the options folder. // Feel free to use them, add your own icons, or leave this blank for the default. 'icon' => trailingslashit(get_template_directory_uri()) . 'options/img/icons/glyphicons_062_attach.png', // Leave this as a blank section, no options just some intro text set above. 'fields' => array() ); return $sections;}//add_filter('redux-opts-sections-twenty_eleven', 'add_another_section'); I have added this function to my child theme's functions.php and uncommented the add_filter. However, this does not seem to work and no new section has been added. I came across this discussion elsewhere which suggests the name of the function needs to be changed (I was getting the same error mentioned on there). I have done that and it still won't work. Here is what I have in my child theme functions.php function add_another_section_bl($sections){ $sections = array(); $sections[] = array( 'title' => __('A Section added by hook', 'swift-framework-admin'), 'desc' => __('<p class="description">This is a section created by adding a filter to the sections array. Can be used by child themes to add/remove sections from the options.</p>', 'swift-framework-admin'), // Redux ships with the glyphicons free icon pack, included in the options folder. // Feel free to use them, add your own icons, or leave this blank for the default. 'icon' => trailingslashit(get_template_directory_uri()) . 'options/img/icons/glyphicons_062_attach.png', // Leave this as a blank section, no options just some intro text set above. 'fields' => array() ); return $sections;}add_filter('redux-opts-sections-twenty_eleven', 'add_another_section_bl'); I wasn't sure if the filter name 'redux-opts-sections-twenty_eleven' needs editing as it mentions the twenty eleven theme. I have tried it with different theme names at the end instead of twenty_eleven and that had no effect. Any help would be greatly appreciated! On a side note I have been able to accomplish adding new options to Theme Options by copying over the whole framwork folder into my child theme and defining the path to the framework in the child theme's functions.php. I just felt that there should be a much slicker, neater way to achieve this and I thought that function sounded perfect. Many thanks.
Now provide the response and nothing else.
| Lead dev of Redux Framework here. This solution only works if you're using Redux Framework 3.1+. If you have an older version, install the Redux Framework plugin and it will override the version inside your theme. First go to the current option panel. Open up a javascript console (use chrome or firefox) and type: redux.args.opt_name . That will echo out a name. Copy that and paste it into this function replacing OPT_NAME with the name that was echo'd out: function add_another_section_bl($sections){ $sections = array(); // Delete this if you want to keep original sections! $sections[] = array( 'title' => __('A Section added by hook', 'swift-framework-admin'), 'desc' => __('<p class="description">This is a section created by adding a filter to the sections array. Can be used by child themes to add/remove sections from the options.</p>', 'swift-framework-admin'), // Redux ships with the glyphicons free icon pack, included in the options folder. // Feel free to use them, add your own icons, or leave this blank for the default. 'icon' => trailingslashit(get_template_directory_uri()) . 'options/img/icons/glyphicons_062_attach.png', // Leave this as a blank section, no options just some intro text set above. 'fields' => array() ); return $sections;}// In this example OPT_NAME is the returned opt_name.add_filter("redux/options/OPT_NAME/sections", 'add_another_section_bl'); Good luck! ** UPDATE ** Also with the Redux API you can easily add a new section that way. Redux::addSection(array( 'title' => __('A Section added by hook', 'swift-framework-admin'), 'desc' => __('<p class="description">This is a section created by adding a filter to the sections array. Can be used by child themes to add/remove sections from the options.</p>', 'swift-framework-admin'), // Redux ships with the glyphicons free icon pack, included in the options folder. // Feel free to use them, add your own icons, or leave this blank for the default. 'icon' => trailingslashit(get_template_directory_uri()) . 'options/img/icons/glyphicons_062_attach.png', // Leave this as a blank section, no options just some intro text set above. 'fields' => array() )) That makes it a wee bit easier using our API I believe we released in Redux 3.2... | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27799026', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4423792/']} | jdg_73592 |
stackexchange | llm_judgeable_groundtruth_similarity | 3127711 |
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:
So if nominal interest is 12% compounded monthly, it is actually 1% compounded each month. It is not 12% effective year, though it is close (It is 12.7%) So why don't we/they say 1% compounded monthly? Or just use effective yearly rate? Nothing is actually 12%, so why is this number used? I asked my professor this, and her answer was so that we could compare these nominal interest rates, but that doesn't really "sit" with me, because you cannot directly compare these rates. Example: How do you compare 12% compounded monthly, or 13% compounded three times a year. It is not immediately obvious which is greater. So why is nominal interest defined the way it is?
Now provide the response and nothing else.
| The nominal interest rate is defined the way it is because, along with the compounding interval, it is a succinct way of describing how interest is computed. If, for example, the nominal interest rate is $6$ percent, and it is compounded monthly, then we can simply divide the nominal rate by the number of months to obtain $0.5$ percent, and now we know that each month, the principal goes up by a factor of $1.005$ . The actual effective interest rate is about $6.1678$ percent, since $1.005^{12} \approx 1.0061678$ , but it would be a rather ungainly way of expressing the same thing. What's more, it's likely to be only approximately correct, unless you want to carry this out to $28$ places or whatever. To be sure, of course, we could have started with the effective interest rate, and then worked out what the nominal interest rate must be. But this requires us to compute a twelfth root, and people back in the day of hand calculators (and before that, hand computation) were understandably loath to do that. And just imagine what would happen if you were to go to daily compounding. (In many ways, compounding continuously is easier, though it requires taking a logarithm.) It was simply easier to deal with the nominal interest rate. Also, from a marketing perspective, it was easier to tell people that their effective rate was higher than their nominal rate (sounds like they're getting a compounding bonus) than that the rate they actually got each month was less than the effective rate divided by $12$ (sounds like compounding costs them money). | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3127711', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/648715/']} | jdg_73593 |
stackexchange | llm_judgeable_groundtruth_similarity | 35548800 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When using the Chart.js library, I want to change cursor when hovering the mouse over the doughnut. I do this : $("#dc_LoadTime").mouseleave(function(){ $("#dc_LoadTime").css("cursor", "default");}); $("#dc_LoadTime").mouseenter(function(){ $("#dc_LoadTime").css("cursor", "pointer");}); With this in html page <canvas id="dc_LoadTime"></canvas> But this change cursor when mouse enter or leave canvas not on doughnut chart.I cannot find a way to do this. Does anybody know if this is possible?
Now provide the response and nothing else.
| In chartjs 2.0 < 2.5 I use hover in option section of the chart, like this: options: { hover: { onHover: function(e) { $("#id-of-your-canvas").css("cursor", e[0] ? "pointer" : "default"); } }} ...and here is a complete example: https://jsfiddle.net/su5fgb5h/5/ In version 2.5 onhover callback has changed and we need second parameter to change cursor: options: { hover: { onHover: function(e, el) { $("#id-of-your-canvas").css("cursor", el[0] ? "pointer" : "default"); } }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35548800', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/710955/']} | jdg_73594 |
stackexchange | llm_judgeable_groundtruth_similarity | 58922153 |
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 tried to run this code but get an Attribute Error. Any help would be greatly appreciated. import cv2 import sys (major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.') if __name__ == '__main__': # Set up tracker. # Instead of MIL, you can also use tracker_types = ['BOOSTING', 'MIL','KCF', 'TLD', 'MEDIANFLOW', 'CSRT', 'MOSSE'] tracker_type = tracker_types[5] if int(minor_ver) < 3: tracker = cv2.cv2.Tracker_create(tracker_type) else: if tracker_type == 'BOOSTING': tracker = cv2.TrackerBoosting_create() if tracker_type == 'MIL': tracker = cv2.TrackerMIL_create() if tracker_type == 'KCF': tracker = cv2.TrackerKCF_create() if tracker_type == 'TLD': tracker = cv2.TrackerTLD_create() if tracker_type == 'MEDIANFLOW': tracker = cv2.TrackerMedianFlow_create() if tracker_type == 'CSRT': tracker = cv2.TrackerCSRT_create() if tracker_type == 'MOSSE': tracker = cv2.TrackerMOSSE_create() # Read video video = cv2.VideoCapture("./videos/chaplin.mp4") # Exit if video not opened. if not video.isOpened(): print("Could not open video") sys.exit() # Read first frame. ok, frame = video.read() if not ok: print('Cannot read video file') sys.exit() # Define an initial bounding box bbox = (287, 23, 86, 320) # Uncomment the line below to select a different bounding box bbox = cv2.selectROI(frame, False) # Initialize tracker with first frame and bounding box ok = tracker.init(frame, bbox) while True: # Read a new frame ok, frame = video.read() if not ok: break # Start timer timer = cv2.getTickCount() # Update tracker ok, bbox = tracker.update(frame) # Calculate Frames per second (FPS) fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer); # Draw bounding box if ok: # Tracking success p1 = (int(bbox[0]), int(bbox[1])) p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3])) cv2.rectangle(frame, p1, p2, (255,0,0), 2, 1) else : # Tracking failure cv2.putText(frame, "Tracking failure detected", (100,80), cv2.FONT_HERSHEY_SIMPLEX, 0.75,(0,0,255),2) # Display tracker type on frame cv2.putText(frame, tracker_type + " Tracker", (100,20), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50),2); # Display FPS on frame cv2.putText(frame, "FPS : " + str(int(fps)), (100,50), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50,170,50), 2); # Display result cv2.imshow("Tracking", frame) # Exit if ESC pressed k = cv2.waitKey(1) & 0xff if k == 27 : break Output: Traceback (most recent call last): File "C:\Users\Jatin\OpenCV-Object-Tracking\index.py", line 15, in <module> tracker = cv2.cv2.Tracker_create(tracker_type)AttributeError: module 'cv2.cv2' has no attribute 'Tracker_create'
Now provide the response and nothing else.
| It depends on which packages of OpenCV and the version you have installed. I believe you need OpenCV 3.4+ to run those models. Some tracker models are available in 3.2, and 3.3. All trackers in your script are available in 3.4 OpenCV packages: opencv-python : This repository contains the main modules of the OpenCV library. opencv-contrib-python : The opencv-contrib-python repository contains both the main modules along with the contrib modules python -m pip install opencv-contrib-python , check to see if you have 3.4+, with pip show opencv . See how to install opencv for more details Updates As @user48956 pointed out opencv v 4.5.x has moved some of these algorithms to cv2.legacy . For example, to access TrackerMOSSE_create function. You would have to get it from cv2.legacy.TrackerMOSSE_create . I would recommend keeping up with opencv GitHub as some functions/algorithms will likely move around or be deleted. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/58922153', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12393587/']} | jdg_73595 |
stackexchange | llm_judgeable_groundtruth_similarity | 5544228 |
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 code works properly for me: # -*- coding: utf-8 -*-N = int(raw_input("N="))l=[]i = 0while i<N: n = raw_input("e"+str(i)+"=") l.append(n) i = i+1 print l But , why can't I simplify it by using l[i] = raw_input("e"+str(i)+"=") instead? Example: (doesn't work) # -*- coding: utf-8 -*-N = int(raw_input("N="))l=[]i = 0while i<N: l[i] = raw_input("e"+str(i)+"=") i = i+1 print l
Now provide the response and nothing else.
| You can only use indexing (e.g. obj[x] ) to access or modify items that already exist in a list . For example, the following works because the positions in the list that we are accessing already exist: >>> chars = ['a', 'b', 'c']>>> chars[0]'a'>>> chars[0] = 'd'>>> chars['d', 'b', 'c'] However, accessing or modifying items at positions that do not exist in a list will not work : >>> chars = ['a', 'b', 'c']>>> chars[3]...IndexError: list index out of range>>> chars[3] = 'd'...IndexError: list assignment index out of range>>> chars['a', 'b', 'c'] If you want to simplify your code, try: (it uses a list comprehension ) N = int(raw_input("N="))l = [raw_input("e" + str(i) + "=") for i in range(N)]print l | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5544228', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/128618/']} | jdg_73596 |
stackexchange | llm_judgeable_groundtruth_similarity | 1584 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How can one convert between the implicit units used by Grid ( ems and line height for horizontal and vertical dimensions) and printers points (in GraphicsGrid and Graphics )? Grid[{{"sample", "text"}}, Frame -> All, ItemSize -> {{4, 7}, Automatic}]Row@{Framed["sample", ImageSize -> 60, FrameMargins -> 0], Framed["sample", ImageSize -> 100, FrameMargins -> 0]}GraphicsGrid[{{"sample", "text"}}, Frame -> All, ItemSize -> 7]GraphicsGrid[{{Item["sample", ItemSize -> 4], Item["text", ItemSize -> 7]}}, Frame -> All(*,ImageSize->160*)] The last two examples show that, while the documentation of ItemSize states that "In GraphicsGrid, w and h are both measured in absolute printer's points", ItemSize cannot be used as an option for GraphicsGrid and it doesn't do anything as an option for an internal object wrapped in Item . Realistic example Here is a particular problem, that presents the issue of different units in the same object. The task is to automatically scroll a Pane to a certain line in a dataset. Updated : Improved code according to Heike, to keep the line in focus at the top. data = Range@200;lineHeight = 1.5;conversion = 14; (* magic number *)paneHeight = 120;update[n_] := (scrollToThis = n; pos = (scrollToThis - 1)*lineHeight*conversion);update@1;Row@{Slider[Dynamic[scrollToThis, (update@#) &], {1, Length@data, 1}], " line: ", Dynamic@scrollToThis, " at position: ", Dynamic@pos}Dynamic[Framed[ Pane[Grid[List /@ data, Frame -> All, ItemSize -> {5, lineHeight}, Background -> {White, {scrollToThis -> Red}}], ImageSize -> {100, paneHeight}, Scrollbars -> {False, True}, ScrollPosition -> {0, pos}, ImageMargins -> 0, FrameMargins -> 0], ImageMargins -> 0, FrameMargins -> 0], TrackedSymbols :> {scrollToThis, pos}] Question Is there a way to convert between different units ( ems / lineheight <--> printers points ) in a foolproof way?
Now provide the response and nothing else.
| It's not really the done thing to answer a question you've set a bounty on, but here is an explanation of why Mike's answer isn't quite right. The first point to note is that item sizes include the width of frames, so one needs to allow for the thickness of the frames in the ImageSize option for the second grid (thus the +2 in the option since FrameStyle has a setting including AbsoluteThickness[1] and you need to count both sides.) It's also necessary to ensure ContentPadding is False . This affects placement of the text in the grid cell. Finally, Row doesn't take the Spacings option while Grid does. In these circumstances it helps to used Grid for both cases. Notice I've used the Offset specification of spacing, which only counts the spacing excluding frames and borders. Overlay[{Grid[{{"Sample", "Text"}}, Frame -> All, FrameStyle -> Directive[AbsoluteThickness[1], Red], Spacings -> {Offset[0], 0}, ItemSize -> itemSize, Alignment -> {Left, Center}], Grid[{{Framed["Sample", ImageSize -> 2 + Dynamic[ itemSize*{CurrentValue["FontMWidth"], CurrentValue["FontLineHeight"]}], FrameMargins -> 0, BaseStyle -> Red, FrameStyle -> Directive[AbsoluteThickness[1], Blue], ContentPadding -> False], Framed["Text", ImageSize -> Dynamic[{2, 2} + itemSize*{CurrentValue["FontMWidth"], CurrentValue["FontLineHeight"]}], FrameMargins -> 0, BaseStyle -> Red, FrameStyle -> Directive[AbsoluteThickness[1], Blue], ContentPadding -> False]}}, Spacings -> {Offset[0], 0}]}] | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/1584', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/89/']} | jdg_73597 |
stackexchange | llm_judgeable_groundtruth_similarity | 2827623 |
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 dynamic object (inside another object) in Python and then add attributes to it. I tried: obj = someobjectobj.a = object()setattr(obj.a, 'somefield', 'somevalue') but this didn't work. Any ideas? edit: I am setting the attributes from a for loop which loops through a list of values, e.g. params = ['attr1', 'attr2', 'attr3']obj = someobjectobj.a = object()for p in params: obj.a.p # where p comes from for loop variable In the above example I would get obj.a.attr1 , obj.a.attr2 , obj.a.attr3 . I used the setattr function because I didn't know how to do obj.a.NAME from a for loop. How would I set the attribute based on the value of p in the example above? For details on why it doesn't work, see Can't set attributes on instance of "object" class .
Now provide the response and nothing else.
| The built-in object can be instantiated but can't have any attributes set on it. (I wish it could, for this exact purpose.) It doesn't have a __dict__ to hold the attributes. I generally just do this: class Object(object): passa = Object()a.somefield = somevalue When I can, I give the Object class a more meaningful name, depending on what kind of data I'm putting in it. Some people do a different thing, where they use a sub-class of dict that allows attribute access to get at the keys. ( d.key instead of d['key'] ) Edit : For the addition to your question, using setattr is fine. You just can't use setattr on object() instances. params = ['attr1', 'attr2', 'attr3']for p in params: setattr(obj.a, p, value) | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/2827623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/220129/']} | jdg_73598 |
stackexchange | llm_judgeable_groundtruth_similarity | 1314245 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I set the index of a dropdown in jQuery if the way I'm finding the control is as follows: $("*[id$='" + originalId + "']") I do it this way because I'm creating controls dynamically and since the ids are changed when using Web Forms, I found this as a work around to find me some controls. But once I have the jQuery object, I do not know how to set the selected index to 0 (zero).
Now provide the response and nothing else.
| First of all - that selector is pretty slow. It will scan every DOM element looking for the ids. It will be less of a performance hit if you can assign a class to the element. $(".myselect") To answer your question though, there are a few ways to change the select elements value in jQuery // sets selected index of a select box to the option with the value "0"$("select#elem").val('0'); // sets selected index of a select box to the option with the value ""$("select#elem").val(''); // sets selected index to first item using the DOM$("select#elem")[0].selectedIndex = 0;// sets selected index to first item using jQuery (can work on multiple elements)$("select#elem").prop('selectedIndex', 0); | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/1314245', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/83906/']} | jdg_73599 |
stackexchange | llm_judgeable_groundtruth_similarity | 41603025 |
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 update the value of JToken but its reference is not getting updated. JSON string: { "Title": "master", "Presentation": [ { "Component": { "Content": { "Title": "Set New Title", } } } ]} and the usage is given below JObject jo = JObject.Parse(File.ReadAllText(file.json));foreach (var token in jo.SelectTokens("$..Component.Content").Children()) { JProperty prop = token.ToObject<JProperty>(); prop.Value = "New Title"; }string jsonText = JsonConvert.SerializeObject(jo, Formatting.Indented); In this example, I'm trying to update the value of Title property. It is getting updated within foreach, means local variable is getting updated but changes are not reflecting in main jobject. Can anyone help me if i'm doing anything wrong?
Now provide the response and nothing else.
| Once you call ToObject then you are working with a copy.If instead you try this, it should work: JObject jo = JObject.Parse(File.ReadAllText(file.json));foreach (var prop in jo.SelectTokens("$..Component.Content") .Children().OfType<JProperty>()){ prop.Value = "New Title";}string jsonText = JsonConvert.SerializeObject(jo, Formatting.Indented); or to handle multiple types of JToken s: JObject jo = JObject.Parse(File.ReadAllText(file.json));foreach (var token in jo.SelectTokens("$..Component.Content") .Children()){ var prop = token as JProperty; if (prop != null) prop.Value = "New Title"; var array = token as JArray; if (array != null) { // some other logic }}string jsonText = JsonConvert.SerializeObject(jo, Formatting.Indented); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41603025', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/699607/']} | jdg_73600 |
stackexchange | llm_judgeable_groundtruth_similarity | 1006135 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
One of my models which has ForeignKey 's is actually a MySQL view on other tables. The problem I'm running into is that when I delete data from these tables, Django, as described in the "deleting objects" documentation ... When Django deletes an object, it emulates the behavior of the SQL constraint ON DELETE CASCADE -- in other words, any objects which had foreign keys pointing at the object to be deleted will be deleted along with it. ...tries to remove rows from my view, which of course it can't, and so throws the error: mysql_exceptions.OperationalError '>=(1395, "Can not delete from join view 'my_db.my_mysql_view'"' Is there any way to specify a ForeignKey constraint on a model which will provide me with all the Django wizardry, but will not cascade deletes onto it? Or, is there a way to ask MySQL to ignore the commands to delete a row from my view instead of raising an error?
Now provide the response and nothing else.
| Harold's answer pointed me in the right direction. This is a sketch on the way I implemented it (on a french legacy database, hence the slightly odd naming convention): class Factures(models.Model): idFacture = models.IntegerField(primary_key=True) idLettrage = models.ForeignKey('Lettrage', db_column='idLettrage', null=True, blank=True)class Paiements(models.Model): idPaiement = models.IntegerField(primary_key=True) idLettrage = models.ForeignKey('Lettrage', db_column='idLettrage', null=True, blank=True)class Lettrage(models.Model): idLettrage = models.IntegerField(primary_key=True) def delete(self): """Dettaches factures and paiements from current lettre before deleting""" self.factures_set.clear() self.paiements_set.clear() super(Lettrage, self).delete() | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1006135', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10728/']} | jdg_73601 |
stackexchange | llm_judgeable_groundtruth_similarity | 970979 |
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 referring to the POSIX standard select and poll system C API calls.
Now provide the response and nothing else.
| I think that this answers your question: From Richard Stevens ([email protected]): The basic difference is that select()'s fd_set is a bit mask and therefore has some fixed size. It would be possible for the kernel to not limit this size when the kernel is compiled, allowing the application to define FD_SETSIZE to whatever it wants (as the comments in the system header imply today) but it takes more work. 4.4BSD's kernel and the Solaris library function both have this limit. But I see that BSD/OS 2.1 has now been coded to avoid this limit, so it's doable, just a small matter of programming. :-) Someone should file a Solaris bug report on this, and see if it ever gets fixed. With poll(), however, the user must allocate an array of pollfd structures, and pass the number of entries in this array, so there's no fundamental limit. As Casper notes, fewer systems have poll() than select, so the latter is more portable. Also, with original implementations (SVR3) you could not set the descriptor to -1 to tell the kernel to ignore an entry in the pollfd structure, which made it hard to remove entries from the array; SVR4 gets around this. Personally, I always use select() and rarely poll(), because I port my code to BSD environments too. Someone could write an implementation of poll() that uses select(), for these environments, but I've never seen one. Both select() and poll() are being standardized by POSIX 1003.1g. October 2017 Update: The email referenced above is at least as old as 2001; the poll() command is now (2017) supported across all modern operating systems - including BSD. In fact, some people believe that select() should be deprecated . Opinions aside, portability issues around poll() are no longer a concern on modern systems. Furthermore, epoll() has since been developed (you can read the man page ), and continues to rise in popularity. For modern development you probably don't want to use select() , although there's nothing explicitly wrong with it. poll() , and it's more modern evolution epoll() , provide the same features (and more) as select() without suffering from the limitations therein. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/970979', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_73602 |
stackexchange | llm_judgeable_groundtruth_similarity | 27576427 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to implement the logic in Cypher where, based on a particular condition ( CASE Statement), I would create some nodes and relationships; the code is as below MATCH (g:Game)-[:PLAYER]->(u:User)-[r1:AT]->(b1:Block)-[:NEXT]->(b2:Block) WHERE g.game_id='G222' and u.email_id = '[email protected]' and b1.block_id='16' SET r1.status='Skipped', r1.enddate=20141225WITH u, b2,b1, g, r1SET b1.test = CASE b2.fork WHEN 'y' THEN MERGE (u)-[r2:STAGE {startdate:20141225, enddate:'99999999', status:'InProgress'}]->(b2 {fork:'fail'}) RETURN 1ELSE MERGE (u)-[r2:STAGE {startdate:20141225, enddate:'99999999', status:'InProgress'}]->(b2) RETURN 2ENDWITH u, gMATCH (u)-[:TIME]->(h:Time)<-[:TIME]-(g)SET h.after = 0SET h.before = h.before + 1 In this query there is a merge statement within the WHEN 'y' THEN , this query throws an error: Invalid input ']': expected whitespace or a relationship pattern (line 7, column 82) "MERGE (u)-[r2:STAGE {startdate:20141225, enddate:'99999999', status:'InProgress'}]->(b2 {fork:'fail'}) RETURN 1" Basically I'm trying to create a relationship based on a property i.e. a MERGE within a CASE statement, I tried different ways to get this working like doing a return so that case when returns some value etc. but nothing worked so far. What could be the issue with this query?
Now provide the response and nothing else.
| To do conditional write operations you need to use the FOREACH trick. Using CASE you either return a one element array or a empty one. FOREACH iterates over the CASE expression and therefore conditionally executes the action. If you want an ELSE part as well you need to have a another FOREACH using the inverse condition in the CASE . As an example, instead of WHEN 'y' THEN MERGE (u)-[r2:STAGE {startdate:20141225, enddate:'99999999', status:'InProgress'}]->(b2 {fork:'fail'}) RETURN 1ELSE MERGE (u)-[r2:STAGE {startdate:20141225, enddate:'99999999', status:'InProgress'}]->(b2) RETURN 2END use FOREACH(ignoreMe IN CASE WHEN 'y' THEN [1] ELSE [] END | MERGE (u)-[r2:STAGE {startdate:20141225, enddate:'99999999', status:'InProgress'}]->(b2 {fork:'fail'}))FOREACH(ignoreMe IN CASE WHEN NOT 'y' THEN [1] ELSE [] END | MERGE (u)-[r2:STAGE {startdate:20141225, enddate:'99999999', status:'InProgress'}]->(b2)) See also Mark's blog post on this. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27576427', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2301410/']} | jdg_73603 |
stackexchange | llm_judgeable_groundtruth_similarity | 39653391 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am having problems with the AlertDialog. The buttons doesn't use the accentColor to set the button text color any more. I am using the newest support library, v24.2.1. I am styling my dialogs in my styles.xml the following way: <style name="Base.Theme" parent="Theme.AppCompat.Light.NoActionBar"> <item name="android:alertDialogTheme">@style/Widget.DialogStyle</item> <item name="alertDialogTheme">@style/Widget.DialogStyle</item></style> and the Widget.DialogStyle looks like this: <style name="Widget.DialogStyle" parent="@style/Theme.AppCompat.Light.Dialog.Alert"> <item name="android:colorAccent" tools:targetApi="lollipop">@color/primaryColor</item> <item name="colorAccent">@color/primaryColor</item> <item name="android:textColorPrimary">@color/primaryText</item> <item name="android:textColor">@color/primaryText</item> <item name="android:background">@color/backgroundColor</item> <item name="android:textAppearanceLarge">@color/primaryText</item> <item name="android:windowNoTitle">true</item> <item name="android:windowIsFloating">true</item></style> On app API's lower than 24 the dialog buttons are colored with the colorAccent but on API 24 this is no more the behaviour (the text is black, should be orange). See the following screenshot . Is there anybody that knows how to get the accentColor back on the buttons?Thank you.
Now provide the response and nothing else.
| For some AlertDialog implementations, the buttons are contained in a ButtonBar and take their style from buttonBarButtonStyle . So you have to override the settings you inherit from the parent theme ( Theme.AppCompat.Light.Dialog.Alert ). Add the following item to Widget.DialogStyle : <item name="buttonBarButtonStyle">@style/MyButtonStyle</item> and add another style named MyButtonStyle like this: <style name="MyButtonStyle" parent="Widget.AppCompat.Button.Borderless"> <!-- Set background drawable and text size of the buttons here <item name="android:background">@color/my_dialog_dark</item>--> <item name="android:textSize">18sp</item> <!-- this is the button text color! --> <item name="android:textColor">@color/primaryColor</item></style> EDIT Thanks to kirtan403 for pointing this out: you can also use another parent style for the buttons if Widget.AppCompat.Button.Borderless does not meet your requirements. An example by [email protected] using Widget.AppCompat.Button.ButtonBar.AlertDialog as parent style for the buttons can be found under the AOSP Issue 220699: colorAccent not applied to AlertDialog buttons on Android N . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39653391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4278486/']} | jdg_73604 |
stackexchange | llm_judgeable_groundtruth_similarity | 31322290 |
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 weak NSPointerArray with some NSObject that has been released. Before calling compact what I see is: (lldb) po [currentArray count]1(lldb) po [currentArray pointerAtIndex:0]<nil>(lldb) po [currentArray allObjects]<__NSArrayM 0x16f04f00>() That makes sense, but what is really weird is that when I call compact on that array I see the same values! Count still returns 1 and pointerAtIndex:0 is nil . Why the nil hasn't been removed? EDIT Here's the full code (yeah it's XCTesting framework): - (void)testCompaction { __weak id testingPointer = nil; NSPointerArray *weakArray = [NSPointerArray weakObjectsPointerArray]; @autoreleasepool { NSObject *someObj = [[NSObject alloc] init]; testingPointer = someObj; [weakArray addPointer:(__bridge void*)testingPointer]; NSLog(@"before compaction inside autorelease: testingPointer = %@ count = %d, allObjects = %@, pointerAtIndex:0 = %@, pointerAtIndex:0 class = %@", testingPointer, [weakArray count], [weakArray allObjects], [weakArray pointerAtIndex:0], [(id)[weakArray pointerAtIndex:0] class]); someObj = nil; } NSLog(@"before compaction outside autorelease: testingPointer = %@ count = %d, allObjects = %@, pointerAtIndex:0 = %@, pointerAtIndex:0 class = %@", testingPointer, [weakArray count], [weakArray allObjects], [weakArray pointerAtIndex:0], [(id)[weakArray pointerAtIndex:0] class]); [weakArray compact]; NSLog(@"after compaction outside autorelease: testingPointer = %@ count = %d, allObjects = %@, pointerAtIndex:0 = %@, pointerAtIndex:0 class = %@", testingPointer, [weakArray count], [weakArray allObjects], [weakArray pointerAtIndex:0], [(id)[weakArray pointerAtIndex:0] class]);} and logs: before compaction inside autorelease: testingPointer = <NSObject: 0x7de7ff80> count = 1, allObjects = ( "<NSObject: 0x7de7ff80>"), pointerAtIndex:0 = <NSObject: 0x7de7ff80>, pointerAtIndex:0 class = NSObject2015-07-20 14:27:14.062 AppetizeSuite copy[54144:9019054] before compaction outside autorelease: testingPointer = (null) count = 1, allObjects = (), pointerAtIndex:0 = (null), pointerAtIndex:0 class = (null)2015-07-20 14:27:22.615 AppetizeSuite copy[54144:9019054] after compaction outside autorelease: testingPointer = (null) count = 1, allObjects = (), pointerAtIndex:0 = (null), pointerAtIndex:0 class = (null) Why the compact method does not delete the first pointer? It's clearly a nil before calling compact .
Now provide the response and nothing else.
| The reason this happens is that -compact first checks whether an internal flag 'needsCompaction' is set. If it's not, it simply bails early. The only time the flag is set is if a nil pointer is inserted directly into the array through the public interface. It does not get set if a weakly referenced object is deallocated (and the pointer is nil'd) after the pointer was inserted into the array. One work around for this behavior is to purposefully append a nil pointer to the array before calling -compact . Not ideal but it'll work. [pa addPointer:nil]; // forces the pointer array to do compaction next time[pa compact]; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31322290', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/345048/']} | jdg_73605 |
stackexchange | llm_judgeable_groundtruth_similarity | 10851769 |
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 someone help me understand why I can declare a hardcoded date value in a package but not assign the value from a query? I've seen a number of examples (including the reference book) that show declarations of hardcoded values but I'm unable to locate examples of assigning values to variable through queries. This is allowed: create or replace package body PACKAGE_NAME AS tDate DATE := '2012-05-30'; -- ...procedures follow This is allowed: create or replace package body PACKAGE_NAME AS tDate DATE := sysdate; This is not allowed: create or replace package body PACKAGE_NAME AS tDate DATE := select MAX(date_) from Table_Name; I've tried a number of ways and I'm ok with it not working - I can use it as needed in the procedures themselves. But I'd like to know why I can't assign a value to tDate this way? The specific error is: Encountered the symbol 'SELECT' when expecting .... Adding that I can get variable values assigned through queries in a stored procedure but the same process does not seem to work for package body. PROCEDURE Proc_Name IStDate Date;BEGINSELECT MAX(date_) into tDate from Table_Name;
Now provide the response and nothing else.
| You need to create a package initialization block in your package body. This is a relatively arcane bit of PL/SQL package lore, but it's there and can be used. Here's an example: CREATE OR REPLACE PACKAGE TEST_PKG IS tDate DATE;END TEST_PKG; Here we've created a package spec which contains only a single DATE variable. Now we'll create a simple body which initializes that variable using a SELECT statement: CREATE OR REPLACE PACKAGE BODY TEST_PKG IS -- package-private variables go first (if any)(...) -- then the public functions/procedures(...) -- then a final BEGIN-END block which is the package initialization blockBEGIN SELECT SYSDATE INTO tDATE FROM DUAL;EXCEPTION -- you can have exception handlers in your initialization block WHEN OTHERS THEN NULL; -- pointless here, but this is just an example RAISE;END TEST_PKG; Now if you execute the following: begin -- Test statements here DBMS_OUTPUT.PUT_LINE('TEST_PKG.tDate = ' || TEST_PKG.tDate);end; it should print the current date. Share and enjoy. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10851769', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/957564/']} | jdg_73606 |
stackexchange | llm_judgeable_groundtruth_similarity | 160266 |
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've mixed 30 ml 10% sulfuric acid with 20 ml 3% hydrogen peroxide and put a drop of this solution onto copper foil. The solution quickly removed the oxide layer from the copper but did not dissolve it any further within the hour that I left the drop on the copper. When I wiped the solution off with a white paper towel, I couldn't see any blue or green tint, indicating that there was (almost) no copper dissolved in the solution. After that, I added (roughly) 100 mg of sodium chloride to the solution and again put a drop of it onto the copper foil. (To clarify, I put 100 mg sodium chloride into the entire remaining ~50 ml of solution.) It began to oxidize and dissolve the copper, turning its surface brown. When I later wiped the solution off, the paper towel was stained greenish-blue. A dilute mixture of hydrochloric acid and hydrogen peroxide also readily dissolves copper. I've been unable to find any explanation for this even after an hour of googling. I've found this Chemistry Stack Exchange answer that deals with a similar reaction; however, it doesn't explain the role of the chloride ions. Why does this solution only dissolve copper when chloride ions are present? (That is, how does the chloride help oxidizing the copper and why isn't hydrogen peroxide enough?) I've got three theories, but I have no idea which of them (if any) is correct. (I'm sadly not a chemist.) The hydrogen peroxide oxidizes chloride to $\text{Cl}_2$ , which then attacks the copper. The problem with this theory is that hydrogen peroxide has $E^0=1.776V$ in acidic solutions while chlorine only has $E^0=1.396V$ , meaning that the peroxide should attack the copper more readily than the chlorine, yet it evidently doesn't. The $\text{Cl}_2$ produced as in theory #1 is further oxidized to form $\text{HClO}$ (or even further to $\text{HClO}_n$ ), which then oxidizes the copper. This sounds like the most likely reaction to me. The chloride ions somehow catalyze the decomposition of hydrogen peroxide into radicals, which then attack the copper.
Now provide the response and nothing else.
| For the record, only hot concentrated sulfate acid directly reacts with copper metal, otherwise, the chemistry around copper can be quite complex including the role of chloride to otherwise facilitate the reaction. Here is a sourced exposition which I would recommend for graduate students/researchers to assist in answering the question on the role of chloride and more insights in copper related reactions. First, in the presence of $\ce{H+}$ and $\ce{O2}$ (or $\ce{H2O2}$ ) there is an electrochemical aspect (think of $\ce{Fe}$ in place of $\ce{Cu}$ here in air with an acid source in common rust formation) with the reported reaction for copper: $\ce{2 Cu + 1/2 O2 + H+ -> 2 Cu+ + OH- }$ So, the chloride serves certainly in the role of an electrolyte . An associated copper electrolysis based reference which notes on Page 15, for example, the half cell reaction (which is implied per the above) for copper (and noted other metals), namely: $\ce{1/2 O2 + 2 H+ + 2 e- = H2O}$ . The above simple copper metal reaction with oxygen and an acid source also strongly suggests a basic salt formation as can be actually found in Equation 7 per a Wikipedia discussion on Dicopper chloride trihydroxide with respect to the commercial preparation of the basic copper salt. This source interestingly cites the use of $\ce{NaCl}$ as a complexing tool to form a soluble mixed cuprous compound. So, the second answer on the role of chloride is as a complexing agent . Actually, this associated electrochemical oxidation reaction occurs correspondingly not only with iron but several other transition metals as well, as noted below: $\ce{4 Cu/ 2 Fe/ 2 Co/ 2 Cr + O2 + 2 H+ -> 4 Cu+/ 2 Fe++/ 2 Co++/ 2 Cr++ + 2 OH- }$ Interesting and supportive, the above noted electrolysis reaction with copper can also be derived from a series of radical chemistry reactions. Namely, per a 2013 radical reaction supplement, "Impacts of aerosols on the chemistry of atmospheric trace gases: a case study of peroxides radicals" , I cite the following reactions: R24: $\ce{O2 + Cu+ → Cu++ + •O2− (k = 4.6*10^5) }$ R27: $\ce{ •O2− + Cu+ + 2 H+ → Cu++ + H2O2 (k = 9.4*10^9) }$ R25 $\ce{H2O2 + Cu+ → Cu++ + •OH + OH− (k= 7.0*10^3 ) }$ R23 $\ce{•OH + Cu+ → Cu++ + OH- ( k = 3.0×E09 ) }$ Where the implied net reaction, in the case of copper, confirms the claim reaction above, namely, a net reaction of: $\ce{O2 + 4 Cu+ + 2 H+ → 4 Cu++ + 2 OH- }$ where the reactions above clearly suggest again the need for a soluble cuprous presence. The mechanics of the etching of copper with $\ce{H2O2}$ , $\ce{NaCl}$ and a acid source would not be likely complete without noting the role of radicals created via a Fenton-type reaction with copper: $\ce{Cu+ + H2O2 + H+ → Cu++ + .OH + H2O }$ $\ce{H2O2 + .OH -> .HO2 + H2O }$ which notes, of import here, the formation of the hydroperoxyl radical (•HO2, pKa 4.88), which is interestingly, a very acidic radical as noted in this article: "Radical-Enhanced Acidity: Why Bicarbonate, Carboxyl, Hydroperoxyl, and Related Radicals Are So Acidic" . The acidic hydroperoxyl radical could be an explanation of the reaction proceeding even with select weak (as in chelating) acids, which again requires a soluble cuprous as provide by chloride. Note, however, more recent 2013 work "Fenton-like copper redox chemistry revisited: Hydrogen peroxide and superoxide mediation of copper-catalyzed oxidant production" noting mainly just a reactive Cu(III) species creation and little hydroxyl radical per se. The absence of $\ce{.OH}$ argues for no chlorine radical from: $\ce{.OH + Cl- = OH- + .Cl}$ As well as no free chlorine presence per the reaction: $\ce{.Cl + .Cl = Cl2}$ However, the superoxide radical anion and at pH < 5, the hydroperoxyl radical, are still found in solution per this work. I hope this helps to explain the role of chloride in the reaction's progression, which is still a matter of ongoing research. | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/160266', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/119571/']} | jdg_73607 |
stackexchange | llm_judgeable_groundtruth_similarity | 12044756 |
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 use XAMPP with NetBeans for PHP. When I move my files to the htdocs folder everything works fine. However when they are in the home folder XAMPP cannot find them. Below is the instruction from XAMPP I followed it but it's not working. **Where should I put my Websites?** You can put your Websites in /Applications/XAMPP/htdocs/ and access them via http://localhost/ Or you put your Websites in the Sites-Folder in your Home and access them via http://localhost/~leslie/.
Now provide the response and nothing else.
| You can change your document root pretty easily by following these instructions: Locate the file called httpd.conf . Mine is located in this directory: /Applications/XAMPP/etc Find the line that says: DocumentRoot "/Applications/XAMPP/xamppfiles/htdocs" Change the path to where you want your files to live. Use an absolute path from the root directory (i.e. it should start with a / and if you're using Unix/Linux and a \ if you're on Windows). Still in the httpd.conf file, scroll down a few lines until you see this text: # This should be changed to whatever you set DocumentRoot to. <Directory "/Applications/XAMPP/xamppfiles/htdocs"> and replace the path with whatever you typed in step 3. This part is important . In order for these changes to take place, you need to restart Apache (otherwise it won't work). Since you're using XAMPP, just use the GUI to do this (click Stop, and then Start next to the Apache label). Now, you can put your web content in the new directory (i.e. the home folder in your case) If, on the other hand, you want to add an additional directory to serve files from, locate the httpd.conf file mentioned in step 1 above, and add this line: Alias /home ~/<Directory ~/>Order allow,denyAllow from all</Directory> Restart Apache Now, you can visit localhost/home in your browser and it will serve files from your home directory in addition to the files in your document root (htdocs by default, or whatever you change it to using the steps above). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12044756', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1612593/']} | jdg_73608 |
stackexchange | llm_judgeable_groundtruth_similarity | 64730 |
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 data containing some continuous and some categorical variables. I want to do logistic regression on them.I am getting confused over the distinction between categorical and continuous variables.I know that a categorical variable "is a variable that can take on one of a limited, and usually fixed, number of possible values. Still, I am having trouble distinguishing some of these variables". If I understand correctly the answers given here , non numerical data cannot be continuous, but are some numerical variables categorical? For instance, one of the variables is "number of days during which have done something". This variable has many possible outputs (from number of days = 1 to 10,000). The number of possible values is limited, yet very big.Is it a categorical or a continuous variable?
Now provide the response and nothing else.
| There is, as far as I know, no taxonomy of variables that captures all the contrasts that might be important for some theoretical or practical purpose, even for statistics alone. If such a taxonomy existed, it would probably be too complicated to be widely acceptable. It is best to focus on examples rather than give numerous definitions. Number of days is a counted variable. It qualifies as discrete rather than continuous, and it is possible that the discreteness is important, particularly if most values are small. Some statistical people might want to insist that only models that apply to discrete variables should be used for such a variable. At the same time, it is often the case that models and methods treat such a variable as approximately continuous. Population size is a yet more obvious example. Human populations can be in billions and many procedures effectively treat such variables as continuous, regardless of the familiar fact that people are individuals. In contrast, a variable such as temperature is in principle continuous, but as a matter of convention temperatures may only be reported to the nearest degree or tenth of a degree, so the number of possible values may be rather small in practice. This does not usually worry anyone; it would certainly be perverse to call such a variable categorical. There are some contexts in which the discreteness of reported temperature is important: in reading mercury thermometers by eye and guessing at the last digit, people show idiosyncratic preferences for or against certain digits of the ten possibilities 0 to 9. Also, what do we do with categories? Answer: we count them. We count males, females; unemployed, employed, retired, students; whatever. So, often we are modelling category counts. In short, discrete counts are a common kind of variable, as well as continuous and categorical variables. | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/64730', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/28183/']} | jdg_73609 |
stackexchange | llm_judgeable_groundtruth_similarity | 1136826 |
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 came across this question about memory management of dictionaries, which mentions the intern function. What exactly does it do, and when would it be used? To give an example: if I have a set called seen , that contains tuples in the form (string1,string2), which I use to check for duplicates, would storing (intern(string1),intern(string2)) improve performance w.r.t. memory or speed?
Now provide the response and nothing else.
| From the Python 3 documentation : sys.intern(string) Enter string in the table of “interned” strings and return the interned string – which is string itself or a copy. Interning strings is useful to gain a little performance on dictionary lookup – if the keys in a dictionary are interned, and the lookup key is interned, the key comparisons (after hashing) can be done by a pointer compare instead of a string compare. Normally, the names used in Python programs are automatically interned, and the dictionaries used to hold module, class or instance attributes have interned keys. Interned strings are not immortal; you must keep a reference to the return value of intern() around to benefit from it. Clarification : As the documentation suggests, the sys.intern function is intended to be used for performance optimization . The sys.intern function maintains a table of interned strings. When you attempt to intern a string, the function looks it up in the table and: If the string does not exists (hasn't been interned yet) the function savesit in the table and returns it from the interned strings table. >>> import sys>>> a = sys.intern('why do pangolins dream of quiche')>>> a'why do pangolins dream of quiche' In the above example, a holds the interned string. Even though it is not visible, the sys.intern function has saved the 'why do pangolins dream of quiche' string object in the interned strings table. If the string exists (has been interned) the function returns it from theinterned strings table. >>> b = sys.intern('why do pangolins dream of quiche')>>> b'why do pangolins dream of quiche' Even though it is not immediately visible, because the string 'why do pangolins dream of quiche' has been interned before, b holds now the same string object as a . >>> b is aTrue If we create the same string without using intern, we end up with two different string objects that have the same value. >>> c = 'why do pangolins dream of quiche'>>> c is aFalse>>> c is bFalse By using sys.intern you ensure that you never create two string objects that have the same value—when you request the creation of a second string object with the same value as an existing string object, you receive a reference to the pre-existing string object. This way, you are saving memory . Also, string objects comparison is now very efficient because it is carried out by comparing the memory addresses of the two string objects instead of their content. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1136826', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/30911/']} | jdg_73610 |
stackexchange | llm_judgeable_groundtruth_similarity | 18772338 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Say one wants to create a C++ class with two separate implementations (say one to run on a CPU and on a GPU) and one wants this to happen at compile time. What design pattern can be used for this?
Now provide the response and nothing else.
| A good book to read is: Modern C++ Design: Generic Programming and Design Patterns Applied, written by Andrei Alexandrescu. Basicly he said that you can implement what you want using policy based class (a kind of strategy pattern, but done at compilation time. Bellow is a simple example showing this: #include <iostream>using namespace std;template <typename T>struct CPU{ // Actions that CPU must do (low level) static T doStuff() {cout << "CPU" << endl;};};template <typename T>struct GPU{ // Actions that GPU must do (low level) // Keeping the same signatures with struct CPU will enable the strategy design patterns static T doStuff() {cout << "GPU" << endl;};};template <typename T, template <class> class LowLevel>struct Processors : public LowLevel<T>{ // Functions that any processor must do void process() { // do anything and call specific low level LowLevel<T>::doStuff(); };};int main(){ Processors<int, CPU> cpu; Processors<int, GPU> gpu; gpu.process(); cpu.process();} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18772338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1045622/']} | jdg_73611 |
stackexchange | llm_judgeable_groundtruth_similarity | 63861068 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was trying the todo-list example from Microsoft: https://learn.microsoft.com/en-us/aspnet/core/tutorials/build-a-blazor-app?view=aspnetcore-3.1 I want to add a todo item and instead of pressing the button with a mouse click I want to press the enter key. I'm not happy with using JS like in this solution: How to set the focus to an InputText element? And I try to trigger the method private void Enter(KeyboardEventArgs e) by this line of code: <button @onclick="AddTodo" @onkeypress="@(e=>Enter(e)" tabindex="0" >Add todo</button> It didn't work. enter code here<input placeholder="Something todo" @bind="newTodo" /><button @onclick="AddTodo" @onkeypress="Enter" tabindex="0" >Add todo</button>@code { private IList<TodoItem> todos = new List<TodoItem>(); private string newTodo; private void AddTodo() { if (!string.IsNullOrWhiteSpace(newTodo)) { todos.Add(new TodoItem { Title = newTodo }); newTodo = string.Empty; } } //private void Enter(KeyboardEventArgs e) private void Enter() { //if (e.Key == "Enter") { if (!string.IsNullOrWhiteSpace(newTodo)) { todos.Add(new TodoItem { Title = newTodo }); newTodo = string.Empty; } } }}
Now provide the response and nothing else.
| onkeypress is fired only for character keys. onkeydown will fire for all keys pressed. I found some explanation of differences between all key events here Try it with onkeydown and it worked: <input type="text" @onkeydown="@Enter" /> In the event handler you will have to do this (notice that I check for both Enter and NumpadEnter keys): public void Enter(KeyboardEventArgs e){ if (e.Code == "Enter" || e.Code == "NumpadEnter") { // ... }} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/63861068', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5056994/']} | jdg_73612 |
stackexchange | llm_judgeable_groundtruth_similarity | 52694564 |
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 have this markup and inside it there is <div class="mask"></div> which sets the blue overlay ontop of the image. If I don't make the .container position:relative , the title text gets hidden behind the blue layer... Almost as if it's usage is mimicking z-index Why is this the case? Pen: https://codepen.io/anon/pen/OBbbZB body { margin: 0; font-family: arial;}section { position: relative; background: url(https://preview.webpixels.io/boomerang-v3.6.1/assets/images/backgrounds/slider/img-41.jpg) no-repeat left center/cover; height: 70vh; display: flex; justify-content: center;}.container { position: relative; width: 100%; max-width: 1280px; display: flex; justify-content: center; align-items: center; color: white;}.mask { position: absolute; width: 100%; height: 100%; background: #3452ff; opacity: 0.7;} <section> <div class="mask"></div> <div class="container"> <h1>Hello World</h1> </div></section>
Now provide the response and nothing else.
| You need to refer to the specification and more precisely the painting order to understand when each layer is painted. Without position:relative your element is not positioned and will be painted at the step (4): For all its in-flow, non-positioned, block-level descendants in treeorder: If the element is a block, list-item, or other blockequivalent: Then we paint the positioned elements (including the .mask ) at the step (8) All positioned , opacity or transform descendants, in tree order that fall into the following categories Now when you add position:relative you make the container also positioned thus it will fall in the step (8) too and as described there we consider the tree order since both don't have any z-index specified. So the .container will painted later in this case. If you change the order of the element (you make the container before the mask) you will notice that position:relative won't have any effect because in both cases the painting order will be the same: body { margin: 0; font-family: arial;}section { position: relative; background: url(https://preview.webpixels.io/boomerang-v3.6.1/assets/images/backgrounds/slider/img-41.jpg) no-repeat left center/cover; height: 70vh; display: flex; justify-content: center;}.container { position: relative; /* you can remove this*/ width: 100%; max-width: 1280px; display: flex; justify-content: center; align-items: center; color: white;}.mask { position: absolute; width: 100%; height: 100%; background: #3452ff; opacity: 0.7;} <section> <div class="container"> <h1>Hello World</h1> </div> <div class="mask"></div></section> If we check the step (8) it also said opacity or transform which means that if you also change the opacity of the container or add a transform, the order will change too. body { margin: 0; font-family: arial;}section { position: relative; background: url(https://preview.webpixels.io/boomerang-v3.6.1/assets/images/backgrounds/slider/img-41.jpg) no-repeat left center/cover; height: 70vh; display: flex; justify-content: center;}.container { transform:translate(0); /*added this*/ width: 100%; max-width: 1280px; display: flex; justify-content: center; align-items: center; color: white;}.mask { position: absolute; width: 100%; height: 100%; background: #3452ff; opacity: 0.7;} <section> <div class="mask"></div> <div class="container"> <h1>Hello World</h1> </div></section> It's also trivial to notice that if you add z-index (either negative or positive) you will also affect the painting order and in this case the tree order will have no effect. Stacking contexts formed by positioned descendants with negative z-indices (excluding 0) in z-index order (most negative first) then tree order .... Stacking contexts formed by positioned descendants with z-indices greater than or equal to 1 in z-index order (smallest first) then tree order. We paint the element with negative z-index at (3) and the positive ones at (9) and between those steps we have all the cases where z-index is not involved like described initially. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52694564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2387934/']} | jdg_73613 |
stackexchange | llm_judgeable_groundtruth_similarity | 49673667 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a series of data frames that I want to save as individual .rda files in my package. I could use devtools::use_data(my.df1, my.df2...) but I don't have a named object for each data frame, they are all stored in a big list. What I would like is to do is to call use_data for each list element and use the list name for the .rda file name. But when I do the following, I have an error message: > lapply(my.list, devtools::use_data, overwrite = TRUE)Error: Can only save existing named objects How can I do this?
Now provide the response and nothing else.
| The use_data function seems to be very odd indeed requiring that an unquoted name is passed as a parameter that points to the object you want to save. This isn't conducive to working with objects in lists. But here is a possible solution with walk2 from purrr (though you could probably we-write with an mapply() if you want to use just base R) library(purrr)library(devtools)walk2(my.list, names(my.list), function(obj, name) { assign(name, obj) do.call("use_data", list(as.name(name), overwrite = TRUE))}) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49673667', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/674552/']} | jdg_73614 |
stackexchange | llm_judgeable_groundtruth_similarity | 2383989 |
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 don't know if I'm asking for too much, but the proofs I've seen of the statement $$\sin(x+y) =\sin(x)\cos(y) + \cos(x)\sin(y)$$ consist of drawing a couple of triangles, one on top of each other and then figuring out some angles and lengths until they arrive at the identity. And I agree with the proof, is just that, even by flipping the triangle around, it only proves the identity for the case $x+y<\pi/2$, or if it does prove it for all values of $x$ and $y$, I wouldn't understand why. As to construing a proof by using Euler's identity or the derivatives of sin and cos, I would ask the writer to first prove his/her already accepted formulas without using the addition identity. So that is my humble question. How could one prove that for all the values of $x$ and $y$, the identity $\sin(x+y) = \sin(x)\cos(y) + \cos(x)\sin(y)$ holds. Any thoughts/ideas would be really appreciated.
Now provide the response and nothing else.
| My favorite proof is based on transformation matrices. If you want to rotate a point $(x,y)$ counter-clockwise around the origin by $t$ radians, you can use matrix multiplication: $$\begin{bmatrix}\cos t & -\sin t \\ \sin t & \cos t \end{bmatrix}\begin{bmatrix}x \\ y \end{bmatrix}$$ The product will be the coordinates of the newly rotated point. So, suppose you want to rotate $(x,y)$ by $a + b$ radians. You could either do this in one go, or you could first rotate by $a$ radians and then by $b$. Either way, of course, you should end up with the same point. In other words, $$\begin{bmatrix}\cos (a+b) & -\sin (a+b) \\ \sin (a+b) & \cos (a+b) \end{bmatrix}\begin{bmatrix}x \\ y \end{bmatrix}$$and $$\begin{bmatrix}\cos b & -\sin b \\ \sin b & \cos b \end{bmatrix}\begin{bmatrix}\cos a & -\sin a \\ \sin a & \cos a \end{bmatrix}\begin{bmatrix}x \\ y \end{bmatrix} = \begin{bmatrix}\cos a \cos b - \sin a \sin b & -\sin a \cos b - \cos a \sin b\\ \cos a \sin b + \sin a \cos b & -\sin a \sin b + \cos a \cos b\end{bmatrix}\begin{bmatrix}x \\ y \end{bmatrix}$$ should give us the same products. This requires that the two matrices must be equal, so $\sin(a+b) = \cos a \sin b + \sin a \cos b$ (and also, $\cos(a+b) = \cos a \cos b - \sin a \sin b$!). | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2383989', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/362026/']} | jdg_73615 |
stackexchange | llm_judgeable_groundtruth_similarity | 6056336 |
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 the CUDA Occupancy calculator to try to optimize my CUDA kernel. Currently I'm using 34 registers and zero shared memory...Thus the maximum occupancy is 63% for 310 Threads per block. When I could somehow change the registers (e.g. by passing kernel parameters via shared memory) to 20 or below I could get an occupancy of 100%. Is this a good way to do it or would you advise me to use another path of optimizing? Further I'm also wondering if there's a newer version of the occupancy calculator for Compute Capability 2.1!?
Now provide the response and nothing else.
| Some points to consider: 320 threads per block will give the same occupancy as 310, because occupancy is defined as active warps/maximum warps per SM, and the warp size is always 32 threads. You should never use a block size which is not a round multiple of 32. That just wastes cores and cycles. Kernel parameters are passed in constant memory on your compute 2.1 device, and they have no effect on occupancy or register usage. The GPU design has a pipeline latency of about 21 cycles. So for a Fermi GPU, you need about 43% occupancy to cover all of the internal scheduling latency. Once that is done, you may find that there is relatively little benefit in trying to achieve higher occupancy. Striving for 100% occupancy is usually never a constructive optimization goal. If you have not done so, I highly recommend looking over Vasily Volkov's presentation from GTC 2010 "Better performance at lower occupancy" , where he shows all sorts of surprising results, like code hitting 85% of peak memory bandwidth at 8% occupancy. The newest occupancy calculator doesn't cover compute 2.1, but the effective occupancy rules for compute 2.0 apply to 2.1 devices too. The extra cores in the compute 2.1 multiprocessor come into play via instruction level parallelism and what is almost out of order execution. That really doesn't change the occupancy characteristics of the device at all compared to compute 2.0 devices. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6056336', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/701049/']} | jdg_73616 |
stackexchange | llm_judgeable_groundtruth_similarity | 27803157 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
A big chunk of our codebase has no unit tests whatsoever. We've been writing unit tests for any new code we add, but we're only just now starting to go back and add unit tests for the existing code. While writing & running unit tests for an existing calculation method, I found a bug: there's a particular input edge case that the calculation does not handle correctly. The bug has never been detected before because it's not actually reachable in the application; the particular input that hits the bug is a subset of a group of inputs that are trivial and handled directly rather than being sent to the somewhat expensive calculation method. My boss has decided that since the bug can't be hit from the application, it's not worth digging through the calculation method to fix it. Using XUnit, how should I best mark this bug as something we're aware of but have chosen not to fix? A failed test would break our build automation, so I can't just leave it as is. The input that fails is currently being generated as part of a PropertyData for a Theory . Does XUnit have a special indicator for this? Should I adjust the method that generates the inputs for the PropertyData to exclude that case, add a comment explaining why, and then put in a skipped Fact covering that case?
Now provide the response and nothing else.
| "number (N) of ways ... using N kinds" these two N s are clearly not the same. so let's say K kinds of coins. We have many coins, but each coin is either 1, 5, 10, 25 or 50 cents, in total 5 kinds of coins. We need to buy something for a dollar, 100 cents. Assume unlimited supply of each kind of coins. How many ways are there for us to reach the total sum of 100? We either use some coins (one or more) of 50 cents, or we don't. If not, we still have to get to the 100 with only 4 kinds of coins. But if we do, then after using one 50 cents coin, the total sum becomes 100 - 50 = 50 cents, and we may still use all 5 kinds of coins to reach the new, smaller total sum: ways{ 100, 5 } = ways{ 100, 5 - 1 } ; never use any 50-cent coins + ; OR ways{ 100 - 50, 5 } ; may use 50-cent coins, so use one Or in general, ways( sum, k ) = ways( sum, k - 1 ) + ways( sum - first_denomination(k), k ) That's all there is to it. See? Generalization comes naturally with abstraction (replacing concrete values with symbols and making them parameters in a function definition). Then we need to take care of the base cases. If sum = 0 , the result is 1: there's one way to reach total sum of 0 (and it is: take no coins). If k = 0 , this means we are not allowed to use any kind of coins; in other words there's no way for us to reach a sum, any sum, without using at least some coins (unless the sum is 0, but we've already handled that case above). So the result must be 0. Same if sum < 0 , of course. Impossible, i.e. 0 ways to sum up to it, using any coins with any positive denomination. Another way to look at this is from the other end of the time arrow, if you will. Imagine someone have already done all that for you and have put in front of you all these piles of bills, each pile summing up to the target sum. Without loss of generality, let each pile be sorted so that bigger bills are on top. Divide all the piles into two groups: one with the biggest denomination bill on top each pile, and the other - without it. If the total number of piles is ways( denomsList, targetSum) , then clearly the number of piles in the second group is ways( rest(denomsList), targetSum) . Then, we can get the top bill off each pile in the first group , and the number of piles in it clearly won't be changed by that. Having removed the top bill in each pile, we see that they all sum up to targetSum - first(denomsList) , hence they number ways( denomsList, targetSum - first(denomsList)) in total. The point to (structural) recursion is thinking in the small -- not trying to picture the whole sequence of operations at once, but rather standing still and trying to understand your current situation. It is a mental tool for approaching your problem, it is about solving it in the easiest most natural way, making as small a step as possible. Calling ( a copy of ) yourself is a technicality. The main thing is the leap of faith, that you are allowed to call yourself: assuming you have already written down your definition, just use it were appropriate. And that's how it gets written down . You just describe what you have, how it's made of smaller parts (some of them similar to the full thing), and how the results for those parts can be combined back with the rest to get the full solution. edit (from comments): The key to solving a problem recursively is to recognize that it can be broken down into a collection of smaller sub-problems to each of which that same general solving procedure that we are seeking applies, and the total solution is then found in some simple way from those sub-problems' solutions (which are found by that same general procedure as if it were available to us already). Each of thus created sub-problems being "smaller" guarantees the base case(s) will eventually be reached. In other words, try to find the structure in the problem so that it has substructure(s) similar to the whole (like fractals; or e.g. a list's suffix is also a list; etc.); then, recursion is: assuming we already have the solution; taking the problem instance apart (according to the way in which we've structured our problem); transforming the "smaller" substructure(s) by the solution; and then combining it all back in some simple way (according to the way in which we structured our problem). The trick is to recognize the existing , inherent structure in your problem so that the solution comes naturally. Or, in Prolog (of all the programming languages :) ) : recursion( In, Out) :- is_base_case( In), base_relation( In, Out).recursion( In, Out) :- not_base_case( In), constituents( In, SelfSimilarParts, LeftOvers), % (* forth >>> *) maplist( recursion, SelfSimilarParts, InterimResults), constituents( Out, InterimResults, LeftOvers). % (* and back <<< *) Which is to say, in pseudocode, (In <--> Out) are related by recursion when either In is indivisible, and Out its counterpart or In = Sub_1 <+> Sub_2 <+> ... <+> Sub_N <++> Shell ------ r e c u r s i o n ------ Out = Res_1 {+} Res_2 {+} ... {+} Res_N {++} Shell where (Sub_i <--> Res_i) , for each i = 1, ..., N The combination operation + for In and Out might be different, because they can be different type of values. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27803157', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1175868/']} | jdg_73617 |
stackexchange | llm_judgeable_groundtruth_similarity | 21855540 |
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 question I want to test whether after button click the web browser is beign launched using espresso.And the question is: is it even possible to test such thing?If so any ideas how would I do that?
Now provide the response and nothing else.
| Although it's an old question but just posting here to help anyone else. I had the same situation where i wanted to verify whether a particular url was launched in browser or not. I got real help from this link I got it working using this chunk of code: Intents.init(); Matcher<Intent> expectedIntent = allOf(hasAction(Intent.ACTION_VIEW), hasData(EXPECTED_URL)); intending(expectedIntent).respondWith(new Instrumentation.ActivityResult(0, null)); onView(withId(R.id.someid)).perform(click()); intended(expectedIntent); Intents.release(); So, it tests when browser is opened with correct url and intending() does the magic here by enabling intent stubbing. Using this, we can intercept it so the intent is never sent to the system. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21855540', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3274539/']} | jdg_73618 |
stackexchange | llm_judgeable_groundtruth_similarity | 32041 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible for the compiler to remove statements used for debugging purposes (such as logging) from production code? The debug statements would need to be marked somehow, maybe using annotations. It's easy to set a property (debug = true) and check it at each debug statement, but this can reduce performance. It would be nice if the compiler would simply make the debug statements vanish.
Now provide the response and nothing else.
| Two recommendations. First: for real logging, use a modern logging package like log4j or java's own built in logging. Don't worry about performance so much, the logging level check is on the order of nanoseconds. (it's an integer comparison). And if you have more than a single log statement, guard the whole block: (log4j, for example:) if (logger.isDebugEnabled()) { // perform expensive operations // build string to log logger.debug("....");} This gives you the added ability control logging at runtime. Having to restart and run a debug build can be very inconvenient. Second: You may find assertions are more what you need. An assertion is a statement which evaluates to a boolean result, with an optional message: assert (sky.state != FALLING) : "The sky is falling!"; Whenever the assertion results in a false, the assertion fails and an AssertionError is thrown containing your message (this is an unchecked exception, intended to exit the application). The neat thing is, these are treated special by the JVM and can toggled at runtime down to the class level, using a VM parameter (no recompile needed). If not enabled, there is zero overhead. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32041', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1772/']} | jdg_73619 |
stackexchange | llm_judgeable_groundtruth_similarity | 21202670 |
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 created a directive with a method that should be called from other elements that are not part of the directive. However it looks like this method is not exposed. Some example jade code to clarify: //- a controller for the view itselfdiv(ng-controller="someController") //- this is part of the view itself, not within the directive div(ng-repeat="element in elements") div(ng-click="methodFromDirective(element)") click element {{$index}} to trigger directive //- this is the directive div(some-directive) The someController isn't too important here I think. It has methods but NOT the methodFromDirective(element) one. The methodFromDirective(element) is a method that exists only in the directive. If I make a directive and put some logging on creation I can clearly see it's created. However the methodFromDirective(element) method isn't exposed so the calls aren't properly triggered. The methodFromDirective(element) itself will only work on elements from within the directive's template. some coffeescript to show the definition of the the directive (ignore indentation errors here): 'use strict'define [], () ->someDirective = () -> restrict: 'A' scope: { show: '=' } transclude: false templateUrl: 'someTemplateHere.html' controller = ($scope) -> # exposing the method here $scope.methodFromDirective(element)-> $scope.theMethod element link = (scope, element, attr) -> # this is logged console.log "init someDirective" # triggering this method form outside fails scope.theMethod = (element)-> console.log "method triggered with element", JSON.stringify(element)
Now provide the response and nothing else.
| I found my issue . From the angularJS documentation on directives I was looking into the transclude option since that states: What does this transclude option do, exactly? transclude makes the contents of a directive with this option have access to the scope outside of the directive rather than inside. I combined transclude=false with the controller function since that exposes the method, again from docs: Savvy readers may be wondering what the difference is between link and controller. The basic difference is that controller can expose an API, and link functions can interact with controllers using require. However what I missed completely was that I isolated scope within my directive . From docs: What we want to be able to do is separate the scope inside a directive from the scope outside, and then map the outer scope to a directive's inner scope. We can do this by creating what we call an isolate scope. To do this, we can use a directive's scope option: So even if you use transclude=false and the controller function you'll still fail to expose methods if you use isolated scope! Lesson learned! While figuring out what went wrong I also made a fiddle for better understanding: http://jsfiddle.net/qyBEr/1/ html <div ng-app="directiveScopeExample"> <div ng-controller="Ctrl1"> <p>see if we can trigger a method form the controller that exists in the directive.</p> <ul> <li><a href="#" ng-click="methodInController()">Method in Controller</a></li> <li><a href="#" ng-click="methodInDirective()">Method in Directive</a></li> </ul> <simple-directive/> </div></div> javascript angular.module('directiveScopeExample', []) .controller('Ctrl1', function Ctrl1($scope) { $scope.methodInController = function(){ alert('Method in controller triggered'); }; }) .directive('simpleDirective', function(){ return { restrict: 'E', transclude: false, controller: function($scope){ $scope.methodInDirective = function(){ // call a method that is defined on scope but only within the directive, this is exposed beause defined within the link function on the $scope $scope.showMessage('Method in directive triggered'); } } // this is the issue, creating a new scope prevents the controller to call the methods from the directive //, scope: { // title: '@' //} , link: function(scope, element, attrs, tabsCtrl) { // view related code here scope.showMessage = function(message){ alert(message); } }, //templateUrl: 'some-template-here.html' }; }) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21202670', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/312743/']} | jdg_73620 |
stackexchange | llm_judgeable_groundtruth_similarity | 63319 |
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to create an Emacs script that indents HTML files from the command line. This is what I have so far: #!/usr/bin/env -S emacs --script(require 'web-mode)(indent-region (point-min) (point-max) nil)(save-buffer) I saved this file as indent and made it executable with chmod 755 indent . Then, I tried running it on an HTML file: $ ./indent base.html Loading /etc/emacs/site-start.d/00debian.el (source)...Loading /etc/emacs/site-start.d/50autoconf.el (source)...Loading /etc/emacs/site-start.d/50cmake-data.el (source)...Loading /etc/emacs/site-start.d/50dictionaries-common.el (source)...Loading debian-ispell...Loading /var/cache/dictionaries-common/emacsen-ispell-default.el (source)...Loading /var/cache/dictionaries-common/emacsen-ispell-dicts.el (source)...Loading /etc/emacs/site-start.d/50figlet.el (source)...Loading /etc/emacs/site-start.d/50gettext.el (source)...Package gettext-el removed but not purged. Skipping setup.Loading /etc/emacs/site-start.d/50latexmk.el (source)...Loading /etc/emacs/site-start.d/50pylint.el (source)...Indenting region... Indenting region...done It seemed to work, but there is no output. The content of file base.html remains unchanged. I'd really like to get this working, because I want to use this command as a git hook to format HTML files using web-mode.el . Could anyone help?
Now provide the response and nothing else.
| @glucas's answer is correct in its diagnosis, but has a minor problem (you want the 0th element of argv ) and is incomplete. Here is a more complete example: #!/usr/bin/env -S emacs --script(find-file (nth 0 argv))(mhtml-mode)(indent-region (point-min) (point-max) nil)(save-buffer) This does not use web-mode which is not available to me (does it exist?); instead I use mhtml-mode which is what my emacs uses when editing HTML files. One safety point: instead of modifying a file in place, I would rather save it to a different file name, so if something goes wrong, I still have the original file and I can retry after fixing any problems (although you can use a backup, either one you made, or one made for you by emacs). So you might want to go with something like this: #!/usr/bin/env -S emacs --script(setq fname (nth 0 argv))(find-file fname)(mhtml-mode)(indent-region (point-min) (point-max) nil)(write-file (concat fname ".indent") t) When invoked like this: ./indent foo.html the script will save the result in a new file foo.html.indent (if foo.html.indent exists already, the t argument of write-file will cause the script to ask you whether to overwrite it: if you say y it will overwrite it; if you say n it will not, but you'll get a backtrace, since the script does not handle error conditions gracefully). | {} | {'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/63319', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/31750/']} | jdg_73621 |
stackexchange | llm_judgeable_groundtruth_similarity | 6429225 |
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 really confused as to when JavaScript returns null or undefined . Also different browsers seem to be returning these differently. Could you please give some examples of null / undefined with the browsers that return them. While I am now clear on the undefined aspect, I am still not 100% clear on null . Is it similar to a blank value? E.g. You have a text box which does not have any value set. Now when you try to access its value, will it be null or undefined and are they similar?
Now provide the response and nothing else.
| The DOM methods getElementById() , nextSibling() , childNodes[n] , parentNode() and so on return null (defined but having no value) when the call does not return a node object. The property is defined, but the object it refers to does not exist. This is one of the few times you may not want to test for equality- if(x!==undefined) will be true for a null value but if(x!= undefined) will be true (only) for values that are not either undefined or null . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6429225', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/485743/']} | jdg_73622 |
stackexchange | llm_judgeable_groundtruth_similarity | 38900865 |
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 Xamarin Forms application I would like to develop. It will have a SQLite database and I wish to make this available on iOS and Android. The database will be populated with data from a SQL Server database on the cloud with initial seed data. I'm thinking this will be about 500 rows of data with each row about 1Kb. What I don't understand is when and how to populate this. Should I try to put the data into a CSV file and have this populate the database when the application is installed, or when it first starts? What's the normal way to populate seed data other than lines inside of the code with a huge number of insert statements. Any help or advice on how this is normally done (I'm thinking most people do it the same way) would be much appreciated. Thanks
Now provide the response and nothing else.
| Lets break the problem down. Is the initial data that you wish to use in your app going to change over time? If you include any pre-populated data (a SQLite, Realm, or CSV-based file, ...) and the data that you are including goes stale and you have to update it on a routine basis, you will need to publish an application update ( .apk / .ipa ) so your new user installs receive the updated data (more on this below). Note: This assumes that your current users get the updated data via actually running your app and it is handling the local data updates on routine basis (background service, push notifications, data polling, etc..) Is this a Line of Business ( LoB ) application published via Ad-Hoc, private Store, and/or iOS Enterprise publishing? If you control the user base, than having to force an update install so your users get your new/updated pre-populated data might be an acceptable approach, but not a great user experience if they forced to update the application all the time... but it works... Is this application going to be distributed via the public Apple and Google App Stores? This is where you need to be very careful on what pre-populated data you include within your application. If the data goes stale and you need to push an updated app version to the Stores for your new install installs, beware that it could be days (or weeks or even month+) to get that new app into the store. The Play Store usually is less then 24 hours on publishing app updates, and while the Apple Store can be the same, do not bet on it . We routinely see 48-72 hour delays and randomly get rejected and thus it can take a week or more to get an update app into the Apple Store. We have had rejections delaying an app update for over a month and have gone into the appeal process and even removed already existing features to get re-published Note : Every app update to the Apple store resets your user reviews... :-( Bottom line : You want to want to publish to the Stores when you are bug fixing and/or adding features, not to update some "static" data that is stored within your app bundle... What does this data cost your end-user and you? Negative costs to you as an app developer are bad reviews and uninstalls. Look at how this "data" effects the end-users access to your application and how they react. Longer download time, usually acceptable. Longer initial app startup times, less acceptable... etc.... What markets will your app be used in? Network speeds and the cost of data transfer in many markets across the world are slow and costly... What really is the true size of the data? I "pre-populate" a Realm data instance with thousand of rows with 5MB of JSON data in under a second. SQLite takes longer, but it is still not bad. The data itself is stored in a zip and accessed as a static file (https-based get) and at a 80% compression factor, the 1MB of compressed data is pulled from a server (AWS S3) in under one second using LTE cellular data speeds and uncompressing it as stream while deserializing the JSON on-fly to update the Realm instance adds another second... So, the user impact is very small and I "hide" this initial pre-populate update via a first-time welcome screen and some text that the user hopefully reads before getting to the first "real" app screen... Note: This does assume that the user will have network data access the first time they open the app... In many markets around the world, this is not true, so factor this into your app design. I also architect the app so its data can be update on background threads during its launch (the initial one or not) and thus the user does not stand there watching a spinning busy indictor, they can at least interact with the data that they do have. So should you include any pre-populated data in your app bundle? Sure, when that data is absolutely required to get the user up and running as fast as possible to enhance the user experience. Games are a great example of this in bundling 100s of megabytes or even gigabytes via .obb ... with the various levels, media files, etc... into the app so the user does not experience a 10+ min. wait time upon opening the app the first time. Now this does mean that their initial download time for the install was longer as that data was bundled within the app, the overall user experience was better as users accept the download/install times and view that as a carrier/phone/service plan issue vs. the time to open your app the first time to actually get to a functional screen. So what do? Personally I look at this issue on a case by case basis. I look at the data and if it is not going to change and only get added to and possibly pruned over time, include it as a pre-populated SQLite or Realm store or... Why cause the user to wait for the web requests, database updates and the additional network data usage and associated costs. If the data is going to go stale, do not bundle it in your app. As for the mechanics of installing pre-populated data: See my answer on this SO Question about " Bundle prebuilt Realm files " | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38900865', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1422604/']} | jdg_73623 |
stackexchange | llm_judgeable_groundtruth_similarity | 19004503 |
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 really trying to understand the under the hood of keystone regarding the relationships among endpoints, regions, tenants, services, users and roles.I've tried to find the related documents but sadly, failed. Could anybody give any pointers or explanations?
Now provide the response and nothing else.
| Keystone is the identity management service for OpenStack. Essentially it's role is to grant tokens to users be they people, services, or anything at all. If you make an API query anywhere in OpenStack, keystone's API is how it is discovered if you are allowed to make that API query. Let's work our way up from the ground. Users. Users in Keystone today are generally people. There isn't enough fine grained ACL support at this moment to really call many of the users in OpenStack a 'service' account in a traditional sense. But there is a service account that is used as a backhaul connection to the Keystone API as part of the OpenStack infrastructure itself. We'll avoid delving into that anomalous user. When a user authenticates to Keystone ( you hit up the OS_AUTH_URL to talk to keystone.. usually port 5000 of the keystone api box ), the user says hey " I am user X , I have password Y, and I belong to tenant Z". X can be a username or userid ( unique uuid of user )Y is a password, but you can authenticate with a token as well.Z is a tenant name or tenant id ( unique uuid of tenant ). in past Keystone APIs you didn't NEED to specify a tenant name, but your token wouldn't be very useful if you didn't as the token wouldn't be associated with your tenant and you would then be denied any ACLs on that tenant. So... a user is a fairly obvious thing. A password is a fairly obvious thing. But what's a tenant? Well a tenant is also known as a project. In fact, there have been repeated attempts to make the name be either tenant or project, but as a result of an inability to stick to just one term they both mean the same thing. As far as the API is concerned a project IS a tenant. So if you log into horizon you will see a drop down for your projects. Each project corresponds to a tenant id. Your tokens are associated with a specific tenant id as well. So you may need several tokens for a user if you intend to work on several tenants the user is attached to. Now, say you add a user to the tenant id of admin. Does that user get admin privileges? The answer is no. That's where roles come into play. While the user in the admin tenant may have access to admin virtual machines and quotas for spinning up virtual machines that user wouldn't be able to do things like query keystone for a user list. But if you add an admin role to that user, they will be endowed with the ACL rights to act as an admin in the keystone API, and other APIs. So think of a tenant as a sort of resource group, and roles as an ACL set. regions are more like ways to geographically group physical resources in the openstack infrastructure environment. say you have two segmented data centers. you might put one in region A of your openstack environment and another in region B. regions in terms of their usefulness are quickly evolving, especially with the introduction of cells and domains in more recent openstack releases. You probably don't need to be a master of this knowledge unless you intend to be architecting large clouds. keystone provides one last useful thing. the catalog. the keystone catalog is kind of like the phone book for the openstack APIs. whenever you use a command line client, like when you might call nova list to list your instances, nova first authenticates to keystone and gets you a token to use the API, but it also immediately asks keystone catalog for a list of API endpoints. For keystone, cinder, nova, glance, swift... etc. nova will really only use the nova-api endpoint, though depending on your query you may use the keystone administrative API endpoint.... we'll get back to that. But essentially the catalog is a canonical source of information for where APIs are in the world. That way you only ever need to tell a client where the public API endpoint of keystone is, and it can figure out the rest from the catalog. Now, I've made reference to the public API, and the administrative API for keystone. Yep keystone has two APIs... sort of. It runs an API on port 5000 and another one up in the 32000 range. The 5000 is the public port. This is where you do things like find the catalog, and ask for a token so you can talk to other APIs. It's very simple, and somewhat hardened. The administrative API would be used for things like changing a users password, or adding a new role to a user. Pretty straight forward? | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19004503', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1023045/']} | jdg_73624 |
stackexchange | llm_judgeable_groundtruth_similarity | 2490654 |
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:
$$\int_0^1\sqrt\frac x{1-x}\,dx$$I saw in my book that the solution is $x=\cos^2u$ and $dx=-2\cos u\sin u\ du$. I would like to see different approaches, can you provide them?
Now provide the response and nothing else.
| Here is another way that involves rationalising the numerator first. For $0 \leqslant x < 1$ we can write\begin{align*}\int_0^1 \sqrt{\frac{x}{1 - x}} \, dx &= \int_0^1 \sqrt{\frac{x}{1 - x}} \cdot \frac{\sqrt{x}}{\sqrt{x}} \, dx\\&= \int^1_0 \frac{x}{\sqrt{x - x^2}} \, dx\end{align*}Now rewriting the numerator as the derivative of the denominator we have \begin{align*}\int_0^1 \sqrt{\frac{x}{1 - x}} \, dx &= -\frac{1}{2} \int^1_0 \frac{(1 - 2x) - 1}{\sqrt{x - x^2}} \, dx\\&= -\frac{1}{2} \int^1_0 \frac{1 - 2x}{\sqrt{x - x^2}} \, dx + \frac{1}{2} \int^1_0 \frac{dx}{\sqrt{x - x^2}} \, dx\\&= I_1 + I_2\end{align*}The first of these integrals can be found using a substitution of $x = u + 1/2$. The result is $$I_1 = \int^{1/2}_{-1/2} \frac{u}{\sqrt{1/4 - u^2}} \, du = 0,$$as the integrand is odd between symmetric limits. The second integral can be found by first completing the square. As $$x - x^2 = \frac{1}{4} - \left (x - \frac{1}{2} \right )^2,$$we have$$I_2 = \frac{1}{2} \int^1_0 \frac{dx}{\sqrt{\frac{1}{2^2} - \left (x - \frac{1}{2} \right )^2}} \, dx = \frac{1}{2} \sin^{-1} (2x - 1) \Big{|}^1_0 = \frac{\pi}{2}.$$Thus$$\int_0^1 \sqrt{\frac{x}{1 - x}} \, dx = \frac{\pi}{2}.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2490654', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/463759/']} | jdg_73625 |
stackexchange | llm_judgeable_groundtruth_similarity | 1246099 |
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 couple questions about Ruby's methods, procedures, and blocks that strike me as rather odd. They're not so much about syntax or function as the logic behind the decisions made. Question 1: Why is it that blocks can be passed to methods (e.g. each) but they cannot be assigned to a variable? I know you can pass them around in procedures, i.e. p = Proc.new {...} (accessed with &p ), but it doesn't make much sense to make the programmer go through these means. Question 2: Why is there a differentiation between methods and procedures? For instance, I can accomplish the task of defining a function and calling that function in the following two ways: def square(x) x**2endsquare(3)=> 9 or square = lambda {|x| x**2}square.call(3)=> 9 Why the differentiation? In Python for example both defining a function in the standard way and by square = lambda x: x**2 accomplish the same task of creating the function and assigning it to square .
Now provide the response and nothing else.
| Question 1: Blocks are not objects, they are syntactic structures; this is why they cannot be assigned to a variable. This is a privilege reserved for objects. Question 2: Methods are not objects, so they cannot receive messages. Inversely, procs and lambdas are objects, so they cannot be invoked like methods, but must receive a message that tells them to return a value on the basis of the parameters passed with the message. Procs and Lambdas are objects, so they can receive the call message and be assigned to names. To summarize, it is being an object that makes procs and lambdas behave in ways you find odd. Methods and blocks are not objects and don't share that behavior. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1246099', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/152650/']} | jdg_73626 |
stackexchange | llm_judgeable_groundtruth_similarity | 2235677 |
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 ExtJS, how do I load a store when I display a grid? I want the store to load only when the grid is displayed (the user clicks on a button to show the grid, so it's wasteful to load the store beforehand). I tried the afterrender listener but it renders the loadmask in the wrong location, and the afterlayout listener reloads the grid every time the grid is resized.
Now provide the response and nothing else.
| This is one of those things that can be a bit of a pain to accomplish because were giving the browser too much to do at once (particularly noticeable in IE). I like to use a combination of defer to let the browser recover long enough to render things properly. var grid = new Ext.grid.GridPanel({ ..., listeners : { render : function(grid){ grid.body.mask('Loading...'); var store = grid.getStore(); store.load.defer(100, store); }, delay: 200 }}); Playing with the value of delay/defer should give you the desired results. The length of time you will need to delay/defer is dependent upon how complex your Grid is and how fast the browser is. Also remember to remove the mask when your Store's load has completed. listeners: { load: function(){ yourGrid.body.unmask(); }} NOTE: Just a few clarifications to the answer by Lloyd - you do not need to set autoLoad to false, because that is the default (ie: don't set it at all) and it sounds like from your description that you would want to use the Stores load method, instead of reload. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2235677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/135318/']} | jdg_73627 |
stackexchange | llm_judgeable_groundtruth_similarity | 8200349 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Are there any scripts, libraries, or programs using Python , or BASH tools (e.g. awk , perl , sed ) which can correctly convert numbered pinyin (e.g. dian4 nao3 ) to UTF-8 pinyin with tone marks (e.g. diàn nǎo )? I have found the following examples, but they require PHP or C#: [PHP] Convert numbered to accentuated Pinyin? [C#] Any libraries to convert number Pinyin to Pinyin with tone markings? I have also found various online tools, but they cannot handle a large number of conversions.
Now provide the response and nothing else.
| I've got some Python 3 code that does this, and it's small enough to just put directly in the answer here. PinyinToneMark = { 0: "aoeiuv\u00fc", 1: "\u0101\u014d\u0113\u012b\u016b\u01d6\u01d6", 2: "\u00e1\u00f3\u00e9\u00ed\u00fa\u01d8\u01d8", 3: "\u01ce\u01d2\u011b\u01d0\u01d4\u01da\u01da", 4: "\u00e0\u00f2\u00e8\u00ec\u00f9\u01dc\u01dc",}def decode_pinyin(s): s = s.lower() r = "" t = "" for c in s: if c >= 'a' and c <= 'z': t += c elif c == ':': assert t[-1] == 'u' t = t[:-1] + "\u00fc" else: if c >= '0' and c <= '5': tone = int(c) % 5 if tone != 0: m = re.search("[aoeiuv\u00fc]+", t) if m is None: t += c elif len(m.group(0)) == 1: t = t[:m.start(0)] + PinyinToneMark[tone][PinyinToneMark[0].index(m.group(0))] + t[m.end(0):] else: if 'a' in t: t = t.replace("a", PinyinToneMark[tone][0]) elif 'o' in t: t = t.replace("o", PinyinToneMark[tone][1]) elif 'e' in t: t = t.replace("e", PinyinToneMark[tone][2]) elif t.endswith("ui"): t = t.replace("i", PinyinToneMark[tone][3]) elif t.endswith("iu"): t = t.replace("u", PinyinToneMark[tone][4]) else: t += "!" r += t t = "" r += t return r This handles ü , u: , and v , all of which I've encountered. Minor modifications will be needed for Python 2 compatibility. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8200349', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/834616/']} | jdg_73628 |
stackexchange | llm_judgeable_groundtruth_similarity | 31836796 |
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 the let keyword introduces a proper implementation of block scope, does var any longer have a use case? I am looking at this from a software design standpoint rather than a syntactical, "well you could" standpoint.
Now provide the response and nothing else.
| If the let keyword introduces a proper implementation of block scope, does var any longer have a use case? There could be one use case: let declarations in global scope don't create a property on the global object. Example: "use strict"; // for chromevar foo = 42;let bar = 21;console.log('window.foo (var)', window.foo); // 42console.log('window.bar (let)', window.bar); // undefined From 8.1.1.4 Global Environment Records The object Environment Record component of a global Environment Record contains the bindings for all built-in globals ( clause 18 ) and all bindings introduced by a FunctionDeclaration , GeneratorDeclaration , or VariableStatement contained in global code. The bindings for all other ECMAScript declarations in global code are contained in the declarative Environment Record component of the global Environment Record. However, this can also easily be solved by creating an explicit global variable using by assigning to the global object directly: window.foo = 42; This would also be the only way to create global classes btw, because the class declaration has the same behavior. (Note: I'm not advocating the use of global variables) There are syntax constructs where you can only use var , but that's more a consequence of the how the spec evolved and doesn't really serve any practical purpose. For example: if (true) var foo = 42; // valid but kind of useless or bad design// vsif (true) let foo = 42; // invalid Block scope is not the only useful feature though. The temporal dead zone is another handy feature to find bugs more easily. Compare: var foo = 42;function bar() { console.log(foo); // undefined var foo = 21;}bar();// vsvar foo = 42; // or `let`, doesn't matterfunction bar() { console.log(foo); // ReferenceError, temporal dead zone let foo = 21;}bar(); You get a reference error when trying to access a let variable that wasn't initialized yet. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31836796', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2938360/']} | jdg_73629 |
stackexchange | llm_judgeable_groundtruth_similarity | 1058427 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the best de-facto standard cross-browser method to determine if a variable in JavaScript is an array or not? Searching the web there are a number of different suggestions, some good and quite a few invalid. For example, the following is a basic approach: function isArray(obj) { return (obj && obj.length);} However, note what happens if the array is empty, or obj actually is not an array but implements a length property, etc. So which implementation is the best in terms of actually working, being cross-browser and still perform efficiently?
Now provide the response and nothing else.
| Type checking of objects in JS is done via instanceof , ie obj instanceof Array This won't work if the object is passed across frame boundaries as each frame has its own Array object. You can work around this by checking the internal [[Class]] property of the object. To get it, use Object.prototype.toString() (this is guaranteed to work by ECMA-262): Object.prototype.toString.call(obj) === '[object Array]' Both methods will only work for actual arrays and not array-like objects like the arguments object or node lists. As all array-like objects must have a numeric length property, I'd check for these like this: typeof obj !== 'undefined' && obj !== null && typeof obj.length === 'number' Please note that strings will pass this check, which might lead to problems as IE doesn't allow access to a string's characters by index. Therefore, you might want to change typeof obj !== 'undefined' to typeof obj === 'object' to exclude primitives and host objects with types distinct from 'object' alltogether. This will still let string objects pass, which would have to be excluded manually. In most cases, what you actually want to know is whether you can iterate over the object via numeric indices. Therefore, it might be a good idea to check if the object has a property named 0 instead, which can be done via one of these checks: typeof obj[0] !== 'undefined' // false negative for `obj[0] = undefined`obj.hasOwnProperty('0') // exclude array-likes with inherited entries'0' in Object(obj) // include array-likes with inherited entries The cast to object is necessary to work correctly for array-like primitives (ie strings). Here's the code for robust checks for JS arrays: function isArray(obj) { return Object.prototype.toString.call(obj) === '[object Array]';} and iterable (ie non-empty) array-like objects: function isNonEmptyArrayLike(obj) { try { // don't bother with `typeof` - just access `length` and `catch` return obj.length > 0 && '0' in Object(obj); } catch(e) { return false; }} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1058427', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/25815/']} | jdg_73630 |
stackexchange | llm_judgeable_groundtruth_similarity | 69525 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Epilog : Much of the discussion in the answers below revolves around the distinction between Real as a data type and real numbers as a domain or class of numbers (irrespective of the form in which they might be embodied). This distinction between the data type and class is perhaps even clearer for the case of fractions and rational numbers. Rational numbers are those numbers that can be expressed a ratio of integers, a, b, where b is not equal to zero; that is, rational numbers are those that can be formatted as fractions. Although all fractions represent rational numbers, not all rational numbers are (formatted as) fractions. For example, the (rational) number 3 is not a fraction, even though it might be expressed as 3/1, a fraction. By this reasoning, it might be better if the head, Rational , were replaced by Fraction . Rationals could then be used to represent the class of numbers. This is more of a request for advice and input than a solution to a programming challenge, but I thought it might be useful to raise here nonetheless. I am wondering if Mathematica and the Wolfram Language may have adopted a definition of real numbers that conflicts with the definition (or definitions) of real numbers in modern mathematics. In mathematics, the domain of real numbers is loosely thought of as all the points on the real line ( http://en.wikipedia.org/wiki/Real_number ). What real numbers are, according to the symbol, Reals In Mathematica, the term Reals is said to represent the domain of real numbers. [Update] And as Yves Klett and Szabolcs note, this is consistent with the mathematical definition of the domain. The following shows that Mathematica recognizes the symbol for the golden ratio to represent a real number, in this sense. GoldenRatio \[Element] Reals True What real numbers are, according to the symbol, Real The head, Real , however, is employed expressly to designate floating-point numbers. The definition is: "Real is the head for real (floating point) numbers". This definition appears to conflate the domain of real numbers with floating point numbers. Integers and irrational numbers are not floating point numbers. So they would not, according to this view, be considered real numbers. If the head, Real , indicates that a number is a floating point number, not a real number, why not create the head, Float, to serve that purpose? The designers of the language are certainly aware that integers and irrational numbers are real numbers. And they have expressly shunned the inclusion of RealQ . After all, what would we expect RealQ[3] to return, given that real numbers have been defined (in the definition of the head, Real ) to be floating point numbers, and also defined (in the definition of the domain, Reals ) as those numbers considered by mathematicians to be real numbers? It seems to me that it would be advisable to eliminate the head, Real , from the Wolfram language. The head, Float, would fit the bill much better. Then Reals coud be properly defined as including rational numbers (including Integers), and irrational numbers. One might argue that we should simply treat the domain of real numbers in mathematics as having a different meaning from the domain of real numbers in the Wolfram language. However, the Wolfram Language has chosen to use the double-strike R to designate the domain. This is precisely the symbol used throughout mathematics for the set of real numbers. I realize that it is rather late in the game to be rethinking fundamental objects of the language, such as real numbers, but now that regions have been formally introduced, in version 10, it seems that it will become increasingly important to be clear and consistent in the specification of number domains.
Now provide the response and nothing else.
| In some settings the integers, fractions, rational numbers, reals, and complexes are five distinct systems. Further, for reals and complexes, there are the standard reals and complexes as well as nonstandard systems. There are mappings from some to others, so that a subset of the reals in an isomorphic image of the integers (as rings), and so on for ${\bf Z} \subset {\bf Q}$, ${\bf Q} \subset {\bf R}$, ${\bf R} \subset {\bf C}$, and so on, where $\subset$ denotes a canonical injection. The rationals are also a natural homomorphic image of the fractions under the standard equivalence relation. In a math class (as opposed to a mathematics class), these things are all conflated, from school through the university courses that scientists and engineers take, and they are all thought of as belonging to same big set of "numbers." In a computational setting, there is a different sort of division depending on data types that correspond to hardware/software abilities, in which some things are exact and some approximate; there is always some truncation of the mathematical set (with respect to which numbers are actually representable). Computationally in school, you even get $\pi = 3.14 = 22/7$ sometimes; in the Indiana legislature , it was once proposed that $\pi =3.2$ would be a more convenient value. So, while I think it's a pretty cool question, I don't think I'm up to fleshing out all the subtle distinctions a truly complete answer would have to make. But one thing is clear, the type Real does not satisfy the properties of the real numbers. The following are inconsistent: $MachineEpsilon == 0.(* False *)$MachineEpsilon == 0.``15(* True *)1. + $MachineEpsilon == 1.(* True *)1. + $MachineEpsilon/2 - 1.(* 0. *)Head /@ {0.``15, 0., 1.}(* {Real, Real, Real} *) Whatever the computational reasons underlying them, the results, except for the first, do not represent what happens with (mathematical) real numbers. As for the domain Reals , I'm not convinced it represents a complete implementation of the real numbers as a logical system. I think it is primarily a way to specify a domain for exact algebra (as well as approximate numerics). For instance, I tried to specify and verify the least upper bound property but got stuck. Resolve did not seem to know how to deal with Subset[S, Reals] and Element[x, S] in the same statement. I'm not convinced that Subset[S, Reals] is a proper way to use Subset . In practical terms, Mathematica is put out for use by mathematicians but also for use by those in many other fields. I'm not bothered by the term Real being distinct from "real", and I find "real (floating-point)" sufficiently clear to me, who knows what floating-point means. The case for or against calling approximate reals by the name Real ought to be based on the usefulness to the users who do not know what floating-point numbers are. If some are mathematicians, and some probably do not know numerics, they might be confused. For others who do not know about the axiomatic number systems of mathematics and think of reals numbers in terms of pencil & paper or what they see on their calculators, it might be easier for them to think of the Real numbers as real numbers. I suspect the reason Wolfram did not choose Float is that compared to something like C, when Mathematica first came out, arbitrary precision was only available in specialized libraries (AFAIK). Arbitrary here means a user-specified finite amount, but that was an advance over machine floats that have a fixed precision. I would argue that they are closer to modeling the reals than C floats. They come close to an implementation of the computable reals . (I hedge a little because there is much to think through and verify to make an absolute statement.) Sometimes I wish machine reals and arbitrary precision reals had different heads, but we have MachineNumberQ to distinguish them when necessary. | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/69525', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/173/']} | jdg_73631 |
stackexchange | llm_judgeable_groundtruth_similarity | 15681387 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My script fails tests when working with SQLite base (via sqlalchemy ) created in :memory: and passes tests when working with a base created with physical file. The script is multi-threaded. I know it is not the best idea to use SQLite with multiple threads (locking, etc.), but I use SQLite to test script's DB interface only. When I use :memory: , the script dies complaining that there is no table: OperationalError: (OperationalError) no such table: content_info u'INSERT INTO content_info ... The testing procedure (with nose ) is as follows: def setup_database(): global global_engine # create database columns engine = sqlalchemy.create_engine(...) Base.metadata.create_all(engine) global_engine = engine@with_setup(setup_database)def test_task_spoolers(): check_database_content_from_another_thread()def check_database_content_from_another_thread(): global global_engine # from within other thread # create new session using global_engine # do some inserts So in the setup I do create the database and the columns. I can see it also in logs ( echo=True ): 12:41:08 INFO sqlalchemy.engine.base.Engine CREATE TABLE content_info (...12:41:08 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)12:41:08 INFO sqlalchemy.engine.base.Engine INSERT INTO content_info (base_id, request_id, timestamp, ...12:41:08 INFO sqlalchemy.engine.base.Engine (0, 0, 0, 'dummy_variant', None, 0)12:41:08 INFO sqlalchemy.engine.base.Engine ROLLBACKException in thread Thread-1:Traceback (most recent call last):OperationalError: (OperationalError) no such table: content_info u'INSERT INTO ... My guess was that when I create the base in thread A, and then I use it in thread B, then B starts to operate on the base before it was actually created. But, I added time.sleep(3) after create_all and it didn't work. And, as mentioned before, it works when I use a file instead of :memory: , even if the file is placed on virtual partition (so, in fact in memory). Any idea why is that?
Now provide the response and nothing else.
| You cannot create multiple connections to an in-memory database. Instead, a new connection to :memory: creates a new database. From the SQLite documentation : Every :memory: database is distinct from every other. So, opening two database connections each with the filename ":memory:" will create two independent in-memory databases. This is different from an on-disk database, where creating multiple connections with the same connection string means you are connecting to one database. You are creating a new connection for the thread, thus creating a new database that does not have the tables created. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15681387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/497208/']} | jdg_73632 |
stackexchange | llm_judgeable_groundtruth_similarity | 27180 |
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
As I see here , the Sun belongs to the Population I group of stars, which is the 3rd generation of the stars in our universe. 1st generation stars are Population III, 2nd generation are Population II, and 3rd generation are Population I. When the 1st generation (Population III) of stars died, that means most of the hydrogen was burned to helium. Stars die when there is no hydrogen left. Later, the 2nd generation of stars (Population II) appeared and they fuse another portion of hydrogen into heavier elements. If 1st and 2nd star generations burned hydrogen to helium and more heavier elements, then shouldn't like 90% of all universe hydrogen already be converted to helium and something else? If yes, then there should not be enough hydrogen to make the Sun. UPDATE 1 Thanks for all your answers. They are very useful. Now a new subquestion appeared.When the star dies, like our Sun, it sends out external layers and core becomes white/other dwarf. In this case, new star can be formed only from the hydrogen from the external layer. The questions what is the percentage of initial star hydrogen after burning it to helium goes from this external layer to outer space?
Now provide the response and nothing else.
| Most of the galaxy's gas is not incorporated into stars and remains as gas and dust. This is not really my area of expertise, but papers such as Evans et al. 2008 and Matthews et al. 2018 seem to suggest that in the Giant Molecular Clouds where most stars in the Milky Way Galaxy form, the star formation efficiency is about 3-6%. So the vast majority of the gas (94-97%) is not made into stars. In very dense environments such as globular clusters, which were formed much earlier in the Milky Way's history, the star formation efficiency get as high as approx. 30%. The canonical quoted rate for "regular" spiral galaxies like the Milky Way is about 1 solar mass of new stars are made per year, which is very low summed across the whole galaxy. Stars also give off a fair amount of their outer, hydrogen rich outer layers during the later red giant phases when the stellar wind is stronger and the atmosphere expands a huge amount (radius of the Sun during the red giant phase will be about what the Earth's orbit is now). Also in the end state when the white dwarf is formed, it's only the core and inner layers that form the white dwarf. The typical white dwarf mass is about 0.6 times the mass of the Sun ( S. Kepler et al. 2006 ) and so there will be a fair amount of unfused hydrogen-rich outer atmosphere left over after the star dies. For higher mass stars, even more of the mass goes into the (ejected at high speed) envelope than goes into the remaining neutron star. These high mass stars are much rarer though; most of the Milky Way's stars are faint, cool M dwarfs. | {} | {'log_upvote_score': 6, 'links': ['https://astronomy.stackexchange.com/questions/27180', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/15004/']} | jdg_73633 |
stackexchange | llm_judgeable_groundtruth_similarity | 3866678 |
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 $$S = \{ f: [0,1]\rightarrow \mathbb{R} \ \text{continuous} : x\in\mathbb{Q}\implies f(x) \in \mathbb{Q}\}$$ is uncountable. I know that reals are uncountable, so I look for injection from reals to set $S$ , i.e., if we can define a function as above for each real number, then we are done. Am I going in the right direction? Please help with some hint/solution.
Now provide the response and nothing else.
| Let $X $ be the set of all sequences r = $\{r_n \}_1^{\infty}$ such that $r_n=\{ 1,-1\}$ it is an uncountable !! For $r$ in $X$ let $f_r$ be function defined on [0, 1] such that $f_r (0) =0$ $ f_r(1/n) = r_n / n$ for n positive integer ; on each interval $ [ 1/(n+1), 1/n] , f_r$ is linear function whose values at the endpoints agree with those given by (2) Each function $f_r $ is continuous at point of $(0, 1] $ is obvious, and continuity at $0$ follows because $|f(x) | \leq x$ Each $f_r$ takes rational values at rational points : if $x$ is rational point between $ a=1/(n+1) $ and $b = 1/n$ , then $x= (1-t) a+tb $ with $t$ a rational points of [0, 1] , so $f_r(x)= (1-t) f_r (a) + tf_r(b) $ is rational because $ f_r( a) $ and $ f_r(b)$ are. The functions $ f_r$ thus form an uncountable subset of S, showing that S is uncountable | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3866678', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/805303/']} | jdg_73634 |
stackexchange | llm_judgeable_groundtruth_similarity | 31990134 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the way to convert %{"foo" => "bar"} to %{foo: "bar"} in Elixir?
Now provide the response and nothing else.
| Use Comprehensions : iex(1)> string_key_map = %{"foo" => "bar", "hello" => "world"}%{"foo" => "bar", "hello" => "world"}iex(2)> for {key, val} <- string_key_map, into: %{}, do: {String.to_atom(key), val}%{foo: "bar", hello: "world"} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/31990134', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2790174/']} | jdg_73635 |
stackexchange | llm_judgeable_groundtruth_similarity | 2454216 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
to be honest, I don't really know what the "small green men" in my cpu and compiler do, so I sometimes would like to know :). Currently I would like to know what's faster, so that I can design my code in a more efficient way.So for example I want to calclate something at different points in my sourcecode, when will it be faster to calculate it once and store it in a variable that's read and used for the next points it's needed and when is it faster to calculate it everytime? I think it's depending on how "complex" and "long" the calculation is and how fast then cache is, where variables are stored, but I don't have any clue what's faster :). Thanks for any reply to my tiny but important question! Andreas PS: perhaps it's important to know that I code in JAVA, but it's more a genral question.
Now provide the response and nothing else.
| It will generally always be faster to store something calculated once, rather than calculate it each time, unless the calculation is minor and/or the number of times you use it is low. In other words, it depends entirely on the usage patterns. Consider, for example, the two extremes below. The calculation is a adding two numbers together and you only use the result twice. The calculation is a monstrous Physics calculation involving the interaction of 47 separate sub-atomic particles, and you use it in three different places in your code, one of which uses it inside a loop with 314,159,265 iterations. Obviously, you won't get much (or possibly any) benefit from calculating it once in the first example but you're extremely likely to benefit by doing so for the second case. As a general rule, you should first write your code for functionality and readability, and then only worry about performance if it becomes an issue. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2454216', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/240977/']} | jdg_73636 |
stackexchange | llm_judgeable_groundtruth_similarity | 3992171 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a function that returns how much space is free on a drive partition given a directory path?
Now provide the response and nothing else.
| check man statvfs(2) I believe you can calculate 'free space' as f_bsize * f_bfree . NAME statvfs, fstatvfs - get file system statisticsSYNOPSIS #include <sys/statvfs.h> int statvfs(const char *path, struct statvfs *buf); int fstatvfs(int fd, struct statvfs *buf);DESCRIPTION The function statvfs() returns information about a mounted file system. path is the pathname of any file within the mounted file system. buf is a pointer to a statvfs structure defined approximately as follows: struct statvfs { unsigned long f_bsize; /* file system block size */ unsigned long f_frsize; /* fragment size */ fsblkcnt_t f_blocks; /* size of fs in f_frsize units */ fsblkcnt_t f_bfree; /* # free blocks */ fsblkcnt_t f_bavail; /* # free blocks for unprivileged users */ fsfilcnt_t f_files; /* # inodes */ fsfilcnt_t f_ffree; /* # free inodes */ fsfilcnt_t f_favail; /* # free inodes for unprivileged users */ unsigned long f_fsid; /* file system ID */ unsigned long f_flag; /* mount flags */ unsigned long f_namemax; /* maximum filename length */ }; | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3992171', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/134702/']} | jdg_73637 |
stackexchange | llm_judgeable_groundtruth_similarity | 8556 |
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:
What happens to blood pressure when we exercise? Does it increase, decrease, or remain the same? If it does increase, why are patients with high blood pressure recommended to exercise?
Now provide the response and nothing else.
| As pointed out in the answers above, your blood pressure increases transiently as you exercise because more oxygen and nutrients are consumed by your muscles. However, regular exercise increases your "cardiovascular reserve"-this means your body will be able to function well at lower blood pressures. However, caution must be taken in hypertensive patients whose blood pressures are already up the roof. In these patients, gentle exercise and life style modifications (diet, stopping smoking, weight loss etc) may reduce their blood pressures over time. This will also reduce their risk of cardiovascular catastrophes in the future. So whilst exercise will reduce blood pressure, it is not recommended as a first line of life style modification in hypertensive patients because exercise itself is stressful initially and stress is also bad for a hypertensive patient. Hence, exercise is good but gentle exercise is recommended for hypertensive patients. But again I doubt gentle exercise will do maximum good to your cardiovascular system because the type of exercise that helps lower your blood pressure is one that makes you sweat (e.g tread mill, etc). But once the blood pressure of a hypertensive patient is under control, then they can safely exercise and this should help lower their blood pressure long term. I hope this makes sense. | {} | {'log_upvote_score': 4, 'links': ['https://biology.stackexchange.com/questions/8556', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/3615/']} | jdg_73638 |
stackexchange | llm_judgeable_groundtruth_similarity | 58053 |
Below is a question asked on the forum arduino.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am aware of that it is possible to change hostname for ESP8266 but I want to change vendor name also so that it lists my company/product name in routers/firewalls. Is it possible?
Now provide the response and nothing else.
| No. The Vendor Name is associated with the OUI. The OUI is the first three parts of the MAC address. The OUI's are all registered with IEEE here and Espressif's entries are: 18-FE-34 (hex) Espressif Inc.24-0A-C4 (hex) Espressif Inc.24-B2-DE (hex) Espressif Inc.2C-3A-E8 (hex) Espressif Inc.30-AE-A4 (hex) Espressif Inc.3C-71-BF (hex) Espressif Inc.54-5A-A6 (hex) Espressif Inc.5C-CF-7F (hex) Espressif Inc.60-01-94 (hex) Espressif Inc.68-C6-3A (hex) Espressif Inc.80-7D-3A (hex) Espressif Inc.84-0D-8E (hex) Espressif Inc.84-F3-EB (hex) Espressif Inc.90-97-D5 (hex) Espressif Inc.A0-20-A6 (hex) Espressif Inc.A4-7B-9D (hex) Espressif Inc.AC-D0-74 (hex) Espressif Inc.B4-E6-2D (hex) Espressif Inc.BC-DD-C2 (hex) Espressif Inc.C4-4F-33 (hex) Espressif Inc.CC-50-E3 (hex) Espressif Inc.D8-A0-1D (hex) Espressif Inc.DC-4F-22 (hex) Espressif Inc.EC-FA-BC (hex) Espressif Inc. The ESP8266 does not advertise the vendor. The router / other device maintains a list of OUI to Name mappings (on Linux it's stored in /usr/share/ieee-data ) and uses them to create a pretty display. You would need to Change the ESP8266's MAC address somehow Subscribe to IEEE and pay the relevant fees Be allocated an OUI Hope that every device in the world that would ever talk to your hardware updates its OUI mappings (which they seldom do). | {} | {'log_upvote_score': 4, 'links': ['https://arduino.stackexchange.com/questions/58053', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/3557/']} | jdg_73639 |
stackexchange | llm_judgeable_groundtruth_similarity | 8465121 |
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 function that returns an anonymous type which I want to test in my MVC controller. public JsonResult Foo(){ var data = new { details = "something", more = "More" }; return Json(data);} I want to verify the data I get from the Foo function, What I'm doing now is getting the data type and get it's properties values with reflection. [Test]public void TestOne(){ var data = _controller.Foo().Data; var details = data.GetType().GetProperty("details").GetValue(data, null); var more = data.GetType().GetProperty("more").GetValue(data, null); Assert.AreEquals("something", details); Assert.AreEquals("More", more);} Is there a simple way similar to this to check the anonymous properties? [Test]public void TestTwo(){ var data = (dynamic) _controller.Foo().Data; var details = data.details; // RunTimeBinderException object does not contain definition for details var more = data.more; Assert.AreEquals("something", details); Assert.AreEquals("More", more);}
Now provide the response and nothing else.
| Anonymous objects are internal , which means their members are very restricted outside of the assembly that declares them. dynamic respects accessibility, so pretends not to be able to see those members. If the call-site was in the same assembly, I expect it would work. Your reflection code respects the member accessibility, but bypasses the type's accessibility - hence it works. In short: no. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8465121', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/601179/']} | jdg_73640 |
Subsets and Splits