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
456955
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: Are pulsed neutron sources beams of neutrons that are not created continuously? If so what is the benefit of having a discontinuous beam of neutrons rather than a continuous one? Under what conditions is it better to use a neutron source in a particle accelerator than it is a proton beam? Now provide the response and nothing else.
Pulsed neutron sources are typically either nuclear reactors or "spallation sources."At a reactor (a continuous source), the pulsing must be achieved by rotating some kind of absorber (a "chopper") in and out of the neutron beam.At a spallation source, an energetic charged-particle accelerator is dumped into a heavy-metal target. The nuclei in the metal basically boil and emit lots of nasty things; the neutrons and photons are the longest-lived electrically neutral component, so they're what you see outside of the innermost shielding. You can isolate the neutrons from the photons by bending the beam around a corner. Most high-intensity neutron sources (pulsed or continuous) are used for materials science, rather than particle physics. People (like me) who are interested in the free neutron from the perspective of nuclear and particle physics tend to set up experiments at facilities that are mostly producing neutrons for materials science purposes. Dubbers has written several review papers with titles like "doing particle physics with neutrons" which would interest you. What makes neutrons nice from a materials-science standpoint is a kind of happy coincidence: a neutron from near the intensity peak of a room-temperature Maxwell-Boltzmann distribution has kinetic energy $$\frac12mv^2 \approx kT = 25 \text{ milli-eV.}$$ The de Broglie wavelength of such a neutron is $$\lambda = \frac hp \approx 2\,Å,$$ which is not very different from the lattice spacing in a typical material.So suppose you have a nuclear reactor for other purposes, like power generation, and part of the cooling systems for this reactor is a liquid water moderator. If you open a window in the shielding around this moderator so that some of the neutrons can escape, and put some material in the path of this cool neutron beam, the neutrons will undergo strong diffraction in a way that depends on the crystal structure in the material. If you have a cryogenic neutron moderator, rather than a room-temperature moderator, the neutrons have on average longer wavelengths and the diffraction effects are stronger. Reactor neutrons are produced continuously while the reactor is operating. However, if you can make it so that your neutrons are produced in brief pulses, and put a flight path of length $L$ between the pulsed neutron source and your experiment, then you develop a simple relationship between the time of the neutron pulse, the arrival time of the neutron at your experiment, and the neutron wavelength: $$\lambda = \frac hp = \frac h{mv} = \frac h{mL} t$$ As a grad student designing neutron flight paths, it became useful for me to memorize that the neutron has $h/m = 4.0 \text{ Å m/ms}$ . (It's actually 1% smaller than that.) That means, if your data acquisition clock starts when your pulse of neutrons is created, and your experiment is at the end of a flight path with $L=20\,\text m$ , the 1Å neutrons arrive at $\rm 5\,ms$ , the 2Å neutrons at $\rm 10\,ms$ , the 4Å neutrons at $\rm 20\,ms$ , and so on. In most countries the AC power from the electric grid provides a pretty good clock that's a few tens of milliseconds long, with which it's easy to synchronize your neutron pulses. So you can put a neutron detector at the end of your beamline, read off the neutron intensity as a function of time, and just cross off the "time" axis on your plot and write "wavelength" instead. It's a nice system. From a particle-physics standpoint, neutron beams are completely different from proton beams. Neutrons, unlike protons, can't be re-accelerated. Neutrons can (in practice) only be steered by interacting with material neutron guides, where protons can be steered using electromagnetic fields. And neutrons have a nasty habit of going around corners, and of inducing radioactivity ("activation") in mostly everything that they land on. A person who cut their teeth doing particle physics at a proton accelerator would be instantly right at home doing particle physics at an electron accelerator; that same person would have a lot of "facts" to un-learn during their first year on a pulsed-neutron experiment.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/456955', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/75621/']}
jdg_79941
stackexchange
llm_judgeable_groundtruth_similarity
1842537
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: In $\triangle ABC$ , prove: $$\frac{r_a}{bc} + \frac{r_b}{ca} + \frac{r_c}{ab} = \frac{1}{r} - \frac{1}{2R}$$ for circumradius $R$ , inradius $r$ , and exradii $r_a$ , $r_b$ , $r_c$ in the standard arrangement. It is known that $r_a = \sqrt{\dfrac{s\left(s-b\right)\left(s-c\right)}{s-a}}$ , where $s = \dfrac12\left(a+b+c\right)$ is the semiperimeter of $\triangle ABC$ . Similar formulas exist for $r_b$ , $r_c$ and $r$ . But how does $R$ connect with all of this? Now provide the response and nothing else.
We will use the $\sum_{cyc}$ notation for cyclic sums: $$\sum_{cyc}f(a,b,c) = f(a,b,c)+f(b,c,a)+f(c,a,b)$$ for any function $f$ . Also, let $\Delta$ be the area of triangle $ABC$ . We have: $$ \frac{r_a}{bc}=\frac{\Delta}{(s-a)bc}=\frac{\frac{1}{2}\sin(A)}{s-a}=\frac{a}{4R(s-a)}\tag{1}$$ hence we have to prove that: $$ 2+\sum_{cyc} \frac{a}{s-a} = \frac{4R}{r} \tag{2}$$ that is equivalent to: $$ 2r+\sum_{cyc}\frac{a}{\cot\left(\frac{A}{2}\right)} = 2R\tag{3}$$ or to: $$ 2r+\sum_{cyc}2R(1-\cos(A)) = 2R\tag{4}$$ that follows from Carnot's theorem .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1842537', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/296971/']}
jdg_79942
stackexchange
llm_judgeable_groundtruth_similarity
2823765
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: 2.$$\begin{cases}C_n=4C_{n-1}+6n-1\\C_0=2\\\end{cases} $$ $\begin{cases}C_n=D_n+dn+e\\D_n=\lambda D_{n-1}\end{cases}$ $D_n+dn+e=4C_{n-1}+6n-1$ But $C_{n-1}=D_{n-1}+d(n-1)+e$ So $D_n+dn+e=4(D_{n-1}+d(n-1)+e)+6n-1$ $D_n+dn+e=4D_{n-1}+4dn-4d+4e+6n-1$ But for $\lambda=4$ we get $4D_{n-1}+dn+e=4D_{n-1}+4dn-4d+4e+6n-1$ and $0=-dn-e+4dn-4d+4e+6n-1$ or $0=(3d+6)n+3e-4d-1$ So $d=-2,e=1.5$ $C_n=D_n+dn+e$ So $C_n=D_n-2n+1.5$ And $C_0=D_0+1.5$ So $2=D_0+1.5$ And $D_0=-0.5$ $D_n=4D_{n-1}$ So $C_n=D_n+dn+e=4^n-2n+1.5$ which is $O(4^n)$ Is it correct? Now provide the response and nothing else.
The "normal" definition goes like this: It is claimed that, at fixed point, for any given ball $B_\epsilon$ of radius $\epsilon$ in the image, there exists a ball $B_\delta$, in the preimage, of radius $\delta$ such that $Im (B_\delta) \subset B_\epsilon$. This is the implication $$(...) < \delta \implies (...) < \epsilon $$ Very informally, you could compare the statement, for continuous $f$, For any ball $B_\epsilon$ in the image, you can find a ball $B_\delta$ mapping into $B_\epsilon$ and For any ball $B_\epsilon$ in the image, its preimage contains a ball $B_\delta$ and The preimages of open sets are open. In topological spaces, the last one is often taken as a definition. Regarding your interpretation IF $U \subseteq Y$ is open THEN $f^{−1}(U)$ is open This is perfectly valid and translates as "IF you give me an $\epsilon$ THEN I can find you a corresponding $\delta$". Regarding the implication, let me explain in this way, to show what happens with that implication: Let $U \subset Y$ be open, then for this set you can have its preimage, $f^{-1}(U) \subset X$, which is the set that satisfies:$$x \in f^{-1}(U) \implies f(x) \in U $$ So now you can freely say: For any open $U \subset Y$, there is a set $f^{-1}(U) \subset X.$ If is just so happens, that $f^{-1}(U)$ is open for any open $U$, then we call $f$ continuous. Translating, this means that if it just so happens that for any given radius $\epsilon$, can find a corresponding $\delta$ such that $$ x\in B_\delta \implies f(x) \in B_\epsilon, $$ then $f$ is continuous. A few more details: You have be rather careful when you state exactly what you mean with mapping "nearby points to nearby points". Given a metric, we can always have balls as subsets of that space. The open sets are precisely those that, for each $x$, have some ball around them completely contained in the open set. This is true regardless of whether the open set is a union of open intervals, the whole space, a single interval, or any other open set. To say that $f$ maps "nearby points to nearby points" means to say that, if you fix a point $x_0$, and look at what happens to points nearby $x_0$, they will all be mapped to points close to $f(x_0)$. The exact meaning of this is that: for each fixed $x\in f^{-1}(U)$, for any ball $B_\epsilon$ around $f(x)$ (and one exists, and satisies $B_\epsilon \subset U$, by openness), there is a ball $B_\delta$ around the point $x$ that maps into $B_\epsilon$. Since $B_\epsilon \subset U$, we have $B_\delta \subset f^{-1}(U) $, which by definition makes the preimage open. It's a ball around an arbitrary point completely in $f^{-1}(U) $. Whatever open set you have, all of the points in there will be interior, so continuity (finding matching balls $B_\delta$ and $B_\epsilon$) works at each point at a time, so to speak. And now it almost rolls off the tongue:$$\forall x \ \forall \epsilon \ \exists \delta \ (...) $$ To me, it is somehow intuitively clear that if you want a statement about how some values of $f(x)$ behave, you would start with something about its target set. Maybe that's just me. You sort of start with the question "How close to $f(x_0)$ do you want the outputs of $f$ to be", which is a question about the target set.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2823765', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/300848/']}
jdg_79943
stackexchange
llm_judgeable_groundtruth_similarity
22252075
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am new to Node.js so this is probably a fundamental question and I am missing something obvious. In the code below, I am trying to set the sql_file name from foo but I keep getting an error on the file not existing because the variable is not working. If I hard code the file name in sql_util.js it works fine. So how do I pass a parameter or any object from one js file into the function of another? foo.js var misc = require('./sql_get');console.log(misc.sql_file("on.sql")); sql_util.js fs = require('fs');file = 'on.sql'function sql_file(cb) { var fileName = "./SQLs/" + sql_file; fs.readFile(fileName, function(err, buffer) { if (err) return cb(err); return cb(null, buffer.toString()); });}sql_file(function(err, sqlstatement) { if (err) throw err; console.log('sql statement is: ' + sqlstatement);});};module.exports.x = x;module.exports.sql_fil = sql_file; Now provide the response and nothing else.
Took me a few hours to figure it out. Posting here in case anyone anyone else has the same problem. The idea is that you have to register your activity as a broadcast receiver. The easiest way to do this is like so: //register your activity onResume()@Overridepublic void onResume() { super.onResume(); context.registerReceiver(mMessageReceiver, new IntentFilter("unique_name"));}//Must unregister onPause()@Overrideprotected void onPause() { super.onPause(); context.unregisterReceiver(mMessageReceiver);}//This is the handler that will manager to process the broadcast intentprivate BroadcastReceiver mMessageReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // Extract data included in the Intent String message = intent.getStringExtra("message"); //do other stuff here }}; The above code goes in the activity that you want to 'listen' for events. Now, how do we send data to this 'listener'? Go to your push notification handler(or from where you want to update your activity) and when you receive a notification call this function: // This function will create an intent. This intent must take as parameter the "unique_name" that you registered your activity withstatic void updateMyActivity(Context context, String message) { Intent intent = new Intent("unique_name"); //put whatever data you want to send, if any intent.putExtra("message", message); //send broadcast context.sendBroadcast(intent);} When you call the above function, your activity should receive it. Note : Your activity must be running/open to receive the broadcast intent Note2 : I switched to a library called 'otto'. It does actually the same thing but easier, 'broadcasts events' thoughout the app. Here's a link http://square.github.io/otto/
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/22252075', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3124121/']}
jdg_79944
stackexchange
llm_judgeable_groundtruth_similarity
9843884
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given options = { underscored: true}products = { foo: bar} I'd like to get products = { underscored: true foo: bar} Is it possible to push an object into another object in Javascript? Now provide the response and nothing else.
ES5 <script>function mix(source, target) { for(var key in source) { if (source.hasOwnProperty(key)) { target[key] = source[key]; } }} mix(options, products);</script> ES6 - this will mutate objectToMergeTo const combinedObject = Object.assign(objectToMergeTo, source1, source2) ES7 (syntax beauty with spread operator) -this version however creates a new instance, you can't add into an object with spread operator. const combined = { ...source1, ...source2 }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9843884', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/159856/']}
jdg_79945
stackexchange
llm_judgeable_groundtruth_similarity
516768
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 about using "this" with methods in Java? Is it optional or there are situations when one needs to use it obligatory? The only situation I have encountered is when in the class you invoke a method within a method. But it is optional. Here is a silly example just to show what I mean: public class Test { String s; private String hey() { return s; } public String getS(){ String sm = this.hey(); // here I could just write hey(); without this return sm; }} Now provide the response and nothing else.
Three obvious situations where you need it: Calling another constructor in the same class as the first part of your constructor Differentiating between a local variable and an instance variable (whether in the constructor or any other method) Passing a reference to the current object to another method Here's an example of all three: public class Test{ int x; public Test(int x) { this.x = x; } public Test() { this(10); } public void foo() { Helper.doSomethingWith(this); } public void setX(int x) { this.x = x; }} I believe there are also some weird situations using inner classes where you need super.this.x but they should be avoided as hugely obscure, IMO :) EDIT: I can't think of any examples why you'd want it for a straight this.foo() method call. EDIT: saua contributed this on the matter of obscure inner class examples: I think the obscure case is: OuterClass.this.foo() when accessing foo() of the outer class from the code in an Inner class that has a foo() method as well.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/516768', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/42155/']}
jdg_79946
stackexchange
llm_judgeable_groundtruth_similarity
9597
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to pipe grep output to rm , but it outputs useless stuff. Is any switch required for rm ? Or can rm can be provided a regexp directly? ls | grep '^\[Daruchini'| rm rm: missing operandTry `rm --help' for more information. Now provide the response and nothing else.
You need to use xargs to turn standard input into arguments for rm . $ ls | grep '^Dar' | xargs rm (Beware of special characters in filenames; with GNU grep, you might prefer $ ls | grep -Z '^Dar' | xargs -0 rm ) Also, while the shell doesn't use regexps, that's a simple pattern: $ rm Dar* (meanwhile, I think I need more sleep.)
{}
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/9597', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/5871/']}
jdg_79947
stackexchange
llm_judgeable_groundtruth_similarity
70565357
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 Python 3 application running on CentOS Linux 7.7 executing SSH commands against remote hosts. It works properly but today I encountered an odd error executing a command against a "new" remote server (server based on RHEL 6.10): encountered RSA key, expected OPENSSH key Executing the same command from the system shell (using the same private key of course) works perfectly fine. On the remote server I discovered in /var/log/secure that when SSH connection and commands are issued from the source server with Python (using Paramiko) sshd complains about unsupported public key algorithm: userauth_pubkey: unsupported public key algorithm: rsa-sha2-512 Note that target servers with higher RHEL/CentOS like 7.x don't encounter the issue. It seems like Paramiko picks/offers the wrong algorithm when negotiating with the remote server when on the contrary SSH shell performs the negotiation properly in the context of this "old" target server. How to get the Python program to work as expected? Python code import paramikoimport loggingssh_user = "my_user"ssh_keypath = "/path/to/.ssh/my_key.rsa"server = "server.tld"ssh_client = paramiko.SSHClient()ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(server,port=22,username=ssh_user, key_filename=ssh_keypath) # SSH commandcmd = "echo TEST : $(hostname)"stdin, stdout, stderr = ssh_client.exec_command(cmd, get_pty=True)exit_code = stdout.channel.recv_exit_status() cmd_raw_output = stdout.readlines()out = "".join(cmd_raw_output)out_msg = out.strip() # Ouput (logger code omitted)logger.debug(out_msg)if ssh_client is not None: ssh_client.close() Shell command equivalent ssh -i /path/to/.ssh/my_key.rsa [email protected] "echo TEST : $(hostname)" Paramiko logs (DEBUG) DEB [YYYYmmdd-HH:MM:30.475] thr=1 paramiko.transport: starting thread (client mode): 0xf6054ac8DEB [YYYYmmdd-HH:MM:30.476] thr=1 paramiko.transport: Local version/idstring: SSH-2.0-paramiko_2.9.1DEB [YYYYmmdd-HH:MM:30.490] thr=1 paramiko.transport: Remote version/idstring: SSH-2.0-OpenSSH_5.3INF [YYYYmmdd-HH:MM:30.490] thr=1 paramiko.transport: Connected (version 2.0, client OpenSSH_5.3)DEB [YYYYmmdd-HH:MM:30.498] thr=1 paramiko.transport: === Key exchange possibilities ===DEB [YYYYmmdd-HH:MM:30.498] thr=1 paramiko.transport: kex algos: diffie-hellman-group-exchange-sha256, diffie-hellman-group-exchange-sha1, diffie-hellman-group14-sha1, diffie-hellman-group1-sha1DEB [YYYYmmdd-HH:MM:30.498] thr=1 paramiko.transport: server key: ssh-rsa, ssh-dssDEB [YYYYmmdd-HH:MM:30.498] thr=1 paramiko.transport: client encrypt: aes128-ctr, aes192-ctr, aes256-ctr, arcfour256, arcfour128, aes128-cbc, 3des-cbc, blowfish-cbc, cast128-cbc, aes192-cbc, aes256-cbc, arcfour, [email protected] [YYYYmmdd-HH:MM:30.498] thr=1 paramiko.transport: server encrypt: aes128-ctr, aes192-ctr, aes256-ctr, arcfour256, arcfour128, aes128-cbc, 3des-cbc, blowfish-cbc, cast128-cbc, aes192-cbc, aes256-cbc, arcfour, [email protected] [YYYYmmdd-HH:MM:30.499] thr=1 paramiko.transport: client mac: hmac-md5, hmac-sha1, [email protected], hmac-sha2-256, hmac-sha2-512, hmac-ripemd160, [email protected], hmac-sha1-96, hmac-md5-96DEB [YYYYmmdd-HH:MM:30.499] thr=1 paramiko.transport: server mac: hmac-md5, hmac-sha1, [email protected], hmac-sha2-256, hmac-sha2-512, hmac-ripemd160, [email protected], hmac-sha1-96, hmac-md5-96DEB [YYYYmmdd-HH:MM:30.499] thr=1 paramiko.transport: client compress: none, [email protected] [YYYYmmdd-HH:MM:30.499] thr=1 paramiko.transport: server compress: none, [email protected] [YYYYmmdd-HH:MM:30.499] thr=1 paramiko.transport: client lang: <none>DEB [YYYYmmdd-HH:MM:30.499] thr=1 paramiko.transport: server lang: <none>.DEB [YYYYmmdd-HH:MM:30.499] thr=1 paramiko.transport: kex follows: FalseDEB [YYYYmmdd-HH:MM:30.500] thr=1 paramiko.transport: === Key exchange agreements ===DEB [YYYYmmdd-HH:MM:30.500] thr=1 paramiko.transport: Kex: diffie-hellman-group-exchange-sha256DEB [YYYYmmdd-HH:MM:30.500] thr=1 paramiko.transport: HostKey: ssh-rsaDEB [YYYYmmdd-HH:MM:30.500] thr=1 paramiko.transport: Cipher: aes128-ctrDEB [YYYYmmdd-HH:MM:30.500] thr=1 paramiko.transport: MAC: hmac-sha2-256DEB [YYYYmmdd-HH:MM:30.501] thr=1 paramiko.transport: Compression: noneDEB [YYYYmmdd-HH:MM:30.501] thr=1 paramiko.transport: === End of kex handshake ===DEB [YYYYmmdd-HH:MM:30.548] thr=1 paramiko.transport: Got server p (2048 bits)DEB [YYYYmmdd-HH:MM:30.666] thr=1 paramiko.transport: kex engine KexGexSHA256 specified hash_algo <built-in function openssl_sha256>DEB [YYYYmmdd-HH:MM:30.667] thr=1 paramiko.transport: Switch to new keys ...DEB [YYYYmmdd-HH:MM:30.669] thr=2 paramiko.transport: Adding ssh-rsa host key for server.tld: b'caea********************.'DEB [YYYYmmdd-HH:MM:30.674] thr=2 paramiko.transport: Trying discovered key b'b49c********************' in /path/to/.ssh/my_key.rsaDEB [YYYYmmdd-HH:MM:30.722] thr=1 paramiko.transport: userauth is OKDEB [YYYYmmdd-HH:MM:30.722] thr=1 paramiko.transport: Finalizing pubkey algorithm for key of type 'ssh-rsa'DEB [YYYYmmdd-HH:MM:30.722] thr=1 paramiko.transport: Our pubkey algorithm list: ['rsa-sha2-512', 'rsa-sha2-256', 'ssh-rsa']DEB [YYYYmmdd-HH:MM:30.723] thr=1 paramiko.transport: Server-side algorithm list: ['']DEB [YYYYmmdd-HH:MM:30.723] thr=1 paramiko.transport: Agreed upon 'rsa-sha2-512' pubkey algorithmINF [YYYYmmdd-HH:MM:30.735] thr=1 paramiko.transport: Authentication (publickey) failed.DEB [YYYYmmdd-HH:MM:30.739] thr=2 paramiko.transport: Trying SSH agent key b'9d37********************'DEB [YYYYmmdd-HH:MM:30.747] thr=1 paramiko.transport: userauth is OK.DEB [YYYYmmdd-HH:MM:30.748] thr=1 paramiko.transport: Finalizing pubkey algorithm for key of type 'ssh-rsa'DEB [YYYYmmdd-HH:MM:30.748] thr=1 paramiko.transport: Our pubkey algorithm list: ['rsa-sha2-512', 'rsa-sha2-256', 'ssh-rsa']DEB [YYYYmmdd-HH:MM:30.748] thr=1 paramiko.transport: Server-side algorithm list: ['']DEB [YYYYmmdd-HH:MM:30.748] thr=1 paramiko.transport: Agreed upon 'rsa-sha2-512' pubkey algorithmINF [YYYYmmdd-HH:MM:30.868] thr=1 paramiko.transport: Authentication (publickey) failed... Shell command logs OpenSSH_7.4p1, OpenSSL 1.0.2k-fips 26 Jan 2017debug1: Reading configuration data /etc/ssh/ssh_configdebug1: /etc/ssh/ssh_config line 58: Applying options for *debug2: resolving "server.tld" port 22debug2: ssh_connect_direct: needpriv 0debug1: Connecting to server.tld [server.tld] port 22.debug1: Connection established.debug1: permanently_set_uid: 0/0debug1: key_load_public: No such file or directorydebug1: identity file /path/to/.ssh/my_key.rsa type -1debug1: key_load_public: No such file or directorydebug1: identity file /path/to/.ssh/my_key.rsa-cert type -1debug1: Enabling compatibility mode for protocol 2.0debug1: Local version string SSH-2.0-OpenSSH_7.4debug1: Remote protocol version 2.0, remote software version OpenSSH_5.3debug1: match: OpenSSH_5.3 pat OpenSSH_5* compat 0x0c000000debug2: fd 3 setting O_NONBLOCKdebug1: Authenticating to server.tld:22 as 'my_user'debug3: hostkeys_foreach: reading file "/path/to/.ssh/known_hosts"debug3: record_hostkey: found key type RSA in file /path/to/.ssh/known_hosts:82debug3: load_hostkeys: loaded 1 keys from server.tlddebug3: order_hostkeyalgs: prefer hostkeyalgs: [email protected],rsa-sha2-512,rsa-sha2-256,ssh-rsadebug3: send packet: type 20debug1: SSH2_MSG_KEXINIT sentdebug3: receive packet: type 20debug1: SSH2_MSG_KEXINIT receiveddebug2: local client KEXINIT proposaldebug2: KEX algorithms: curve25519-sha256,[email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1,ext-info-cdebug2: host key algorithms: [email protected],rsa-sha2-512,rsa-sha2-256,ssh-rsa,[email protected],[email protected],[email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-ed25519,ssh-dssdebug2: ciphers ctos: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected],aes128-cbc,aes192-cbc,aes256-cbcdebug2: ciphers stoc: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected],aes128-cbc,aes192-cbc,aes256-cbcdebug2: MACs ctos: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1debug2: MACs stoc: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1debug2: compression ctos: none,[email protected],zlibdebug2: compression stoc: none,[email protected],zlibdebug2: languages ctos:debug2: languages stoc:debug2: first_kex_follows 0debug2: reserved 0debug2: peer server KEXINIT proposaldebug2: KEX algorithms: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1debug2: host key algorithms: ssh-rsa,ssh-dssdebug2: ciphers ctos: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]: ciphers stoc: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]: MACs ctos: hmac-md5,hmac-sha1,[email protected],hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96debug2: MACs stoc: hmac-md5,hmac-sha1,[email protected],hmac-sha2-256,hmac-sha2-512,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96debug2: compression ctos: none,[email protected]: compression stoc: none,[email protected]: languages ctos:debug2: languages stoc:debug2: first_kex_follows 0debug2: reserved 0debug1: kex: algorithm: diffie-hellman-group-exchange-sha256debug1: kex: host key algorithm: ssh-rsadebug1: kex: server->client cipher: aes128-ctr MAC: [email protected] compression: nonedebug1: kex: client->server cipher: aes128-ctr MAC: [email protected] compression: nonedebug1: kex: diffie-hellman-group-exchange-sha256 need=16 dh_need=16debug1: kex: diffie-hellman-group-exchange-sha256 need=16 dh_need=16debug3: send packet: type 34debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<3072<8192) sentdebug3: receive packet: type 31debug1: got SSH2_MSG_KEX_DH_GEX_GROUPdebug2: bits set: 1502/3072debug3: send packet: type 32debug1: SSH2_MSG_KEX_DH_GEX_INIT sentdebug3: receive packet: type 33debug1: got SSH2_MSG_KEX_DH_GEX_REPLYdebug1: Server host key: ssh-.:**************************************************debug3: hostkeys_foreach: reading file "/path/to/.ssh/known_hosts"debug3: record_hostkey: found key type RSA in file /path/to/.ssh/known_hosts:8..2debug3: load_hostkeys: loaded 1 keys from server.tlddebug1: Host 'server.tld' is known and matches the RSA host key.debug1: Found key in /path/to/.ssh/known_hosts:82debug2: bits set: 1562/3072debug3: send packet: type 21debug2: set_newkeys: mode 1debug1: rekey after 4294967296 blocksdebug1: SSH2_MSG_NEWKEYS sentdebug1: expecting SSH2_MSG_NEWKEYSdebug3: receive packet: type 21debug1: SSH2_MSG_NEWKEYS receiveddebug2: set_newkeys: mode 0debug1: rekey after 4294967296 blocksdebug2: key: <foo> (0x55bcf6d1d320), agentdebug2: key: /path/to/.ssh/my_key.rsa ((nil)), explicitdebug3: send packet: type 5debug3: receive packet: type 6debug2: service_accept: ssh-userauthdebug1: SSH2_MSG_SERVICE_ACCEPT receiveddebug3: send packet: type 50debug3: receive packet: type 51debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,passworddebug3: start over, passed a different list publickey,gssapi-keyex,gssapi-with-mic,passworddebug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,passworddebug3: authmethod_lookup gssapi-keyexdebug3: remaining preferred: gssapi-with-mic,publickey,keyboard-interactive,passworddebug3: authmethod_is_enabled gssapi-keyexdebug1: Next authentication method: gssapi-keyexdebug1: No valid Key exchange contextdebug2: we did not send a packet, disable methoddebug3: authmethod_lookup gssapi-with-micdebug3: remaining preferred: publickey,keyboard-interactive,passworddebug3: authmethod_is_enabled gssapi-with-micdebug1: Next authentication method: gssapi-with-micdebug1: Unspecified GSS failure. Minor code may provide more informationNo Kerberos credentials available (default cache: KEYRING:persistent:0)debug1: Unspecified GSS failure. Minor code may provide more informationNo Kerberos credentials available (default cache: KEYRING:persistent:0)debug2: we did not send a packet, disable methoddebug3: authmethod_lookup publickeydebug3: remaining preferred: keyboard-interactive,passworddebug3: authmethod_is_enabled publickeydebug1: Next authentication method: publickeydebug1: Offering RSA public key: <foo>debug3: send_pubkey_testdebug3: send packet: type 50debug2: we sent a publickey packet, wait for replydebug3: receive packet: type 51debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,passworddebug1: Trying private key: /path/to/.ssh/my_key.rsadebug3: sign_and_send_pubkey: RSA SHA256:**********************************debug3: send packet: type 50debug2: we sent a publickey packet, wait for replydebug3: receive packet: type 52debug1: Authentication succeeded (publickey).Authenticated to server.tld ([server.tld]:22).debug1: channel 0: new [client-session]debug3: ssh_session2_open: channel_new: 0debug2: channel 0: send opendebug3: send packet: type 90debug1: Requesting [email protected]: send packet: type 80debug1: Entering interactive session.debug1: pledge: networkdebug3: receive packet: type 91debug2: callback startdebug2: fd 3 setting TCP_NODELAYdebug3: ssh_packet_set_tos: set IP_TOS 0x08debug2: client_session2_setup: id 0debug1: Sending environment.debug3: Ignored env XDG_SESSION_IDdebug3: Ignored env HOSTNAMEdebug3: Ignored env SELINUX_ROLE_REQUESTEDdebug3: Ignored env TERMdebug3: Ignored env SHELLdebug3: Ignored env HISTSIZEdebug3: Ignored env SSH_CLIENTdebug3: Ignored env SELINUX_USE_CURRENT_RANGEdebug3: Ignored env SSH_TTYdebug3: Ignored env CDPATHdebug3: Ignored env USERdebug3: Ignored env LS_COLORSdebug3: Ignored env SSH_AUTH_SOCKdebug3: Ignored env MAILdebug3: Ignored env PATHdebug3: Ignored env PWDdebug1: Sending env LANG = xx_XX.UTF-8debug2: channel 0: request env confirm 0debug3: send packet: type 98debug3: Ignored env SELINUX_LEVEL_REQUESTEDdebug3: Ignored env HISTCONTROLdebug3: Ignored env SHLVLdebug3: Ignored env HOMEdebug3: Ignored env LOGNAMEdebug3: Ignored env SSH_CONNECTIONdebug3: Ignored env LESSOPENdebug3: Ignored env XDG_RUNTIME_DIRdebug3: Ignored env _debug1: Sending command: echo TEST : $(hostname)debug2: channel 0: request exec confirm 1debug3: send packet: type 98debug2: callback donedebug2: channel 0: open confirm rwindow 0 rmax 32768debug2: channel 0: rcvd adjust 2097152debug3: receive packet: type 99debug2: channel_input_status_confirm: type 99 id 0debug2: exec request accepted on channel 0TEST : server.tlddebug3: receive packet: type 96debug2: channel 0: rcvd eofdebug2: channel 0: output open -> draindebug2: channel 0: obuf emptydebug2: channel 0: close_writedebug2: channel 0: output drain -> closeddebug3: receive packet: type 98debug1: client_input_channel_req: channel 0 rtype exit-status reply 0debug3: receive packet: type 98debug1: client_input_channel_req: channel 0 rtype [email protected] reply 0debug2: channel 0: rcvd eowdebug2: channel 0: close_readdebug2: channel 0: input open -> closeddebug3: receive packet: type 97debug2: channel 0: rcvd closedebug3: channel 0: will not send data after closedebug2: channel 0: almost deaddebug2: channel 0: gc: notify userdebug2: channel 0: gc: user detacheddebug2: channel 0: send closedebug3: send packet: type 97debug2: channel 0: is deaddebug2: channel 0: garbage collectingdebug1: channel 0: free: client-session, nchannels 1debug3: channel 0: status: The following connections are open: #0 client-session (t4 r0 i3/0 o3/0 fd -1/-1 cc -1)debug3: send packet: type 1Transferred: sent 3264, received 2656 bytes, in 0.0 seconds.Bytes per second: sent 92349.8, received 75147.4debug1: Exit status 0. Now provide the response and nothing else.
Imo, it's a bug in Paramiko. It does not handle correctly absence of server-sig-algs extension on the server side. Try disabling rsa-sha2-* on Paramiko side altogether: ssh_client.connect( server, username=ssh_user, key_filename=ssh_keypath, disabled_algorithms=dict(pubkeys=["rsa-sha2-512", "rsa-sha2-256"])) (note that there's no need to specify port=22 , as that's the default) I've found related Paramiko issue: RSA key auth failing from paramiko 2.9.x client to dropbear server Though it refers to Paramiko 2.9.0 change log , which seems to imply that the behavior is deliberate: When the server does not send server-sig-algs , Paramiko will attempt the first algorithm in the above list. Clients connecting to legacy servers should thus use disabled_algorithms to turn off SHA2. Since 2.9.2 , Paramiko will say: DEB [20220113-14:46:13.882] thr=1 paramiko.transport: Server did not send a server-sig-algs list; defaulting to our first preferred algo ('rsa-sha2-512') DEB [20220113-14:46:13.882] thr=1 paramiko.transport: NOTE: you may use the 'disabled_algorithms' SSHClient/Transport init kwarg to disable that or other algorithms if your server does not support them! Obligatory warning: Do not use AutoAddPolicy – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server" . Your code for waiting for command to complete and reading its output is flawed too. See Wait to finish command executed with Python Paramiko . And for most purposes, the get_pty=True is not a good idea either.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/70565357', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8647786/']}
jdg_79948
stackexchange
llm_judgeable_groundtruth_similarity
31037882
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 asking this as a reminder to myself the next time I use CMake. It never sticks, and Google results aren't great. What's the syntax to set and use variables in CMake? Now provide the response and nothing else.
When writing CMake scripts there is a lot you need to know about the syntax and how to use variables in CMake. The Syntax Strings using set() : set(MyString "Some Text") set(MyStringWithVar "Some other Text: ${MyString}") set(MyStringWithQuot "Some quote: \"${MyStringWithVar}\"") Or with string() : string(APPEND MyStringWithContent " ${MyString}") Lists using set() : set(MyList "a" "b" "c") set(MyList ${MyList} "d") Or better with list() : list(APPEND MyList "a" "b" "c") list(APPEND MyList "d") Lists of File Names: set(MySourcesList "File.name" "File with Space.name") list(APPEND MySourcesList "File.name" "File with Space.name") add_excutable(MyExeTarget ${MySourcesList}) The Documentation CMake/Language Syntax CMake: Variables Lists Strings CMake: Useful Variables CMake set() Command CMake string() Command CMake list() Command Cmake: Generator Expressions The Scope or "What value does my variable have?" First there are the "Normal Variables" and things you need to know about their scope: Normal variables are visible to the CMakeLists.txt they are set in and everything called from there ( add_subdirectory() , include() , macro() and function() ). The add_subdirectory() and function() commands are special, because they open-up their own scope. Meaning variables set(...) there are only visible there and they make a copy of all normal variables of the scope level they are called from (called parent scope). So if you are in a sub-directory or a function you can modify an already existing variable in the parent scope with set(... PARENT_SCOPE) You can make use of this e.g. in functions by passing the variable name as a function parameter. An example would be function(xyz _resultVar) is setting set(${_resultVar} 1 PARENT_SCOPE) On the other hand everything you set in include() or macro() scripts will modify variables directly in the scope of where they are called from. Second there is the "Global Variables Cache". Things you need to know about the Cache: If no normal variable with the given name is defined in the current scope, CMake will look for a matching Cache entry. Cache values are stored in the CMakeCache.txt file in your binary output directory. The values in the Cache can be modified in CMake's GUI application before they are generated. Therefore they - in comparison to normal variables - have a type and a docstring . I normally don't use the GUI so I use set(... CACHE INTERNAL "") to set my global and persistant values. Please note that the INTERNAL cache variable type does imply FORCE In a CMake script you can only change existing Cache entries if you use the set(... CACHE ... FORCE) syntax. This behavior is made use of e.g. by CMake itself, because it normally does not force Cache entries itself and therefore you can pre-define it with another value. You can use the command line to set entries in the Cache with the syntax cmake -D var:type=value , just cmake -D var=value or with cmake -C CMakeInitialCache.cmake . You can unset entries in the Cache with unset(... CACHE) . The Cache is global and you can set them virtually anywhere in your CMake scripts. But I would recommend you think twice about where to use Cache variables (they are global and they are persistant). I normally prefer the set_property(GLOBAL PROPERTY ...) and set_property(GLOBAL APPEND PROPERTY ...) syntax to define my own non-persistant global variables. Variable Pitfalls and "How to debug variable changes?" To avoid pitfalls you should know the following about variables: Local variables do hide cached variables if both have the same name The find_... commands - if successful - do write their results as cached variables "so that no call will search again" Lists in CMake are just strings with semicolons delimiters and therefore the quotation-marks are important set(MyVar a b c) is "a;b;c" and set(MyVar "a b c") is "a b c" The recommendation is that you always use quotation marks with the one exception when you want to give a list as list Generally prefer the list() command for handling lists The whole scope issue described above. Especially it's recommended to use functions() instead of macros() because you don't want your local variables to show up in the parent scope. A lot of variables used by CMake are set with the project() and enable_language() calls. So it could get important to set some variables before those commands are used. Environment variables may differ from where CMake generated the make environment and when the the make files are put to use. A change in an environment variable does not re-trigger the generation process. Especially a generated IDE environment may differ from your command line, so it's recommended to transfer your environment variables into something that is cached. Sometimes only debugging variables helps. The following may help you: Simply use old printf debugging style by using the message() command. There also some ready to use modules shipped with CMake itself: CMakePrintHelpers.cmake , CMakePrintSystemInformation.cmake Look into CMakeCache.txt file in your binary output directory. This file is even generated if the actual generation of your make environment fails. Use variable_watch() to see where your variables are read/written/removed. Look into the directory properties CACHE_VARIABLES and VARIABLES Call cmake --trace ... to see the CMake's complete parsing process. That's sort of the last reserve, because it generates a lot of output. Special Syntax Environment Variables You can can read $ENV{...} and write set(ENV{...} ...) environment variables Generator Expressions Generator expressions $<...> are only evaluated when CMake's generator writes the make environment (it comparison to normal variables that are replaced "in-place" by the parser) Very handy e.g. in compiler/linker command lines and in multi-configuration environments References With ${${...}} you can give variable names in a variable and reference its content. Often used when giving a variable name as function/macro parameter. Constant Values (see if() command) With if(MyVariable) you can directly check a variable for true/false (no need here for the enclosing ${...} ) True if the constant is 1 , ON , YES , TRUE , Y , or a non-zero number. False if the constant is 0 , OFF , NO , FALSE , N , IGNORE , NOTFOUND , the empty string, or ends in the suffix -NOTFOUND . This syntax is often use for something like if(MSVC) , but it can be confusing for someone who does not know this syntax shortcut. Recursive substitutions You can construct variable names using variables. After CMake has substituted the variables, it will check again if the result is a variable itself. This is very powerful feature used in CMake itself e.g. as sort of a template set(CMAKE_${lang}_COMPILER ...) But be aware this can give you a headache in if() commands. Here is an example where CMAKE_CXX_COMPILER_ID is "MSVC" and MSVC is "1" : if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC") is true, because it evaluates to if("1" STREQUAL "1") if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC") is false, because it evaluates to if("MSVC" STREQUAL "1") So the best solution here would be - see above - to directly check for if(MSVC) The good news is that this was fixed in CMake 3.1 with the introduction of policy CMP0054 . I would recommend to always set cmake_policy(SET CMP0054 NEW) to "only interpret if() arguments as variables or keywords when unquoted." The option() command Mainly just cached strings that only can be ON or OFF and they allow some special handling like e.g. dependencies But be aware , don't mistake the option with the set command. The value given to option is really only the "initial value" (transferred once to the cache during the first configuration step) and is afterwards meant to be changed by the user through CMake's GUI . References How is CMake used? cmake, lost in the concept of global variables (and PARENT_SCOPE or add_subdirectory alternatives) Looping over a string list How to store CMake build settings CMake compare to empty string with STREQUAL failed When should I quote CMake variables?
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/31037882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2125392/']}
jdg_79949
stackexchange
llm_judgeable_groundtruth_similarity
20581731
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 perform validation with the jQuery Validation plugin for input type="file" . I want to restrict file formats to doc,pdf,rtf, and docx . Here is my code: $("#contact-form").validate({ onfocusout: function(e) { this.element(e); }, rules:{ resume:{ required:true, extension: "docx|rtf|doc|pdf" } }, resume:{ required:"input type is required", extension:"select valied input file format" } }); Now provide the response and nothing else.
You never explained the problem you're having with your code: $("#contact-form").validate({ onfocusout: function(e) { this.element(e); }, rules:{ resume:{ required:true, extension: "docx|rtf|doc|pdf" } }, resume:{ required:"input type is required", extension:"select valied input file format" }}); However, you're declaring messages without using the messages option. This is an error that would likely break the plugin, or at the least, your custom error messages would be ignored. Your code should look like this... $("#contact-form").validate({ onfocusout: function(e) { // this option is not needed this.element(e); // this is the default behavior }, rules:{ resume:{ required:true, extension: "docx|rtf|doc|pdf" } }, messages: { // <-- you must declare messages inside of "messages" option resume:{ required:"input type is required", extension:"select valid input file format" } }}); Working DEMO: http://jsfiddle.net/ZqxR2/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20581731', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2717065/']}
jdg_79950
stackexchange
llm_judgeable_groundtruth_similarity
2591546
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I need help to prove the following inequality with a nested radical. $$\sqrt{1!\sqrt{2!\sqrt{3!\sqrt{\cdots\sqrt{n!}}}}} <2$$ I have tired to use the Stirling approximation, but I got stuck with the nested radical.Does anyone have any idea? Now provide the response and nothing else.
Following up on Peter's comment below the OP, we have $$\begin{align}\log\left(\sqrt{1!\sqrt{2!\sqrt{\ldots\sqrt{n!}}}}\right)&={1\over2}\log(1!)+{1\over2^2}\log(2!)+\cdots+{1\over2^n}\log(n!)\\&=\left({1\over2}+{1\over4}+\cdots+{1\over2^n}\right)\log1+\left({1\over4}+{1\over8}+\cdots+{1\over2^n}\right)\log2+\cdots+{1\over2^n}\log n\\&\to\log1+{1\over2}\log2+{1\over4}\log3+{1\over8}\log4+\cdots\\&\gt{1\over2}\log2+{1\over4}\log2+{1\over8}\log2+\cdots=\log2\end{align}$$ So the requested inequality is not true.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2591546', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_79951
stackexchange
llm_judgeable_groundtruth_similarity
36352215
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 try to get remote (client) IP addres: var ip = httpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress But it works only for local requests (it will return ::1 value) When I load page from remote machine the value is null. I investigated there is no IHttpConnectionFeature in the Features collection in this case. Why? And how to get remote ip address correctly? Now provide the response and nothing else.
I know that this post is old but I came here looking for the same question and finnaly I did this: On project.json add dependency: "Microsoft.AspNetCore.HttpOverrides": "1.0.0" On Startup.cs, in the Configure method add: app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); And, of course: using Microsoft.AspNetCore.HttpOverrides; Then, I got the ip like this: Request.HttpContext.Connection.RemoteIpAddress In my case, when debugging in VS I got always IpV6 localhost, but when deployed on an IIS I got always the remote IP. Some useful links: How do I get client IP address in ASP.NET CORE? and RemoteIpAddress is always null The ::1 may be because: Connections termination at IIS, which then forwards to Kestrel, the v.next web server, so connections to the web server are indeed from localhost. ( https://stackoverflow.com/a/35442401/5326387 )
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36352215', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2631076/']}
jdg_79952
stackexchange
llm_judgeable_groundtruth_similarity
605504
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 looking to measure the signal width of electronic signals (device under test, DUT). The problem is that these signals have a quite short pulse width which would require me to use a GHz oscilloscope which I don't have (and can not afford at the moment). I might be able to borrow a GHz oscilloscope to have a look at the signals, but want to make sure the signals are somewhat in the range of a few nanoseconds. I found the following image (see below), where from the spectrum of the signals the pulse width (PW) can be read out. Would it be possible to use a (cheap USB) spectrum analyser (like the ldtz 35MHz to 4.4 GHz) to get a approximate feeling of the pulse width (with a accuaracy of around +/- 50%)? The DUT produces signals of around 1-3 ns (I need to adjust the signals width) with the outut voltage of the pulses are 0 V (low) to 5 V (low). The DUT is provided by a 10 MHz Trigger source, the trigger source could be exchanged for something faster, till up to around 60 MHz. I created the DUT, all coponents are placed on a PCB and had a look with a 100 MHzoscilloscope at one example circuit which produces a 3.2 ns wide signal, it did look good... Or would there be some simple alternatives to create a circuit to convert the pulse width of the nanosecond pulses to an analog voltage? Like with comparators? I'm very grateful for any input, thank you very much to everyone have a look at my question. Now provide the response and nothing else.
Given that your signal has constant, known amplitude, there's actually a much simpler way: Filter it with an RC low-pass that has a time constant greater than the maximum expected signal width. As long as the time constant is large enough, you can assume that the capacitor's voltage is negligible compared to the 5V pulse, meaning that the pulse will inject a constant current into the capacitor. The charge, and therefore the capacitor's voltage, is then directly proportional to the pulse width. The voltage on the capacitor will decay slowly enough for you to measure it with a 100MHz oscilloscope. With 500 Ohms and 100pF, you'll get 100mV per nanosecond of pulse width (right after the pulse). Tau is 50ns, so if you measure the voltage 50ns after the pulse is over, you'll be at 63mV/ns due to the exponential decay. That's well within the capabilities of a 100MHz scope. Make sure to use a non-inductive resistor, ideally an SMD thick film part.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/605504', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/269208/']}
jdg_79953
stackexchange
llm_judgeable_groundtruth_similarity
3195693
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $f:\mathbb{R} \to \mathbb{R} $ be a function such that $f(x+r) =f(x) +f(r) $ , $\forall x\in \mathbb{R} $ and $\forall r \in \mathbb{Q} $ . I know that if $f$ were continuous, then we would have $f(x+y) =f(x) +f(y) $ , $\forall x, y \in \mathbb{R} $ using the fact that the rational numbers are dense in the reals. Could the same thing be established without $f$ 's continuity? I think it could not, but I can't find a counterexample. Now provide the response and nothing else.
No, continuity of $f$ is necessary here. Consider the following function: $$f(x)=\begin{cases}0 & \text{if $x$ is rational,}\\1 & \text{if $x$ is irrational.}\end{cases}$$ Clearly for any rational $r$ , we have $x$ rational iff $x+r$ is rational, so $f(x+r)=f(x)=f(x)+0=f(x+r)$ , but $f(\sqrt{2}+\sqrt{2})=1\neq 2=f(\sqrt{2})+f(\sqrt{2})$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3195693', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/628203/']}
jdg_79954
stackexchange
llm_judgeable_groundtruth_similarity
107516
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: Consider simply aqueous solutions of $\ce{H2S}$ and $\ce{HCl}$ . It is pretty much known that $\ce{HCl}$ is stronger than $\ce{H2S}$ in water. The reason behind that first is the electronegativity of $\ce{Cl}$ is higher than $\ce{S}$ , so, in a polar medium, it becomes easier for the $\ce{H-Cl}$ bond to break than the other one. More ever , $\ce{Cl^-}$ ion being smaller in size is extensively hydrated in water than $\ce{HS^-}$ ion, which also favours in the increased acidity of $\ce{HCl}$ . But now consider acidity of $\ce{H2S}$ and $\ce{H2O}$ in water. If we apply the similar reasons as before, we will ultimately conclude water is a stronger acid than $\ce{H2S}$ . But actually it’s the reverse. The only fact supporting the actual phenomenon is the weaker bond energy of $\ce{H-S}$ , but if we apply this to the earlier case of $\ce{HCl}$ and $\ce{H2S}$ , it will again contradict the actual phenomenon. Why is this the case ? If my reasoning is incorrect, what is the actual reasoning that will support the correct acidity in both the cases ? Now provide the response and nothing else.
You are right that electronegativity is an important consideration but another factor that is also very important is size of the atom. Although there is a decrease in electronegativity from $\ce {O}$ to $\ce {S}$ , the size of the atom which the charge is mainly centred on is now larger. This allows the charge to be distributed over a larger volume of space, decreasing inter-electronic repulsions, providing greater stabilisation of the negative charge. However, the greater size decreases charge density, decreasing the strength of ion-dipole interactions between the anion and the surrounding water molecules. Thus, the extent of solvation decreases for the larger anion. Electronegativity is defined as the ability of the atom to attract a bonding pair of electrons. It merely serves as a proxy for the ability of the atom to stabilise negative charge. It should not be viewed as the most important factor that influences the atom's ability to stabilise negative charge. Also, mentioned in your answer, the strength of the bond formed with the larger atom with more diffuse orbitals decreases. A bond that is more easily cleaved would facilitate bond cleavage and thus, favour the acid with the larger atom bonded to $\ce {H}$ as the stronger acid. Consolidating the above discussion, there are really two factors on each side of the table below. Perhaps, the distribution of charge increases very significantly and the bond energy also decreases significantly while the decrease in extent of solvation and the electronegativity exhibit a relatively less significant effect. It would be great if someone is able to quantitatively show this... \begin{array}{|c|c|c|c|} \hline\text{Favouring acids with larger atom} & \text{Favouring acids with smaller atom} \\ \hline\ce{Distribution of charge} & \ce{Extent of solvation}\\ \hline\ce{Bond strength} & \ce{Electronegativity}\\ \hline\end{array}
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/107516', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/58497/']}
jdg_79955
stackexchange
llm_judgeable_groundtruth_similarity
38960763
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: From GNU's website: -ftrapv This option generates traps for signed overflow on addition, subtraction, multiplication operations. -fwrapv This option instructs the compiler to assume that signed arithmetic overflow of addition, subtraction and multiplication wraps around using twos-complement representation. This flag enables some optimizations and disables others. https://gcc.gnu.org/onlinedocs/gcc-4.4.2/gcc/Code-Gen-Options.html I have two questions: Which of these options is better for performance? What what does it mean when the -ftrapv definition says it generates "traps?" Does this mean exceptions? (I'm guessing no, but it's worth asking.) Now provide the response and nothing else.
The whole point of both of these options is to give the optimiser less leeway than it normally has. Therefore, unless you encounter a bug in the optimiser, the fastest should be to use neither, where the optimiser assumes your code doesn't have any overflows and doesn't emit code to handle overflows. What what does it mean when the -ftrapv definition says it generates "traps?" Does this mean exceptions? It doesn't mean a C++ exception. It's target-dependent, but assuming x86, it means the GCC runtime libraries cause SIGABRT to be raised that will normally abort your program. On other platforms, it might use special CPU instructions that cause a hardware exception. It's mainly useful for debugging purposes and perhaps in a few cases for safety, where the risk of continuing after overflow is greater than the risk of the program suddenly terminating.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38960763', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3124459/']}
jdg_79956
stackexchange
llm_judgeable_groundtruth_similarity
3672234
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 asked this during an interview and apparently it's an easy question but it wasn't and still isn't obvious to me. Given a string, count all the words in it. Doesn't matter if they are repeated. Just the total count like in a text files word count. Words are anything separated by a space and punctuation doesn't matter, as long as it's part of a word. For example: A very, very, very, very, very big dog ate my homework!!!! ==> 11 words My "algorithm" just goes through looking for spaces and incrementing a counter until I hit a null. Since i didn't get the job and was asked to leave after that I guess My solution wasn't good? Anyone have a more clever solution? Am I missing something? Now provide the response and nothing else.
Assuming words are white space separated: unsigned int countWordsInString(std::string const& str){ std::stringstream stream(str); return std::distance(std::istream_iterator<std::string>(stream), std::istream_iterator<std::string>());} Note: There may be more than one space between words. Also this does not catch other white space characters like tab new line or carriage return. So counting spaces is not enough. The stream input operator >> when used to read a string from a stream. Reads one white space separated word. So they were probably looking for you to use this to identify words. std::stringstream stream(str);std::string oneWord;stream >> oneWord; // Reads one space separated word. When can use this to count words in a string. std::stringstream stream(str);std::string oneWord;unsigned int count = 0;while(stream >> oneWord) { ++count;}// count now has the number of words in the string. Getting complicated: Streams can be treated just like any other container and there are iterators to loop through them std::istream_iterator. When you use the ++ operator on an istream_iterator it just read the next value from the stream using the operator >>. In this case we are reading std::string so it reads a space separated word. std::stringstream stream(str);std::string oneWord;unsigned int count = 0;std::istream_iterator loop = std::istream_iterator<std::string>(stream);std::istream_iterator end = std::istream_iterator<std::string>();for(;loop != end; ++count, ++loop) { *loop; } Using std::distance just wraps all the above in a tidy package as it find the distance between two iterators by doing ++ on the first until we reach the second. To avoid copying the string we can be sneaky: unsigned int countWordsInString(std::string const& str){ std::stringstream stream; // sneaky way to use the string as the buffer to avoid copy. stream.rdbuf()->pubsetbuf (str.c_str(), str.length() ); return std::distance(std::istream_iterator<std::string>(stream), std::istream_iterator<std::string>());} Note: we still copy each word out of the original into a temporary. But the cost of that is minimal.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3672234', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/750/']}
jdg_79957
stackexchange
llm_judgeable_groundtruth_similarity
3604569
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 looking up the keyword volatile and what it's for, and the answer I got was pretty much: It's used to prevent the compiler from optimizing away code. There were some examples, such as when polling memory-mapped hardware: without volatile the polling loop would be removed as the compiler might recognize that the condition value is never changed. But since there only were one example or maybe two, it got me thinking: Are there other situations where we need to use volatile in terms of avoiding unwanted optimization? Are condition variables the only place where volatile is needed? I imagine that optimization is compiler-specific and therefore is not specified in the C++ specification. Does that mean we have to go by gut feeling, saying Hm, I suspect my compiler will do away with this if I don't declare that variable as volatile or are there any clear rules to go by? Now provide the response and nothing else.
Basically, volatile announces that a value might change behind your program's back. That prevents compilers from caching the value (in a CPU register) and from optimizing away accesses to that value when they seem unnecessary from the POV of your program. What should trigger usage of volatile is when a value changes despite the fact that your program hasn't written to it, and when no other memory barriers (like mutexes as used for multi-threaded programs) are present.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3604569', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/426092/']}
jdg_79958
stackexchange
llm_judgeable_groundtruth_similarity
14221524
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 question concerns the implementation of shared_ptr 's assignment operator template in GCC 4.7.2, which I suspect to contain a bug. PREMISE 1: C++11 STANDARD Here is the signature of the assignment operator template I am talking about: template<class Y> shared_ptr& operator=(const shared_ptr<Y>& r) noexcept; From the C++11 Standard (20.7.2.2.3): "Equivalent to shared_ptr(r).swap(*this) ." In other words, the assignment operator template is defined in terms of constructor template. The signature of the constructor template is as follows: template<class Y> shared_ptr(const shared_ptr<Y>& r) noexcept; From the C++11 Standard (20.7.2.2.1): "Requires: The [...] constructor shall not participate in the overload resolution unless Y* is implicitly convertible to T*." PREMISE 2: GCC 4.7.2's IMPLEMENTATION: Now GCC 4.7.2's implementation of the constructor template seems correct to me ( std::__shared_ptr is a base class of std::shared_ptr ): template<typename _Tp1, typename = typename std::enable_if<std::is_convertible<_Tp1*, _Tp*>::value>::type>__shared_ptr(__shared_ptr<_Tp1, _Lp>&& __r) noexcept : _M_ptr(__r._M_ptr), _M_refcount(){ _M_refcount._M_swap(__r._M_refcount); __r._M_ptr = 0;} However, GCC 4.7.2's implementation of the assignment operator template is the following: template<typename _Tp1>__shared_ptr& operator=(const __shared_ptr<_Tp1, _Lp>& __r) noexcept{ _M_ptr = __r._M_ptr; _M_refcount = __r._M_refcount; // __shared_count::op= doesn't throw return *this;} What strikes me is that this operation is not defined in terms of the constructor template, nor of swap() . In particular, the plain assignment _M_ptr = __r._M_ptr does not yield the same result as when the types _Tp1* and _Tp* are explicitly checked for convertibility through std::is_convertible ( which can be specialized ). PREMISE 3: VC10 IMPLEMENTATION I noticed that VC10 does have a more conforming implementation in this respect, which I consider to be correct and behaves as I expected in my test cases (while GCC's doesn't): template<class _Ty2>_Myt& operator=(const shared_ptr<_Ty2>& _Right){ // assign shared ownership of resource owned by _Right shared_ptr(_Right).swap(*this); return (*this);} QUESTION : Is there indeed a bug in GCC 4.7.2's implementation of shared_ptr ? I could not find any bug report for this issue. POST SCRIPTUM : If you wish to ask me what my test cases are, why do I care about this seemingly unimportant detail and why do I seem to imply that I need to specialize std::is_convertible , please do so in chat. It is a long story and there's no way of summing it up without being misunderstood (with all of its unpleasant consequences). Thank you in advance. Now provide the response and nothing else.
What strikes me is that this operation is not defined in terms of the constructor template, nor of swap() . It doesn't need to be, it only needs to behave as if it was defined in those terms. In particular, the plain assignment _M_ptr = __r._M_ptr does not yield the same result as when the types _Tp1* and _Tp* are explicitly checked for convertibility through std::is_convertible ( which can be specialized ). I disagree: [meta.type.synop]/1 The behavior of a program that adds specializations for any of the class templates defined in this subclause is undefined unless otherwise specified. So you can't change the meaning of is_convertible<Y*, T*> and if Y* is convertible to T* then the assignment will work and since both assignments (of the pointer and the refcount object) are noexcept the end result is equivalent to the swap. If the pointers are not convertible then the assignment will fail to compile, but so would shared_ptr(r).swap(*this) , so it's still equivalent. If I'm wrong then please file a bug report and I'll fix it, but I don't think a conforming program can detect the difference between the libstdc++ implementation and the requirements of the standard. That said, I wouldn't have any objections to changing it to be implemented in terms of swap . The current implementation came straight from the shared_ptr in Boost 1.32 , I don't know if Boost still does it the same way or if it uses shared_ptr(r).swap(*this) now. [Full disclosure, I'm a libstdc++ maintainer and mostly responsible for the shared_ptr code, which was originally kindly donated by the authors of boost::shared_ptr and then mutiliated by me since then.]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14221524', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1932150/']}
jdg_79959
stackexchange
llm_judgeable_groundtruth_similarity
12226624
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 learning Haskell I am wondering when an IO action will be performed. In several places I found descriptions like this: "What’s special about I/O actions is that if they fall into the main function, they are performed." But in the following example, 'greet' never returns and therefore nothing should be printed. import Control.Monadmain = greetgreet = forever $ putStrLn "Hello World!" Or maybe I should ask: what does it mean to "fall into the main function"? Now provide the response and nothing else.
First of all, main is not a function. It is indeed just a regular value and its type is IO () . The type can be read as: An action that, when performed, produces a value of type () . Now the run-time system plays the role of an interpreter that performs the actions that you have described. Let's take your program as example: main = forever (putStrLn "Hello world!") Notice that I have performed a transformation. That one is valid, since Haskell is a referentially transparent language. The run-time system resolves the forever and finds this: main = putStrLn "Hello world!" >> MORE1 It doesn't yet know what MORE1 is, but it now knows that it has a composition with one known action, which is executed. After executing it, it resolves the second action, MORE1 and finds: MORE1 = putStrLn "Hello world!" >> MORE2 Again it executes the first action in that composition and then keeps on resolving. Of course this is a high level description. The actual code is not an interpreter. But this is a way to picture how a Haskell program gets executed. Let's take another example: main = forever (getLine >>= putStrLn) The RTS sees this: main = forever MORE1<< resolving forever >>MORE1 = getLine >>= MORE2<< executing getLine >>MORE2 result = putStrLn result >> MORE1<< executing putStrLn result (where 'result' is the line read) and starting over >> When understanding this you understand how an IO String is not "a string with side effects" but rather the description of an action that would produce a string. You also understand why laziness is crucial for Haskell's I/O system to work.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12226624', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1640285/']}
jdg_79960
stackexchange
llm_judgeable_groundtruth_similarity
6034728
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Seems like this has to be documented somewhere but I'm not finding is anywhere. Perhaps my Google-fu is weakening. Now provide the response and nothing else.
You realize that this will depend on what you call .NET Framework classes . You probably might want to specify which assemblies you are looking for. Armed with this information you can load those assemblies and use reflection to list all public types that implement IDisposable in a given assembly. Let's take the System assembly as example: class Program{ static void Main() { var types = Assembly .Load("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089") .GetTypes() .Where(t => typeof(IDisposable).IsAssignableFrom(t)) .OrderBy(t => t.Name); foreach (var type in types) { Console.WriteLine(type); } }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6034728', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/62478/']}
jdg_79961
stackexchange
llm_judgeable_groundtruth_similarity
244469
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: To start with, I apologize if this is a painfully obvious/trivial issue, I'm still learning the ins and outs of linux/unix. I work with a few servers that require access via ssh and private key to log into. So, the command is something like this: ssh -i /path/to/key.pem [email protected] I've created a bash script that let's me just use my own call, access , and just has a basic switch statement for the arguments that follow to control which server I log into. For example, access server1 would issue the appropriate ssh command to log into server1. The Problem The ssh call just hangs up and I'm left with an empty terminal that won't accept SIGINT ( Ctrl + C ) and I must quit the terminal and open it up again to even use it. As far as I can tell, this might be a permissions thing for the private key. Its permissions are currently 600 . Changing it to 644 gives me an error that the permissions are too open and exits the ssh attempt. Any advice? Now provide the response and nothing else.
There is ssh_config , made for this, where you can specify your hosts aliases and keys and store it without creating such hara-kiri as bash scripts to do so. It is basically stored in your ~/.ssh/config in this format: Host host1 Hostname 000.000.000.000 User user IdentityFile /path/to/key.pem and then you can simply call ssh host1 to get to 000.000.000.000 If you really want to be effective and have even shorter shortcuts, bash alias is more suitable than the bash scripts. alias access="ssh -i /path/to/key.pem [email protected]" If you really want to use bash script, you need to force ssh to allocate you TTY on remote server using -tt option: ssh -tti /path/to/key.pem [email protected] For more tips, you can browse through the manual page for ssh and ssh_config .
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/244469', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/144178/']}
jdg_79962
stackexchange
llm_judgeable_groundtruth_similarity
17734420
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I was reading http://msdn.microsoft.com/en-US/library/vstudio/hh191443.aspx .Example code: async Task<int> AccessTheWebAsync(){ // You need to add a reference to System.Net.Http to declare client. HttpClient client = new HttpClient(); // GetStringAsync returns a Task<string>. That means that when you await the // task you'll get a string (urlContents). Task<string> getStringTask = client.GetStringAsync("http://msdn.microsoft.com"); // You can do work here that doesn't rely on the string from GetStringAsync. DoIndependentWork(); // The await operator suspends AccessTheWebAsync. // - AccessTheWebAsync can't continue until getStringTask is complete. // - Meanwhile, control returns to the caller of AccessTheWebAsync. // - Control resumes here when getStringTask is complete. // - The await operator then retrieves the string result from getStringTask. string urlContents = await getStringTask; // The return statement specifies an integer result. // Any methods that are awaiting AccessTheWebAsync retrieve the length value. return urlContents.Length;} The page also says: The async and await keywords don't cause additional threads to be created. Async methods don't require multithreading because an async method doesn't run on its own thread Does this "no additional thread is created" applies within scope of the method marked as async? I would imagine in order for both GetStringAsync and AccessTheWebAsync to be running at the same time (otherwise GetStringAsync will never finish as AccessTheWebAsync has control now), eventually GetStringAsync has to run on a different thread from AccessTheWebAsync's thread. To me, writing async method is only useful at not adding more thread when the method it awaits is also async (which already use extra thread to do its own thing in parallel) Is my understanding correct? Now provide the response and nothing else.
This is the key to the power of async . GetStringAsync and other naturally-asynchronous operations do not require a thread . GetStringAsync just sends out the HTTP request and registers a callback to run when the server replies. There's no need for a thread just to wait for the server to respond. In reality, the thread pool is used just a tiny bit. In the example above, the callback registered by GetStringAsync will execute on a thread pool thread, but all it does is notify AccessTheWebAsync that it can continue executing. I have an async intro blog post you may find helpful.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17734420', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/156144/']}
jdg_79963
stackexchange
llm_judgeable_groundtruth_similarity
5691979
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 strange problem. I set a JProgressBar: private JProgressBar progressBar;public void foo(){ ... progressBar = new JProgressBar(0, 100); progressBar.setValue(0); progressBar.setStringPainted(true); ... contentPane.add(progressBar); ...} But it changes only when I put setValue function it in some places in code, not everywhere: public void foo2(){ progressBar.setValue(100); //working if(...) { System.out.println("These instructions are executing"); //working progressBar.setValue(0); //not working } } So, what am I doing wrong? Why the second instruction doesn't work? Now provide the response and nothing else.
The value of the progress bar is really updated. But it isn't simply on the screen yet. Often, we use progress bars in loops. But, while you are in the loop, which you probably invoked by clicking a button it isn't painted. Why? Because you invoked it by clicking a button. When you click a button, all the code you've made for that button is being executed by the AWTEventThread . This is the same thread that keep track of all the Swing components, and checks wether they have to be repainted. That is the thread that makes your JFrame come alive. When you hover a button and the color changes a bit, it's done by the AWTEventThread . So, while you are working in the loop, the AWTEventThread can't update the screen anymore. This means there are two solutions: (Recommend) You should create a separate thread which executes the loop. This means the AWTEventThread can update the screen if necessary (when you call bar.setValue(...); ) public void yourButtonClickMethod(){ Runnable runner = new Runnable() { public void run() { //Your original code with the loop here. } }; Thread t = new Thread(runner, "Code Executer"); t.start();} Manually repaint the progress bar. I did it always with bar.repaint(); but I'm wondering if it will work. I though it was that method. If that doesn't work, try: bar.update(bar.getGraphics()); .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5691979', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/711880/']}
jdg_79964
stackexchange
llm_judgeable_groundtruth_similarity
45875334
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 code below lays out a chart in which I'd need to achieve for the chart to be expanded in both vertical (height) and horizontal (width) direction. The suggested method (e.g. https://docs.flutter.io/flutter/widgets/Row-class.html ) is to use Expanded in Row or Column . The chart widget I am trying to expand extends CustomPaint , with no children, everything is painted using a CustomPainter on canvas, in the CustomPainter.paint(canvas, size) . This code return new Scaffold( appBar: new AppBar( title: new Text(widget.title), ), body: new Center( child: new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new Text( 'vvvvvvvv:', ), new RaisedButton( color: Colors.green, onPressed: _chartStateChanger, ), new Text( 'vvvvvvvv:', ), new Expanded( // Expanded in Column, no expansion vertically child: new Row( children: [ new Text('>>>'), new Expanded(// Expanded in Row, expands horizontally child: new Chart( // extends CustomPaint // size: chartLogicalSize, painter: new ChartPainter( // extends CustomPainter chartData: _chartData, chartOptions: _chartOptions, ), ), ), new Text('<<<'), ], ), // row ), new Text('^^^^^^:'), new RaisedButton( color: Colors.green, onPressed: _chartStateChanger, ), ], ), ),); result looks like this: (code of ChartPainter is not shown for brevity) Inside the ChartPainter.paint(canvas, size) there is a print() printing the size. print(" ### Size: paint(): passed size = ${size}"); The result from the paint->print above is: I/flutter ( 4187): ### Size: paint(): passed size = Size(340.0, 0.0) The print along with the image shows, that the width expansion on the row level was passed to the CustomPainter.print(canvas, size) (width = 340.0), but the height expansion on the column did not get passed to the custom painter print (height = 0.0). Although the result shows that the row did get it's expanded height, if was not passed inside the row to the CustomPainter - 0 height was received. What do I need to change to achieve the height expansion as well? Thanks Now provide the response and nothing else.
Here is a reduced test case for the issue you are seeing. The solution is to give your Row a crossAxisAlignment of CrossAxisAlignment.stretch . Otherwise it will try to determine the intrinsic height of your CustomPaint which is zero because it doesn't have a child. import 'package:flutter/material.dart';// from https://stackoverflow.com/questions/45875334/how-to-achieve-expansion-of-a-widget-in-both-vertical-height-and-horizontal-wclass MyCustomPainter extends CustomPainter { @override void paint(Canvas canvas, Size size) { // NOT using crossAxisAlignment: CrossAxisAlignment.stretch => width = 222.0, height=0.0 // using crossAxisAlignment: CrossAxisAlignment.stretch => width = 222.0, height=560.0 print("width = ${size.width}, height=${size.height}"); canvas.drawRect(Offset.zero & size, new Paint()..color = Colors.blue); } @override bool shouldRepaint(MyCustomPainter other) => false;}void main() { runApp(new MaterialApp( home: new Scaffold( body: new Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new Text('Above Paint'), // Expanded - because we are in Column, expand the // contained row's height new Expanded( child: new Row( // The crossAxisAlignment is needed to give content height > 0 // - we are in a Row, so crossAxis is Column, so this enforces // to "stretch height". crossAxisAlignment: CrossAxisAlignment.stretch, children: <Widget>[ new Text('Left of Paint'), // Expanded - because we are in Row, expand the // contained Painter's width new Expanded( child: new CustomPaint( painter: new MyCustomPainter(), ), ), new Text('Right of Paint'), ], ), ), new Text('Below Paint'), ], ) ), ));}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45875334', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2767348/']}
jdg_79965
stackexchange
llm_judgeable_groundtruth_similarity
56900407
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Swift has a Result type that is declared like this enum Result<Success, Failure: Error> { case success(Success) case failure(Failure)} Which can be used like this: enum FooError: Error { case fizzReason case barReason case bazReason}func returnResult() -> Result<String, FooError> { // ... Just imagine this method returns an error}switch returnResult() {case .success(let string): print(s)case .failure(.fizzReason): // do somethingcase .failure(.barReason): // do somethingcase .failure(.bazReason): // do something} Does Kotlin have a similar Data Type which can be used in the same manner? Now provide the response and nothing else.
I don't know whether Kotlin has something like that but here is an implementation that should do the same: sealed class Result<out Success, out Failure>data class Success<out Success>(val value: Success) : Result<Success, Nothing>()data class Failure<out Failure>(val reason: Failure) : Result<Nothing, Failure>() Actual example: fun echoString(string : String) : Result<String, Exception> { return if (string.isEmpty()) { Failure(Exception("Error")) } else { Success(string) }}fun main(args : Array<String>) { when(val result = echoString("string")) { is Success -> println(result.value) is Failure -> println(result.reason) }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/56900407', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5928180/']}
jdg_79966
stackexchange
llm_judgeable_groundtruth_similarity
80802
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is it true that if $A$ is discrete as a subspace of $X$, and $X \;$ is compact, then $A$ is finite? If this doesn't hold, then does it hold for $X\;$ manifold? Now provide the response and nothing else.
It is not true in general. Let $X = \{0\}\cup\{2^{-n}:n\in\mathbb{N}\}$ with the topology inherited from $\mathbb{R}$; then $X$ is compact, and $X\setminus \{0\}$ is an infinite discrete subset of $X$. Of course every closed discrete subset of a compact space is finite, so infinite discrete subsets won’t be closed, but in general they will exist. For instance, the space $X$ just described can be embedded in any infinite compact metric space.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/80802', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/3416/']}
jdg_79967
stackexchange
llm_judgeable_groundtruth_similarity
26619566
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 save a file before closing my JavaFX application. This is how I'm setting up the handler in Main::start : primaryStage.setOnCloseRequest(event -> { System.out.println("Stage is closing"); // Save file}); And the controller calling Stage::close when a button is pressed: @FXMLpublic void exitApplication(ActionEvent event) { ((Stage)rootPane.getScene().getWindow()).close();} If I close the window clicking the red X on the window border (the normal way) then I get the output message " Stage is closing ", which is the desired behavior. However, when calling Controller::exitApplication the application closes without invoking the handler (there's no output). How can I make the controller use the handler I've added to primaryStage ? Now provide the response and nothing else.
If you have a look at the life-cycle of the Application class: The JavaFX runtime does the following, in order, whenever an application is launched: Constructs an instance of the specified Application class Calls the init() method Calls the start(javafx.stage.Stage) method Waits for the application to finish, which happens when either of the following occur: the application calls Platform.exit() the last window has been closed and the implicitExit attribute on Platform is true Calls the stop() method This means you can call Platform.exit() on your controller: @FXMLpublic void exitApplication(ActionEvent event) { Platform.exit();} as long as you override the stop() method on the main class to save the file. @Overridepublic void stop(){ System.out.println("Stage is closing"); // Save file} As you can see, by using stop() you don't need to listen to close requests to save the file anymore (though you can do it if you want to prevent window closing).
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/26619566', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4181593/']}
jdg_79968
stackexchange
llm_judgeable_groundtruth_similarity
43418812
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 a way to check whether a string contains Japanese or Chinese text. Currently I'm using this: string.match(/[\u3400-\u9FBF]/); but it does not work with this for example: ディアボリックラヴァーズ or バッテリー . Could you help me with that? Thanks Now provide the response and nothing else.
The ranges of Unicode characters which are routinely used for Chinese and Japanese text are: U+3040 - U+30FF: hiragana and katakana (Japanese only) U+3400 - U+4DBF: CJK unified ideographs extension A (Chinese, Japanese, and Korean) U+4E00 - U+9FFF: CJK unified ideographs (Chinese, Japanese, and Korean) U+F900 - U+FAFF: CJK compatibility ideographs (Chinese, Japanese, and Korean) U+FF66 - U+FF9F: half-width katakana (Japanese only) As a regular expression, this would be expressed as: /[\u3040-\u30ff\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff\uff66-\uff9f]/ This does not include every character which will appear in Chinese and Japanese text, but any significant piece of typical Chinese or Japanese text will be mostly made up of characters from these ranges. Note that this regular expression will also match on Korean text that contains hanja . This is an unavoidable result of Han unification .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43418812', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1535655/']}
jdg_79969
stackexchange
llm_judgeable_groundtruth_similarity
50236403
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to create jsons from the data in the table.Table looks like that: |code |+------+|D5ABX0||MKT536||WAEX44| I am using FOR JSON PATH which is nice: SELECT [code]FROM featureFOR JSON PATH but the return value of this query are three concatenated jsons in one row: |JSON_F52E2B61-18A1-11d1-B105-00805F49916B |+----------------------------------------------------------+1 |[{"code":"D5ABX0"},{"code":"MKT536"},{"code":"WAEX44"}]| I need to have each row to be a separate json, like that: |JSON_return |+---------------------+1 |{"code":"D5ABX0"} |2 |{"code":"MKT536"} |3 |{"code":"WAEX44"} | I was trying to use splitting function (CROSS APPLY) which needs to have a separator as a parameter but this is not a robust solution as the json could be more expanded or branched and this could separate not the whole json but the json inside the json: ;WITH split AS (SELECT [json] = (SELECT code FROM feature FOR JSON PATH))SELECT T.StringElementFROM split SCROSS APPLY dbo.fnSplitDelimitedList([json], '},{') T The output is: |StringElement |+---------------------+1 |[{"code":"D5ABX0" |2 |"code":"MKT536" |3 |"code":"WAEX44"}] | Is there a way to force sqlserver to create one json per row? Now provide the response and nothing else.
You'll need to use as subquery to achieve this; FOR JSON will create a JSON string for the entire returned dataset. This should get you what you're after: CREATE TABLE #Sample (code varchar(6));INSERT INTO #SampleVALUES ('D5ABX0'), ('MKT536'), ('WAEX44');SELECT (SELECT Code FROM #Sample sq WHERE sq.code = S.code FOR JSON PATH)FROM #Sample S;DROP TABLE #Sample;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50236403', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6786387/']}
jdg_79970
stackexchange
llm_judgeable_groundtruth_similarity
17498210
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I saw this char szPrivateKey[] definition on a source when I was reading so I went to check it out what it was, strangely this makes a sound when the program is run. Is there an easter egg in here or something? (compiled using visual studio 2003/ windows) int _tmain(int argc, _TCHAR* argv[]){ const unsigned char szPrivateKey[] = { 0x30 ,0x82 ,0x04 ,0xBB ,0x02 ,0x01 ,0x00 ,0x30 ,0x0D ,0x06 ,0x09 ,0x2A ,0x86 ,0x48 ,0x86 ,0xF7 , 0x0D ,0x01 ,0x01 ,0x01 ,0x05 ,0x00 ,0x04 ,0x82 ,0x04 ,0xA5 ,0x30 ,0x82 ,0x04 ,0xA1 ,0x02 ,0x01 , 0x00 ,0x02 ,0x82 ,0x01 ,0x01 ,0x00 ,0x87 ,0x1F ,0xEC ,0xFD ,0xAF ,0xD2 ,0x2F ,0xAA ,0x4E ,0xC2 , 0xAD ,0x5A ,0x4C ,0x3A ,0x7A ,0x81 ,0x9E ,0xBA ,0x28 ,0x6A ,0x84 ,0xE9 ,0xB7 ,0xF9 ,0x36 ,0x87 , 0x56 ,0x16 ,0xC5 ,0xA4 ,0x1D ,0x11 ,0x67 ,0x12 ,0x87 ,0x81 ,0xF5 ,0xFA ,0xF6 ,0x01 ,0xE7 ,0x55 , 0x83 ,0x4A ,0xAC ,0x40 ,0x4D ,0x2C ,0x90 ,0x62 ,0x77 ,0xFC ,0x73 ,0xF9 ,0x5E ,0x7F ,0x67 ,0x8C , 0xA7 ,0x94 ,0x32 ,0x28 ,0xDD ,0xEF ,0x91 ,0xE5 ,0x94 ,0xD6 ,0x5C ,0xB5 ,0x63 ,0xC4 ,0x76 ,0x2D , 0xFF ,0x03 ,0x75 ,0x55 ,0x85 ,0x60 ,0x56 ,0x44 ,0x37 ,0x18 ,0x08 ,0xE7 ,0x0A ,0x90 ,0x74 ,0xA0 , 0x9E ,0x82 ,0x4F ,0x56 ,0x4C ,0xD9 ,0xE5 ,0x73 ,0x88 ,0x9E ,0x0F ,0xD2 ,0x0C ,0x9E ,0xF1 ,0x90 , 0x65 ,0xEF ,0xA4 ,0x23 ,0x99 ,0xCC ,0xE8 ,0x16 ,0xF7 ,0x96 ,0x54 ,0xDA ,0xF0 ,0x45 ,0x66 ,0x48 , 0xFE ,0xE6 ,0x89 ,0xA9 ,0xFC ,0x57 ,0xA5 ,0xD0 ,0xEC ,0x48 ,0x61 ,0xC7 ,0x7B ,0x8E ,0xC9 ,0x26 , 0x39 ,0xB3 ,0x8D ,0x64 ,0x89 ,0xAB ,0x4E ,0xF5 ,0xCD ,0x5A ,0x72 ,0xC5 ,0xEE ,0x2F ,0x73 ,0x34 , 0x9E ,0x0F ,0xA4 ,0x2E ,0x54 ,0x6D ,0x09 ,0x3B ,0x14 ,0x37 ,0x6C ,0x82 ,0x75 ,0x75 ,0xE0 ,0x80 , 0x5D ,0xB9 ,0xA8 ,0xFC ,0x5F ,0xE6 ,0x8F ,0x9D ,0x23 ,0x1C ,0x4B ,0xDA ,0xC1 ,0xB2 ,0x52 ,0x83 , 0xEA ,0xF6 ,0xE9 ,0x30 ,0x47 ,0x22 ,0x8C ,0x7E ,0x74 ,0x98 ,0x82 ,0x05 ,0x0B ,0x39 ,0xBD ,0x47 , 0x38 ,0x6B ,0xAE ,0x5F ,0xD4 ,0x21 ,0x0F ,0xE1 ,0xBA ,0x86 ,0x50 ,0x01 ,0x40 ,0x22 ,0x90 ,0xE0 , 0xE4 ,0xC4 ,0x11 ,0x50 ,0xA6 ,0x02 ,0x2F ,0x6C ,0x66 ,0xFC ,0xBE ,0x4B ,0x29 ,0xB0 ,0x0D ,0xE1 , 0x65 ,0x87 ,0xFE ,0x8B ,0x88 ,0x59 ,0x8D ,0x22 ,0xFC ,0x67 ,0xE2 ,0xE3 ,0x96 ,0x99 ,0xE5 ,0xAB , 0x2F ,0xA4 ,0x15 ,0x22 ,0x37 ,0x57 ,0x02 ,0x01 ,0x11 ,0x02 ,0x82 ,0x01 ,0x00 ,0x0B ,0xEC ,0x3A , 0x8E ,0xDA ,0xCE ,0xC7 ,0xF8 ,0x70 ,0x5C ,0x78 ,0xB5 ,0x24 ,0xD7 ,0xFB ,0xC0 ,0x24 ,0x97 ,0xF4 , 0x81 ,0xDE ,0x8D ,0x17 ,0xC3 ,0x2A ,0x75 ,0x5A ,0x6B ,0x6B ,0xCA ,0xB7 ,0x45 ,0x4C ,0xDB ,0xFC , 0xE5 ,0xD1 ,0xF0 ,0x7F ,0x1E ,0x49 ,0x1E ,0x22 ,0x2C ,0x3C ,0x60 ,0x06 ,0xCF ,0x39 ,0xEA ,0x92 , 0x1D ,0xCD ,0xFF ,0x6A ,0x38 ,0x6B ,0x04 ,0xE1 ,0x9C ,0x22 ,0x8B ,0x22 ,0xA4 ,0x32 ,0x85 ,0x32 , 0xC7 ,0x9E ,0xC4 ,0xB5 ,0xFA ,0xBF ,0x22 ,0x2D ,0x16 ,0xE4 ,0xB4 ,0xB8 ,0xF1 ,0xE9 ,0x7E ,0x7D , 0x54 ,0xF1 ,0xBA ,0x08 ,0x76 ,0x28 ,0x68 ,0x86 ,0x74 ,0xE8 ,0xE1 ,0xF7 ,0xB8 ,0xDF ,0x8A ,0x31 , 0xB3 ,0x97 ,0xFB ,0xF2 ,0x0E ,0x06 ,0x41 ,0x72 ,0x67 ,0xF7 ,0xE5 ,0x06 ,0x0A ,0x8C ,0xF2 ,0xF7 , 0xBA ,0x70 ,0xE6 ,0x24 ,0x42 ,0x5B ,0xD9 ,0x43 ,0xAA ,0xEE ,0x07 ,0x78 ,0x25 ,0xB9 ,0x18 ,0xBA , 0x11 ,0x92 ,0xA8 ,0x0C ,0xE8 ,0x89 ,0xD9 ,0x3C ,0xC7 ,0x4E ,0xF8 ,0x16 ,0x0B ,0x6C ,0xA1 ,0x2E , 0x39 ,0x1C ,0x8B ,0xED ,0xD9 ,0x11 ,0xE7 ,0xED ,0x2A ,0x1A ,0x31 ,0x25 ,0x25 ,0x8D ,0xD5 ,0x3A , 0x9B ,0x3C ,0x29 ,0x9E ,0xB0 ,0x51 ,0x98 ,0x6F ,0x25 ,0x8D ,0xBC ,0x9A ,0x55 ,0x96 ,0x51 ,0x15 , 0x1F ,0x1C ,0x91 ,0x5C ,0x25 ,0x55 ,0xD3 ,0x24 ,0xDA ,0xB5 ,0xD0 ,0xFA ,0xAA ,0x1C ,0x60 ,0x62 , 0x0A ,0x2D ,0xA9 ,0x83 ,0x78 ,0xDD ,0xDF ,0x5D ,0x71 ,0x13 ,0xF1 ,0x22 ,0x15 ,0x13 ,0x6C ,0x04 , 0x6C ,0x9A ,0xE4 ,0x4A ,0xB9 ,0x4C ,0xAF ,0xC7 ,0xD6 ,0xF6 ,0x11 ,0x6C ,0x4A ,0x9C ,0x5B ,0x65 , 0x78 ,0x6E ,0xA3 ,0x0A ,0xFF ,0xFB ,0xDA ,0x41 ,0xA6 ,0x15 ,0x6B ,0x86 ,0xDE ,0x77 ,0xFF ,0xC2 , 0x13 ,0x50 ,0xD8 ,0x91 ,0x3E ,0xD2 ,0xF0 ,0xB1 ,0xC3 ,0x43 ,0x51 ,0x0B ,0xCD ,0x02 ,0x81 ,0x81 , 0x00 ,0xB6 ,0x40 ,0x45 ,0x5C ,0xB8 ,0x4D ,0x50 ,0x48 ,0xB7 ,0x0D ,0xA0 ,0x26 ,0x03 ,0xE3 ,0xFA , 0x3C ,0x2F ,0x04 ,0x9E ,0x72 ,0x1F ,0x1D ,0x30 ,0xEC ,0xEA ,0xF4 ,0xCE ,0x62 ,0xE6 ,0xE0 ,0xE7 , 0x3D ,0x3D ,0x03 ,0x68 ,0x3A ,0x90 ,0xE0 ,0xE3 ,0xB0 ,0x29 ,0x15 ,0x26 ,0x69 ,0xDE ,0xBB ,0x6E , 0x1A ,0xC2 ,0x5F ,0x5D ,0xB7 ,0x2B ,0x27 ,0x61 ,0x49 ,0x98 ,0x94 ,0x27 ,0x40 ,0x05 ,0x67 ,0xF3 , 0xC1 ,0x77 ,0x5B ,0x12 ,0x6D ,0x8D ,0x75 ,0xFA ,0x13 ,0x4D ,0x26 ,0x14 ,0x29 ,0x06 ,0x43 ,0xF8 , 0x3D ,0xB9 ,0x9F ,0x10 ,0x5E ,0xF9 ,0x30 ,0x79 ,0xF9 ,0x1B ,0x7D ,0x6A ,0x66 ,0x9F ,0xAA ,0x88 , 0x9F ,0x5E ,0x72 ,0xD4 ,0x3E ,0xE0 ,0xC0 ,0x04 ,0xC2 ,0xB2 ,0xD2 ,0xDF ,0x50 ,0xAB ,0x80 ,0xB9 , 0x5B ,0xF8 ,0x23 ,0x7D ,0x36 ,0xBD ,0x6F ,0xB2 ,0xFC ,0xF3 ,0x1F ,0x14 ,0xB9 ,0xC7 ,0xE9 ,0xAA , 0x25 ,0x02 ,0x81 ,0x81 ,0x00 ,0xBD ,0xCD ,0xBF ,0x79 ,0xD6 ,0x09 ,0x98 ,0xFA ,0xA2 ,0x7A ,0x93 , 0x65 ,0x5F ,0xDA ,0x40 ,0x42 ,0xFB ,0x79 ,0x23 ,0x0B ,0xBA ,0xCC ,0x35 ,0xA6 ,0x67 ,0xFB ,0x4F , 0xCF ,0x94 ,0x75 ,0xC8 ,0x30 ,0xDA ,0x1C ,0x69 ,0x1D ,0x87 ,0x1F ,0x35 ,0xF7 ,0x70 ,0x00 ,0xF6 , 0x50 ,0xD9 ,0x3C ,0xC7 ,0x57 ,0x25 ,0xA6 ,0xD6 ,0x04 ,0x87 ,0x99 ,0x4C ,0x16 ,0xED ,0x41 ,0x77 , 0x5D ,0x81 ,0xDD ,0x3A ,0x83 ,0xD3 ,0x89 ,0xB5 ,0xB7 ,0x99 ,0xB8 ,0x94 ,0x77 ,0x48 ,0x3D ,0xAB , 0xEB ,0xC6 ,0x19 ,0xAE ,0xF4 ,0x7A ,0x25 ,0x22 ,0xAD ,0xD0 ,0xB5 ,0x77 ,0x4A ,0xBA ,0xF0 ,0xA1 , 0x83 ,0xE2 ,0x35 ,0xFC ,0xBF ,0xE4 ,0xED ,0xBF ,0x68 ,0xF7 ,0xA8 ,0xA8 ,0x42 ,0xDF ,0x64 ,0xF3 , 0x87 ,0xB5 ,0x9D ,0x81 ,0x24 ,0x45 ,0x02 ,0x3D ,0x00 ,0xE6 ,0x88 ,0x20 ,0x2A ,0x46 ,0x8E ,0xE6 , 0xEF ,0xFC ,0xF7 ,0x5C ,0xCB ,0x02 ,0x81 ,0x81 ,0x00 ,0xAB ,0x87 ,0xC8 ,0xCF ,0xBC ,0x85 ,0x00 , 0x44 ,0x70 ,0x0C ,0xD2 ,0xF6 ,0x9A ,0x3F ,0xFA ,0x92 ,0xFF ,0x13 ,0x67 ,0xF2 ,0xF0 ,0x1B ,0x79 , 0x57 ,0x73 ,0xB9 ,0x3A ,0xB7 ,0x6F ,0xE2 ,0xBB ,0x84 ,0xEE ,0x21 ,0x53 ,0x09 ,0xF1 ,0xC4 ,0x9A , 0x0F ,0x35 ,0xB9 ,0x8D ,0x90 ,0xD1 ,0xA1 ,0x58 ,0x91 ,0xA7 ,0xE1 ,0x49 ,0x24 ,0xDD ,0x52 ,0x3D , 0x72 ,0x71 ,0x7C ,0x61 ,0x2D ,0x32 ,0x43 ,0xB8 ,0x3D ,0x9D ,0x82 ,0xE4 ,0x2A ,0xDF ,0x7E ,0x18 , 0x8A ,0xA2 ,0xF6 ,0xA9 ,0x90 ,0x05 ,0xE5 ,0x9E ,0x58 ,0x36 ,0x3B ,0x5A ,0xB3 ,0xBD ,0x5A ,0xCD , 0x26 ,0xB0 ,0x76 ,0x09 ,0xC9 ,0xFF ,0xAF ,0x8F ,0xA5 ,0x0D ,0x99 ,0x40 ,0x3B ,0x2D ,0xE1 ,0xE6 , 0x5C ,0xE4 ,0x8A ,0x3B ,0x97 ,0x38 ,0x00 ,0xAE ,0x74 ,0xAD ,0x4E ,0x93 ,0xF7 ,0x48 ,0xE1 ,0x99 , 0x66 ,0x8A ,0x77 ,0x9B ,0x09 ,0x34 ,0x9F ,0xAF ,0x31 ,0x02 ,0x81 ,0x80 ,0x6F ,0xA6 ,0x34 ,0x65 , 0xC9 ,0x32 ,0xD2 ,0x75 ,0x50 ,0x84 ,0x56 ,0xB4 ,0x1A ,0x44 ,0x25 ,0xCD ,0x0C ,0x65 ,0x5F ,0xE8 , 0xC8 ,0x3B ,0xE3 ,0x52 ,0xD3 ,0xC1 ,0x01 ,0xC5 ,0x66 ,0x63 ,0x66 ,0xB3 ,0x53 ,0x1F ,0xC5 ,0x5C , 0xA9 ,0xD6 ,0x1F ,0xBE ,0xBA ,0x5A ,0xEB ,0x3E ,0x9D ,0xE7 ,0x84 ,0x51 ,0x61 ,0x71 ,0x32 ,0x99 , 0x40 ,0xB4 ,0x87 ,0x1C ,0x8B ,0x8F ,0xEB ,0xDC ,0xA6 ,0xBE ,0x5E ,0xA7 ,0xE5 ,0xD8 ,0x89 ,0x02 , 0x96 ,0xA8 ,0xCF ,0xCD ,0xB2 ,0x06 ,0x28 ,0xE5 ,0x0B ,0x1E ,0x2A ,0xAD ,0xED ,0x7F ,0x41 ,0x93 , 0x6B ,0xB6 ,0x09 ,0xEF ,0xB9 ,0x42 ,0x40 ,0xE4 ,0x2A ,0xB6 ,0x58 ,0x70 ,0xE1 ,0x04 ,0x52 ,0x79 , 0xFB ,0x17 ,0xEA ,0x81 ,0xB0 ,0x95 ,0xBC ,0x6D ,0xF2 ,0x5C ,0xA6 ,0x51 ,0x92 ,0x01 ,0x51 ,0x0F , 0x96 ,0xAA ,0x6D ,0x46 ,0x0B ,0x63 ,0x1E ,0x6F ,0x0D ,0x46 ,0x36 ,0x95 ,0x02 ,0x81 ,0x80 ,0x41 , 0x3E ,0xA8 ,0x3B ,0x77 ,0xDC ,0xD7 ,0xAB ,0x2D ,0xD8 ,0x82 ,0x96 ,0x1C ,0x1B ,0x3B ,0xC6 ,0x85 , 0x92 ,0x88 ,0xAC ,0xC8 ,0xAC ,0x9F ,0x18 ,0x74 ,0x9D ,0x45 ,0xB4 ,0x7B ,0x13 ,0xAB ,0x78 ,0x8D , 0x8B ,0xB5 ,0x9E ,0x9E ,0xD2 ,0xD7 ,0xF2 ,0x84 ,0x34 ,0xFB ,0x08 ,0xB2 ,0x23 ,0xC7 ,0x0B ,0xF0 , 0xA9 ,0xCA ,0x17 ,0x1A ,0xA2 ,0x6D ,0x63 ,0xD3 ,0x90 ,0xEF ,0xD1 ,0x62 ,0xE6 ,0x46 ,0x25 ,0x6D , 0x6D ,0x23 ,0x3B ,0xB0 ,0x65 ,0xEA ,0xE2 ,0x22 ,0x24 ,0xC9 ,0x09 ,0x1B ,0x0D ,0x42 ,0x9D ,0x77 , 0xE1 ,0x63 ,0xB2 ,0x03 ,0x0D ,0x4A ,0xA2 ,0xFD ,0x2E ,0x2D ,0xCD ,0x4B ,0x9E ,0x63 ,0x91 ,0x0F , 0x42 ,0xC2 ,0x01 ,0x24 ,0x68 ,0x4C ,0xB5 ,0xA8 ,0x35 ,0xE3 ,0x31 ,0xE8 ,0x86 ,0x32 ,0xB1 ,0xA9 , 0x4F ,0xBE ,0x23 ,0x3A ,0x3C ,0x0A ,0x5D ,0x26 ,0xBE ,0xA7 ,0x5D ,0xC0 ,0x60 ,0x42 ,0x1D ,}; for( int i =0; i<sizeof(szPrivateKey); i++ ) { cout << szPrivateKey[i] << endl; } return 0;} Now provide the response and nothing else.
Because there is an 0x07 (in the line starting with 0xBA) in the szPrivateKey - 0x07, or CTRL-G, on most systems, will be a BEL character, so it rings the bell on an old teletype. Modern computers, and even 30 year old terminals, don't have mechanical bells (nor do typewriters, if you can find one these days), so they use a beep instead. In C and C++ you can make a BEL character in a string with "\a" (and it will work OK also on systems that aren't using ASCII, where it will generate whatever corresponding character is in a non-ASCII system). By the way, this is not an "easter egg", it's the consequence of printing something that isn't really "text", so shouldn't be displayed with cout . You can get the same with type myfile.dat or something like that (assuming myfile.dat is a binary file and has a 0x07 byte in it).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17498210', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1513286/']}
jdg_79971
stackexchange
llm_judgeable_groundtruth_similarity
36961650
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 doesn't show any of the fields as filled in nor does it try to fill them in. Do you know what other solutions I could use? Right now I am doing public static void main(String[] args){ WebDriver driver = new FirefoxDriver(); String user = "kek"; String pass = "trekek"; String url = "http://www."+ user + ":" + pass + "@xyz.org/auth.html"; System.out.println(url); driver.get(url);} Now provide the response and nothing else.
There are a few things to check when linking a library and and then subsequently trying to load it. In Linux for example, all the symbols only need to be available at the final load stage (loading the executable), with node this will be when you run node and load the native addon. To force the node addon build to fail if there are missing symbols you must pass -z defs as a linker option in node-gyp. So you would add the following in your binding.gyp to the "link_settings" element or where appropriate: "ldflags": [ "-Wl,-z,defs" ] Please look at a node-gyp tutorial (something like this ) if you don't know how to edit building and linking. Note : It appears that node defers symbol loading of a lot of its internals as well, so unfortunately you are going to get a whole lot of undefined symbols for v8 stuff as well. This is probably unavoidable as node loads these symbols dynamically. You will have to inspect the output and pipe it to a pager or grep to find opencv missing symbols. The names will not be mangled at this stage. When you are done remove those flags. If you get opencv undefined errors here it means you are linking the library incorrectly or not at all. Some things to look out for are: if you have all the -lopencv_* library link flags in a "libraries" element somewhere, if you don't you are not actually linking opencv but it would not normally complain without -z defs ; if it is linking the library which corresponds to the headers you are using (the easiest way to avoid these kind of problems is just to use your distribution's opencv). You can be explicit about these things, if you need to use a checked out version of opencv, in your binding.gyp, by setting build flags for include and library search paths. You can use nm to look what symbols are defined in your final node addon... anything with a "U" (undefined) is expected to be made available at the final load stage. You should still see the opencv symbols as undefined unless you statically linked opencv. So call: $ nm -C myaddon.node The -C will demangle the names, you should see cv::Feature2D as undefined if you linked the shared library. The final step is to check what libraries will be loaded when your library is loaded. Use ldd to do this. $ ldd myaddon.node This will show you any libraries that could not be found. If the opencv libraries are not found here you have not linked the shared library. It will also show you where it finds the libraries if it does find them (you can use these paths to make sure you are using your checked out libraries). Just a final nuclear option, opencv has quite a few libraries it seems, your best best is to link all of them to resolve missing symbols. Get all those libs with pkgconfig: $ pkg-config --libs opencv You can get the include flags with $ pkg-config --cflags opencv Put that stuff in the appropriate places in your binding.gyp.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36961650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5759380/']}
jdg_79972
stackexchange
llm_judgeable_groundtruth_similarity
7720513
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 test the single sign on, so I wanted to download the Facebook application to the iPhone simulator. Where can I download the Facebook application for iPhone and how can I place it on the simulator? Now provide the response and nothing else.
Unless you are the developer of that app, and more to the point, you have the source code to build from scratch, you cannot take an app downloaded through the App Store and run it in the simulator. Aside from likely being against Apple's terms and conditions, apps built for devices are built for ARM processors, while apps built for the simulator are actually Mac apps and built for the i386 platform. I think you'll have to download the Facebook app to your device via iTunes, then build your app for an iOS device and run it on your device via Xcode. You'll need a developer certificate, of course. That's the only way you'll be able to test SSO with the Facebook app, I believe.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7720513', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/186820/']}
jdg_79973
stackexchange
llm_judgeable_groundtruth_similarity
237601
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Background I am working on a legacy small-business automation system (inventory, sales, procurement, etc.) that has a single database hosted by SQL Server 2005 and a bunch of client applications. The main client (used by all users) is an MS Access 2003 application (ADP), and other clients include various VB/VBA applications like Excel add-ins and command-line utilities. In addition to 60 or so tables (mostly in 3NF), the database contains about 200 views, about 170 UDFs (mostly scalar and table-valued inline ones), and about 50 stored procedures. As you might have guessed, some portion of so-called "business logic" is encapsulated in this mass of T-SQL code (and thus is shared by all clients). Overall, the system's code (including the T-SQL code) is not very well organized and is very refactoring-resistant, so to speak. In particular, schemata of most of the tables cry for all kinds of refactorings, small (like column renamings) and large (like normalization). FWIW, I have pretty long and decent application development experience (C/C++, Java, VB, and whatnot), but I am not a DBA. So, if the question will look silly to you, now you know why it is so. :-) Question While thinking about refactoring all this mess (in a peacemeal fashion of course), I've come up with the following idea: For each table, create a "wrapper" view that (a) has all the columns that the table has; and (b) in some cases, has some additional computed columns based on the table's "real" columns. A typical (albeit simplistic) example of such additional computed column would be sale price of a product derived from the product's regular price and discount. Reorganize all the code (both T-SQL and VB/VBA client code) so that only the "wrapper" views refer to tables directly. So, for example, even if an application or a stored procedure needed to insert/update/delete records from a table, they'd do that against the corresponding "table wrapper" view, not against the table directly. So, essentially this is about isolating all the tables by views from the rest of the system . This approach seems to provide a lot of benefits, especially from maintainability viewpoint. For example: When a table column is to be renamed, it can be done without rewriting all the affected client code at once. It is easier to implement derived attributes (easier than using computed columns). You can effectively have aliases for column names. Obviously, there must be some price for all these benefits, but I am not sure that I am seeing all the catches lurking out there. Did anybody try this approach in practice? What are the major pitfalls? One obvious disadvantage is the cost of maintaining "wrapper" views in sync with their corresponding tables (a new column in a table has to be added to a view too; a column deleted from a table has to be deleted from the view too; etc.). But this price seems to be small and fair for making the overall codebase more resilient. Does anyone know any other, stronger drawbacks? For example, usage of all those "wrapper" views instead of tables is very likely to have some adverse performance impact, but is this impact going to be substantial enough to worry about it? Also, while using ADODB, it is very easy to get a recordset that is not updateable even when it is based just on a few joined tables; so, are the "wrapper" views going to make things substantially worse? And so on, and so forth... Any comments (especially shared real experience) would be greatly appreciated. Thank you! P.S. I stepped on the following old article that discusses the idea of "wrapper" views: The Big View Myth The article advises to avoid the approach described above. But... I do not really see any good reasons against this idea in the article. Quite the contrary, in its list of good reasons to create a view, almost each item is exactly why it is so tempting to create a "wrapper" view for each and every table (especially in a legacy system, as a part of refactoring process). The article is really old (1999), so whatever reasons were good then may be no longer good now (and vice versa). It would be really interesting to hear from someone who considered or even tried this idea recently, with the latest versions of SQL Server and MS Access... Now provide the response and nothing else.
When designing a database, I prefer the following: no direct table access by the code (but is ok from stored procedures and views and functions) a base view for each table that includes all columns an extended view for each table that includes lookup columns (types, statuses, etc.) stored procedures for all updates functions for any complex queries this allows the DBA to work directly with the table (to add columns, clean things up, inject data, etc.) without disturbing the code base, and it insulates the code base from any changes made to the table (temporary or otherwise) there may be performance penalties for doing things this way, but so far they have not been significant - and the benefits of the layer of insulation have been life-savers several times
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/237601', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31415/']}
jdg_79974
stackexchange
llm_judgeable_groundtruth_similarity
129046
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How would I disable and later enable all indexes in a given schema/database in Oracle? Note: This is to make sqlldr run faster. Now provide the response and nothing else.
Here's making the indexes unusable without the file: DECLARE CURSOR usr_idxs IS select * from user_indexes; cur_idx usr_idxs% ROWTYPE; v_sql VARCHAR2(1024);BEGIN OPEN usr_idxs; LOOP FETCH usr_idxs INTO cur_idx; EXIT WHEN NOT usr_idxs%FOUND; v_sql:= 'ALTER INDEX ' || cur_idx.index_name || ' UNUSABLE'; EXECUTE IMMEDIATE v_sql; END LOOP; CLOSE usr_idxs;END; The rebuild would be similiar.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/129046', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9435/']}
jdg_79975
stackexchange
llm_judgeable_groundtruth_similarity
3334048
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 xml -layout file main with two textviews A/B and a view C.I have two other xml -layout files option1 and option2 .Is it possible to load either option1 or option2 in run time via Java into C? If so, what function do I have to use? Now provide the response and nothing else.
You could replace any view at any time. int optionId = someExpression ? R.layout.option1 : R.layout.option2;View C = findViewById(R.id.C);ViewGroup parent = (ViewGroup) C.getParent();int index = parent.indexOfChild(C);parent.removeView(C);C = getLayoutInflater().inflate(optionId, parent, false);parent.addView(C, index); If you don't want to replace already existing View , but choose between option1/option2 at initialization time, then you could do this easier: set android:id for parent layout and then: ViewGroup parent = (ViewGroup) findViewById(R.id.parent);View C = getLayoutInflater().inflate(optionId, parent, false);parent.addView(C, index); You will have to set "index" to proper value depending on views structure. You could also use a ViewStub : add your C view as ViewStub and then: ViewStub C = (ViewStub) findViewById(R.id.C);C.setLayoutResource(optionId);C.inflate(); That way you won't have to worry about above "index" value if you will want to restructure your XML layout.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/3334048', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/25282/']}
jdg_79976
stackexchange
llm_judgeable_groundtruth_similarity
4635688
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 replace parts of a string without having to create a whole new variable? Right now I do it like this: $someString = "how do you do this";$someString = s/how do/this is how/; What I am trying to do is keep the original string ($someString) and be able to substitute a few characters without modifying the original string. Im more familiar with Javascript and I can do it like this in your code without having to create/modify a variable. someString.replace(/how do/, "this is how") Any help is appreciated, thanks alot Now provide the response and nothing else.
Note quite sure I understand the question. If you want to leave the original string unchanged, you need to create a new variable. $newstring = $someString ;$newstring =~ s/how do/this is how/; Note that the operator is =~ not = addition I think I now see what you want - to return the changed string rather than modify a variable. There will be a way to do this in Perl 5.14 but I am not aware of a way at present. See Use the /r substitution flag to work on a copy at The Effective Perler . Update The s/ / /r functionallity has been in released Perl for some time. you can do use 5.14.0 ;my $someString = "how do you do this";say ($someString =~ s/how do/this is how/r) ;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4635688', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/523640/']}
jdg_79977
stackexchange
llm_judgeable_groundtruth_similarity
10216182
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: MSDN says: "Without the suffix m, the number is treated as a double, thus generating a compiler error." What does the "M" in: decimal current = 10.99M; stand for? Is it any different than: decimal current = (decimal)10.99 Now provide the response and nothing else.
M makes the number a decimal representation in code. To answer the second part of your question, yes they are different. decimal current = (decimal)10.99 is the same as double tmp = 10.99;decimal current = (decimal)tmp; Now for numbers larger than sigma it should not be a problem but if you meant decimal you should specify decimal. Update : Wow, i was wrong. I went to go check the IL to prove my point and the compiler optimized it away. Update 2 : I was right after all!, you still need to be careful. Compare the output of these two functions. class Program{ static void Main(string[] args) { Console.WriteLine(Test1()); Console.WriteLine(Test2()); Console.ReadLine(); } static decimal Test1() { return 10.999999999999999999999M; } static decimal Test2() { return (decimal)10.999999999999999999999; }} The first returns 10.999999999999999999999 but the seccond returns 11 Just as a side note, double will get you 15 decimal digits of precision but decimal will get you 96 bits of precision with a scaling factor from 0 to 28 . So you can represent any number in the range ((-2 96 to 2 96 ) / 10 (0 to 28) )
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10216182', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1179562/']}
jdg_79978
stackexchange
llm_judgeable_groundtruth_similarity
1805191
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: When calculating the SVD of the matrix $$A = \begin{bmatrix}3&1&1\\-1&3&1\end{bmatrix}$$ I followed these steps $$A A^{T} = \begin{bmatrix}3&1&1\\-1&3&1\end{bmatrix} \begin{bmatrix}3&-1\\1&3\\1&1\end{bmatrix} = \begin{bmatrix}11&1\\1&11\end{bmatrix}$$ $$\det(A A^{T} - \lambda I) = (11-\lambda)^{2} - 1 = 0$$ Hence, the eigenvalues are $\lambda_{1} = 12$ and $\lambda_{2} = 10$. When $\lambda_{1} = 12$: $$ \begin{bmatrix}11-\lambda_{1}&1\\1&11-\lambda_{1}\end{bmatrix} \begin{bmatrix}x_{1}\\x_{2}\end{bmatrix} = \begin{bmatrix}0\\0\end{bmatrix}$$ $$x_{1} = x_{2} \implies u_{1} = \begin{bmatrix}t\\t\end{bmatrix}$$ And for $\lambda_{2} = 10$: $$x_{1} = -x_{2} \implies u_{2} = \begin {bmatrix}t\\-t\end{bmatrix}$$ Now $$U = \begin {bmatrix} u_{1}&u_{2} \end{bmatrix}$$ $u_{1}$ and $u_{2}$ are orthonormal.So the for $u_{1} = \begin{bmatrix}t\\t\end{bmatrix}$ , $u_{2} = \begin{bmatrix}t\\-t\end{bmatrix}$ I know $\left| t \right| = \frac{1}{\sqrt{2}}$ and $u_{1}.u_{2}=0$. My question how can we decide about the sign? For example I think both $U= \begin{bmatrix}\frac{1}{\sqrt{2}} &\frac{1}{\sqrt{2}} \\\frac{1}{\sqrt{2}} &\frac{-1}{\sqrt{2}} \end{bmatrix}$ and $U=\begin{bmatrix}\frac{-1}{\sqrt{2}} &\frac{1}{\sqrt{2}} \\\frac{1}{\sqrt{2}} &\frac{1}{\sqrt{2}} \end{bmatrix}$ could be answers. Then Which one should I choose? ====== Update1: Based on answers posted I rewrite:$u_{1} = sgn (t_1) \begin{bmatrix} \frac{1}{\sqrt{2}}\\ \frac{1}{\sqrt{2}}\end{bmatrix}$ $u_{2} = sgn (t_2) \begin{bmatrix} \frac{1}{\sqrt{2}}\\ \frac{-1}{\sqrt{2}}\end{bmatrix}$ $$U= \begin{bmatrix} \frac{1}{\sqrt{2}}& \frac{-1}{\sqrt{2}} \\ \frac{1}{\sqrt{2}}& \frac{1}{\sqrt{2}}\end{bmatrix} \begin{bmatrix} \operatorname{sgn} (t_1)&0 \\ 0& \operatorname{sgn} (t_2) \end{bmatrix}$$ ====== Update2: I continued by calculation of $V$ as follow: $ A^{T} A = \begin{bmatrix}3&-1\\1&\\1&1\end{bmatrix} \begin{bmatrix}3&1&1\\-1&3&1\end{bmatrix} = \begin{bmatrix}10&0&2\\0&10&4\\2&4&2\end{bmatrix}$ $det( A^{T} A- \lambda I)=0$ $\lambda_{1} = 12 , v_1 = sgn(t_3) \begin{bmatrix}t_{3}\\ 2t_{3} \\ t_{3} \end{bmatrix}$ $\lambda_{2} = 10 , V_{2} = sgn(t_4) \begin{bmatrix}t_{4}\\ -0.5t_{4} \\ 0 \end{bmatrix}$ $\lambda_{3} = 0 , V_{3} = sgn(t_5) \begin{bmatrix}t_{5}\\ 2t_{5} \\ -5t_{5} \end{bmatrix}$ $V= \begin{bmatrix}\frac{1}{\sqrt{6}} &\frac{2}{\sqrt{5}} &\frac{1}{\sqrt{30}}\\ \frac{2}{\sqrt{6}}&\frac{-1}{\sqrt{5}}&\frac{2}{\sqrt{30}}\\ \frac{1}{\sqrt{6}}& 0& \frac{-5}{\sqrt{30}}\end{bmatrix}\begin{bmatrix} \operatorname{sgn} (t_3)&0&0 \\ 0& \operatorname{sgn} (t_4)&0\\ 0&0& \operatorname{sgn} (t_5) \end{bmatrix}$ I try to check if all possible answers for U and V are valid : $A = U\Sigma V^{*}$ $A = \begin{bmatrix} \frac{1}{\sqrt{2}}& \frac{-1}{\sqrt{2}} \\ \frac{1}{\sqrt{2}}& \frac{1}{\sqrt{2}}\end{bmatrix} \begin{bmatrix} \operatorname{sgn} (t_1)&0 \\ 0& \operatorname{sgn} (t_2) \end{bmatrix} \Sigma (\begin{bmatrix}\frac{1}{\sqrt{6}} &\frac{2}{\sqrt{5}} &\frac{1}{\sqrt{30}}\\ \frac{2}{\sqrt{6}}&\frac{-1}{\sqrt{5}}&\frac{2}{\sqrt{30}}\\ \frac{1}{\sqrt{6}}& 0& \frac{-5}{\sqrt{30}}\end{bmatrix} \begin{bmatrix} \operatorname{sgn} (t_3)&0&0 \\ 0& \operatorname{sgn} (t_4)&0\\ 0&0& \operatorname{sgn} (t_5) \end{bmatrix} )^{*} $ $A = \begin{bmatrix} \frac{1}{\sqrt{2}}& \frac{-1}{\sqrt{2}} \\ \frac{1}{\sqrt{2}}& \frac{1}{\sqrt{2}}\end{bmatrix} \begin{bmatrix} \operatorname{sgn} (t_1)&0 \\ 0& \operatorname{sgn} (t_2) \end{bmatrix} \Sigma \begin{bmatrix} \operatorname{sgn} (t_3)&0&0 \\ 0& \operatorname{sgn} (t_4)&0\\ 0&0& \operatorname{sgn} (t_5) \end{bmatrix} \begin{bmatrix}\frac{1}{\sqrt{6}} &\frac{2}{\sqrt{5}} &\frac{1}{\sqrt{30}}\\ \frac{2}{\sqrt{6}}&\frac{-1}{\sqrt{5}}&\frac{2}{\sqrt{30}}\\ \frac{1}{\sqrt{6}}& 0& \frac{-5}{\sqrt{30}}\end{bmatrix}^{*} $ When I assigned $U= \begin{bmatrix}\frac{-1}{\sqrt{2}} &\frac{-1}{\sqrt{2}} \\\frac{-1}{\sqrt{2}} &\frac{1}{\sqrt{2}} \end{bmatrix}$ and $V= \begin{bmatrix}\frac{-1}{\sqrt{6}} &\frac{-2}{\sqrt{5}} &\frac{-1}{\sqrt{30}}\\ \frac{-2}{\sqrt{6}}&\frac{1}{\sqrt{5}} & \frac{-2}{\sqrt{30}} \\ \frac{-1}{\sqrt{6}}& 0& \frac{5}{\sqrt{30}}\end{bmatrix}$ and $\Sigma = \begin{bmatrix}\sqrt{20}&0&0\\ 0&\sqrt{10}&0\end{bmatrix} $in $A = U\Sigma V^{*}$I got the A. But when I updated U as $U = \begin{bmatrix}\frac{1}{\sqrt{2}} &\frac{1}{\sqrt{2}} \\\frac{1}{\sqrt{2}} &\frac{-1}{\sqrt{2}} \end{bmatrix}$, it produced -A.This probably means certain version of $U$ and $V$ will reproduce A. I haven't figured how should I choose them. Now provide the response and nothing else.
The left singular vectors are $$\mathrm{u}_1 \in \left\{ t_1 \begin{bmatrix} 1\\ 1\end{bmatrix} : t_1 \in \mathbb R \right\}$$ $$\mathrm{u}_2 \in \left\{ t_2 \begin{bmatrix} 1\\ -1\end{bmatrix} : t_2 \in \mathbb R \right\}$$ We want the left singular vectors to be orthonormal . They are already orthogonal. Normalizing, $$\mathrm{u}_1 = \frac{t_1}{\sqrt{2 t_1^2}} \begin{bmatrix} 1\\ 1\end{bmatrix} = \operatorname{sgn} (t_1) \begin{bmatrix} \frac{1}{\sqrt{2}}\\ \frac{1}{\sqrt{2}}\end{bmatrix}$$ $$\mathrm{u}_2 = \frac{t_2}{\sqrt{2 t_2^2}} \begin{bmatrix} 1\\ -1\end{bmatrix} = \operatorname{sgn} (t_2) \begin{bmatrix} \frac{1}{\sqrt{2}}\\ -\frac{1}{\sqrt{2}}\end{bmatrix}$$ where $\operatorname{sgn}$ denotes the signum function. Hence, $$\mathrm U = \begin{bmatrix} | & |\\ \mathrm{u}_{1} & \mathrm{u}_{2}\\ | & |\end{bmatrix} = \begin{bmatrix} \frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}}\\ \frac{1}{\sqrt{2}} & -\frac{1}{\sqrt{2}}\end{bmatrix} \begin{bmatrix} \operatorname{sgn} (t_1) & 0\\ 0 & \operatorname{sgn} (t_2)\end{bmatrix}$$ There are $2^2 = 4$ possible choices.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1805191', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/342108/']}
jdg_79979
stackexchange
llm_judgeable_groundtruth_similarity
4515979
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: With a list of around 100,000 key/value pairs (both string, mostly around 5-20 characters each) I am looking for a way to efficiently find the value for a given key. This needs to be done in a php website. I am familiar with hash tables in java (which is probally what I would do if working in java) but am new to php. I am looking for tips on how I should store this list (in a text file or in a database?) and search this list. The list would have to be updated occasionally but I am mostly interested in look up time. Now provide the response and nothing else.
You could do it as a straight PHP array, but Sqlite is going to be your best bet for speed and convenience if it is available. PHP array Just store everything in a php file like this: <?phpreturn array( 'key1'=>'value1', 'key2'=>'value2', // snip 'key100000'=>'value100000',); Then you can access it like this: <?php$s = microtime(true); // gets the start time for benchmarking$data = require('data.php');echo $data['key2'];var_dump(microtime(true)-$s); // dumps the execution time Not the most efficient thing in the world, but it's going to work. It takes 0.1 seconds on my machine. Sqlite PHP should come with sqlite enabled, which will work great for this kind of thing. This script will create a database for you from start to finish with similar characteristics to the dataset you describe in the question: <?php// this will *create* data.sqlite if it does not exist. Make sure "/data" // is writable and *not* publicly accessible.// the ATTR_ERRMODE bit at the end is useful as it forces PDO to throw an// exception when you make a mistake, rather than internally storing an// error code and waiting for you to retrieve it.$pdo = new PDO('sqlite:'.dirname(__FILE__).'/data/data.sqlite', null, null, array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));// create the table if you need to$pdo->exec("CREATE TABLE stuff(id TEXT PRIMARY KEY, value TEXT)");// insert the data$stmt = $pdo->prepare('INSERT INTO stuff(id, value) VALUES(:id, :value)');$id = null;$value = null;// this binds the variables by reference so you can re-use the prepared statement$stmt->bindParam(':id', $id);$stmt->bindParam(':value', $value);// insert some data (in this case it's just dummy data)for ($i=0; $i<100000; $i++) { $id = $i; $value = 'value'.$i; $stmt->execute();} And then to use the values: <?php$s = microtime(true);$pdo = new PDO('sqlite:'.dirname(__FILE__).'/data/data.sqlite', null, null, array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));$stmt = $pdo->prepare("SELECT * FROM stuff WHERE id=:id");$stmt->bindValue(':id', 5);$stmt->execute();$value = $stmt->fetchColumn(1);var_dump($value);// the number of seconds it took to do the lookupvar_dump(microtime(true)-$s); This one is waaaay faster. 0.0009 seconds on my machine. MySQL You could also use MySQL for this instead of Sqlite, but if it's just one table with the characteristics you describe, it's probably going to be overkill. The above Sqlite example will work fine using MySQL if you have a MySQL server available to you. Just change the line that instantiates PDO to this: $pdo = new PDO('mysql:host=your.host;dbname=your_db', 'user', 'password', array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION)); The queries in the sqlite example should all work fine with MySQL, but please note that I haven't tested this. Let's get a bit crazy: Filesystem madness Not that the Sqlite solution is slow (0.0009 seconds!), but this about four times faster on my machine. Also, Sqlite may not be available, setting up MySQL might be out of the question, etc. In this case, you can also use the file system: <?php$s = microtime(true); // more hack benchmarkingclass FileCache{ protected $basePath; public function __construct($basePath) { $this->basePath = $basePath; } public function add($key, $value) { $path = $this->getPath($key); file_put_contents($path, $value); } public function get($key) { $path = $this->getPath($key); return file_get_contents($path); } public function getPath($key) { $split = 3; $key = md5($key); if (!is_writable($this->basePath)) { throw new Exception("Base path '{$this->basePath}' was not writable"); } $path = array(); for ($i=0; $i<$split; $i++) { $path[] = $key[$i]; } $dir = $this->basePath.'/'.implode('/', $path); if (!file_exists($dir)) { mkdir($dir, 0777, true); } return $dir.'/'.substr($key, $split); }}$fc = new FileCache('/tmp/foo');/*// use this crap for generating a test example. it's slow to create though.for ($i=0;$i<100000;$i++) { $fc->add('key'.$i, 'value'.$i);}//*/echo $fc->get('key1', 'value1');var_dump(microtime(true)-$s); This one takes 0.0002 seconds for a lookup on my machine. This also has the benefit of being reasonably constant regardless of the cache size.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4515979', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/552007/']}
jdg_79980
stackexchange
llm_judgeable_groundtruth_similarity
14734243
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 protect_from_forgery option is mentioned in application_controller, then I can log in and perform any GET requests, but on very first POST request Rails resets the session, which logs me out. I turned the protect_from_forgery option off temporarily, but would like to use it with Angular.js. Is there some way to do that? Now provide the response and nothing else.
I think reading CSRF-value from DOM is not a good solution, it's just a workaround. Here is a document form angularJS official website http://docs.angularjs.org/api/ng.$http : Since only JavaScript that runs on your domain could read the cookie, your server can be assured that the XHR came from JavaScript running on your domain. To take advantage of this (CSRF Protection), your server needs to set a token in a JavaScript readable sessioncookie called XSRF-TOKEN on first HTTP GET request. On subsequentnon-GET requests the server can verify that the cookie matchesX-XSRF-TOKEN HTTP header Here is my solution based on those instructions: First, set the cookie: # app/controllers/application_controller.rb# Turn on request forgery protectionprotect_from_forgeryafter_action :set_csrf_cookiedef set_csrf_cookie cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery?end Then, we should verify the token on every non-GET request. Since Rails has already built with the similar method, we can just simply override it to append our logic: # app/controllers/application_controller.rbprotected # In Rails 4.2 and above def verified_request? super || valid_authenticity_token?(session, request.headers['X-XSRF-TOKEN']) end # In Rails 4.1 and below def verified_request? super || form_authenticity_token == request.headers['X-XSRF-TOKEN'] end
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/14734243', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/999355/']}
jdg_79981
stackexchange
llm_judgeable_groundtruth_similarity
188236
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: When an nucleus is split, what form of energy is released? All of the websites I have looked at say there is a lot of energy released when an atom is split, but it never says what form of energy it is in. Is it electrical energy, or is it just a lot of heat, or something else? Now provide the response and nothing else.
A lot of different forms, but mostly kinetic energy. A good table is given at Hyperphysics . The energy released from fission of uranium-235 is about 215 MeV. This is divided into: Kinetic energy of fragments (heat): ~168 MeV Assorted gamma rays: ~15-24 MeV Beta particles (electrons/positrons) and their kinetic energy: ~8 MeV Assorted neutrons and their kinetic energy: ~17 MeV Neutrinos and their kinetic energy: ~? Note that neutrons can, if left alone for long enough, decay, typically by this reaction: $$\text{n} \to \text{p} + \bar{\text{v}}_{\text{e}} + \text{e}^{-}$$ where $\text{n}$ , $\text{p}$ , $\bar{\text{v}}_{\text{e}}$ , and $\text{e}^{-}$ represent neutrons, protons, anti-electron neutrinos, and electrons, respectively.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/188236', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/83094/']}
jdg_79982
stackexchange
llm_judgeable_groundtruth_similarity
44798593
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 Java class that is becoming long. When I run it through code quality tools, I get flagged for number of lines in the class. This is a lower layer class, used by upper layers with Spring's @Autowired . The class has a lot of private instance methods which are not static. They don't use any instance fields, working only on method parameters. Can I safely move these methods as public static in some separate utility class? What are the downsides? Now provide the response and nothing else.
"Wrong" mindset here. You do not rework your classes because tools are complaining about this or that. You want to improve the quality of your source code; and such tools can help with identifying "topics worth thinking think about". You take their feedback as hint ; not as "order". Therefore you don't worry about "lines of codes" within a class. Instead, you worry about the responsibilities that this class has. Meaning: the line number count isn't a problem per se - but violations of the Single Responsibility Principle are. Thus: you step back and check out what exactly your class is doing. And when it is clearly doing more than one thing, you extract such aspects into other classes! Meaning: if you actually find that all this code "belongs" to the responsibility of that class; then keep it in there. Don't start putting internal implementation details into unrelated helper classes; just because some tool warns you about number of lines. On the other hand, turning private methods into something that is static/package protected would allow you to unit test those methods. Which could be an advantage. But as said: as long as we are talking about implementation details , they should stay private; and they shouldn't be unit tested anyway. Long story code: know and understand what "clean code" is about; and try to follow the ideas outlined there.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/44798593', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3850730/']}
jdg_79983
stackexchange
llm_judgeable_groundtruth_similarity
35370732
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 had defined in my project a global Automapper configuration that would allow me to use Mapper.Map<targetType>(sourceObject); in my code. (See my configuration below.) I updated the NuGet package, and I see the message that Mapper.Map is obsolete/depreciated. I went back to Automapper on GitHub and see examples like this: [Test]public void Example(){ var config = new MapperConfiguration(cfg => { cfg.CreateMap<Source1, SubDest1>().FixRootDest(); cfg.CreateMap<Source2, SubDest2>().FixRootDest(); }); config.AssertConfigurationIsValid(); var mapper = config.CreateMapper(); var subDest1 = mapper.Map<Source1, SubDest1>(new Source1 {SomeValue = "Value1"}); var subDest2 = mapper.Map<Source2, SubDest2>(new Source2 {SomeOtherValue = "Value2"}); subDest1.SomeValue.ShouldEqual("Value1"); subDest2.SomeOtherValue.ShouldEqual("Value2");} Am I going to have to create a configuration in EVERY method that uses a mapping? My current global configuration: namespace PublicationSystem.App_Start{ public class AutoMapperConfig { public static void CreateMaps() { CreateProjectMaps(); } private static void CreateProjectMaps() { Mapper.CreateMap<Project, ProjectCreate>(); Mapper.CreateMap<Project, ProjectSelectable>(); //... } }} UPDATE: Thanks to some coaching from Scott Chamberlain I have created a class like this: public class MkpMapperProfile : AutoMapper.Profile { protected override void Configure() { this.CreateMap<Project, ProjectCreate>(); this.CreateMap<Project, ProjectSelectable>(); this.CreateMap<Project, ProjectDetails>(); // Many Many other maps } } I'm thinking I should have the 'MapperConfiguration' in my BaseController class. I started to do something like this: public partial class BaseController : Controller{ private MapperConfiguration mapConfig; public BaseController() { db = new MkpContext(); SetMapperConfig(); } private void SetMapperConfig() { mapConfig = new MapperConfiguration(cfg => { cfg.AddProfile<MkpMapperProfile>(); }); } public BaseController(MapperConfiguration config) { db = new MkpContext(); this.mapConfig = config; }} Am I on the right track? Now provide the response and nothing else.
This is how I've handled it. Create maps in a Profile, taking care to use the Profile's CreateMap method rather than Mapper's static method of the same name: internal class MappingProfile : Profile{ protected override void Configure() { CreateMap<Project, ProjectCreate>(); }} Then, wherever dependencies are wired-up (ex: Global.asax or Startup), create a MapperConfiguration and then use it to create an IMapper. var mapperConfiguration = new MapperConfiguration(cfg => { cfg.AddProfile(new MappingProfile()); }); Then, use the configuration to generate an IMapper: var mapper = mapperConfiguration.CreateMapper(); Then, register that mapper with the dependency builder (I'm using Autofac here) builder.RegisterInstance(mapper).As<IMapper>(); Now, wherever you need to map stuff, declare a dependency on IMapper: internal class ProjectService : IProjectService { private readonly IMapper _mapper; public ProjectService(IMapper mapper) { _mapper = mapper; } public ProjectCreate Get(string key) { var project = GetProjectSomehow(key); return _mapper.Map<Project, ProjectCreate>(project); }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35370732', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/405883/']}
jdg_79984
stackexchange
llm_judgeable_groundtruth_similarity
35631903
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: With Entity Framework Core removing dbData.Database.SqlQuery<SomeModel> I can't find a solution to build a raw SQL Query for my full-text search query that will return the tables data and also the rank. The only method I've seen to build a raw SQL query in Entity Framework Core is via dbData.Product.FromSql("SQL SCRIPT"); which isn't useful as I have no DbSet that will map the rank I return in the query. Any Ideas??? Now provide the response and nothing else.
If you're using EF Core 3.0 or newer You need to use keyless entity types , previously known as query types: This feature was added in EF Core 2.1 under the name of query types.In EF Core 3.0 the concept was renamed to keyless entity types. The[Keyless] Data Annotation became available in EFCore 5.0. To use them you need to first mark your class SomeModel with [Keyless] data annotation or through fluent configuration with .HasNoKey() method call like below: public DbSet<SomeModel> SomeModels { get; set; }protected override void OnModelCreating(ModelBuilder modelBuilder){ modelBuilder.Entity<SomeModel>().HasNoKey();} After that configuration, you can use one of the methods explained here to execute your SQL query. For example you can use this one: var result = context.SomeModels.FromSqlRaw("SQL SCRIPT").ToList();var result = await context.SomeModels.FromSql("SQL_SCRIPT").ToListAsync(); If you're using EF Core 2.1 If you're using EF Core 2.1 Release Candidate 1 available since 7 may 2018, you can take advantage of the proposed new feature which is query types : In addition to entity types, an EF Core model can contain query types,which can be used to carry out database queries against data thatisn't mapped to entity types. When to use query type? Serving as the return type for ad hoc FromSql() queries. Mapping to database views. Mapping to tables that do not have a primary key defined. Mapping to queries defined in the model. So you no longer need to do all the hacks or workarounds proposed as answers to your question. Just follow these steps: First you defined a new property of type DbQuery<T> where T is the type of the class that will carry the column values of your SQL query. So in your DbContext you'll have this: public DbQuery<SomeModel> SomeModels { get; set; } Secondly use FromSql method like you do with DbSet<T> : var result = context.SomeModels.FromSql("SQL_SCRIPT").ToList();var result = await context.SomeModels.FromSql("SQL_SCRIPT").ToListAsync(); Also note that DbContext s are partial classes , so you can create one or more separate files to organize your 'raw SQL DbQuery' definitions as best suits you.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/35631903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4241818/']}
jdg_79985
stackexchange
llm_judgeable_groundtruth_similarity
9547122
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: maybe I don't get. When I do self.tweetPeak.transform = CGAffineTransformMakeRotation(RADIANS(45)); where RADIAN is #define RADIANS(degrees) ((degrees * M_PI) / 180.0) on a simple UIView Object it will disappear. I guess it's just to thin to see. My impression is that the view is getting smaller in a range between 20 to 45 degrees. What is it? I tried to set the view opaque. No effect. chris Now provide the response and nothing else.
You need to stop adjusting the frame after the rotation, it causes undesired stretching to the transform matrix, I'm unsure to the formal reason why, but it has something to do with Apple using their own matrix system rather than traditional matrices to represent 2D/3D translations/rotations/scale. I was having the same problem the other day, to fix it, instead of rotating that view, I just made it a container with the actual view I wanted rotated inside, and rotated that.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9547122', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1056644/']}
jdg_79986
stackexchange
llm_judgeable_groundtruth_similarity
30625380
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 MongoCollection<Document> in which I assign a collection.I'm trying to find a user by his id. user = (Document) usersCollection.find(new Document("_id", username)); with that I'm getting an error java.lang.ClassCastException: com.mongodb.FindIterableImpl cannot be cast to org.bson.Document When I try BasicDBObject query = new BasicDBObject(); BasicDBObject fields = new BasicDBObject("_id", username); usersCollection.find(query, fields); I'm getting an error The method find(Bson, Class) in the type MongoCollection is not applicable for the arguments (BasicDBObject, BasicDBObject) Now provide the response and nothing else.
Try to create a filter to pass to the find() method to get a subset of the documents in your collection. For example, to find the document for which the value of the _id field is test , you would do the following: import static com.mongodb.client.model.Filters.*;MongoClient client = new MongoClient();MongoDatabase database = client.getDatabase("mydb");MongoCollection<Document> collection = database.getCollection("mycoll");Document myDoc = collection.find(eq("_id", "test")).first();System.out.println(myDoc.toJson());
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30625380', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1693990/']}
jdg_79987
stackexchange
llm_judgeable_groundtruth_similarity
327534
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a list of data that looks like the following: // timestep,x_position,y_position0,4,70,2,70,9,50,6,71,2,51,4,71,9,01,6,8 ... and I want to make this look like: 0, (4,7), (2,7), (9,5), (6,7)1, (2,5), (4,7), (9,0), (6.8) My plan was to use a dictionary, where the value of t is the key for the dictionary, and the value against the key would be a list. I could then append each (x,y) to the list. Something like: # where t = 0, c = (4,7), d = {}# code 1d[t].append(c) Now this causes IDLE to fail. However, if I do: # code 2d[t] = []d[t].append(c) ... this works. So the question is: why does code 2 work, but code 1 doesn't? PS Any improvement on what I'm planning on doing would be of great interest!! I think I will have to check the dictionary on each loop through the input to see if the dictionary key already exists, I guess by using something like max(d.keys()): if it is there, append data, if not create the empty list as the dictionary value, and then append data on the next loop through. Now provide the response and nothing else.
Let's look at d[t].append(c) What is the value of d[t] ? Try it. d = {}t = 0d[t] What do you get? Oh. There's nothing in d that has a key of t . Now try this. d[t] = []d[t] Ahh. Now there's something in d with a key of t . There are several things you can do. Use example 2. Use setdefault . d.setdefault(t,[]).append(c) . Use collections.defaultdict . You'd use a defaultdict(list) instead of a simple dictionary, {} . Edit 1. Optimization Given input lines from a file in the above form: ts, x, y, the grouping process is needless. There's no reason to go from a simple list of ( ts, x, y ) to a more complexlist of ( ts, (x,y), (x,y), (x,y), ... ). The original list can be processed exactly as it arrived. d= collections.defaultdict(list)for ts, x, y in someFileOrListOrQueryOrWhatever: d[ts].append( (x,y) ) Edit 2. Answer Question "when initialising a dictionary, you need to tell the dictionary what the key-value data structure will look like?" I'm not sure what the question means. Since, all dictionaries are key-value structures, the question's not very clear. So, I'll review the three alternatives, which may answer the question. Example 2 . Initialization d= {} Use if t not in d: d[t] = list()d[t].append( c ) Each dictionary value must be initialized to some useful structure. In this case, we check to see if the key is present; when the key is missing, we create the key and assign an empty list. Setdefault Initialization d= {} Use d.setdefault(t,list()).append( c ) In this case, we exploit the setdefault method to either fetch a value associated with a key or create a new value associated with a missing key. default dict Initialization import collectionsd = collections.defaultdict(list) Use d[t].append( c ) The defaultdict uses an initializer function for missing keys. In this case, we provide the list function so that a new, empty list is created for a missing key.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/327534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/41121/']}
jdg_79988
stackexchange
llm_judgeable_groundtruth_similarity
611775
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Exact Duplicate: Using a regular expression to validate an email address What are valid email address characters and patterns and how would you write a regular expression which matches it? Now provide the response and nothing else.
Here you go: (?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*:(?:(?:\r\n)?[ \t])*(?:(?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*)(?:,\s*(?:(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*|(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)*\<(?:(?:\r\n)?[ \t])*(?:@(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*(?:,@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*)*:(?:(?:\r\n)?[ \t])*)?(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|"(?:[^\"\r\\]|\\.|(?:(?:\r\n)?[ \t]))*"(?:(?:\r\n)?[ \t])*))*@(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*)(?:\.(?:(?:\r\n)?[ \t])*(?:[^()<>@,;:\\".\[\] \000-\031]+(?:(?:(?:\r\n)?[ \t])+|\Z|(?=[\["()<>@,;:\\".\[\]]))|\[([^\[\]\r\\]|\\.)*\](?:(?:\r\n)?[ \t])*))*\>(?:(?:\r\n)?[ \t])*))*)?;\s*) No, I'm not joking. http://www.ex-parrot.com/~pdw/Mail-RFC822-Address.html
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/611775', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/30470/']}
jdg_79989
stackexchange
llm_judgeable_groundtruth_similarity
39392012
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 handling some XPath strings that I want to modify before actually using them. For those of you who are not familiar with XPath, XPath is -- in short -- a way of resembling an XML structure, and it is often used as a formal input for an XPath/XQuery-based search engine. The goal To see an expanded/prettified version of the XPath snippets below, I can direct you to the following beautifier . Disclaimer, I am the author of that tool. My XPath strings can be quite simple //node[@cat="smain" and node[@rel="su" and @pt="vnw"] and node[@rel="hd" and @pt="ww"] and node[@rel="predc" and @cat="np" and node[@rel="det" and @pt="lid"] and node[@rel="hd" and @pt="n"]]] but also very elaborate //node[@cat="top" and node[@rel="--" and @cat="smain" and node[@rel="su" and @pt="vnw" and @word="Dit" and @lemma="dit" and number(@begin) < ../node[@rel="hd" and @pt="ww" and @lemma="zijn"]/number(@begin)] and node[@rel="hd" and @pt="ww" and @lemma="zijn" and number(@begin) < ../node[@rel="predc" and @cat="np"]/node[@rel="det" and @pt="lid" and @word="een" and @cs="no" and @lemma="een"]/number(@begin)] and node[@rel="predc" and @cat="np" and node[@rel="det" and @pt="lid" and @word="een" and @cs="no" and @lemma="een" and number(@begin) < ../node[@rel="hd" and @pt="n" and @cs="no" and @lemma="zin"]/number(@begin)] and node[@rel="hd" and @pt="n" and @cs="no" and @lemma="zin" and number(@begin) < ../../../node[@rel="--" and @pt="let"]/number(@begin)]]] and node[@rel="--" and @pt="let"]] As you may have noticed, a node is the basic element that is used. There are no other element names. However, attributes differ. The attributes that I am interested in are @cs="no" , which means that case sensitivity is not wanted in a future search request on the attributes @word and/or @lemma . To accomplish case in sensitivity I want to transform these two attributes into lower-case(@attr) . The thing is that I only want that for nodes that contain @cs="no" . What I tried so far In PHP, I thought I'd be a smart guy and do something like this: Check to see if the (XPath) string matches @cs="no" If so, find all individual nodes with a regular expression preg_match_all("/(?<=node\[).*?(?=node\[|\])/", $xpath, $matches); Loop through all these matches (strings), and check if they contain @cs="no" again If so, remove that attribute, and replace the @word and @lemma tags with the lower-case equivalent. Place result in dummy variable. And now comes the tricky part: In the original XPath string, find and replace the matched substring by the dummy variable. You can see this in action here , but I also duplicated the PHP code below. <?php $xpath = '//node[@cat="top" and node[@rel="--" and @cat="smain" and node[@rel="su" and @pt="vnw" and @word="Dit" and @lemma="dit" and number(@begin) < ../node[@rel="hd" and @pt="ww" and @lemma="zijn"]/number(@begin)] and node[@rel="hd" and @pt="ww" and @lemma="zijn" and number(@begin) < ../node[@rel="predc" and @cat="np"]/node[@rel="det" and @pt="lid" and @word="een" and @cs="no" and @lemma="een"]/number(@begin)] and node[@rel="predc" and @cat="np" and node[@rel="det" and @pt="lid" and @word="een" and @cs="no" and @lemma="een" and number(@begin) < ../node[@rel="hd" and @pt="n" and @cs="no" and @lemma="zin"]/number(@begin)] and node[@rel="hd" and @pt="n" and @cs="no" and @lemma="zin" and number(@begin) < ../../../node[@rel="--" and @pt="let"]/number(@begin)]]] and node[@rel="--" and @pt="let"]]'; $xpath = applyCs($xpath); var_dump($xpath); function applyCs($xpath) { if (strpos($xpath, '@cs="no"') !== false) { preg_match_all("/(?<=node\[).*?(?=node\[|\])/", $xpath, $matches); foreach ($matches as $match) { var_dump($match); if (strpos($match, '@cs="no"') !== false) { $dummyMatch = preg_replace('/(?:and )?@cs="no"/', '', $match); if (strpos($dummyMatch, '@word="') !== false) { $dummyMatch = str_replace('@word="', 'lower-case(@word)="', $dummyMatch); } if (strpos($dummyMatch, '@lemma="') !== false) { $dummyMatch = str_replace('@lemma="', 'lower-case(@lemma)="', $dummyMatch); } $xpath = str_replace($match, $dummyMatch, $xpath); } } } return $xpath; } Problems with my function First of all you will see in the Ideone example provided via the link above that the first node with a word attribute does not have the @cs="no" attribute, yet in the resulting XPath it does get lower-case() 'd. Secondly, something that you may not see reproduced in the example: because I simply find-and-replace the old match with the new dummy, it is very well possible that I replace values in nodes of the original XPath for which there is no @cs attribute available. I obviously do not want that. And finally I am not sure this is the best way. Efficiency is important to me, and I mostly don't like using regular expressions because of it. That's why I am using strpos and str_replace as much as I can. However, if there is a way to "parse" XPath (similarly to how you can parse XML in Perl with Twig for instance), and manipulate the XPath accordingly in a fast way that's good as well. However, effectiveness is required above efficiency. Tl;dr: in an XPath string, how can I replace an attribute by another string if its sister attribute is set (to a particular value) by using PHP without additional modules . Ideas Find a regular expression that can match each node without leaving out any gaps, and after editing a match where necessary simply glue all of them back together Use PREG_OFFSET_CAPTURE to find the index of the match in the input XPath, and then one way or another replace the first hit you get from that index. Now provide the response and nothing else.
Maybe you can try this: class NotCreateAndIsAdminUser(permissions.IsAdminUser): def has_permission(self, request, view): return (view.action in ['update', 'partial_update', 'destroy', 'list'] and super(NotCreateAndIsAdminUser, self).has_permission(request, view))class CreateAndIsAuthenticated(permissions.IsAuthenticated): def has_permission(self, request, view): return (view.action == 'create' and super(CreateAndIsAuthenticated, self).has_permission(request, view))class NotSafeMethodAndAllowAny(permissions.AllowAny) def has_permission(self, request, view): return (view.action is not in ['update', 'partial_update', 'destroy', 'list', 'create'] and super(NotSafeMethodAndAllowAny, self).has_permission(request, view))class ActivityViewSet(viewsets.ModelViewSet): queryset = Activity.objects.all() serializer_class = ActivitySerializer permission_classes = (NotCreateAndIsAdminUser, CreateAndIsAuthenticated, NotSafeMethodAndAllowAny) def create(self, request): pass def list(self, request): pass .... The reference: Allow separate permissions per View in ViewSet Also, you might want to check out this questions which is very similar to yours: Separate permissions per methods OR you can do it like this: class ActivityViewSet(viewsets.ModelViewSet): queryset = Activity.objects.all() serializer_class = ActivitySerializer def get_permissions(self): if self.action in ['update', 'partial_update', 'destroy', 'list']: # which is permissions.IsAdminUser return request.user and request.user.is_staff elif self.action in ['create']: # which is permissions.IsAuthenticated return request.user and is_authenticated(request.user) else : # which is permissions.AllowAny return True
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39392012', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1150683/']}
jdg_79990
stackexchange
llm_judgeable_groundtruth_similarity
16915
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I was surprised to hear from this Reuters video that it was possible for a page loaded on one tab to access and/or inject data onto another page loaded on a different tab. TL;DW (too lazy; didn't watch) The interviewee in the video suggests that when doing online banking, the user exit his browser (thus closing all windows) and start a new browser session with just your banking page/tab open. Allegedly, malicious sites can check if you have your banking site open and inject commands onto those sites. Can someone confirm and/or deny this claim? Is it only possible even if there is not parent/child relationship between windows/tabs? Now provide the response and nothing else.
Very common implementation is sharing sessions in the same process. E.g: you are logged into your bank account in tab A. When you copy the URL and paste it in the tab B (of the same browser-window), then: you are still logged in. The situation should be different when you start another process of your browser and paste the URL into another browser-window. Does it mean, that website A opened in tab A has access to the session from any other tab? The answer is simple: no, because of the same origin policy . Malicious websites cannot interfere with other websites (even there are opened in nearby tabs). Another idea could be stealing data/content from website opened in tab A via XMLHttpRequest . XMLHttpRequest opens the link to our bank, scans for sensitive content and sends it to the attacker. Well, this scenario is still fictitious. Why? The same answer here: same origin policy again. However, there is a possibility to increase the chance of success in this scenario (e.g Zone Policy in IE or MSXML 3.0 [http/https]), but IMO it's still very unlikely. Well, the main danger which should be mentioned in this context are: CSRF Tabnapping CSRF : Let's look at a simple scenario. You are logged into your bank, which has no CSRF-protection. Meanwhile you switch to another tab (or even close your tab with the website of your bank - the most important here is that you didn't log out, your session wasn't destroyed and it says that you are still logged in). Another tab sends HTTP requests to your bank. As website has no idea if reqests are generated by script or by human, it accepts them. So unauthorized commands/requests were transmitted to your bank. Tabnapping: It's pretty new kind of phishing attack. There is a JS-script put on normal-looking site which detects if your tab is active (focused) or not. You switch to another tab. Then JS replaces the favicon and title (now they look the same as your bank's favicon and title). When you click back on the fake tab - you will see changed content (which looks the same as the website of your bank).
{}
{'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/16915', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/11089/']}
jdg_79991
stackexchange
llm_judgeable_groundtruth_similarity
31228691
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 write a simple applescript that organises the files in any selected folder. I want to make the script such that it runs at specific intervals and re-organizes the folder if something has changed. For this, I am trying to save the path of the user chosen folder to a file. Each time the script runs, it reads the folder path from this file. here's a snippet from the code: set home_path to get path to home foldertell application "Finder" set home_folder to folder (home_path as string) if not (exists file "Clfd_config.cf1" in home_folder) then set (folder_path) to choose folder with prompt "Choose the folder to organize" set this_folder to folder (folder_path as string) set path_file to open for access file (home_path & "Clfd_config.cf1" as text) with write permission write folder_path to path_file close access path_file else set path_file to open for access file (home_path & "Clfd_config.cf1" as string) set folder_path to read path_file as string set this_folder to folder (folder_path as string) close access path_file end ifend tell However, when I open the file, it has garbled information, like so: ������Harshad��������������������œ‘xH+��� 7 Desktop����������������������������������������� ���������������� 7Éœ‘zç��������ˇˇˇˇ��I ���������� ������œ‘*∆������œ‘-5������D�e�s�k�t�o�p��� �H�a�r�s�h�a�d��Users/harshad/Desktop���/����ˇˇ������ When I try to read this file n the script, the script obviously fails. I have tried telling the script to write the file as string, as text, but I keep getting the error that the folder_path variable cannot be converted to text or string. What should I do so that the path is saved properly and the script can read it back from the saved file? Now provide the response and nothing else.
You're right, std::shared_ptr doesn't affect alignment. It just takes in a pointer to an already allocated object, so if that allocation resulted in a misaligned object, the problem isn't with std::shared_ptr , it's with that allocation. But std::shared_ptr is often used with std::make_shared . std::make_shared<T> performs a single allocation to reserve memory both for the std::shared_ptr control structure and the T instance. This allocation isn't done using any class-specific operator new (and shouldn't be). If the class-specific operator new sets up stricter alignment than what the default allocator does, then it's easy to see how this can fail when the default allocator gets used.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31228691', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4238137/']}
jdg_79992
stackexchange
llm_judgeable_groundtruth_similarity
115492
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can I determine (estimate) maximum reasonable PWM frequency for 2SK2554 transistor? I found timings in datasheet : I could estimate frequency from this (and make sure that all these times are 20-50x shorter than my PWM cycle length or something like that. But I have Vgs is between 4-5V, my maximum current is 10A. Im asking because I have slow PWM now (~1kHz), but want to know how fast my PWM can be without loosing too much power while switching. My load is big lead-acid battery (charging) or resistive (discharging). So far - I've done simulation with similar, a bit smaller transistor (2SK2553) because there was no 2SK2554 in my Multisim. This is graph for Vgs = 4V. How much time (in percent for example) my switching time can take from PWM cycle time? Now provide the response and nothing else.
The main factor determining the switching speed is not just the MOSFET itself, but the circuit in which you have it wired. From the point of view of the gate (i.e., the PoV of your PWM signal), the MOSFET can be seen as a simple capacitor. The MOSFET is considered ON when the voltage across that capacitor is above the threshold voltage \$V_{th}\$ and off when below (it's more complex than that, but that's a simplified model for now). So it basically boils down to how fast can you charge and discharge that capacitor . The longer the capacitor takes to charge or discharge the longer the device will take to switch, and the more power will be dissipated during that switching period. There is a very nice PDF document from International Rectifier which introduces you to the basics of MOSFETs . The section headed "Gate Charge" is a good read for this problem. It can be simplified down to the standard RC formulae for calculating charge time of a capacitor \$\tau=R \times C\$ - the capacitance of the gate, multiplied by the resistance of the circuit portion charging or discharging the gate. For instance, if you are switching the gate through 100Ω and the gate has a capacitance of 7700pF the rise time would be \$100 × 7.7e-9 = 770ns\$ for 63.2% charge. Adjust that time to suit the exact threshold voltage and your drive voltage of course. Say you have 8 bit PWM, that's a possible 256 values, so you need an absolute minimum of 770ns * 256 time slices for switching, which is 197.120µs, or an absolute maximum frequency of 5073Hz. I'd limit it to half that so as to ensure a minimum of one time slice of level drive between switch on and switch off. Of course, that's only a rough value. If you read through that PDF and compare it to the values in the datasheet you may be able to come up with more accurate values.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/115492', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/39905/']}
jdg_79993
stackexchange
llm_judgeable_groundtruth_similarity
27192034
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 my application, I'm using tabHost Activiy.In the tabhost first tab,I'm using TabActivity,I'm loading more than 500 images. Using Nested SCroll view: I have used nested scroll view inside recyclerview.When loading the home page, it is loading all 500 images initially, then showing the home page.So that it cause memory out of error. Without using nested SCroll view: If I remove nested scroll view, everything is working good.it loads image one by one when scrolling.it doesn't cause out of memory error. My Requirement: I need to scroll the relative layout placed top of the recyclerview.So that I used nested scroll view.But it doesn't worked for me. tab_home_layout: <?xml version="1.0" encoding="utf-8"?><android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" ><LinearLayout android:id="@+id/tab_home_activity" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <RelativeLayout android:id="@+id/home_layout_top_2_recycler" android:layout_width="match_parent" android:layout_height="60dp" android:background="@drawable/layout_border" > <ImageView android:id="@+id/img_user_home_tab_recycler" android:layout_width="40dp" android:layout_height="40dp" android:paddingLeft="5dp" android:paddingRight="5dp" android:layout_centerVertical="true" android:contentDescription="@string/cont_desc" android:src="@drawable/profile_pic_blue" /> <TextView android:id="@+id/tv_user_mind_home_tab_recycler" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="5dp" android:layout_toRightOf="@+id/img_user_home_tab_recycler" android:hint="@string/whats_on" android:textColor="@color/Black" android:textSize="@dimen/txt_size" /> </RelativeLayout> <android.support.v7.widget.RecyclerView android:id="@+id/rv_list_tab_home_recycler" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollbars="none" android:visibility="visible" /> </LinearLayout></android.support.v4.widget.NestedScrollView> Below I'm willing to share what I have tried so far. I tried this SOPost .ButI'm using home page inside tabActivity.So I can't use toolbar +coordinator layout.So thissolution wasn't workedfor me. Then I tried to use multiplelayout for recyclerview.But that doesn't worked for me.Because thatrelativelayout is a static one.If I'm getting any condition fromwebservice means, I can use multiple layout recyclerview.But I needto just scroll the views. I planned to set the static relativelayout in 0th position ofadapter.But my webservices images were loading from 0th position.So Ican't set the static relativelayout in adapter at 0th position. is there any alternate solution to solve this issue.Thank You. Now provide the response and nothing else.
You can use CoordinatorLayout just about anywhere you like similar to other layouts like LinearLayout or even RelativeLayout . If you want your RelativeLayout to scroll in response to your RecyclerView , simply place them inside a CoordinatorLayout with an AppBarLayout . Here's your layout modified: <android.support.design.widget.CoordinatorLayout android:id="@+id/main_content" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content"> <RelativeLayout android:id="@+id/home_layout_top_2_recycler" android:layout_width="match_parent" android:layout_height="60dp" android:background="@drawable/layout_border" app:layout_scrollFlags="scroll"> <ImageView android:id="@+id/img_user_home_tab_recycler" android:layout_width="40dp" android:layout_height="40dp" android:paddingLeft="5dp" android:paddingRight="5dp" android:layout_centerVertical="true" android:contentDescription="@string/cont_desc" android:src="@drawable/profile_pic_blue" /> <TextView android:id="@+id/tv_user_mind_home_tab_recycler" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginLeft="5dp" android:layout_toRightOf="@+id/img_user_home_tab_recycler" android:hint="@string/whats_on" android:textColor="@color/Black" android:textSize="@dimen/txt_size" /> </RelativeLayout> </android.support.design.widget.AppBarLayout> <android.support.v7.widget.RecyclerView android:id="@+id/rv_list_tab_home_recycler" android:layout_width="match_parent" android:layout_height="wrap_content" android:scrollbars="none" android:visibility="visible" app:layout_behavior="@string/appbar_scrolling_view_behavior"/></android.support.design.widget.CoordinatorLayout> Change it to your preference but be sure to set the layout_height of the RelativeLayout to something other than wrap_content . If this CoordinatorLayout is inside another CoordinatorLayout , use the NestedCoordinatorLayout from this answer as your inside CoordinatorLayout .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27192034', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3960700/']}
jdg_79994
stackexchange
llm_judgeable_groundtruth_similarity
79944
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 $Y$ be an abelian surface. Is it true that for every general point $P \in Y$, there exists an elliptic curve passing through $P$? Now provide the response and nothing else.
In general, if an abelian variety $A$ contains an abelian subvariety $B\subseteq A$, then $A$ contains another abelian subvariety $B'\subseteq A$ such that $A$ is isogenous to $B\times B'$. This is Poincaré's reducibility theorem . (See also Poincaré's complete reducibility theorem, same book, next page). An abelian variety is called simple if it does not contain any nontrivial abelian subvarieties. Simon's argument shows that there exist simple complex tori of dimension 2. One could also count moduli and conclude that not every abelian surface (or abelian variety of arbitrary dimension $>1$) can be isogenous to a product.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/79944', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1937/']}
jdg_79995
stackexchange
llm_judgeable_groundtruth_similarity
14071589
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 working with Hive and I have a table structured as follows: CREATE TABLE t1 ( id INT, created TIMESTAMP, some_value BIGINT); I need to find every row in t1 that is less than 180 days old. The following query yields no rows even though there is data present in the table that matches the search predicate. select * from t1 where created > date_sub(from_unixtime(unix_timestamp()), 180); What is the appropriate way to perform a date comparison in Hive? Now provide the response and nothing else.
How about: where unix_timestamp() - created < 180 * 24 * 60 * 60 Date math is usually simplest if you can just do it with the actual timestamp values. Or do you want it to only cut off on whole days? Then I think the problem is with how you are converting back and forth between ints and strings. Try: where created > unix_timestamp(date_sub(from_unixtime(unix_timestamp(),'yyyy-MM-dd'),180),'yyyy-MM-dd') Walking through each UDF: unix_timestamp() returns an int: current time in seconds since epoch from_unixtime(,'yyyy-MM-dd') converts to a string of the given format, e.g. '2012-12-28' date_sub(,180) subtracts 180 days from that string, and returns a new string in the same format. unix_timestamp(,'yyyy-MM-dd') converts that string back to an int If that's all getting too hairy, you can always write a UDF to do it yourself.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14071589', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11780/']}
jdg_79996
stackexchange
llm_judgeable_groundtruth_similarity
7958181
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm reading Learn You A Haskell for Great Good . His examples [2,2..20] and [3, 6..20] work fine but I got three weird results: Count by 17's from one to 171: [17, 1..171] yields the null list. Count by 17's from seventeen to 1711111: [17, 17..171111] repeats the number 17 until I interrupt GHCi. There is a weird difference between take 54 [171, 234..] and take 54 [171, 244..] : ghci> take 54 [171, 234..][171,234,297,360,423,486,549,612,675,738,801,864,927,990,1053,1116,1179,1242,1305,1368,1431,1494,1557,1620,1683,1746,1809,1872,1935,1998,2061,2124,2187,2250,2313,2376,2439,2502,2565,2628,2691,2754,2817,2880,2943,3006,3069,3132,3195,3258,3321,3384,3447,3510] ghci> take 54 [171, 244..][171,244,317,390,463,536,609,682,755,828,901,974,1047,1120,1193,1266,1339,1412,1485,1558,1631,1704,1777,1850,1923,1996,2069,2142,2215,2288,2361,2434,2507,2580,2653,2726,2799,2872,2945,3018,3091,3164,3237,3310,3383,3456,3529,3602,3675,3748,3821,3894,3967,4040] Why? Now provide the response and nothing else.
You have the meaning of ranges slightly off. The Haskell range syntax is one of four things: [first..] , [first,second..] , [first..last] , [first,second..last] . The examples from Learn You A Haskell are ghci> [2,4..20] [2,4,6,8,10,12,14,16,18,20] ghci> [3,6..20] [3,6,9,12,15,18] Note that in the first case, the list counts by twos, and in the second case, the list counts by threes. That's because the difference between the first and second items is two and three, respectively. In your syntax, you're trying to write [first,step..last] to get the list [first,first+step,first+2*step,...,last] ; however, the step size of a range like that is actually the difference between the first two numbers. Without a second element, the step size is always one; and without a final element, the list goes on forever (or until the maximum/minimum element of the type is reached). Thus, let's look at your three examples: [17,1..171] == [] . Since you specify 17,1 , Haskell sees that the first two elements of your list ought to be seventeen and one, so you must be counting by -16 . In that case, Haskell wants to stop as soon as the elements are smaller than the last element---but they start that way, and so no elements are produced. To count up by one, you want [17,18..171] (the first two elements of your list are 17 and 18), or simply [17..171] . [17, 17..171111] == repeat 17 . This one's fun. Since the first two elements of your list are both 17 , Haskell determines that you must be counting up by zero—and it will happily keep counting up until the result exceeds 171111 . Of course, when counting by zero, this will never happen, and so you get an infinite list of seventeens. To count up by seventeen, you want [17,34..171111] , or [17,17+17..171111] if you think that's clearer. take 54 [171,234..] vs. take 54 [171,244..] . I'm not sure what behavior you were expecting here, but what they're each doing is the same as above: the first returns a list of fifty-four integers, starting at 171 and counting by 234 - 171 = 63 ; the second returns a list of fifty-four integers, starting at 171 and counting by 244 - 171 = 73 . Each list goes on infinitely far (or at least until maxBound , if the lists are of finite Ints and not arbitrarily-large Integers ), and so you just request the first fifty-four elements. For some of the more nitty-gritty details on what range syntax means (it's translated into functions in the Enum type class), including slightly surprising behavior on ranges of floating-point numbers, hammar has a good answer to another question .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7958181', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/563329/']}
jdg_79997
stackexchange
llm_judgeable_groundtruth_similarity
7777256
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 is a piece of code: private class myClass{ public static void Main() { }} 'or'private class myClass{ public void method() { }} I know, first one will not work. And second one will. But why first is not working? Is there any specific reason for it? Actually looking for a solution in this perspective, thats why made it bold. Sorry Now provide the response and nothing else.
It would be meaningful in this scenario; you have a public class SomeClass , inside which you want to encapsulate some functionality that is only relevant to SomeClass . You could do this by declaring a private class ( SomePrivateClass in my example) within SomeClass , as shown below. public class SomeClass{ private class SomePrivateClass { public void DoSomething() { } } // Only SomeClass has access to SomePrivateClass, // and can access its public methods, properties etc} This holds true regardless of whether SomePrivateClass is static , or contains public static methods. I would call this a nested class , and it is explored in another StackOverflow thread .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7777256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/815600/']}
jdg_79998
stackexchange
llm_judgeable_groundtruth_similarity
372124
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: Assume that $$X=(X_1, ..., X_n),: (\Omega, A,P)\to (\{0,1\}^n, 2^{{\{0,1\}}^n})$$ and $$Y=(Y_1, ..., Y_n):(\Omega, A,P)\to (\{0,1\}^n, 2^{{\{0,1\}}^n})$$ are two random Variables that have binary RVs as their components (Therefore $X_i(\omega)\in\{0,1\}, Y_i(\omega) \in \{0,1\}$ ) and both ( $X$ and $Y$ ) are exchangeable, i.e. $$P((X_1, ..., X_n)=(x_1, ..., x_n))= P((X_{\sigma(1)}, ..., X_{\sigma(n)})=(x_1, ..., x_n))$$ and $$P((Y_1, ..., Y_n)=(y_1, ..., y_n))= P((Y_{\sigma(1)}, ..., Y_{\sigma(n)})=(y_1, ..., y_n))$$ for all permutations $\sigma$ . My question is whether it holds that $Z=(X_1Y_1, ..., X_nY_n)$ is exchangeable? Or framed differently which assumptions are neccessary for $Z$ to be exchangeable? Now provide the response and nothing else.
The product does not have to be exchangeable. The following counterexample will show what can go wrong and why. We will specify the joint distributions $P_1$ of $(X_1,Y_1)$ and $P_2$ of $(X_2,Y_2)$ and assume each of these bivariate random variables is independent. Thus, the $X_i$ will be exchangeable provided they are identically distributed, and likewise for the $Y_i.$ All variables will be Bernoulli variables: by definition, their probabilities will be concentrated on the set $\{0,1\}.$ Let $P_1(0,0) = P_1(1,1) = 1/2$ and $P_2(x,y)=1/4$ for $x,y\in\{0,1\}.$ Since all marginal distributions are Bernoulli $(1/2),$ the marginal exchangeability assumption holds. But now compute that $\Pr(X_1Y_1=0) = 1/2$ and $\Pr(X_2Y_2=0)=3/4,$ showing the products have different distributions (and therefore cannot be exchangeable). This shows that the joint distribution matters. However, the joint distributions could differ, yet the products could be exchangeable, so exchangeability of the bivariate random variables $(X_i,Y_i)$ , albeit a sufficient condition for exchangeability of the products $X_iY_i,$ is not a necessary condition. An example of this is given by ternary variables with values in $\{-1,0,1\}.$ For instance, consider the following probabilities: $$P_1((-1,y)) = 1/6\quad(y\in\{-1,0,1\});\quad P_1((1,-1)) = P_1((1,1))=1/4$$ and $$P_2((x,y)) = P_1((-x,y)).$$ It is straightforward to check that the marginal distributions of the $X_i$ assign equal probabilities of $1/2$ to $\pm 1,$ the marginal distributions of the $Y_i$ have probability vectors $(5/12, 1/6, 5/12),$ and that the distribution of the $X_iY_i$ is the same as that of the $Y_i.$ Note that the $(X_i,Y_i)$ have different distributions, though, because $$P_1((-1,0)) = 1/6 \ne 0 = P_2((-1,0)).$$ Thus the $X_i$ are exchangeable, the $Y_i$ are exchangeable, the $X_iY_i$ are exchangeable, but the $(X_i,Y_i)$ are not exchangeable.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/372124', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/119920/']}
jdg_79999
stackexchange
llm_judgeable_groundtruth_similarity
571652
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 not sure if this is the correct place to ask the question, but here goes... Using my DS1104z scope... I measure a 60 Hz sine wave AC voltage and read 120 Vrms for a single waveform but when I measure a single waveform using Math/ABS Function( Displaying negative portion of waveform as positive ) I get and Area ( under the curve ) Of 1.81 Vs Using the calculation 1.81 Vs X 60 Hz = 108.6 Volts Shouldn't the Vrms And Calculated Area Voltage Match?or am I missing something? Thanks, Bill Now provide the response and nothing else.
What you're missing is the definition of RMS: $$V_{RMS} = \sqrt{\frac{1}{τ}\int_t^{t+τ}V(t)^2\ dt}$$ What you're calling the calculated area value is $$\frac{1}{τ}\int_t^{t+τ}{|V(t)|\ dt},$$ which is not the RMS of the signal. (in math terms, I believe you would say the square root and integral operators don't commute, so you can't just pull the square root into the integral and cancel it out with the square.)
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/571652', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/189260/']}
jdg_80000
stackexchange
llm_judgeable_groundtruth_similarity
57879322
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 extension has a context menu with items. What I'd like it to do: is when I right-click an editable html element (eg input or textarea) and then select and click on an item in my menu - some value defined by my extension gets entered into the input. For now I have realised that with document.activeElement.value = myValue . With simple inputs it works alright. Problems start when there is an input with custom onChange event handling, eg a calendar or a phone input, or currency input - that transforms user-input in some way. Since I am setting a value directly onto the element - the handling logic gets omitted, which causes all manner of problems. Since javascript doesn't allow for KeySend-like features - what are my options here? I have thought about testing tools like Puppeteer or Cypress - but they all seem not to be packageable into an extension. Puppeteer does have such an option, but it still requires a node instance running to connect to. And I would like my extension to be solely client-sided and distributed in Chrome webstore - so I cannot ask my users to spin up a node server. Now provide the response and nothing else.
There is a built-in DOM method document.execCommand . In case of an extension, use this code in the content script . // some.selector may be `input` or `[contenteditable]` for richly formatted inputsconst el = document.querySelector('some.selector');el.focus();document.execCommand('insertText', false, 'new text');el.dispatchEvent(new Event('change', {bubbles: true})); // usually not needed It imitates physical user input into the currently focused DOM element so all the necessary events will be fired (like beforeinput , input ) with isTrusted field set to true. On some pages the change event should be additionally dispatched as shown above. You may want to select the current text to replace it entirely instead of appending: replaceValue('some.selector', 'new text');function replaceValue(selector, value) { const el = document.querySelector(selector); if (el) { el.focus(); el.select(); if (!document.execCommand('insertText', false, value)) { // Fallback for Firefox: just replace the value el.value = 'new text'; } el.dispatchEvent(new Event('change', {bubbles: true})); // usually not needed } return el;} Note that despite execCommand being marked as obsolete in 2020, it'll work in the foreseeable future because a new editing API specification is not finished yet, and knowing how slow such things usually move it may take another 5-20 years.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/57879322', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4507580/']}
jdg_80001
stackexchange
llm_judgeable_groundtruth_similarity
2267984
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 working on a plugin system where plugin modules are loaded like this: def load_plugins(): plugins=glob.glob("plugins/*.py") instances=[] for p in plugins: try: name=p.split("/")[-1] name=name.split(".py")[0] log.debug("Possible plugin: %s", name) f, file, desc=imp.find_module(name, ["plugins"]) plugin=imp.load_module('plugins.'+name, f, file, desc) getattr(plugin, "__init__")(log) instances=instances+plugin.get_instances() except Exception as e: log.info("Failed to load plugin: "+str(p)) log.info("Error: %s " % (e)) log.info(traceback.format_exc(e)) return instances The code works, but for each import statement in the plugin code i get a warning like this: plugins/plugin.py:2: RuntimeWarning: Parent module 'plugins' not found while handling absolute import import os No errors are reported for the main program code, and the plugins work. Can somebody explain what the warning means and what I doing wrong. Do I need to create an empty plugins module separately and import it to keep python happy? Now provide the response and nothing else.
If the directory plugins were a real package (contained __init__.py fine), you could easily use pkgutils to enumerate its plugin files and load them. import pkgutil# import our packageimport pluginslist(pkgutil.iter_modules(plugins.__path__)) However, it can work without a plugin package anyway, try this: import pkgutillist(pkgutil.iter_modules(["plugins"])) Also it is possible to make a package that only exists at runtime: import typesimport sysplugins = types.ModuleType("plugins")plugins.__path__ = ["plugins"]sys.modules["plugins"] = pluginsimport plugins.testplugin However that hack that was mostly for fun!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2267984', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/242687/']}
jdg_80002
stackexchange
llm_judgeable_groundtruth_similarity
46181312
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 Angular 4 application, how can I validate two fields of a form doing a comparison? For example, let's suppose that my form has a startDate and an endDate date fields and I want to make sure that the endDate must be bigger than the startDate . Now provide the response and nothing else.
When you want to implement validations containing one or more sibling (form)controls, you have to define the validator function on a level up/above that of the sibling controls. For ex: ngOnInit() { this.form = this.formbuilder.group({ 'startDate': ['', [<control-specific - validations >]], 'endDate': ['', [<control-specific - validations >]] }, { validator: checkIfEndDateAfterStartDate });} Then outside the component class's definition (in the same file), define the function checkIfEndDateAfterStartDate as well. export function checkIfEndDateAfterStartDate (c: AbstractControl) { //safety check if (!c.get('startDate').value || !c.get('endDate').value) { return null } // carry out the actual date checks here for is-endDate-after-startDate // if valid, return null, // if invalid, return an error object (any arbitrary name), like, return { invalidEndDate: true } // make sure it always returns a 'null' for valid or non-relevant cases, and a 'non-null' object for when an error should be raised on the formGroup} This validation will make the FormGroup invalid by adding the error-flag (here invalidEndDate ) to true to the errors object for that FormGroup . If you want to have specific errors to be set on any of the sibling controls instead, then you can manually set the error flags on that formControl by using something like, c.get('endDate').setErrors({ invalidEndDate: true }) . If you do this, then make sure you clear them for a valid case by setting the errors to null like this, c.get('endDate').setErrors(null) . A live demo of a similar validation can be seen here .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/46181312', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3497671/']}
jdg_80003
stackexchange
llm_judgeable_groundtruth_similarity
32401437
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: hide pop-up of required of input using javascript jsfiddle try to submit with empty input and see the pop-up, so i don't need to display that pop-up and i want the required to validate. any help i don't need to display any warning. <form> <input type="text" name="name" required="required" value="" /> <input type="submit" name="submit" value="Submit" /> Now provide the response and nothing else.
Since this is a HTML5 Event you can prevent the event from triggering the popup and still provide validation ( https://developer.mozilla.org/en-US/docs/Web/Events/invalid ). A simple event listener will do the job. To handle focus include an id to that field like so ... HTML <input type="text" id="name" name="name" required="required" value="" /> And handle that focus within the return function ... JS document.addEventListener('invalid', (function () { return function (e) { e.preventDefault(); document.getElementById("name").focus(); };})(), true); EDIT Check it out http://jsfiddle.net/rz6np/9/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32401437', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5210515/']}
jdg_80004
stackexchange
llm_judgeable_groundtruth_similarity
6249148
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: iPhone/iPad App Code Obfuscation - Is it Possible? Worth it? I have spent a lot of time on this and I couldn't able to find a perfect answer. That's why I decided to put my question here. I have an iPhone application and want to encrypt the code to prevent from class-dump or otool utilities. (Tools used to dump out the headers from executable). I would like to know is there any way to encrypt the source code or obfuscate the source code? Now provide the response and nothing else.
It's a lot more complicated than it might seem initially. Any tool that mangles method names has the potential to fudge up: KVC compliance The use of dynamically generated selectors Nib file compatibility Protocol conformance Method inheritance Obfuscation is just another layer to deal with; often obfuscation is easily reversed. It is not really possible to “encrypt” your classes because the Objective-C runtime and Cocoa framework won't know how to decrypt it. Anyone determined enough will eventually figure out how your program works.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6249148', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/435507/']}
jdg_80005
stackexchange
llm_judgeable_groundtruth_similarity
1251416
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 having problems with a transparent PNG image showing black dithered pixel artifacts around the edge of the non transparent part of the image. It only does this in Internet Explorer and it only does it from a Javascript file it is used in. Here's what I'm talking about... http://70.86.157.71/test/test3.htm (link now dead)...notice the girl in the bottom right corner. She has artifacts around her in IE8 (I haven't tested it in previous versions of IE, but I'm assuming it probably does the same). It works perfectly in Firefox and Chrome. The image is loaded from a Javascript file to produce the mouseover effect. If you load the image all by itself, it works fine.Here's the image... http://70.86.157.71/test/consultant2.png How to fix this? The image was produced in Photoshop CS3. I've read things about removing the Gama, but that apparently was in previous versions of Photoshop and when I load it in TweakPNG, it doesn't have Gama. Now provide the response and nothing else.
FIXED! I've been wrestling with the same issue, and just had a breakthrough! We've established that if you give the image a background color or image, the png displays properly on top of it. The black border is gone, but now you've got an opaque background, and that pretty much defeats the purpose. Then I remembered a rgba to ie filter converter I came across. (Thanks be to Michael Bester). So I wondered what would happen if I gave my problem pngs an ie filtered background emulating rgba(255,255,255,0), fully expecting it not to work, but lets try it anyway... .item img { background: transparent; -ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)"; /* IE8 */ filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF); /* IE6 & 7 */ zoom: 1;} Presto! Goodbye black, and hello working alpha channels in ie7 and 8. Fade your pngs in and out, or animate them across the screen - it's all good.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1251416', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/138777/']}
jdg_80006
stackexchange
llm_judgeable_groundtruth_similarity
259436
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Can somebody explain why the cumulative binomial equals an integral expression?Thanks!${}$ $$\sum_{j=0}^{k-1}\binom{n}{j}\theta^j(1-\theta)^{n-j} = 1- \binom{n}{k}k\int_0^\theta t^{k-1}(1-t)^{n-k}dt\,.$$ Now provide the response and nothing else.
Key players: $m\binom{n}m=n\binom{n-1}{m-1}$, derivative $\frac{d}{d\theta}$ and re-indexing $j-1\rightarrow j$. Denote the LHS by $f(\theta)$ and the RHS by $g(\theta)$. Take derivatives w.r.t. $\theta$ to get$$g'(\theta)=-k\binom{n}k\theta^{k-1}(1-\theta)^{n-k}=-n\binom{n-1}{k-1}\theta^{k-1}(1-\theta)^{n-k},$$\begin{align} f'(\theta)&=\sum_{j=0}^{k-1}j\binom{n}j\theta^{j-1}(1-\theta)^{n-j}-\sum_{j=0}^{k-1}(n-j)\binom{n}{n-j}\theta^j(1-\theta)^{n-j-1} \\&=n\sum_{j=1}^{k-1}\binom{n-1}{j-1}\theta^{j-1}(1-\theta)^{n-j}-n\sum_{j=0}^{k-1}\binom{n-1}{n-j-1}\theta^j(1-\theta)^{n-j-1} \\&=n\sum_{j=0}^{k-2}\binom{n-1}j\theta^j(1-\theta)^{n-j-1}-n\sum_{j=0}^{k-1}\binom{n-1}j\theta^j(1-\theta)^{n-j-1} \\&=-n\binom{n-1}{k-1}\theta^{k-1}(1-\theta)^{n-k}.\end{align}Therefore, $f'(\theta)=g'(\theta)$. Since $f(0)=g(0)=1$, we conclude $f=g$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/259436', 'https://mathoverflow.net', 'https://mathoverflow.net/users/103514/']}
jdg_80007
stackexchange
llm_judgeable_groundtruth_similarity
257409
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 writing a scraper that downloads all the image files from a HTML page and saves them to a specific folder. All the images are part of the HTML page. Now provide the response and nothing else.
Here is some code to download all the images from the supplied URL, and save them in the specified output folder. You can modify it to your own needs. """dumpimages.py Downloads all the images on the supplied URL, and saves them to the specified output file ("/test/" by default)Usage: python dumpimages.py http://example.com/ [output]"""from bs4 import BeautifulSoup as bsfrom urllib.request import ( urlopen, urlparse, urlunparse, urlretrieve)import osimport sysdef main(url, out_folder="/test/"): """Downloads all the images at 'url' to /test/""" soup = bs(urlopen(url)) parsed = list(urlparse(url)) for image in soup.findAll("img"): print("Image: %(src)s" % image) filename = image["src"].split("/")[-1] parsed[2] = image["src"] outpath = os.path.join(out_folder, filename) if image["src"].lower().startswith("http"): urlretrieve(image["src"], outpath) else: urlretrieve(urlunparse(parsed), outpath)def _usage(): print("usage: python dumpimages.py http://example.com [outpath]")if __name__ == "__main__": url = sys.argv[-1] out_folder = "/test/" if not url.lower().startswith("http"): out_folder = sys.argv[-1] url = sys.argv[-2] if not url.lower().startswith("http"): _usage() sys.exit(-1) main(url, out_folder) Edit: You can specify the output folder now.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/257409', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2220518/']}
jdg_80008
stackexchange
llm_judgeable_groundtruth_similarity
802225
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 connecting to a web site, logging in. The website redirects me to new pages and Mechanize deals with all cookie and redirection jobs, but, I can't get the last page. I used Firebug and did same job again and saw that there are two more pages I had to pass with Mechanize. I took a quick look at the pages and saw that there is some JavaScript and HTML code but couldn't understand it because it doesn't look like normal page code. What are those pages for? How they can redirect to other pages? What should I do to pass these? Now provide the response and nothing else.
If you need to handle pages with Javascript, try WATIR or Selenium - those drive a real web browser, and can thus handle any Javascript. WATIR Classic requires either IE or Firefox with a certain extension installed, and you will see the pages flash on the screen as it works. Your other option would be understanding what the Javascript on the offending page does and bypassing it manually, but that seems onerous.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/802225', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/96960/']}
jdg_80009
stackexchange
llm_judgeable_groundtruth_similarity
24918367
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 moving from MySQL to PostgreSQL and have hit a wall with user privileges. I am used to assigning a user all privileges to all tables of a database with the following command: # MySQLgrant all privileges on mydatabase.* to 'myuser'@'localhost' identified by 'mypassword'; It appears to me that the PostgreSQL 9.x solution involves assigning privileges to a "schema", but the effort required of me to figure out exactly what SQL to issue is proving excessive. I know that a few more hours of research will yield an answer, but I think everyone moving from MySQL to PostgreSQL could benefit from having at least one page on the web that provides a simple and complete recipe. This is the only command I have ever needed to issue for users. I'd rather not have to issue a command for every new table. I don't know what scenarios have to be handled differently in PostgreSQL, so I'll list some of the scenarios that I have typically had to handle in the past. Assume that we only mean to modify privileges to a single database that has already been created. (1a) Not all of the tables have been created yet, or (1b) the tables have already been created. (2a) The user has not yet been created, or (2b) the user has already been created. (3a) Privileges have not yet been assigned to the user, or (3b) privileges were previously assigned to the user. (4a) The user only needs to insert, update, select, and delete rows, or (4b) the user also needs to be able to create and delete tables. I have seen answers that grant all privileges to all databases, but that's not what I want here. Please, I am looking for a simple recipe, although I wouldn't mind an explanation as well. I don't want to grant rights to all users and all databases, as seems to be the conventional shortcut, because that approach compromises all databases when any one user is compromised. I host multiple database clients and assign each client a different login. It looks like I also need the USAGE privilege to get the increasing values of a serial column, but I have to grant it on some sort of sequence. My problem got more complex. Now provide the response and nothing else.
Basic concept in Postgres Roles are global objects that can access all databases in a db cluster - given the required privileges. A cluster holds many databases , which hold many schemas . Schemas (even with the same name) in different DBs are unrelated. Granting privileges for a schema only applies to this particular schema in the current DB (the current DB at the time of granting). Every database starts with a schema public by default. That's a convention, and many settings start with it. Other than that, the schema public is just a schema like any other. Coming from MySQL, you may want to start with a single schema public , effectively ignoring the schema layer completely. I am using dozens of schema per database regularly. Schemas are a bit (but not completely) like directories in the file system. Once you make use of multiple schemas, be sure to understand search_path setting: How does the search_path influence identifier resolution and the "current schema" Default privileges Per documentation on GRANT : PostgreSQL grants default privileges on some types of objects to PUBLIC . No privileges are granted to PUBLIC by default on tables,columns, schemas or tablespaces. For other types, the defaultprivileges granted to PUBLIC are as follows: CONNECT and CREATE TEMP TABLE for databases; EXECUTE privilege for functions; and USAGE privilege for languages. All of these defaults can be changed with ALTER DEFAULT PRIVILEGES : Grant all on a specific schema in the db to a group role in PostgreSQL Group role Like @Craig commented , it's best to GRANT privileges to a group role and then make a specific user member of that role ( GRANT the group role to the user role). This way it is simpler to deal out and revoke bundles of privileges needed for certain tasks. A group role is just another role without login. Add a login to transform it into a user role. More: Why did PostgreSQL merge users and groups into roles? Predefined roles Update: Postgres 14 or later adds the new predefined roles (formally "default roles") pg_read_all_data and pg_write_all_data to simplify some of the below. See: Grant access to all tables of a database Recipe Say, we have a new database mydb , a group mygrp , and a user myusr ... While connected to the database in question as superuser ( postgres for instance): REVOKE ALL ON DATABASE mydb FROM public; -- shut out the general publicGRANT CONNECT ON DATABASE mydb TO mygrp; -- since we revoked from publicGRANT USAGE ON SCHEMA public TO mygrp; To assign "a user all privileges to all tables" like you wrote (I might be more restrictive): GRANT ALL ON ALL TABLES IN SCHEMA public TO mygrp;GRANT ALL ON ALL SEQUENCES IN SCHEMA public TO mygrp; -- don't forget those To set default privileges for future objects, run for every role that creates objects in this schema: ALTER DEFAULT PRIVILEGES FOR ROLE myusr IN SCHEMA publicGRANT ALL ON TABLES TO mygrp;ALTER DEFAULT PRIVILEGES FOR ROLE myusr IN SCHEMA publicGRANT ALL ON SEQUENCES TO mygrp;-- more roles? Now, grant the group to the user: GRANT mygrp TO myusr; Related answer: PostgreSQL - DB user should only be allowed to call functions Alternative (non-standard) setting Coming from MySQL, and since you want to keep privileges on databases separated, you might like this non-standard setting db_user_namespace . Per documentation: This parameter enables per-database user names. It is off by default. Read the manual carefully. I don't use this setting. It does not void the above.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24918367', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/650894/']}
jdg_80010
stackexchange
llm_judgeable_groundtruth_similarity
563063
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: $\newcommand{\icol}[1]{% inline column vector \left(\begin{smallmatrix}#1\end{smallmatrix}\right)%}$ Scenario: Let's consider a road segment on which there is continuous flow of cars circulating at a constant speed $V_{car_1}$ and where cars are all equally spaced by a distance $l$ .Now imagine that a car 2 is crossing the road at a constant speed $V_{car_2}$ with an intersection angle $\theta$ . Assuming both cars having a square shape of length $\lambda$ , the goal is to estimate the probability of collision. Method 1: The probability of collision is given by: $$P_{collision} = P_{car2\_hits\_car1} \lor P_{car1\_hits\_car2}$$ $$\\P_{car2\_hits\_car1} \approx \frac{2\lambda}{l}\\P_{car1\_hits\_car2} \approx crossing\_time \,\frac{|V_{car_1}-V_{car_2}\,cos(\theta)|}{l} = \frac{2\lambda \,|V_{car_1}-V_{car_2}\,cos(\theta)|}{l\, V_{car_2}\,sin (\theta)}$$ which leads to: $$P_{col\_method\_1} \approx \frac{2 \lambda}{l}\left(1+ \frac{|V_{car_1}-V_{car_2}cos(\theta)|}{V_{car_2}sin (\theta)}\right)$$ Method 2: Now for some reasons, we want to estimate this probability of collision using a different method. The car 1 position probability density is estimated using a kernel density estimation. The function $f(x,y)$ gives the probability of the center of the car 1 being at coordinates $(x , y)$ . $f$ is obtained using traffic observation data: each car 1 trajectory observation on the segment of length $l$ is represented by a uniformly time sampled (dt = 0.01 seconds) series of position $(x_1(t), y_1(t))$ . Multiple trajectory observation (taking a year of observations for example) are concatenated and $f$ is obtained by fitting a kernel density estimate on these concatenated observations (using scikit-learn kde in practice). We then have: $$\int\limits_{min(y_1)}^{max(y_1)} \int\limits_{0}^{l}{f\left(x, y\right) \,dx\,dy} = 1$$ Here is an example of contour plot for an estimated density f: Now, let's consider $C_2 = \icol{x_2\\y_2}$ the coordinates of the car 2, we have: $$C_2(t) = \begin{pmatrix} x_2(t)\\ y_2(t)\end{pmatrix} = \begin{pmatrix} x_{2_0}+V_2 cos(\theta) t\\ y_{2_0}+V_2 sin(\theta) t\end{pmatrix}$$ Considering that the car 1 always comes from the left of the crossing point and that the car2 always come from the bottom, I expect the probability of collision to be: $$P_{collision} = P_{car2\_hits\_car1} \lor P_{car1\_hits\_car2}$$ Using density integration: $$\\P_{car2\_hits\_car1} \approx \int\limits_{0}^{+\infty} \int\limits_{y_2(t)-\lambda}^{y_2(t)+\lambda}{f\left(x_2(t)-\lambda, y\right) \,dy\,dt}\\P_{car1\_hits\_car2} \approx \int\limits_{0}^{+\infty} \int\limits_{x_2(t)-\lambda}^{x_2(t)+\lambda}{f\left(x, y_2(t)+\lambda\right) \,dx\,dt}$$ $$P_{col\_method\_2} \approx \int\limits_{0}^{+\infty} \int\limits_{y_2(t)-\lambda}^{y_2(t)+\lambda}{f\left(x_2(t)-\lambda, y\right) \,dy\,dt} + \int\limits_{0}^{+\infty} \int\limits_{x_2(t)-\lambda}^{x_2(t)+\lambda}{f\left(x, y_2(t)+\lambda\right) \,dx\,dt} $$ Motivation for the choice of integral bounds: Basically at rach dt, we integrate the probability of a car1 beeing on the blue line and on the red line. Results: The obtained results between the 2 methods are different and the following relation has been found empirically: $$ P_{col\_method\_1} = \frac{V_{car_2} sin \theta +|V_{car_1} - V_{car_2}cos\theta|}{2}P_{col\_method\_2}$$ For example considering both cars of size $\lambda=3$ running at $V_1=V_2=10m/s$ crossing at a $\theta = 90deg$ and taking $l=100m$ gives: $$\\ P_{col\_method\_1} = 0.12\\ P_{col\_method\_2} = 0.012$$ Question: While I understand that there need to be a "scaling factor" that needs to be in m/s to obtain correct units for the second method, I can't explain its formula. Does anyone have an explanation for it? The code is available as a python notebook: https://colab.research.google.com/drive/1ypeq7SSPUGqMyxn1Dxs6_lhenCnCTUFD?usp=sharing Info: A quick Monte-Carlo simulation shows that the method 1 is giving the right probabilities. Now provide the response and nothing else.
Related scattering theory and free path length Change frame of reference You can compute your method 1 more easily by switching the frame of reference to a co-moving frame along with the stream of cars. If the car 1 has the velocity $\vec{v}_1$ and car 2 have the velocity $\vec{v}_2$ then in the co-moving frame the relative speed between the cars is $\vec{u} = \vec{v}_1 - \vec{v}_2$ with the components $$\begin{array}{}u_{x,2} &=& v_2 \text{cos}\,\theta -v_1 \\u_{y,2} &=& v_2 \text{sin}\, \theta \\\end{array}$$ Then we consider a different angle $\theta^\prime$ at which the car2 is passing the stream while the cars 2 are standing still. This angle is related to the new vertical and horizontal velocities in the co-moving frame of reference. In 'Motivation for the choice of integral bounds' you work with two components: The probability of the car 1 hitting car 2, which relates to $u_{x}$ the relative horizontal speed at which car 1 approaches car 2. The probability of the car 2 hitting car 1, which relates to the $u_{y}$ the relative vertical speed at which car 1 crosses the stream. In the viewpoint of the frame of reference that is co-moving with the cars 1, you can see that this idea of two components 'car 1 hitting car 2' and 'car 2 hitting car 1' is confusing. One should not add the horizontal and vertical components $u_{x}$ and $u_{y}$ together (which is like computing the Manhattan distance), but you should use the Euclidian measure for the distance traveled by car 2 relative to the cars in the stream $\sqrt{u_{x}^2 + u_{y}^2}$ . Effective cross-section To compute the collision rate or collision probability, you will have to consider the effective cross-section of the car moving through the stream. If you would do this accurately you will have to determine the distances $d_1$ and $d_2$ which are the distances between the point where the two cars are just touching and lines through the centers of the two cars, these lines are drawn in the direction of travel. To compute these distances is a bit annoying and you have to consider both the angles $\theta$ and $\theta^\prime$ . And, there are different cases, for instance, car 2 might hit the other car on the left or the right side depending on the angle. You could approximate the distance with $\lambda$ if you simplify the shape of the cars as spheres with diameter $\lambda$ . The cross section will then be twice this distance because the car 2 can hit the car 1 on the left and on the right. The distance between the cars 1 or the density in the stream. If we approach the stream at an angle than the distance between the cars in the stream becomes smaller. In the figure below you see that this distance is not $l$ but instead $l \sin \, \theta^\prime$ . Probability of hit with method 1 The probability that a car 2 hits another car in the stream is then $$\frac{\text{cross-section}}{\text{path-width}} \approx \frac{2 \lambda}{l \cdot \sin \, \theta^\prime}$$ and with $$\sin \theta^\prime = \frac{u_{y}}{\sqrt{{u_{x}}^2+{u_{y}}^2}}$$ we can rewrite it as $$\frac{\text{cross-section}}{\text{path-width}} \approx \frac{2 \lambda}{l} \sqrt{ 1 + \left( \frac{v_2 \cos \, \theta - v_1}{v_2 \sin \, \theta} \right)^2}$$ It is possible that this ratio becomes larger than 1 when the cross-section becomes larger than the path width. In that case a collision is certain (if the cars in the stream are with constant distance/gaps in between). Method 2, using density With the method you will have to compute the area that is swept by car 2 and integrate over that area the density of the cars 1 (which is more easy if this density is constant). Note that the angle of the path changes the area of the path. The integral that you compute, and the motivation for it, is not so clear. It is like you are computing the area of the path of a 1 dimensional line. That area is not dependent on the angle of the car 1. But, it is wrong to use a line. You need to consider the entire block. See in the image below how car 2, if it would be taking an alternative path, would sweep a different area of the stream. Also the velocity of cars 1 plays a role because they change the effective angle $\theta^\prime$ which will change the size of the area that the car 2 sweeps through the stream. Note: in the image $\cos \theta^\prime$ should be $\sin \theta^\prime$ . This will be edited later. The image above depicts a stream of uniform density, but you can also consider a nonuniform density in which case you perform an integration over infinitely small slabs. So this area is equal to $$w \cdot x = w \cdot \frac{2\lambda}{\sin\, \theta^\prime}$$ You will have to multiply by the density of the cars which is 1 car per block of size $w$ by $l$ , ie $\rho = 1/(l\cdot w)$ and you will end up with the same expression as method 1. $$w \cdot x \cdot \rho = w \cdot \frac{2\lambda}{\sin\, \theta^\prime} \cdot \frac{1}{l\cdot w} = \frac{2\lambda}{l \cdot \sin\, \theta^\prime} $$ Method 2 variant We can also compute the integral from method 2 in the stationary frame of reference. The area computed above is using the area of the parallelogram as (height times width). This can be done in two ways: one is $w \cdot x$ where $w$ is the width of the stream and $x$ the length of the intersection. Another way would be to multiply the cross-section $2\lambda$ with the length of the path which is depending of the width of the stream and the angle $\theta^\prime$ . This length of the path can be seen as an effective velocity relating how many area the car 2 effectively travels in the co-moving frame of reference of the car 1 stream. Instead of computing the area in the frame of reference of the co-moving frame we could also compute the area in the stationary frame of reference. In the stationary frame of reference the distance traveled is $$\Delta x \cdot \text{cross-section} = v_2 \Delta t \cdot \text{cross-section}$$ In the co-moving frame of reference the distance traveled is $$v_{effective} \Delta t \cdot \text{cross-section}$$ So we could compute the effective area as the area in the stationary frame of reference multiplied by a factor $$v_2 \Delta t \cdot \text{cross-section} \cdot \frac{v_{effective}}{v_2}$$ This factor at the end is the ratio of the difference in speeds of car 1 and car 2 in the numerator and the speed of car 1 in the denominator $$ \frac{v_{effective}}{v_2} = \frac{\sqrt{(v_2 \cos \, \theta -v_1)^2+(v_2 \sin \, \theta)^2}}{v_2}$$ The time traveled in the stream of width $w$ is relating to another factor $$\Delta t = \frac{w}{v_2 \sin \, \theta}$$ If you put those together you get the same result again. If you like to compute an integral to account for some nonhomogeneous density then you could use a path integral $$ \int \text{cross-section}(s) \rho(s) \frac{|\vec{v}_1(s)-\vec{v}_2(s)|}{|\vec{v}_2(s)|} \text{d}\, s$$ Where the velocities are now considered as vectors $\vec{v}_1$ and $\vec{v}_2$ , and the vertical bars $|\cdot|$ denotes the magnitude. If the cross-section $2 \lambda$ , density $\rho = \frac{1}{l\cdot w}$ and speeds are constant then we can take them outside of te integral and we end with $$ \begin{array}{} \text{cross-section} \cdot \rho \cdot \frac{|\vec{v}_1-\vec{v}_2|}{|\vec{v}_2|} \cdot \int \text{d}\, s &=& \overbrace{\left(2 \lambda\right)}^{\text{cross-section}} \cdot \overbrace{\left( \frac{1}{l \cdot w} \right)}^{\text{density}} \cdot \overbrace{\left(\frac{|\vec{v}_1-\vec{v}_2|}{|\vec{v}_2|}\right)}^{\text{velocity factor}} \cdot \overbrace{\left( w \frac{|\vec{v}_2|}{{v}_{2,y}} \right)}^{\text{path length $\int \text{d}s$}} \\&=& \frac{2 \lambda}{l} \frac{|\vec{v}_1-\vec{v}_2|}{{v}_{2,y}} \\&=& \frac{2 \lambda}{l} \frac{\sqrt{(v_2 \sin \theta)^2 + (v_2 \cos \theta- v_1)^2}}{v_2 \sin \theta}\end{array}$$ Note that this gives the average number of collisions. The meaning of an average is different depending on the distribution of the cars in the stream. (See: What distribution to use to model time before a train arrives? ) In your final application with airplanes you might consider the collisions between two streams. Then you can have an integral over the space and use the concentrations of both streams $$ \iint \rho_1(x,y) \rho_2(x,y) \text{cross-section}(x,y) {|\vec{v}_1(x,y)-\vec{v}_2(x,y)|} \text{d}x \text{d} y $$ which gives the rate of collisions per second. You could in addition take into account variations in the speeds at given positions $x,y$ and compute the average of the factor $\text{cross-section}(x,y) {|\vec{v}_1(x,y)-\vec{v}_2(x,y)|}$ .
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/563063', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/320779/']}
jdg_80011
stackexchange
llm_judgeable_groundtruth_similarity
49528
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: Suppose we have some training set $(x_{(i)}, y_{(i)})$ for $i = 1, \dots, m$ . Also suppose we run some type of supervised learning algorithm on the training set. Hypotheses are represented as $h_{\theta}(x_{(i)}) = \theta_0+\theta_{1}x_{(i)1} + \cdots +\theta_{n}x_{(i)n}$ . We need to find the parameters $\mathbf{\theta}$ that minimize the "distance" between $y_{(i)}$ and $h_{\theta}(x_{(i)})$ . Let $$J(\theta) = \frac{1}{2} \sum_{i=1}^{m} (y_{(i)}-h_{\theta}(x_{(i)}))^{2}$$ Then we want to find $\theta$ that minimizes $J(\theta)$ . In gradient descent we initialize each parameter and perform the following update: $$\theta_j := \theta_j-\alpha \frac{\partial J(\theta)}{\partial \theta_{j}} $$ What is the key difference between batch gradient descent and stochastic gradient descent? Both use the above update rule. But is one better than the other? Now provide the response and nothing else.
The applicability of batch or stochastic gradient descent really depends on the error manifold expected. Batch gradient descent computes the gradient using the whole dataset. This is great for convex, or relatively smooth error manifolds. In this case, we move somewhat directly towards an optimum solution, either local or global. Additionally, batch gradient descent, given an annealed learning rate, will eventually find the minimum located in it's basin of attraction. Stochastic gradient descent (SGD) computes the gradient using a single sample. Most applications of SGD actually use a minibatch of several samples, for reasons that will be explained a bit later. SGD works well (Not well, I suppose, but better than batch gradient descent) for error manifolds that have lots of local maxima/minima. In this case, the somewhat noisier gradient calculated using the reduced number of samples tends to jerk the model out of local minima into a region that hopefully is more optimal. Single samples are really noisy, while minibatches tend to average a little of the noise out. Thus, the amount of jerk is reduced when using minibatches. A good balance is struck when the minibatch size is small enough to avoid some of the poor local minima, but large enough that it doesn't avoid the global minima or better-performing local minima. (Incidently, this assumes that the best minima have a larger and deeper basin of attraction, and are therefore easier to fall into.) One benefit of SGD is that it's computationally a whole lot faster. Large datasets often can't be held in RAM, which makes vectorization much less efficient. Rather, each sample or batch of samples must be loaded, worked with, the results stored, and so on. Minibatch SGD, on the other hand, is usually intentionally made small enough to be computationally tractable. Usually, this computational advantage is leveraged by performing many more iterations of SGD, making many more steps than conventional batch gradient descent. This usually results in a model that is very close to that which would be found via batch gradient descent, or better. The way I like to think of how SGD works is to imagine that I have one point that represents my input distribution. My model is attempting to learn that input distribution. Surrounding the input distribution is a shaded area that represents the input distributions of all of the possible minibatches I could sample. It's usually a fair assumption that the minibatch input distributions are close in proximity to the true input distribution. Batch gradient descent, at all steps, takes the steepest route to reach the true input distribution. SGD, on the other hand, chooses a random point within the shaded area, and takes the steepest route towards this point. At each iteration, though, it chooses a new point. The average of all of these steps will approximate the true input distribution, usually quite well.
{}
{'log_upvote_score': 8, 'links': ['https://stats.stackexchange.com/questions/49528', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/20616/']}
jdg_80012
stackexchange
llm_judgeable_groundtruth_similarity
28886
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 cannot figure out why glycine hydrochloride is more acidic than chloroacetic acid. Could I have figured this out from a $\mathrm pK_\mathrm a$ table and maybe am just not seeing it? On the table I have in my book (Organic Chemistry, Seyhan Ege, 3rd edition), neither acid nor its conjugate base are there. Now provide the response and nothing else.
To answer your question about titrating without adding volume—you don’t. This problem is strange in many ways, but I will attempt to help you to understand. Since we are working with dissolved $\ce{B}$, I feel as though it makes the most sense to express the reaction with the given by the equation: $$\ce{B + H2O<=>BH +OH-}$$ So the equilibrium expression of the reaction is given by the equation: $$K_\mathrm{b}=\frac{[\ce{BH}]\cdot[\ce{OH-}]}{\ce{[B]}}$$ If the $\mathrm{p}K_\mathrm{a}$ of the conjugate acid is 8.1, then by mathematical manipulation: $$\mathrm{p}K_\mathrm{a}=-\log K_\mathrm{a}$$ $$-\log K_\mathrm{a}=8.1$$ $$\log K_\mathrm{a}=-8.1$$ $$K_\mathrm{a}=10^{-8.1}\approx7.94\times10^{-9}$$ Since $\mathrm{p}K_\mathrm{w}=\mathrm{p}K_\mathrm{a}\cdot\mathrm{p}K_\mathrm{b}$, the $\mathrm{p}K_\mathrm{b}$ of the base should be, and since $\mathrm{p}K_\mathrm{w}=1\times10^{-14}$: $$1\times10^{-14}=7.94\times10^{-9}\cdot K_\mathrm{b}$$ $$K_\mathrm{b}=\frac{1\times10^{-14}}{7.94\times10^{-9}}\approx1.26\times10^{-6}$$ For the same reason that $1\times10^{-14}=\mathrm{p}K_\mathrm{a}\cdot\mathrm{p}K_\mathrm{b}$, $\mathrm{14=pH+pOH}$. Given that the pH of the water is 8.1 for our first calculation: $$14=8.1+\mathrm{p}\ce{OH}$$ $$\mathrm{pOH}=5.9$$and$$-\log{[\ce{OH-}]}=5.9$$ $$\ce{[OH^{-}]}=\mathrm{10^{-5.9}}\approx1.26\times10^{-6}$$ Since we know that any $\ce{BH}$ that is made must come from the reaction of 1 molecule of $\ce{B}$, then: $$[\ce{B}]=0.1-x~~~~[\ce{BH}]=x$$ Using the knowledge we have gained from the problem, we can now solve (finally!): $$K_\mathrm{b}=\frac{[\ce{BH}]\cdot[\ce{OH-}]}{\ce{[B]}}$$ $$1.26\times10^{-6}=\frac{[x]\cdot[1.26\times10^{-6}]}{[0.1-x]}$$ $$x=0.1-x$$ $$2x=0.1$$ $$x=0.05$$ So: $$[\ce{B}]=0.1-0.05=0.05~\mathrm{M}$$ Try using this process to solve for the $\mathrm{pH}$ of 7.5.
{}
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/28886', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/15654/']}
jdg_80013
stackexchange
llm_judgeable_groundtruth_similarity
27608688
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to get PHP errors to display on the screen using IIS vrs 8.5 and PHP vrs 5.2.17, but I continue to get the IIS 500 error http page, or a blank screen. I have already found numerous SO posts that have supposed fixes, but nothing on them has fixed my problem yet. Here is what I have tried. Changed errorMode to Detailed. Still getting the 500 error page instead of the php error. Removed all of the custom errors in the default IIS config file under the "httpErrors" block. Still getting the IIS custom 500 error page. Added existingResponse="PassThrough" to my httpErrors block in the default IIS config. Doing this causes me to get a blank page instead of the php error, or the IIS 500 error. I have verified that none of these settings are being overwritten in the site default system.config files. Currently I am getting a blank page instead of the IIS 500 error on the screen. I have already verified that display_errors is on, and error_reporting is correct. I also know that the php page runs just fine. I am purposely causing this php error by removing a semi-colon on the page. So I already know everything is working fine. PHP Error logging is also working, but I want the errors to display on the page so I dont have to look at the error log every 5 minutes. What else could be causing this? Now provide the response and nothing else.
IF you set custom error to Detailed in feature settings of error pages for website and server both AND if in your php.ini file you set the display_errors = on & error_reporting = E_ALL THEN there is only one possibility for getting [IIS default 500 error page] is that "Your PHP is not working coz of miss configuration." The required configurations are: After setting Handler Mappings to your php-cgi.exe file(which is in you php installation dir) as FastCGI, open the php.ini file and edit following lines OR add if not found in file. (if php.ini is not exists in you PHP installation dir then rename from existing php.ini-development OR php.ini-production) 1) extension_dir = "ext\" ;ext folder will be in PHP installation, if not create and don't forget ending \ 2) log_errors = On 3) error_log = "C:\inetpub\temp\php-errors.log" 4) cgi.force_redirect = 0 ; may be you need to add this line add it anywhere, for instance-before '; File Uploads ;' 5) cgi.fix_pathinfo = 1 6) fastcgi.impersonate = 1 7) fastcgi.logging = 0 Be careful and there should not `;` before any of these lines. see documentation - installing/configuring PHP Even after correct configurations PHP may not work because of system corruption. You can check by double click on php-cgi.exe and php-win.exe it should run without proper error (other then warnings OR ext/fileName... is missing messages - these are OK). Note: after these many other setting are requires to run all things of php (ex. session), but by these SIMPLE PHP WILL WORK or PHP will properly show the error for what's wrong (NOT 500 page).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27608688', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/244061/']}
jdg_80014
stackexchange
llm_judgeable_groundtruth_similarity
39685125
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking for a way to instantiate a component in Angular2 from within the code of another component. Unlike the many people that have asked a similar question I'm not so much interested in dynamically compiling a new component, just instantiating and inserting one that already exists in my application. For instance: Say I have two components: dashboard-item.component.ts import { Component } from "@angular/core";@Component({ selector: "dashboard-item", template: "Some dashboard item with functionality"})export class DashboardItemComponent { constructor() {} onInit() {}} dashboard.component.ts import { Component } from "@angular/core";@Component({ selector: "dashboard", template: "<h1>Dashboard!</h1><div #placeholder></div>"})export class DashboardComponent { constructor() {} onInit() {}} What I'm looking for is a way to create a DashboardItemComponent in the onInit of the DashboardComponent and add it to the #placeholder div. Two things to note: I will need to be able to use the inputs/outputs of the child component I'm explictly not talking about compiling a new component on the fly like these two issues describe: How can I use/create dynamic template to compile dynamic Component with Angular 2.0? and Equivalent of $compile in Angular 2 These two earlier issues ask a similar question, but their answers are either rather lackluster or pertain to earlier (beta) versions of Angular2 and no longer seem to work. How to instantiate and render Angular2 components? Is it possible to manually instantiate component in angular 2 Now provide the response and nothing else.
Here's a working demo: https://plnkr.co/edit/pgkgYEwSwft3bLEW95Ta?p=preview import {Component, NgModule, ViewChild, ElementRef, Input, Output, EventEmitter, ViewContainerRef, ComponentRef, ComponentFactoryResolver, ReflectiveInjector} from '@angular/core'import {BrowserModule} from '@angular/platform-browser'@Component({ selector: 'any-comp', template: '<div (click)="clicked.emit($event)">here i am.. {{name}}</div>'})export class AnyComponent { @Input() name; @Output() clicked = new EventEmitter(); constructor() { console.log('some1 created me.. ! :)'); }}@Component({ selector: 'my-app', template: ` <div> <h2>Hello {{name}}</h2> <template #placeHolder> </template> </div> `,})export class App { @ViewChild('placeHolder', {read: ViewContainerRef}) private _placeHolder: ElementRef; name:string; constructor(private _cmpFctryRslvr: ComponentFactoryResolver) { this.name = 'Angular2' } ngOnInit() { let cmp = this.createComponent(this._placeHolder, AnyComponent); // set inputs.. cmp.instance.name = 'peter'; // set outputs.. cmp.instance.clicked.subscribe(event => console.log(`clicked: ${event}`)); // all inputs/outputs set? add it to the DOM .. this._placeHolder.insert(cmp.hostView); } public createComponent (vCref: ViewContainerRef, type: any): ComponentRef { let factory = this._cmpFctryRslvr.resolveComponentFactory(type); // vCref is needed cause of that injector.. let injector = ReflectiveInjector.fromResolvedProviders([], vCref.parentInjector); // create component without adding it directly to the DOM let comp = factory.create(injector); return comp; }}@NgModule({ imports: [ BrowserModule ], declarations: [ App, AnyComponent ], // ! IMPORTANT entryComponents: [ AnyComponent ], // ! IMPORTANT --> would be lost due to Treeshaking.. bootstrap: [ App ]})export class AppModule {}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39685125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/138288/']}
jdg_80015
stackexchange
llm_judgeable_groundtruth_similarity
11672438
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: All of the d3 tutorials I've found use data arranged in arrays of objects from which they graph one point for each object in the array. Given data in the following structure: data = [ {id: 1, x: 4, y: 10, type: 1}, {id: 2, x: 5, y: 20, type: 2} ...] The x and y values are used to make a scatterplot. The type parameter is used to change the color of each point. See this jsfiddle for an example: http://jsfiddle.net/uxbHv/ Unfortuately, I have a different data structure and I can't figure out how to create the same graph by drawing two data points for each object. Here is some example data: dataSet = [ {xVar: 5, yVar1: 90, yVar2: 22}, {xVar: 25, yVar1: 30, yVar2: 25}, {xVar: 45, yVar1: 50, yVar2: 80}, {xVar: 65, yVar1: 55, yVar2: 9}, {xVar: 85, yVar1: 25, yVar2: 95}] I can graph xVar individually against yVar1 or yVar2, but I can not figure out how to get both on the same graph: http://jsfiddle.net/634QG/ Now provide the response and nothing else.
The general rule when using a data-join is that you want a one-to-one mapping from data to elements . So, if you have two series in your scatterplot, you’ll want two container elements (such as G elements ) to represent the series. Since you currently have only one data array, you’ll also want to use array.map to convert the data representation into two parallel arrays with the same representation. This way, you don’t have to duplicate code for each series. Say your data was represented in a CSV file with one column for the x -values, and multiple other columns for the y -values of each series: x,y1,y25,90,2225,30,2545,50,8065,55,985,25,95 If you want the code to be completely generic, you first need to compute the series’ names, such as ["y1", "y2"] . (If you added a third column to the CSV file, it might be ["y1", "y2", "y3"] .) You can compute the names using d3.keys , which extracts the named properties from an object. For example, d3.keys({foo: 1, bar: 2}) returns ["foo", "bar"] . // Compute the series names ("y1", "y2", etc.) from the loaded CSV.var seriesNames = d3.keys(data[0]) .filter(function(d) { return d !== "x"; }) .sort(); Now that you have the series names, you can create an array of arrays of points. The outer array represents the series (of which there are two) and the inner arrays store the data points. You can simultaneously convert the points to a consistent representation (objects with x and y properties), allowing you to reuse code across series. // Map the data to an array of arrays of {x, y} tuples.var series = seriesNames.map(function(series) { return data.map(function(d) { return {x: +d.x, y: +d[series]}; });}); Note this code uses the + operator to coerce the CSV values to numbers. (CSV files are untyped, so they are initially strings.) Now that you’ve mapped your data to a regular format, you can create G elements for each series, and then circle elements within for each point. The resulting SVG structure will look like this: <g class="series"> <circle class="point" r="4.5" cx="1" cy="2"/> <circle class="point" r="4.5" cx="3" cy="2"/> …</g><g class="series"> <circle class="point" r="4.5" cx="5" cy="4"/> <circle class="point" r="4.5" cx="7" cy="6"/> …</g> And the corresponding D3 code: // Add the points!svg.selectAll(".series") .data(series) .enter().append("g") .attr("class", "series") .style("fill", function(d, i) { return z(i); }) .selectAll(".point") .data(function(d) { return d; }) .enter().append("circle") .attr("class", "point") .attr("r", 4.5) .attr("cx", function(d) { return x(d.x); }) .attr("cy", function(d) { return y(d.y); }); I’ve also added a bit of code to assign each series a unique color by adding a fill style to the containing G element. There are lots of different ways to do this, of course. (You might want to be more specific about the color for each series, for example.) I’ve also left out the code that computes the domains of your x and y scales (as well as rendering the axes), but if you want to see the entire working example: http://bl.ocks.org/3183403
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11672438', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1112097/']}
jdg_80016
stackexchange
llm_judgeable_groundtruth_similarity
1157
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I tried it in several symbols and timeframes with the same result: $$\frac {mean(HIGH-LOW)}{mean(|CLOSE-OPEN|)}$$ Symbol Result------ ------EURUSD:W1 1.9725 EURUSD:D1 2.0023 EURUSD:H1 2.1766 USDJPY:W1 1.9949 USDJPY:D1 2.0622 USDJPY:H1 2.2327 SAN.MC:D1 2.0075 BBVA.MC:D1 2.0075 REP.MC:D1 2.1320 Now provide the response and nothing else.
There is a very good reason why the ratio$$\frac {mean(HIGH-LOW)}{mean(|CLOSE-OPEN|)} \approx 2$$on various financial series. If the price of a security evolves according to a Wiener process beginning at the opening bell and throughout the day, and the drift is negligible for that period of time, i.e.$\mu=0$, then the denominator of the above ratio closely approximates the average absolute deviation , $$AAD=\frac{2\sigma}{\sqrt{2\pi}}\int_0^\infty xe^{-x^2/2}dx=\sqrt {2/\pi}\cdot\sigma$$ for a normal distribution, where $\sigma$ is the standard deviation. On the other hand$$\mathbb E(HIGH-OPEN) = \sqrt{2/\pi}\cdot\sigma$$$$\mathbb E(LOW-OPEN) = -\sqrt{2/\pi}\cdot\sigma$$(See the running maximum of a Wiener process on Wikipedia .)So we have for such an idealized Wiener process:$$\frac {\mathbb E(HIGH-LOW)}{\mathbb E(|CLOSE-OPEN|)}= \frac{\sqrt{2/\pi}\cdot\sigma-\left(-\sqrt{2/\pi}\cdot\sigma\right)}{\sqrt {2/\pi}\cdot\sigma} = 2.$$It should not be too surprising to see this more or less borne out by observation.
{}
{'log_upvote_score': 5, 'links': ['https://quant.stackexchange.com/questions/1157', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/867/']}
jdg_80017
stackexchange
llm_judgeable_groundtruth_similarity
262410
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: Problem: Describe all polynomials $\mathbb{R}\rightarrow\mathbb{R}$ with coefficients in $\mathbb C$ which send rational numbers to rational numbers and irrational numbers to irrational numbers. Now provide the response and nothing else.
Take a polynomial $f=a_nx^n+a_{n-1}x^{n-1}+...+a_1x+a_0$, and assume $f$ satisfies the problem conditions. Since $f(1),f(2),f(3),...,f(n)$ are all rationals, we can use them to get $n$ independent equations in the variables $a_i$. Then, we can solve for all the $a_i$ with linear algebra. Linear algebra tells us that this equation-solving uses only +,-,*, and /, so all coefficients $a_i$ of the polynomial must be rational. Now, multiply $f$ by all the denominators of all the $a_i$ to get a new polynomial $g=b_nx^n+b_{n-1}x^{n-1}+...+b_1x+b_0$ with integer coefficients. Clearly $g$ satisfies the problem conditions as well. Consider all values $x$ for which $g(x)$ is an integer. By the Rational Root Theorem, any such $x$ can be expressed as $\frac{k}{b_n}$ for some integer $k$. From this we deduce that any two values $x$ for which $g(x)$ is an integer are spaced at least $\frac{1}{b_n}$ apart. But if the polynomial $g(x)$ has degree at least $2$, it attains arbitrarily large slope as $x$ goes to $\infty$. In particular, we can pick $x$ so large that $g(x+\frac{1}{b_n})>g(x)+100$. But then $g$ attains many integer values between $x$ and $x+\frac{1}{b_n}$, violating the deduction in the previous paragraph. Therefore, $g$ has degree at most $1$. After proving this, we are done: the only polynomials $f$ that work are the ones in the form $a_1x+a_0$, where both $a_1$ and $a_0$ are rational.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/262410', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/18240/']}
jdg_80018
stackexchange
llm_judgeable_groundtruth_similarity
5905204
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 std::unordered_map from gnu++0x to store a huge amount of data. I want to pre-allocate space for the large number of elements, since I can bound the total space used. What I would like to be able to do is call: std::unordered_map m;m.resize(pow(2,x)); where x is known. std::unordered_map doesn't support this. I would rather use std::unordered_map if possible, since it will eventually be part of the standard. Some other constraints: Need reliable O(1) access and mutation of the map. The desired hash and comparison functions are already non-standard and somewhat expensive. O(log n) mutation (as with std::map ) is too expensive. -> The expensive hash and comparison also make amortization-based growth way too expensive. Each extra insert requires O(n) operations from those functions, which results in an extra quadratic term in the algorithm's run time, since the exponential storage requirements need O(n) growths. Now provide the response and nothing else.
m.rehash(pow(2,x)); if pow(2, x) is the number of buckets you want preallocated. You can also: m.reserve(pow(2,x)); but now pow(2, x) is the number of elements you are planning on inserting. Both functions do nothing but preallocate buckets. They don't insert any elements. And they are both meant to be used exactly for your use case. Note: You aren't guaranteed to get exactly pow(2, x) buckets. Some implementations will use only a number of buckets which is a power of 2. Other implementations will use only a prime number of buckets. Still others will use only a subset of primes for the number of buckets. But in any case, the implementation should accept your hint at the number of buckets you desire, and then internally round up to its next acceptable number of buckets. Here is the precise wording that the latest (N4660) uses to specify the argument to rehash : a.rehash(n) : Postconditions: a.bucket_count() >= a.size() / a.max_load_factor() and a.bucket_count() >= n . This postcondition ensures that bucket()_count() >= n , and that load_factor() remains less than or equal to max_load_factor() . Subsequently reserve(n) is defined in terms of rehash(n) : a.reserve(n) : Same as a.rehash(ceil(n / a.max_load_factor())) .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5905204', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/740868/']}
jdg_80019
stackexchange
llm_judgeable_groundtruth_similarity
14662535
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 2 bundles, 1 CMS bundle that will be the parent bundle.I have in both bundles duplicated entitys. Like User The user in the CMS bundle i made it a abstract class. (not sure if that is the right choice. Actually, what I want is extending my user entity IF needed.). cms user: abstract class User implements UserInterface bundle user: use MV\CMSBundle\Entity\User as BaseUser;/** * @ORM\Entity(repositoryClass="MV\NameBundle\Repository\UserRepository") * @DoctrineAssert\UniqueEntity(fields={"email"}, message="user.email.already.exist" ) */class User extends BaseUser{ ....} Im getting the error Class "MV\CMSBundle\Entity\User" is not a valid entity or mapped super class. I have searched in the documentation of symfony and found this page: entities-entity-mapping but they didn't add some content xD Oh, and no I dont want to use FOSUserBundle ;) Symfony: 2.1 Now provide the response and nothing else.
Define the base-class as follows: /** * @ORM\MappedSuperclass */abstract class BaseUser{ // ...} Define the real entity: /** * @ORM\Entity */class User extends BaseUser{ // ...} Because you're missing the @MappedSuperclass annotation on the base-class, Doctrine throws the exception you mention.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14662535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1677699/']}
jdg_80020
stackexchange
llm_judgeable_groundtruth_similarity
7735531
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 situation whereby ReadWriterLockSlim is throwing the exception "System.Threading.SynchronizationLockException - The write lock is being released without being held." when I try to execute ExitWriteLock(). As far as I can tell, this shouldn't happen because subsequent threads that enter the try block will 'block' until they can obtain the lock. Am I missing something here? The issue looks very similar to this one , however no solution was posted there. //Code simplified for example. public class i18nService { internal static ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); private string ProcessText() { try { cacheLock.EnterWriteLock(); return "xyz"; } finally { cacheLock.ExitWriteLock(); // Error is throwing here. } }} Thanks very much for your help :-) Now provide the response and nothing else.
try { cacheLock.EnterWriteLock(); return "xyz"; } finally { cacheLock.ExitWriteLock(); // Error is throwing here. } Q: What happens if cacheLock.EnterWriteLock(); fails? A: The finally statement gets executed. cacheLock.ExitWriteLock(); gets called But we don't have the lock Try this: private string ProcessText(){ cacheLock.EnterWriteLock(); try { return "xyz"; } finally { cacheLock.ExitWriteLock(); // Error is throwing here. }} Presumably .NET is designed in such a way that if EnterWriteLock() fails, the lock is released (or never held at all).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7735531', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/494635/']}
jdg_80021
stackexchange
llm_judgeable_groundtruth_similarity
1448092
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 have the same static variable with a different value depending on the type of class. So I would have public class Entity{ public static Bitmap sprite; public void draw(Canvas canvas, int x, int y) { canvas.drawBitmap(sprite, x, y, null); }}public class Marine extends Entity{}public class Genestealer extends Entity{} And then in my main program go: Marine.sprite = // Load sprite for all instances of MarineGenestealer.sprite = // Load sprite for all instances of Genestealer I don't want to store the same sprite in every instance of the class. I want one for each type of class. I want to inherit the static sprite variable and the draw function which will draw the sprite. But I don't want the Genstealer sprite to override the Marine sprite. Is this possible? How would I do it? Now provide the response and nothing else.
Use an abstract method: public class Entity{ public abstract Bitmap getSprite(); public void draw(Canvas canvas, int x, int y) { canvas.drawBitmap(getSprite(), x, y, null); }}public class Marine extends Entity{ public Bitmap getSprite() { return /*the sprite*/; }} The sprite returned by getSprite can be a static if you like. Nice things about this approach: You can't (easily) forget to include a sprite in your subclass, since the compiler will complain if you don't implement the abstract method. It's flexible. Suppose a Marine should look different once he "levels up". Just change Marine's getSprite method to take the level into account. It's the standard OO-idiom for this sort of thing, so people looking at their code won't be left scratching their heads.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1448092', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_80022
stackexchange
llm_judgeable_groundtruth_similarity
712639
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Could you C++ developers please give us a good description of what RAII is, why it is important, and whether or not it might have any relevance to other languages? I do know a little bit. I believe it stands for "Resource Acquisition is Initialization". However, that name doesn't jive with my (possibly incorrect) understanding of what RAII is: I get the impression that RAII is a way of initializing objects on the stack such that, when those variables go out of scope, the destructors will automatically be called causing the resources to be cleaned up. So why isn't that called "using the stack to trigger cleanup" (UTSTTC:)? How do you get from there to "RAII"? And how can you make something on the stack that will cause the cleanup of something that lives on the heap? Also, are there cases where you can't use RAII? Do you ever find yourself wishing for garbage collection? At least a garbage collector you could use for some objects while letting others be managed? Thanks. Now provide the response and nothing else.
So why isn't that called "using the stack to trigger cleanup" (UTSTTC:)? RAII is telling you what to do: Acquire your resource in a constructor! I would add: one resource, one constructor. UTSTTC is just one application of that, RAII is much more. Resource Management sucks. Here, resource is anything that needs cleanup after use. Studies of projects across many platforms show the majority of bugs are related to resource management - and it's particularly bad on Windows (due to the many types of objects and allocators). In C++, resource management is particularly complicated due to the combination of exceptions and (C++ style) templates. For a peek under the hood, see GOTW8 ). C++ guarantees that the destructor is called if and only if the constructor succeeded. Relying on that, RAII can solve many nasty problems the average programmer might not even be aware of. Here are a few examples beyond the "my local variables will be destroyed whenever I return". Let us start with an overly simplistic FileHandle class employing RAII: class FileHandle{ FILE* file;public: explicit FileHandle(const char* name) { file = fopen(name); if (!file) { throw "MAYDAY! MAYDAY"; } } ~FileHandle() { // The only reason we are checking the file pointer for validity // is because it might have been moved (see below). // It is NOT needed to check against a failed constructor, // because the destructor is NEVER executed when the constructor fails! if (file) { fclose(file); } } // The following technicalities can be skipped on the first read. // They are not crucial to understanding the basic idea of RAII. // However, if you plan to implement your own RAII classes, // it is absolutely essential that you read on :) // It does not make sense to copy a file handle, // hence we disallow the otherwise implicitly generated copy operations. FileHandle(const FileHandle&) = delete; FileHandle& operator=(const FileHandle&) = delete; // The following operations enable transfer of ownership // and require compiler support for rvalue references, a C++0x feature. // Essentially, a resource is "moved" from one object to another. FileHandle(FileHandle&& that) { file = that.file; that.file = 0; } FileHandle& operator=(FileHandle&& that) { file = that.file; that.file = 0; return *this; }} If construction fails (with an exception), no other member function - not even the destructor - gets called. RAII avoids using objects in an invalid state. it already makes life easier before we even use the object. Now, let us have a look at temporary objects: void CopyFileData(FileHandle source, FileHandle dest);void Foo(){ CopyFileData(FileHandle("C:\\source"), FileHandle("C:\\dest"));} There are three error cases to handled: no file can be opened, only one file can be opened, both files can be opened but copying the files failed. In a non-RAII implementation, Foo would have to handle all three cases explicitly. RAII releases resources that were acquired, even when multiple resources are acquired within one statement. Now, let us aggregate some objects: class Logger{ FileHandle original, duplex; // this logger can write to two files at once!public: Logger(const char* filename1, const char* filename2) : original(filename1), duplex(filename2) { if (!filewrite_duplex(original, duplex, "New Session")) throw "Ugh damn!"; }} The constructor of Logger will fail if original 's constructor fails (because filename1 could not be opened), duplex 's constructor fails (because filename2 could not be opened), or writing to the files inside Logger 's constructor body fails. In any of these cases, Logger 's destructor will not be called - so we cannot rely on Logger 's destructor to release the files. But if original was constructed, its destructor will be called during cleanup of the Logger constructor. RAII simplifies cleanup after partial construction. Negative points: Negative points? All problems can be solved with RAII and smart pointers ;-) RAII is sometimes unwieldy when you need delayed acquisition, pushing aggregated objects onto the heap. Imagine the Logger needs a SetTargetFile(const char* target) . In that case, the handle, that still needs to be a member of Logger , needs to reside on the heap (e.g. in a smart pointer, to trigger the handle's destruction appropriately.) I have never wished for garbage collection really. When I do C# I sometimes feel a moment of bliss that I just do not need to care, but much more I miss all the cool toys that can be created through deterministic destruction. (using IDisposable just does not cut it.) I have had one particularly complex structure that might have benefited from GC, where "simple" smart pointers would cause circular references over multiple classes. We muddled through by carefully balancing strong and weak pointers, but anytime we want to change something, we have to study a big relationship chart. GC might have been better, but some of the components held resources that should be release ASAP. A note on the FileHandle sample: It was not intended to be complete, just a sample - but turned out incorrect. Thanks Johannes Schaub for pointing out and FredOverflow for turning it into a correct C++0x solution. Over time, I've settled with the approach documented here .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/712639', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/80112/']}
jdg_80023
stackexchange
llm_judgeable_groundtruth_similarity
1108830
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I am running a django app on AWS elastic beanstalk and I'm getting spammed by bots trying to scan for vulnerabilities. It results in a flood of errors such as: (Where xx.xxx.xx.xx is my ec2 instance's ip address.) DisallowedHost at //www/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.phpInvalid HTTP_HOST header: 'xx.xxx.xx.xx'. You may need to add 'xx.xxx.xxx.xx' to ALLOWED_HOSTS. My legitimate users only access the site using the domain name. I've been trying to figure out how to modify my nginx configuration to block all connections that aren't addressed to *.mydomain.com or mydomain.com. I dynamically add and remove subdomains as needed so I do a wildcard for the subdomain. AWS Elastic beanstalk generates the following default config file for me: /etc/nginx/nginx.conf #Elastic Beanstalk Nginx Configuration Fileuser nginx;error_log /var/log/nginx/error.log warn;pid /var/run/nginx.pid;worker_processes auto;worker_rlimit_nofile 32788;events { worker_connections 1024;}http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; include conf.d/*.conf; map $http_upgrade $connection_upgrade { default "upgrade"; } server { listen 80 default_server; access_log /var/log/nginx/access.log main; client_header_timeout 60; client_body_timeout 60; keepalive_timeout 60; gzip off; gzip_comp_level 4; gzip_types text/plain text/css application/json application/javascript $ # Include the Elastic Beanstalk generated locations include conf.d/elasticbeanstalk/*.conf; }} Then I extend it with this file: .platform\nginx\conf.d\elasticbeanstalk\00_application.conf location / { set $redirect 0; if ($http_x_forwarded_proto != "https") { set $redirect 1; } if ($redirect = 1) { return 301 https://$host$request_uri; } proxy_pass http://127.0.0.1:8000; proxy_http_version 1.1; proxy_set_header Connection $connection_upgrade; proxy_set_header Upgrade $http_upgrade; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; gzip on; gzip_comp_level 4; gzip_types text/html text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript; client_max_body_size 2000M;}location = /health-check.html { set $redirect 0; if ($http_x_forwarded_proto != "https") { set $redirect 1; } if ($http_user_agent ~* "ELB-HealthChecker") { set $redirect 0; return 204; } if ($redirect = 1) { return 301 https://$host$request_uri; } proxy_pass http://127.0.0.1:8000; proxy_http_version 1.1; proxy_set_header Connection $connection_upgrade; proxy_set_header Upgrade $http_upgrade; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; The purpose of that override file is so that nginx redirects http to https and responds to ELB health checks. I'm not overly familiar with nginx or elastic beanstalk, but from what I could gather when researching this problem is that I need to have my default server connection return 444 and then have a separate server block with server_name set to my domain. Is this the correct way to handle this problem and will it work with wildcard subdomains? Thank you Now provide the response and nothing else.
It seems like your only virtual host is the one with default_server attribute. It means that if no matching virtual host is found, that block is used to serve the request. To properly handle your case, you need to have: server block with default_server in the listen directive. This block should only have return 404; or return 444; . You might want to turn off access_log in this block too. server block with server_name example.com *.example.com; . This virtual host should contain your actual application. Note, this is how things are configured when one has complete control of nginx configuration. I don't know if Elastic Beanstalk has some features to automatically generate configuration files in this fashion.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/1108830', 'https://serverfault.com', 'https://serverfault.com/users/981015/']}
jdg_80024
stackexchange
llm_judgeable_groundtruth_similarity
8049764
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 draw text with different stroke and fill colors on images with python? Here is some text with red stroke and gray fill. I tried to do this with PIL but there was no option for setting the stroke color. Now provide the response and nothing else.
Using cairo (with much code taken from here ): import cairodef text_extent(font, font_size, text, *args, **kwargs): surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 0, 0) ctx = cairo.Context(surface) ctx.select_font_face(font, *args, **kwargs) ctx.set_font_size(font_size) return ctx.text_extents(text)text='Example'font="Sans"font_size=55.0font_args=[cairo.FONT_SLANT_NORMAL](x_bearing, y_bearing, text_width, text_height, x_advance, y_advance) = text_extent(font, font_size, text, *font_args)surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, int(text_width), int(text_height))ctx = cairo.Context(surface)ctx.select_font_face(font, *font_args)ctx.set_font_size(font_size)ctx.move_to(-x_bearing, -y_bearing)ctx.text_path(text)ctx.set_source_rgb(0.47, 0.47, 0.47)ctx.fill_preserve()ctx.set_source_rgb(1, 0, 0)ctx.set_line_width(1.5)ctx.stroke()surface.write_to_png("/tmp/out.png")
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8049764', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/671575/']}
jdg_80025
stackexchange
llm_judgeable_groundtruth_similarity
2748882
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 site with multiple subdomains and I want the named subdomains robots.txt to be different from the www one. I tried to use .htaccess, but the FastCGI doesn't look at it. So, I was trying to set up routes, but it doesn't seem that you can't do a direct rewrite since every routes needs a controller: map.connect '/robots.txt', :controller => ?, :path => '/robots.www.txt', :conditions => { :subdomain => 'www' }map.connect '/robots.txt', :controller => ?, :path => '/robots.club.txt' What would be the best way to approach this problem? (I am using the request_routing plugin for subdomains) Now provide the response and nothing else.
Actually, you probably want to set a mime type in mime_types.rb and do it in a respond_to block so it doesn't return it as 'text/html' : Mime::Type.register "text/plain", :txt Then, your routes would look like this: map.robots '/robots.txt', :controller => 'robots', :action => 'robots' For rails3: match '/robots.txt' => 'robots#robots' and the controller something like this (put the file(s) where ever you like): class RobotsController < ApplicationController def robots subdomain = # get subdomain, escape robots = File.read(RAILS_ROOT + "/config/robots.#{subdomain}.txt") respond_to do |format| format.txt { render :text => robots, :layout => false } end endend at the risk of overengineering it, I might even be tempted to cache the file read operation... Oh, yeah, you'll almost certainly have to remove/move the existing 'public/robots.txt' file. Astute readers will notice that you can easily substitute RAILS_ENV for subdomain ...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2748882', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/217326/']}
jdg_80026
stackexchange
llm_judgeable_groundtruth_similarity
136479
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: Just a thought I had: is it possible for a VHDL component to have multiple architectures if outputs are not modified by both? If so how can we select the one to use at synthesis time (like the C preprocessor)? What happens if multiple architectures can coexist and outputs conflict? Now provide the response and nothing else.
To supplement @vermaete's answer: An entity defines an interface to a box; an architecture defines what's inside. If you don't have the same interface, you don't have the same entity. If you have the same port names, but each architecture uses them for different purposes, well, that's legal, but maybe not advisable - it depends on the specifics. If you want to use multiple architectures simultaneously, an alternative to configurations is just to use direct instantiation: U1 : entity my_lib.my_comp(arch1) ...U2 : entity my_lib.my_comp(arch2) ... If you want to use only one at a time, some sort of configuration is probably the way to go.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/136479', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/30449/']}
jdg_80027
stackexchange
llm_judgeable_groundtruth_similarity
24272335
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I read some posts here and seems like nothing special but I can not still select the entries of the last days. SELECT p1.kArtikel, p1.cName, p1.cKurzBeschreibung, p1.dLetzteAktualisierung, p1.dErstellt, p1.cSeo, p2.kartikelpict, p2.nNr, p2.cPfad FROM tartikel AS p1 WHERE DATE(dErstellt) > (NOW() - INTERVAL 7 DAY) INNER JOIN tartikelpict AS p2 ON (p1.kArtikel = p2.kArtikel) WHERE (p2.nNr = 1)ORDER BY p1.kArtikel DESCLIMIT 100;', $connection); If I add the between today and last 7 days my Code will not output anything. Now provide the response and nothing else.
The WHERE clause is misplaced, it has to follow the table references and JOIN operations. Something like this: FROM tartikel p1 JOIN tartikelpict p2 ON p1.kArtikel = p2.kArtikel AND p2.nNr = 1WHERE p1.dErstellt >= DATE(NOW() - INTERVAL 7 DAY)ORDER BY p1.kArtikel DESC EDIT (three plus years later) The above essentially answers the question "I tried to add a WHERE clause to my query and now the query is returning an error, how do I fix it?" As to a question about writing a condition that checks a date range of "last 7 days"... That really depends on interpreting the specification, what the datatype of the column in the table is (DATE or DATETIME) and what data is available... what should be returned. To summarize: the general approach is to identify a "start" for the date/datetime range, and "end" of that range, and reference those in a query. Let's consider something easier... all rows for "yesterday". If our column is DATE type. Before we incorporate an expression into a query, we can test it in a simple SELECT SELECT DATE(NOW()) + INTERVAL -1 DAY and verify the result returned is what we expect. Then we can use that same expression in a WHERE clause, comparing it to a DATE column like this: WHERE datecol = DATE(NOW()) + INTERVAL -1 DAY For a DATETIME or TIMESTAMP column, we can use >= and < inequality comparisons to specify a range WHERE datetimecol >= DATE(NOW()) + INTERVAL -1 DAY AND datetimecol < DATE(NOW()) + INTERVAL 0 DAY For "last 7 days" we need to know if that mean from this point right now, back 7 days ... e.g. the last 7*24 hours , including the time component in the comparison, ... WHERE datetimecol >= NOW() + INTERVAL -7 DAY AND datetimecol < NOW() + INTERVAL 0 DAY the last seven complete days, not including today WHERE datetimecol >= DATE(NOW()) + INTERVAL -7 DAY AND datetimecol < DATE(NOW()) + INTERVAL 0 DAY or past six complete days plus so far today ... WHERE datetimecol >= DATE(NOW()) + INTERVAL -6 DAY AND datetimecol < NOW() + INTERVAL 0 DAY I recommend testing the expressions on the right side in a SELECT statement, we can use a user-defined variable in place of NOW() for testing, not being tied to what NOW() returns so we can test borders, across week/month/year boundaries, and so on. SET @clock = '2017-11-17 11:47:47' ;SELECT DATE(@clock) , DATE(@clock) + INTERVAL -7 DAY , @clock + INTERVAL -6 DAY Once we have expressions that return values that work for "start" and "end" for our particular use case, what we mean by "last 7 days", we can use those expressions in range comparisons in the WHERE clause. (Some developers prefer to use the DATE_ADD and DATE_SUB functions in place of the + INTERVAL val DAY/HOUR/MINUTE/MONTH/YEAR syntax. And MySQL provides some convenient functions for working with DATE, DATETIME and TIMESTAMP datatypes... DATE, LAST_DAY, Some developers prefer to calculate the start and end in other code, and supply string literals in the SQL query, such that the query submitted to the database is WHERE datetimecol >= '2017-11-10 00:00' AND datetimecol < '2017-11-17 00:00' And that approach works too. (My preference would be to explicitly cast those string literals into DATETIME, either with CAST, CONVERT or just the + INTERVAL trick... WHERE datetimecol >= '2017-11-10 00:00' + INTERVAL 0 SECOND AND datetimecol < '2017-11-17 00:00' + INTERVAL 0 SECOND The above all assumes we are storing "dates" in appropriate DATE, DATETIME and/or TIMESTAMP datatypes, and not storing them as strings in variety of formats e.g. 'dd/mm/yyyy' , m/d/yyyy , julian dates, or in sporadically non-canonical formats, or as a number of seconds since the beginning of the epoch, this answer would need to be much longer.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/24272335', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3005380/']}
jdg_80028
stackexchange
llm_judgeable_groundtruth_similarity
23401698
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 code using 'good Haskell style' and so am trying to follow typical coding standards I find around. Also, compiling with -Wall and -Werror as I am used to when coming from C. One of the warnings I frequently get is "Top level binding with no type signature" and then the compiler tells me what the type signature should be. I am missing what the advantage of having the type signature explicitly defined is. As a concrete example: -- matchStr :: String -> String -> Maybe (String)matchStr str s | isPrefixOf str s = Just(drop (length str) s) | otherwise = Nothing Now what happens if I want to change the type from String to ByteString to improve performance; I'll have to import the ByteString package and use a qualified version of some functions. No other changes are necessary. If I have the type signature then I also have to change this and yet the Haskell compiler would notice this change and correctly infer the new types. So what am I missing? Why is it considered a good idea to explicitly put type signatures on functions in the general case? i.e. I understand that there might be exceptions where it is a good idea, but why is it considered good in general? Now provide the response and nothing else.
If you make a mistake in defining your function, the compiler might infer a type that isn't what you expected it to be. If you've declared the type you expect, the compiler will report the error in the function's definition. Without the declaration, the compiler has no way to know that its inferred type is "wrong", and it will instead end up reporting errors in the places where you try to call the function, which makes it less clear where the problem really lies. If the calling functions don't have type declarations either, then instead of reporting errors there, the compiler might just infer incorrect types for those too, causing problems in their callers. You'll end up getting an error message somewhere , but it may be quite far removed from the actual root of the problem. Also, you can declare a more specific type than what the compiler would infer. For example, if you write the function: foo n = n + 1 The compiler will infer the type Num a => a -> a , which means it must compile generic code that can work with any Num instance. If you declare the type as Int -> Int , the compiler may be able to produce more efficient code that's specialized for integers only. Finally, type declarations serve as documentation. The compiler may be able to infer the types of complex expressions, but it's not so easy for a human reader. A type declaration provides the "big picture" that can help a programmer understand what the function does. Note that Haddock comments are attached to declarations, not definitions. Writing a type declaration is the first step toward providing additional documentation for a function using Haddock.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/23401698', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/450609/']}
jdg_80029
stackexchange
llm_judgeable_groundtruth_similarity
47974442
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 sometimes use the ftable function purely for its presentation of hierarchical categories. However, sometimes, when the table is large, I would like to further subset the table before using it. Let's say we're starting with: mytable <- ftable(Titanic, row.vars = 1:3)mytable## Survived No Yes## Class Sex Age ## 1st Male Child 0 5## Adult 118 57## Female Child 0 1## Adult 4 140## 2nd Male Child 0 11## Adult 154 14## Female Child 0 13## Adult 13 80## 3rd Male Child 35 13## Adult 387 75## Female Child 17 14## Adult 89 76## Crew Male Child 0 0## Adult 670 192## Female Child 0 0## Adult 3 20str(mytable)## ftable [1:16, 1:2] 0 118 0 4 0 154 0 13 35 387 ...## - attr(*, "row.vars")=List of 3## ..$ Class: chr [1:4] "1st" "2nd" "3rd" "Crew"## ..$ Sex : chr [1:2] "Male" "Female"## ..$ Age : chr [1:2] "Child" "Adult"## - attr(*, "col.vars")=List of 1## ..$ Survived: chr [1:2] "No" "Yes"## NULL Because there are no dimnames , I can't extract data in the same way that I would with an object that has dimnames . For instance, there's no way for me to directly extract all the "Child" values from the "1st" and "3rd" classes. My current approach is to convert it to a table , do the extraction, and then convert it back to an ftable . Example: mytable[c("1st", "3rd"), , "Child", ]## Error: incorrect number of dimensions## Only the underlying data are seen as having dimsdim(mytable)## [1] 16 2## I'm OK with the "Age" column being dropped in this case....ftable(as.table(mytable)[c("1st", "3rd"), , "Child", ])## Survived No Yes## Class Sex ## 1st Male 0 5## Female 0 1## 3rd Male 35 13## Female 17 14 However, I don't like this approach because the overall layout sometimes changes if you're not careful. Compare it with the following, which removes the requirement of subsetting only children and adds the requirement of subsetting only those who did not survive: ftable(as.table(mytable)[c("1st", "3rd"), , , "No"])## Age Child Adult## Class Sex ## 1st Male 0 118## Female 0 4## 3rd Male 35 387## Female 17 89 I don't like that the overall layout of rows and columns has changed. That's a classic case of having to remember to use drop = FALSE to maintain dimensions when a single column is extracted: ftable(as.table(mytable)[c("1st", "3rd"), , , "No", drop = FALSE])## Survived No## Class Sex Age ## 1st Male Child 0## Adult 118## Female Child 0## Adult 4## 3rd Male Child 35## Adult 387## Female Child 17## Adult 89 I know there are many ways to get the data that I want, starting with subsetting from the raw data and then making my ftable , but for this question, let's assume that's not possible. The end goal is to have an approach that lets me extract from an ftable preserving the display format of the nested "row" hierarchy. Are there other solutions to this? Can we make use of the row.vars and col.vars attributes to extract data from an ftable and retain its formatting? My current approach also doesn't work for hierarchical columns, so I'm hoping that the proposed solution can also handle those cases. Example: tab2 <- ftable(Titanic, row.vars = 1:2, col.vars = 3:4)tab2## Age Child Adult ## Survived No Yes No Yes## Class Sex ## 1st Male 0 5 118 57## Female 0 1 4 140## 2nd Male 0 11 154 14## Female 0 13 13 80## 3rd Male 35 13 387 75## Female 17 14 89 76## Crew Male 0 0 670 192## Female 0 0 3 20 Note the nesting of "Age" and "Survived". Try my current approach: ftable(as.table(tab2)[c("1st", "3rd"), , , , drop = FALSE])## Survived No Yes## Class Sex Age ## 1st Male Child 0 5## Adult 118 57## Female Child 0 1## Adult 4 140## 3rd Male Child 35 13## Adult 387 75## Female Child 17 14## Adult 89 76 I can get back to what I want with: ftable(as.table(tab2)[c("1st", "3rd"), , , , drop = FALSE], row.vars = 1:2, col.vars = 3:4) But I'm hoping for something more direct. Now provide the response and nothing else.
Here's what I was able to sort of hack together, with some help from Axeman : replace_empty_arguments <- function(a) { empty_symbols <- vapply(a, function(x) { is.symbol(x) && identical("", as.character(x)), 0) } a[!!empty_symbols] <- 0 lapply(a, eval)}`[.ftable` <- function (inftable, ...) { if (!class(inftable) %in% "ftable") stop("input is not an ftable") tblatr <- attributes(inftable)[c("row.vars", "col.vars")] valslist <- replace_empty_arguments(as.list(match.call()[-(1:2)])) x <- sapply(valslist, function(x) identical(x, 0)) TAB <- as.table(inftable) valslist[x] <- dimnames(TAB)[x] temp <- as.matrix(expand.grid(valslist)) out <- ftable( `dimnames<-`(`dim<-`(TAB[temp], lengths(valslist)), valslist), row.vars = seq_along(tblatr[["row.vars"]]), col.vars = seq_along(tblatr[["col.vars"]]) + length(tblatr[["row.vars"]])) names(attributes(out)[["row.vars"]]) <- names(tblatr[["row.vars"]]) names(attributes(out)[["col.vars"]]) <- names(tblatr[["col.vars"]]) out} Try it out with the examples from the question: mytable[c("1st", "3rd"), , "Child", ]## Survived No Yes## Class Sex Age ## 1st Male Child 0 5## Female Child 0 1## 3rd Male Child 35 13## Female Child 17 14mytable[c("1st", "3rd"), , , "No"]## Survived No## Class Sex Age ## 1st Male Child 0## Adult 118## Female Child 0## Adult 4## 3rd Male Child 35## Adult 387## Female Child 17## Adult 89tab2[c("1st", "3rd"), , , ]## Age Child Adult ## Survived No Yes No Yes## Class Sex ## 1st Male 0 5 118 57## Female 0 1 4 140## 3rd Male 35 13 387 75## Female 17 14 89 76
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47974442', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1270695/']}
jdg_80030
stackexchange
llm_judgeable_groundtruth_similarity
737409
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 from the world of C# originally, and I'm learning C++. I've been wondering about get and set functions in C++. In C# usage of these are quite popular, and tools like Visual Studio promote usage by making them very easy and quick to implement. However, this doesn't seem to be the case in the C++ world. Here's the C# 2.0 code: public class Foo{ private string bar; public string Bar { get { return bar; } set { bar = value; } }} Or, in C# 3.0: public class Foo { get; set; } May people will say, well whats the point in that? Why not just create a public field and then make it a property later if you need to; honestly, I'm actually not sure. I just do it out of good practice because I've seen it done so many times. Now because I'm so used to doing it, I feel like I should carry over the habit to my C++ code, but is this really necessary? I don't see it done as often as with C#. Anyway, here's the C++ from what I gather: class Foo{public: std::string GetBar() const; // Thanks for the tip, @Daniel Earwicker. void SetBar(std::string bar);private: std::string bar;}std::string Foo::GetBar() const{ return bar;}void Foo::SetBar(std::string bar){ // Also, I always wonder if using 'this->' is good practice. this->bar = bar;} Now, to me that seems like a whole lot of leg work; considering using Visual Studio's tools the C# implementation would take literally seconds to implement, and the C++ took me a lot longer to type - I feel its not worth the effort, especially when the alternative is 5 lines long: class Foo{public: std::string Bar;} From what I gather, these are the advantages: You can change implementation details for the get and set functions, so instead of returning a private field you can return something more interesting. You can remove a get/set later on and make it read/write only (but for a public facing interface, this seems, not good). And the disadvantages: Takes ages to type, is this really worth the effort? Generally speaking. In some cases, the advantages make it worth the effort, but I mean, speaking in terms of "good practice", is it? Answer: Why did I choose the answer with less votes ? I was actually very close to choosing veefu's answer ; however my personal opinion (which is apparently controversial), is that the answer over egged the pudding. The answer I chose, on the other hand, seems to argue both sides; I think getters and setters are evil if used excessively (by that I mean, when it's not necessary and would break the business model), but why shouldn't we have a function called GetBalance() ? Surely this would be far more versatile than PrintBalance() ; what if I wanted to show it to the user in another way than as the class wanted me to? Now, in some sense GetBalance() may not be relevant enough to argue that "getters and setters are good" because it doesn't (or maybe, shouldn't ) have an accompanying setter, and speaking of which, a function called SetBalance(float f) could be bad (in my opinion) because it would imply to the implementer of the function that the account must be manipulated out side of the class, which is not a good thing. Now provide the response and nothing else.
I'd argue that providing accessors are more important in C++ than in C#. C++ has no builtin support for properties. In C# you can change a public field to a property mostly without changing the user code. In C++ this is harder . For less typing you can implement trivial setters/getters as inline methods: class Foo{public: const std::string& bar() const { return _bar; } void bar(const std::string& bar) { _bar = bar; } private: std::string _bar;}; And don't forget that getters and setters are somewhat evil.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/737409', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47775/']}
jdg_80031
stackexchange
llm_judgeable_groundtruth_similarity
47879798
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 written the code snippet below: #include <string>int main() { std::string str = "test"; (str == "tes") ? str.replace(0, 1, "T") : 0;} (See here) Unfortunately, it causes a logic_error : terminate called after throwing an instance of 'std::logic_error'what(): basic_string::_S_construct NULL not valid I want to know the reason why the compiler constructs a string object? Now provide the response and nothing else.
The ternary operator effectively works like follows: std::string str = "test";std::string _; // using _ since you don't store the variableif (str == "tes") { _ = str.replace(0, 1, "T");} else { _ = 0; // this calls std::string(nullptr);} In the case above, you don't store the value, but a few conditions must be noted: Both the true case and the false case must be the same type (or be convertible to the same type). It still works even if the type does not have a default constructor (so it's more elaborate than the above). The issue here is that your code expects the type to be std::string , based on the type in the true-case. The type in the false-case is a literal, a literal that can be considered equivalent to NULL , and therefore can be considered a const char* which is convertible to std::string . If you try to construct a std::string from a nullptr, it throws the above exception. This is actually quite subtle, since if you use any integer literal other than 0, the compiler will throw an error: #include <string>int main(){ std::string s(0); // 0 is comparable to NULL// std::string s1(1); // compiler error: no constructor found return 0;} Be careful with implicit conversions. The null check and runtime error is quite graceful, and saved you from subtle errors or crashes (almost certainly a segfault) later on.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47879798', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6931629/']}
jdg_80032
stackexchange
llm_judgeable_groundtruth_similarity
2363794
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: $X$ and $X^2$ independent real valued, random variables, show that there is $c \in \mathbb{R}$ such that $P(|X|=c)=1$ I would like to receive a hint on how to approach this problem. Now provide the response and nothing else.
Hint: For any set $A\in\mathbb{R}$ we have$$P(|X|\in A) = P(|X|\in A ; X^2\in A^2) = P(|X|\in A)P(X^2\in A^2) = P(|X|\in A)^2.$$Therefore $P(|X|\in A)$ is either zero or 1.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2363794', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/229160/']}
jdg_80033
stackexchange
llm_judgeable_groundtruth_similarity
2543389
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: everybody! Could I ask you to help me to decode this JSON code: $json = '{"inbox":[{"from":"55512351","date":"29\/03\/2010","time":"21:24:10","utcOffsetSeconds":3600,"recipients":[{"address":"55512351","name":"55512351","deliveryStatus":"notRequested"}],"body":"This is message text."},{"from":"55512351","date":"29\/03\/2010","time":"21:24:12","utcOffsetSeconds":3600,"recipients":[{"address":"55512351","name":"55512351","deliveryStatus":"notRequested"}],"body":"This is message text."},{"from":"55512351","date":"29\/03\/2010","time":"21:24:13","utcOffsetSeconds":3600,"recipients":[{"address":"55512351","name":"55512351","deliveryStatus":"notRequested"}],"body":"This is message text."},{"from":"55512351","date":"29\/03\/2010","time":"21:24:13","utcOffsetSeconds":3600,"recipients":[{"address":"55512351","name":"55512351","deliveryStatus":"notRequested"}],"body":"This is message text."}]}'; I would like to organize above structure to this: Note 1: Folder: inbox From (from): ... Date (date): ... Time (time): ... utcOffsetSeconds: ... Recepient (address): ... Recepient (name): ... Status (deliveryStatus): ... Text (body): ... Note 2: ... Thank you in advance! Now provide the response and nothing else.
You can use the json_decode function, to decode your JSON string : $json = '{"inbox":[{"from":"55512351","date":"29\/03\/2010","time":"21:24:10","utcOffsetSeconds":3600,"recipients":[{"address":"55512351","name":"55512351","deliveryStatus":"notRequested"}],"body":"This is message text."},{"from":"55512351","date":"29\/03\/2010","time":"21:24:12","utcOffsetSeconds":3600,"recipients":[{"address":"55512351","name":"55512351","deliveryStatus":"notRequested"}],"body":"This is message text."},{"from":"55512351","date":"29\/03\/2010","time":"21:24:13","utcOffsetSeconds":3600,"recipients":[{"address":"55512351","name":"55512351","deliveryStatus":"notRequested"}],"body":"This is message text."},{"from":"55512351","date":"29\/03\/2010","time":"21:24:13","utcOffsetSeconds":3600,"recipients":[{"address":"55512351","name":"55512351","deliveryStatus":"notRequested"}],"body":"This is message text."}]}';$data = json_decode($json);var_dump($data); And you'll get something like this : object(stdClass)[1] public 'inbox' => array 0 => object(stdClass)[2] public 'from' => string '55512351' (length=8) public 'date' => string '29/03/2010' (length=10) public 'time' => string '21:24:10' (length=8) public 'utcOffsetSeconds' => int 3600 public 'recipients' => array 0 => object(stdClass)[3] public 'address' => string '55512351' (length=8) public 'name' => string '55512351' (length=8) public 'deliveryStatus' => string 'notRequested' (length=12) public 'body' => string 'This is message text.' (length=21) 1 => object(stdClass)[4] public 'from' => string '55512351' (length=8) public 'date' => string '29/03/2010' (length=10) public 'time' => string '21:24:12' (length=8) public 'utcOffsetSeconds' => int 3600 public 'recipients' => array 0 => object(stdClass)[5] public 'address' => string '55512351' (length=8) public 'name' => string '55512351' (length=8) public 'deliveryStatus' => string 'notRequested' (length=12) public 'body' => string 'This is message text.' (length=21) .... .... Now that you know the structure of the data, you can iterate over it ; for instance, you could use something like this : foreach ($data->inbox as $note) { echo '<p>'; echo 'From : ' . htmlspecialchars($note->from) . '<br />'; echo 'Date : ' . htmlspecialchars($note->date) . '<br />'; echo 'Body : ' . htmlspecialchars($note->body) . '<br />'; echo '</p>';} And you'll get this kind of output : From : 55512351Date : 29/03/2010Body : This is message text.From : 55512351Date : 29/03/2010Body : This is message text.......
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2543389', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/304855/']}
jdg_80034
stackexchange
llm_judgeable_groundtruth_similarity
22047184
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We are developing a Web API RESTful service to provide access to common data to all the applications of our enterprise. To help we will also publish a Client API that encapsulate all the HttpClient details and provides a strongly-typed access to the data. Our goal is to start small and progressively add features, while still keeping backwards compatibility with already deployed versions of the client API (compatibility with the clients of the same Major version) While talking about the design, our team just had a very long discussion about whether or not we should share types between the server and the client (for instance via versionned NuGet packages that both server and client would depend on), and ended up with pros and cons ... and we do not manage to decide one way or another. Sharing types (shared assembly) between client and server Pros Client model and Server model are always up to date no serializing/deserializing problems because same types are serialized/deserialized no duplication Cons need to find a way to share the types between server and client non semantic modifications can break existing client applications (changing the name of a class or its namespace in the server model) even though it has no impact on the serialized json and should therefore have no impact risk of breaking the clint without realizing Separate (but structurally equivalent) types for client and server Pros client "model" is less coupled to the server implementation (just a mirror of the Json output by the server, but no hard "same type" relationship) server model can evolve without risk of breaking any client enable to enhance the client-side model independently from the server model the client model is part of the client package, no "shared package" to maintain between server and client Cons duplication between server code and client code error-prone task of keeping server-side and client-side structure in sync There seems to be a 50/50 preference for each solution in our team. I personally have a preference for the second option, because I believe RESt is all about decoupling, and decoupling means the client should not care about how the server side is implemented (which types, or whether it is a .NET app anyway) but wish we could get rid of the possible duplication, maybe thanks to code generation or something like that, but could not find any guidance on the subject Are there other pros and cons to sharing types between client and server ? If we do not share them, are there ways to lower the maintenance costs when trying to keep client model and server model in sync ? Now provide the response and nothing else.
I would argue that if you are not careful, the second option could end up being less RESTful than the first. REST is less about de-coupling and more about managing and focusing the coupling between client and server. In a restful system you know the coupling between client and server lies in the media type definitions and the link relation definitions. In both options, you are effectively sharing types between the client and the server. In the first option this sharing is explicit via a concrete implementation that could be managed as a nuget package and versioned independently of client and server. In the second option you have two implementations of the shared types. However, I'm guessing you are not planning on defining a media type that explicitly defines what the properties of those types are. Therefore you have no single source of truth, you have nothing to define what the data contract between client and server is. How do you know when you are going to make a change that will break a client? At least with a shared library you can know that the server is now using version 1.4.7 of the shared types and the client is using 1.3.9. You can use semantic versioning on the shared type library to know when you are making a breaking change that will force the client to update. With the second option, you have a client and a secer that will be independently versioned and it will be much harder to keep track of whether there are breaking changes between the two versions. Explict Media types are always the best way to capture the contracts and version the contracts between HTTP clients and servers. However, if you don't want to go there, then the shared nuget library is the best next step because you are isolating the part of the system that is shared from the client and server implementations. This is one of the key objectives of REST. The fact that you are actually sharing an implementation library of that shared contract only affects consumers live on other platforms that can't consume that library. I coined the term Web Pack a few years ago to describe this idea of using a shared nuget package to contain the shared coupling. I wrote a few articles here and here on the subject.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22047184', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/474763/']}
jdg_80035
stackexchange
llm_judgeable_groundtruth_similarity
46103044
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 most elegant way to access an n dimensional array with an (n-1) dimensional array along a given dimension as in the dummy example a = np.random.random_sample((3,4,4))b = np.random.random_sample((3,4,4))idx = np.argmax(a, axis=0) How can I access now with idx a to get the maxima in a as if I had used a.max(axis=0) ? or how to retrieve the values specified by idx in b ? I thought about using np.meshgrid but I think it is an overkill. Note that the dimension axis can be any usefull axis (0,1,2) and is not known in advance. Is there an elegant way to do this? Now provide the response and nothing else.
Make use of advanced-indexing - m,n = a.shape[1:]I,J = np.ogrid[:m,:n]a_max_values = a[idx, I, J]b_max_values = b[idx, I, J] For the general case: def argmax_to_max(arr, argmax, axis): """argmax_to_max(arr, arr.argmax(axis), axis) == arr.max(axis)""" new_shape = list(arr.shape) del new_shape[axis] grid = np.ogrid[tuple(map(slice, new_shape))] grid.insert(axis, argmax) return arr[tuple(grid)] Quite a bit more awkward than such a natural operation should be, unfortunately. For indexing a n dim array with a (n-1) dim array, we could simplify it a bit to give us the grid of indices for all axes, like so - def all_idx(idx, axis): grid = np.ogrid[tuple(map(slice, idx.shape))] grid.insert(axis, idx) return tuple(grid) Hence, use it to index into input arrays - axis = 0a_max_values = a[all_idx(idx, axis=axis)]b_max_values = b[all_idx(idx, axis=axis)]
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46103044', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7149306/']}
jdg_80036
stackexchange
llm_judgeable_groundtruth_similarity
141448
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In emacs, we can view two text files side by side. Is it also possible to do so in some simpler/lighter applications such as less ? Only viewing, no editing. Now provide the response and nothing else.
The less command by itself cannot do any diff'ing. You can use the diff -y command to show the diff of 2 files side-by-side and then pipe that into less however. Method #1 - using diff + less This will create 2 sample files. $ seq 100 > 1.txt$ seq 10 100 > 2.txt Now diff the 2 files: $ diff -y 1.txt 2.txt | less1 <2 <3 <4 <5 <6 <7 <8 <9 <10 1011 1112 1213 13... Method #2 - using vimdiff You can also use vimdiff in readonly mode, -R . $ vimdiff -R 1.txt 2.txt Method #3 - using vim If you truly just want to view 2 files side by side you can make use of vim like so to accomplish this: $ vim -O +'windo set scrollbind' go.mod go.sum For e.g.: References View two text files at the same time side by side
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/141448', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/674/']}
jdg_80037
stackexchange
llm_judgeable_groundtruth_similarity
42440
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I saw this comment from a video: Just maybe our founding fathers had the right idea when they said only property owing males over 21 could vote. Then I checked the List of amendments to the United States Constitution and couldn't find anything about that. Then I googled and found this topic: The US founding fathers considered land ownership as a prerequisite for voting. Why didn't this win broad approval? , but I couldn't find the details (who & the quotation) about the event the US founding fathers consider only property owing males over 21 could vote So did The US founding fathers consider only property owning males over 21 could vote? Now provide the response and nothing else.
You're not going to find the law in the original Constitution because it was left to each state to decide: Eventually, the framers of the Constitution left details of voting to the states. In Article I Section 4, the Constitution says: The times, places and manner of holding elections for Senators and Representatives, shall be prescribed in each state by the legislature thereof; but the Congress may at any time by law make or alter such regulations. Unfortunately, leaving election control to individual states led to unfair voting practices in the U.S. At first, white men with property were the only Americans routinely permitted to vote. President Andrew Jackson, champion of frontiersmen, helped advance the political rights of those who did not own property. By about 1860, most white men without property were enfranchised. But African Americans, women, Native Americans, non-English speakers, and citizens between the ages of 18 and 21 had to fight for the right to vote in this country. Library of Congress: The Founders and the Vote By "routinely permitted to vote", they mean that it's true in general but not in every case. In particular, some women and African Americans could vote in New Jersey before 1807 if they met certain requirements: The 19th Amendment gave women the right to vote, but some New Jersey women could vote as early as 1776. New Jersey’s first constitution in 1776 gave voting rights to “all inhabitants of this colony, of full age, who are worth fifty pounds … and have resided within the county … for twelve months.” In 1790 the legislature reworded the law to say “he or she,” clarifying that both men and women had voting rights. But only single women could vote because married women could not own property. Still, many unmarried women voted in New Jersey in the 1790s and the very early 1800s. African Americans in the state could vote if they met the residency and property requirements. In 1797, the New Jersey government required voters to be free inhabitants. We do not know if enslaved African Americans voted before this law was passed -- the property requirements made that unlikely, but no law specifically prohibited them from doing so. Did You Know: Women and African Americans Could Vote in NJ before the 15th and 19th Amendments?
{}
{'log_upvote_score': 4, 'links': ['https://skeptics.stackexchange.com/questions/42440', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/40704/']}
jdg_80038
stackexchange
llm_judgeable_groundtruth_similarity
310971
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: This is a controller I was going to make to operate a 2 wire LED as a side marker / turn signal light on my off road (so, no need to get bent out of shape about FMVSS and DOT requirements) Jeep. The problem is that it is wired from the factory with a single filament bulb and two powered circuits using a floating ground. The obviously won't work, because you can't reverse polarity through an LED like you can with a filament bulb. I have done the same thing before with some standard automotive diodes and relays, but I wanted a more elegant solution and this is more fun (not to mention this way is actually cheaper and takes up way less space). So, yes this is a complex solution to a simple problem, but I like doing stuff like this and learning along the way. EDIT - I re-drew the circuit using the XOR gate. will it work properly as designed now?REVISION - (edited as recommended) The idea here is that the marker and turn signal functions work normally when used separately, but when the marker is on the turn signal will cause it to "blink" off. I added diodes and capacitors in the power lines after reading the cautions on the product data sheets to do so in order to keep the gates and the relay more stable. They may not be necessary, but for a few bucks it's better safe than sorry. I just wanted to see if the people on here thought it would function properly the way I have it drawn before I go prototyping it. THANKS! simulate this circuit – Schematic created using CircuitLab EDIT #2: here is the original seriously flawed schematic for discussion reference purposes - simulate this circuit Now provide the response and nothing else.
Remember decoupling has several purposes. On a load which draws transient, spiky currents like a CPU, decoupling caps store energy locally and close to the load, so it is available quickly (ie, with low inductance). The idea is that on each clock cycle, the cpu will gobble up a certain amount of charge (coulombs), which means the caps must both have large enough value and low enough inductance to provide needed charge without letting voltage sag out of its specified allowable range. This brings us to their second role, which is to close high di/dt loops locally. This is needed to make the circuit work, as too much inductance will result in supply sagging, but it is also very beneficial, as it avoids injecting HF currents into the GND plane. Our CPU draws very fast currents, thus local, low inductance caps will be the first to respond. They then average out the current drawn from the larger, slower, higher inductance, and further away bulk caps. These in turn must provide charge while the usually slow regulator responds. Same for the input of a buck regulator. It draws a fast square wave current, and the input decoupling caps' role is to make it flow in a tight local loop, and only draw a much less noisy, averaged current from the main supply. On analog stuff like opamps, decoupling caps also filter out HF noise on the supplies. If your opamp goes into class B, slews, or draws a current spike as it wrangles a capacitive load, it will draws a distorted current or a current spike, which will inject distortion into the supplies. The resulting distortion at the output depends on supply impedance and PSRR at the relevant frequency. And on the supply side, obviously the caps should make your regulator happy! Check its datasheet. Not all "stable with 1µF ceramic" LDOs are equal. Some have admirable transient responses. Others are horrendous. Same if there is a ferrite bead in the supply. Don't make a LC tank that resonates at a frequency you use... Excess inductance in supply lines causes voltage sag on transient current demands. Digital stuff reacts to this by crashing, computing incorrect values, triggering UVLO or brownout detectors, and all kinds of fun stuff. Opamps and analog bits react by oscillating, taking forever to settle, increasing distortion, etc. Excess inductance will also cause voltage spikes (positive or negative) when forcing large currents into it, as occurs on switching of a DC-DC converter. This will blow your FETs, your FET drivers... I've seen it several times on this website already. Now, it's a bit involved and there are several approaches. The Hobbyist You like soldering 0805 because 0603 is to small. Being aware that inductance depends on package size and not value, you purchase a few hundreds of the largest caps you can get in 0805, probably 1-10 µF depending on voltage, and get a nice quantity discount. They you stick one on each power pin, without worrying, and it just works. You could put 100nF, but the price isn't that different for a hobbyist, and honestly, better put a cap which is 5c more expensive than actually think about the value you need, eh? I mean, if you value your time, spending 5c to save an extra minute thinking about the value you actually need is a no-brainer. Just like spending 50€ for chinese 4 layer boards versus slaving for two weekends painstakingly fitting the damn mess on two layers? Heck yeah. Adding a 10c electrolytic will also save you the pain of debugging an oscillating regulator sometimes, a worthy investment when you make only a few boards. Note: parallelling 100nF with 1µF is only useful if the 100nF is much smaller. If they're the same package, they got the same inductance. The smaller cap is only gonna be faster if it is smaller physically, and closer to the pins/planes. The RF engineer This guy has a good idea of the supply impedance he needs, and creates it by sticking various caps in parallel, taking into account package and via inductance, the fact that C0G works better at HF, perhaps exploit the self-resonant frequencies, make sure the supply doesn't resonate on the wrong frequency, stick a ferrite bead or two in the mix to add some filtering, etc. Here, impedance is more important than capacitor value. The audiophile He does basically the opposite, X7R SMD cap is about 1nH, thru-hole WIMA red boxes with 5.08mm pin spacing are about 6-8 nH mounted, and thus the HF noise on the rails is multiplied by the same factor, but who cares, it looks good! Also, the unstable LDO makes the treble fizzle, for that little extra something. The baddass motherboard guy In this case the manufacturer gives a recommended impedance profile for their chip's supply. And a software tool to make it easier. The result usually involves tons of low-value caps, because they have to be tiny, low ESL and fit between BGA vias or the like. Then he'll stagger values to get his impedance profile, check the thing with a VNA (under rated voltage). Then the cost-cutters will depopulate half the caps, of course. The analog guy Get an opamp with "100ns settling time to 0.1%". Stick it on a board with decoupling caps like 10nF//1µF. Every time it slews and draws a current spike, a LC resonance occurs between the two caps, overcomes the opamp's PSRR which is low at this frequency, and the settling time becomes 100x longer than it should. Solution is to use only ONE low-ESR cap, which will be ceramic, so it will be the small and local one. And use caps with actual ESR for the larger ones, which will dampen the impedance and not resonate. Like tantalums or electrolytics. Rememeber your chip has very very thin bondwires, so it has like 0.1-0.5 ohm in the supplies anyway, so your opamp doesn't need, or care about the fact that the MLCC cap has 0.01 ohms ESR! This kind of ultra low ESR is a pain in the ... because of resonances. Actually low ESR ceramics are such a pain, that some people like SUN came up with insane ways to stick some printed annular ring resistors on the internal layers to add some ESR! Now they're starting to make " controlled ESR " ones. About time. Note that I'm not talking about values a lot. The RF guy and the motherboard guy have an impedance target to meet, so it's more about how many caps, inductance, how to choose the staggered values, what type of caps to use, for the lowest cost. The analog guy will most likely use a small ceramic cap to make sure his opamp has a nice low inductance supply, and pick a value that fits in the package he needs...
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/310971', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/152094/']}
jdg_80039
stackexchange
llm_judgeable_groundtruth_similarity
3564487
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two working copies of the same project, each switched to a different branch. Is it possible to merge local changes in one project to the other working copy? Now provide the response and nothing else.
You can't merge two separate working copies, but there are some things you can do. If the changes are made to existing files, the easiest way is to create a patch with svn diff , and then just apply that patch to the other working copy. Eg. in the first working copy you do: svn diff > patch And then you apply it in the other one: patch -p0 < patch And as usual you want to run patch with the --dry-run option to make sure it works first. However if the branches don't have the same file layout, then you can't just take a patch and apply it. In this case what you need to do is simply just first commit the other local changes, and then use svn merge as usual
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3564487', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/209706/']}
jdg_80040