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
|
445890
|
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:
If I run the command ip link | awk '{print $2}' in Ubuntu 18.04, I get this output: lo:00:00:00:00:00:00wlp1s0:2c:6e:85:bf:01:00enp2s0:14:18:77:a3:01:02 I want it formatted like this (without lo ) wlp1s0: 2c:6e:85:bf:01:00enp2s0: 14:18:77:a3:01:02 How do I do this?
Now provide the response and nothing else.
|
You can get the MAC address from /sys/class/net/<dev>/address : $ cat /sys/class/net/enp0s3/address08:00:27:15:dc:fd So, something like: find /sys/class/net -mindepth 1 -maxdepth 1 ! -name lo -printf "%P: " -execdir cat {}/address \; Gives me: enp0s3: 08:00:27:15:dc:fddocker0: 02:42:61:cb:85:33 Or, using ip 's one-line mode, which is convenient for scripting: $ ip -o link | awk '$2 != "lo:" {print $2, $(NF-2)}'enp0s3: 08:00:27:15:dc:fddocker0: 02:42:61:cb:85:33
|
{}
|
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/445890', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/266428/']}
|
jdg_373241
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
378021
|
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:
Trying to create GPG keys which will be used for an apt repository hosted on my Centos7 box. I created a new user "apt", and then tried to create the keys, but at the very end, it states that I need a pass phrase, but then instantly closes stating cancelled by user. No it wasn't! I have since successfully repeated these same steps root and as my standard username which happens to be in the wheels group. Two questions: Is it a good idea to use different gpg keys for different uses such as this apt repository, and should keys ever be created as root? Why am I not able to create a gpg key for this user? Do I need to first create some other key for this user? Thanks [apt@devserver ~]$ gpg --gen-keygpg (GnuPG) 2.0.22; Copyright (C) 2013 Free Software Foundation, Inc.This is free software: you are free to change and redistribute it.There is NO WARRANTY, to the extent permitted by law.Please select what kind of key you want: (1) RSA and RSA (default) (2) DSA and Elgamal (3) DSA (sign only) (4) RSA (sign only)Your selection?RSA keys may be between 1024 and 4096 bits long.What keysize do you want? (2048)Requested keysize is 2048 bitsPlease specify how long the key should be valid. 0 = key does not expire <n> = key expires in n days <n>w = key expires in n weeks <n>m = key expires in n months <n>y = key expires in n yearsKey is valid for? (0) 1yKey expires at Thu 12 Jul 2018 04:32:05 PM UTCIs this correct? (y/N) yGnuPG needs to construct a user ID to identify your key.Real name: somenameEmail address: example@gmail.comComment:You selected this USER-ID: "somename <example@gmail.com>"Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? OYou need a Passphrase to protect your secret key.gpg: cancelled by usergpg: Key generation canceled.[apt@devserver ~]$
Now provide the response and nothing else.
|
As to the "cancelled by user" error: GnuPG tries to make sure it's reading the passphrase directly from the terminal, not (e.g.) piped from stdin. To do so, it tries to open the tty directly. Unfortunately, file permissions get in the way — the tty device is owned by the user you log in as. So only that user and root can open it. GnuPG appears to report the error incorrectly, saying you canceled (when in fact it got a permission denied). As to if you should have a separate key for the repository: yes. There are a couple of reasons that come to mind: A repository can be maintained by more than one person. All of them will need access to the key. You obviously don't want to give them access to your personal key. The software processing new packages will need access to the key. For many repositories, that means you have to keep the key available on an Internet-connected machine. This necessitates a lower level of security than you'd ideally have on your personal key. If you're processing uploads automatically, you may even need to store the key with no passphrase. Obviously lowers security. In case of compromise of your personal key, it's nice to only have to revoke that. Same with compromise of the repository key. It makes revoking a compromised key cheaper. It's pretty normal to use your personal key to sign the repository key. As to running key generation as root: not ideal (don't run things as root without good reason), but likely not really an issue.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/378021', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/137912/']}
|
jdg_373242
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43873546
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Android I tried to use textAlign to make the text justified but it doesn't work. <Text style={{textAlign: 'justify',color:'#1B3D6C', margin: 20}}> Lorem ipsum dolor sit amet, et usu congue vocibus, ei sea alienum repudiandae, intellegam quaerendum an nam. Vocibus apeirian no vis, eos cu conguemoo scaevola accusamus. Et sea placerat persecutii oinn</Text> Edit :Ok , textAlign justify doesnt work on Android , so what im asking now if there is some solution to this? I really need!
Now provide the response and nothing else.
|
Android does not support text justification. The docs of React Native Text component about the style attribute says: textAlign enum('auto', 'left', 'right', 'center', 'justify') :Specifies text alignment. The value 'justify' is only supported on iOSand fallbacks to left on Android . A workaround for this limitation is to use a React Native WebView component. The content of the WebView can be an HTML code with the justified text. Like this: <View style={{flex: 1}}> <WebView source={{ html: "<p style='text-align: justify;'>Justified text here</p>" }} /></View>
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43873546', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6832877/']}
|
jdg_373243
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
40318257
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So there's that: https://groups.google.com/forum/?fromgroups#!topic/golang-dev/Ab1sFeoZg_8 : Today I submitted changes to the garbage collector that make typical worst-case stop-the-world times less than 100 microseconds. This should particularly improve pauses for applications with many active goroutines, which could previously inflate pause times significantly. High GC pauses are one of the things JVM users struggle with for a long time. What are the (architectural?) constraints which prevent JVM from lowering GC pauses to Go levels, but are not affecting Go?
Now provide the response and nothing else.
|
2021 Update : With OpenJDK 16 ZGC now has a max pause time of <1ms and average pause times 50µs It achieves these goals while still performing compaction, unlike Go's collector. Update : With OpenJDK 17 Shenandoah exploits the same techniques introduced by ZGC and achieves similar results . What are the (architectural?) constraints which prevent JVM from lowering GC pauses to golang levels There aren't any fundamental ones as low-pause GCs have existed for a while (see below). So this may be more a difference of impressions either from historic experience or out-of-the-box configuration rather than what is possible. High GC pauses are one if the things JVM users struggle with for a long time. A little googling shows that similar solutions are available for java too Azul offers a pauseless collector that scales even to 100GB+ Redhat is contributing shenandoah to openjdk and oracle zgc . IBM offers metronome , also aiming for microsecond pause times various other realtime JVMs The other collectors in openjdk are, unlike Go's, compacting generational collectors. That is to avoid fragmentation problems and to provide higher throughput on server-class machines with large heaps by enabling bump pointer allocation and reducing the CPU time spent in GC. And at least under good conditions CMS can achieve single-digit millisecond pauses, despite being paired with a moving young-generation collector. Go's collector is non-generational, non-compacting and requires write barriers (see this other SO question ), which results in lower throughput/more CPU overhead for collections, higher memory footprint (due to fragmentation and needing more headroom) and less cache-efficient placement of objects on the heap (non-compact memory layout). So GoGC is mostly optimized for pause time while staying relatively simple (by GC standards) at the expense of several other performance and scalability goals.JVM GCs make different tradeoffs. The older ones often focused on throughput. The more recent ones achieve low pause times and several other goals at the expense of higher complexity.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40318257', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/706650/']}
|
jdg_373244
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
280913
|
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:
Please could someone validate this proof Prove that the sets $(A\cap B)$ \ C and $(A\cap C)$ \ B are disjoint. First we want to show that (1) $(A\cap B)$ \ C $\not \subseteq $ $(A\cap C)$ \ B Assume $ x \in (A\cap B)$ \ C. Then, by the definition of intersection $ x \in A$ and $x \in B$. We are told that $ x \notin C $. Given that $ x \notin $ C, $ x \notin $ $A\cap C$. Furthermore, we know that $ x \in $ B. So, by the definition of setminus, $ x \notin (A\cap C)$ \ B. This proves (1) (2) $(A\cap C)$ \ B$\not \subseteq$ $(A\cap B)$\ C Assume $ x \in (A\cap C)$ \ B. Then, by the definition of intersection $ x \in A$ and $x \in C$. We know by the definition of setminus that $ x \notin B $. Given that $ x \notin $ B, $ x \notin $ $A\cap B$. Furthermore, we know that $ x \in $ C. So, by the definition of setminus, $ x \notin (A\cap B)$ \ C. This proves (2) Thanks in advance
Now provide the response and nothing else.
|
You can’t show that $X\cap Y=\varnothing$ by showing that $X\nsubseteq Y$ and $Y\nsubseteq X$: what if $X=\{0,1\}$ and $Y=\{1,2\}$, say? To show that $(A\cap B)\setminus C$ and $(A\cap C)\setminus B$ are disjoint, just show that if $x\in(A\cap B)\setminus C$, then $x\notin(A\cap C)\setminus B$; that’s all it takes. So suppose that $x\in(A\cap B)\setminus C$; then $x\in A\cap B$, and $x\notin C$. Since $x\notin C$, clearly $x\notin A\cap C$, and it follows at once that $x\notin(A\cap C)\setminus B$. Note that this is exactly the argument that you gave for your (1). The argument is fine, but it doesn’t show what you thought it showed; instead, it does the whole job for you.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/280913', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/43735/']}
|
jdg_373245
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7899359
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to place a best guess estimate as to whether C2DM messages can be received. I've created an application that relies on pushing information to a phone while it is physically inaccessible. I understand that C2DM isn't guaranteed delivery, but I'd at least like to know when the delivery of a message is even possible; when it isn't we fall back to our own push service (and can actually tell when we're connected). I've noticed C2DM on android will still issue auth tokens even when there is not a logged in google account; messages still seem to be delivered in this instance even though it's stated that they shouldn't be. If GTalk isn't connected (firewall or other reasons), no response at all is returned when requesting an auth token. Auth tokens are returned to the application when the phone is in airplane mode. This means it's not as simple as checking if an internet is available. I can't find a reliable way of checking if GTalk is logged in. Again, I don't need to guarantee the delivery of messages, but I'd at least like to know if delivery is even possible . Does anyone have interesting solutions?
Now provide the response and nothing else.
|
Go watch this video , it's a Google I/O talk about C2DM, how to use it and how it works. AFAIK, you can't know if it's connected or not. Probably most of the time they don't even know (until they have to deliver a message and fail). However, it is highly recommended (in the video as well) that you do not send important data through C2DM (as messages can get lost). The service should only be used as a "network tickle" (with a footprint as small as possible). Your application should be woken up by this tickle and it should start fetching the information it needs itself . Now, if you implement it this way, it should be easy to implement a polling mechanism. Since you already separated the "tickle" from the actual information retrieval, you can just trigger the retrieval every once in a while if there's no tickle. Something you can do to check whether C2DM is connected is something like a ping: Send message to phone via C2DM The app receives (or doesn't receive) the message and sends a "pong" back to your server The server waits for the "pong" for a predetermined amount of time (1-2 minutes, I'd say) before marking the device as "offline". Edit: relying on GTalk is not feasible. GTalk relies on C2DM just like your app, it doesn't have anything "extra". Also, GTalk is not present on all devices. I'm not sure how the GTalk app determines whether it's offline or not (it's not open source, unfortunately), but I'd guess it just tries to ping a server and fails.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7899359', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/120226/']}
|
jdg_373246
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
255637
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am unable to prove that For every real $x>0$ and every integer $n>0$, there is one and only one real $y>0$ such that $y^n=x$. Can anyone please help me here? It is clear that there is at most one such real $y$. But how do I go about the existence of such a real?
Now provide the response and nothing else.
|
What you are asking for is the existence of $n$ -th root. This is true in $\mathbb{R}$ but not in $\mathbb{Q}$ (for example $\not \exists q\in \mathbb{Q}:q^2=2$ ). Any proof of this will require the completeness of the real line (Least Upper Bound Property). LUB property: Every subset of $\mathbb{R}$ bounded above must have a supremum. Here is a typical proof of this theorem only using the LUB property and the Binomial Theorem. Let $x>1$ and $S=\left\{ a>0: a^n<x \right\}$ . Obviously $1\in S$ and so $S\neq \emptyset $ . Since $x>1\Rightarrow x^n>x$ we have that $S$ is bounded above by $x$ . Therefore, by the Least Upper Bound Property, $\exists \sup S=r\in \mathbb{R}$ . We shall prove that $r^n=x$ . Suppose that $r^n>x$ and let \begin{equation}\epsilon =\dfrac{1}{2}\min \left\{ 1,\frac{r^n-x}{\sum\limits_{k=1}^n{\binom{n}{k}r^{n-k}}} \right\}\end{equation} Then $0<\epsilon <1$ and so $\epsilon ^n<1$ . Therefore, by the Binomial Theorem, \begin{gather}(r-\epsilon )^n=\sum\limits_{k=0}^{n}{\dbinom{n}{k}r^{n-k}(-\epsilon )^k}=r^n-\epsilon \sum\limits_{k=1}^n{\dbinom{n}{k}r^{n-k}}\epsilon ^{k-1}(-1)^{k-1}\ge \\r^n-\epsilon \sum\limits_{k=1}^n{\dbinom{n}{k}r^{n-k}}\epsilon ^{k-1}> r^n-\epsilon \sum\limits_{k=1}^n{\dbinom{n}{k}r^{n-k}}\\(r-\epsilon)^n>r^n-\dfrac{r^n-x}{\displaystyle\sum\limits_{k=1}^n{\dbinom{n}{k}r^{n-k}}} \displaystyle\sum\limits_{k=1}^n{\dbinom{n}{k}r^{n-k}}=r^n-r^n+x=x\Rightarrow \left( r-\epsilon \right)^n>x\end{gather} which is a contradiction since $r=\sup S$ and $r-\epsilon <r$ Suppose that $r^n<x$ and let \begin{equation}\epsilon =\dfrac{1}{2}\min \left\{ 1,\frac{x-r^n}{\sum\limits_{k=1}^n{\binom{n}{k}r^{n-k}}} \right\}\end{equation} Then, $0<\epsilon <1$ and so $\epsilon ^n<1$ . Therefore, by the Binomial Theorem, \begin{gather}(r+\epsilon )^n=\sum\limits_{k=0}^{n}{\dbinom{n}{k}r^{n-k}\epsilon^k}=r^n+\epsilon \sum\limits_{k=1}^n{\dbinom{n}{k}r^{n-k}}\epsilon ^{k-1}<\\ r^n+\epsilon \sum\limits_{k=1}^n{\dbinom{n}{k}r^{n-k}}\\(r+\epsilon)^n<r^n+\dfrac{x-r^n}{\displaystyle\sum\limits_{k=1}^n{\dbinom{n}{k}r^{n-k}}} \displaystyle\sum\limits_{k=1}^n{\dbinom{n}{k}r^{n-k}}=r^n+x-r^n=x\Rightarrow (r+\epsilon)^n<x\end{gather} and so $\sup S=r<r+\epsilon\in S$ which is a contradiction. Therefore, $r^n=x$ if $x>1$ Let $0<x<1$ . Then $\frac{1}{x}>1\Rightarrow \exists r>0:r^n=\frac{1}{x}\Rightarrow \exists r'=\frac{1}{r}>0:r'^n=\frac{1}{r}^n=\frac{1}{r^n}=x$ . If $x=1$ then $r=1$ . EDIT: Motivation as per request: As I said this is statement is not true if we replace $\mathbb{R}$ with $\mathbb{Q}$ . What sets $\mathbb{R}$ and $\mathbb{Q}$ apart is the completeness of $\mathbb{R}$ . The LUB property therefore must in some way be used. This is why we define $S$ . Because the LUB is an existensial theorem, it shows the existence of a supremum but not its value, it is often used in proofs by contradiction. So assuming $r^n>x$ we need to arrive to a contradiction. Remember $r$ is a very special number, the supremum of $S$ . If we could show that $\exists m\in \mathbb{R}$ so that $m<r$ and is an upper bound of $S$ or $m>r$ and $m\in S$ then we are done. This is what we do with $m=r-\epsilon$ in the first case and with $m=r+\epsilon$ in the second. It all boils down to finding an $\epsilon>0$ so that $r-\epsilon$ is an upper bound of $S$ , that is $(r-\epsilon)^n>x$ . We can make this $\epsilon$ as small as we want. I shall choose an $\epsilon$ for $n=2$ . \begin{equation}(r-\epsilon )^2=r^2-2r\epsilon+\epsilon^2>r^2-2r\epsilon-\epsilon\end{equation} Remember we want $(r-\epsilon )^2>x$ and so it suffices \begin{equation}r^2-2r\epsilon-\epsilon>x\Leftrightarrow \epsilon<\frac{r^2-x}{1+2r}\end{equation}
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/255637', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/43981/']}
|
jdg_373247
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11805207
|
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 does one go about getting specific pieces of information, like the 'duration' from the output of ffmpeg -i /var/thismovie.avi ? I need frame height, frame width, duration of movie and frame rate. All of these are in the out put of the above command but how do i get the bits i need individually and put them in a variable in PHP? I've given up on trying to install ffmpeg-php which is what I used before this to do the same job. Thanks ffmpeg -i /var/thismovie.avi produce an output like this ffmpeg version N-43171-ga763caf Copyright (c) 2000-2012 the FFmpeg developers built on Aug 3 2012 07:56:19 with gcc 4.1.2 (GCC) 20080704 (Red Hat 4.1.2-52) configuration: --enable-version3 --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libvpx --enable-libfaac --enable-libmp3lame --enable-libtheora --enable-libvorbis --enable-pic --enable-libx264 --enable-libxvid --disable-ffplay --enable-shared --enable-gpl --enable-postproc --enable-nonfree --enable-avfilter --enable-pthreads --extra-cflags=-fPIC libavutil 51. 66.100 / 51. 66.100 libavcodec 54. 48.100 / 54. 48.100 libavformat 54. 22.100 / 54. 22.100 libavdevice 54. 2.100 / 54. 2.100 libavfilter 3. 5.102 / 3. 5.102 libswscale 2. 1.100 / 2. 1.100 libswresample 0. 15.100 / 0. 15.100 libpostproc 52. 0.100 / 52. 0.100 [avi @ 0x18e8e240] non-interleaved AVI [avi @ 0x18e8e240] max_analyze_duration 5000000 reached at 5000000 Input #0, avi, from '/var/www/vhosts/mysite.com/httpdocs/movie.avi': Duration: 00:00:10.76, start: 0.000000, bitrate: 5180 kb/s Stream #0:0: Video: h264 (High) (H264 / 0x34363248), yuv420p, 1280x720 [SAR 1:1 DAR 16:9], 25 fps, 25 tbr, 25 tbn, 50 tbc Stream #0:1: Audio: ac3 ([0] [0][0] / 0x2000), 48000 Hz, stereo, s16, 128 kb/s At least one output file must be specified`
Now provide the response and nothing else.
|
Based on ffprobe solution suggested by @blahdiblah and inspired by another question answer: https://github.com/paulofreitas/php-ffprobe Note: requires ffmpeg 0.9+, supports ALL ffmpeg supported file types Using the class // Example 1$info = new ffprobe($filename);var_dump($info->format->format_long_name); // e.g. string(10) "AVI format"var_dump($info->streams[0]->duration); // e.g. string(11) "5674.674675"// Example 2 (prettified)$info = new ffprobe($filename, true);var_dump($info->format->format_long_name); // e.g. string(10) "AVI format"var_dump($info->streams[0]->duration); // e.g. string(14) "1:34:34.674675" Extending the class class ffprobe_ext extends ffprobe{ public function __construct($filename) { parent::__construct($filename); } public function getVideoStream() { foreach ($this->streams as $stream) { if ($stream->codec_type == 'video') { return $stream; } } } public function getVideoInfo() { $stream = $this->getVideoStream(); $info = new ArrayObject(array(), ArrayObject::ARRAY_AS_PROPS); $info->duration = (float) $stream->duration; $info->frame_height = (int) $stream->height; $info->frame_width = (int) $stream->width; eval("\$frame_rate = {$stream->r_frame_rate};"); $info->frame_rate = (float) $frame_rate; return $info; }}$ffprobe = new ffprobe_ext($filename);$info = $ffprobe->getVideoInfo();var_dump($info->duration); // e.g. float(5674.674675) Welcome to further improvements! :-)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11805207', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1135898/']}
|
jdg_373248
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
209293
|
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to solve a set of 5 nonlinear equations using NSolve: exp1 := y*E^(x - z) == 18 a*x + b*yexp2 := E^(x - z) == 8 a*y + b (x + z)exp3 := -y*E^(x - z) == 72 a*z + b*yexp4 := 9 x^2 + 4 y^2 + 36 z^2 == 36exp5 := x*y + y*z == 1NSolve[{exp1, exp2, exp3, exp4, exp5}, {x, y, z, a, b}, Reals] But after 30 minutes running it gives me nothing and I stopped running it because I've thought that I did something wrong or used a non-suitable method.So my question is: Why Mathematica cannot solve this problem in the way that I've asked for?
Now provide the response and nothing else.
|
AbsoluteTiming[ xyz = Reduce[{exp1, exp2, exp3, exp4, exp5, Element[{x, y, z}, Reals]}, {x, y, z}, {a, b}]; ans = NSolve[{exp1, exp2, exp3, xyz}, {x, y, z, a, b}] // Quiet; ] ans {exp1, exp2, exp3, exp4, exp5} /. ans Output {0.466927, Null} {{x -> 0.222444, y -> -2.15701, z -> -0.686049, a -> -0.200401, b -> 2.10858}, {x -> 0.155142, y -> 0.904622, z -> 0.950293, a -> -0.0124473, b -> 0.489938}, {x -> -1.95192, y -> -0.545867, z -> 0.119973, a -> 0.00314125, b -> -0.0762384}, {x -> 1.13873, y -> 1.76806, z -> -0.573138, a -> 0.317141, b -> 1.86267}} {{True, True, True, True, True}, {True, True, True, True, True}, {True, True, True, True, True}, {True, True, True, True, True}}
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/209293', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/68347/']}
|
jdg_373249
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1053849
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This question was bugging me for quite a while (as evidenced by my previous question ): why exactly is print(x) better (which is defined as being more pythonic) than print x ? For those who don't know, the print statement was changed into function in Python 3.0. The formal documentation is in PEP 3105 and motivation is in Guido van Rossum's email . To those points I would like to make a counterpoint: There are other operators, such as import which we write as a statement, though their functionality is actually duplicated with a function __import__ To beginners, the operator print does not belong to the general application logic. To them it's the mysterious operator which is a culmination of their program. They expect it to look differently. All the beginner books which were describing basic Python 2.x are now guaranteed to be broken from the first example . Certainly, languages sometimes change, but those changes are usually less visible to novices. It's not immediately obvious to me that a functionality of print can be duplicated on an application level. For example, sometimes I would like to redirect print from a console as a modal OS dialog. While people say it's hard to rewrite all print statements to a function, they have forced every Python 2.x developer to do exactly that for all their projects. Good, it's not hard with automatic converter. Everyone who enjoys having an ability to manipulate function print would be just as well-served if print was a statement wrapping function __print__ . So, can we please have a canonical answer to this question on the pages of Stack Overflow?
Now provide the response and nothing else.
|
Looks to me like yours is a debate, not a question -- are you really going to accept an answer that shows how deeply and badly wrong you were in your assertions?! On to your debating points: There are other operators, such as import which we write as a statement, though their functionality is actually duplicated with a function __import__ Absolutely wrong: function __import__ (like every other function -- and operator, for that matter) binds no names in the scope of "caller" (code containing it) -- any "thingie" that binds names in the "caller's scope" must be a statement (just like assignment, def , and call ). Your "point" appears to totally miss the extremely deep and crucial distinction that Python draws between statements and expressions -- one may reasonably dislike this distinction, but ignoring it is, most obviously, simply wrong. Python statements are things the Python compiler must be specifically aware of -- they may alter the binding of names, may alter control flow, and/or may need to be entirely removed from the generated bytecode in certain conditions (the latter applies to assert ). print was the only exception to this assertion in Python 2; by removing it from the roster of statements, Python 3 removes an exception, makes the general assertion "just hold", and therefore is a more regular language. Special cases are not special enough to break the rules has long been a Pythonic tenet (do import this at an interactive interpreter's >>> prompt to see "the Zen of Python" displayed), and this change to the language removes a violation of this tenet that had to remain for many years due to an early, erroneous design decision. To beginners, the operator print does not belong to the general application logic. To them it's the mysterious operator which is a culmination of their program. They expect it to look differently. Curing beginners of their misconceptions as early as feasible is a very good thing. All the beginner books which were describing basic Python 2.x are now guaranteed to be broken from the fist example. Certainly, languages sometimes changes, but changes are usually less visible to novices. Languages rarely change in deep and backwards-incompatible ways (Python does it about once a decade) and few language features are "highly visible to novices", so the total number of observations is small -- yet even within that tiny compass we can easily find counter-examples, where a feature highly visible to beginners was just so badly designed that removing it was well worth the disruption. For example, modern dialects of Basic, such as Microsoft's Visual Basic, don't use explicit user-entered line numbers, a "feature" that was both terrible and highly visible to absolutely everybody since it was mandatory in early dialects of Basic. Modern variants of Lisp (from Scheme onwards) don't use dynamic scoping, a misfeature that was sadly highly visible (usually manifesting as hard-to-understand bugs in their code) to beginners, basically as soon as they started writing functions in Lisp 1.5 (I once was a beginner in that and can testify to how badly it bit me). It's not immediately obvious to me that a functionality of print can be duplicated on an application level. For example, sometimes I would like to redirect print from a console as a modal OS dialog. Not sure I follow this "point". Just change sys.stdout to your favorite pseudo-file object and redirect to your heart's contents -- you have the option of monkey patching the built-in function print (which you never had in Python 2), but nobody's twisting your arm and forcing you to do so. While people say it's hard to rewrite all print statements to a function, they have forced every Python 2.x developer to do exactly that for all their projects. Good, it's not hard with automatic converter. The 2to3 tool does indeed take care of all such easy surface incompatibilities -- no sweat (and it needs to be run anyway to take care of quite a few more besides print , so people do use it extensively). So, what's your "point" here? Everyone who enjoys having an ability to manipulate function print would be just as well-served if print was a statement wrapping function print . Such an arrangement would not, per se, remove an unnecessary keyword (and most especially, an unjustified irregularity , as I explained above: a statement that has no good reason to be a statement because there is absolutely no need for the compiler to be specially aware of it in any way, shape, or form!). It's far from clear to me that having such an underlying function would add any real value, but if you have real use cases you can certainly propose the case in the Python Ideas mailing list -- such an underlying function, if proven to be precious indeed, could be retrofitted to be used by the print statement in Python 2.7 as well as by the print function in Python 3.2. However, consider a typical case in which one might want to monkey-patch the built-in print : adding keyword arguments to allow fancy tweaks. How would the __print__ function you're apparently proposed ever ge those KW arguments from a __print__ statement? Some funkier syntax yet than the horrors of >> myfile and the trailing comma...?! With print as a function, keyword arguments follow just the perfectly normal and ordinary rules that apply to every function and function call -- bliss! So, in summary, it's more Pythonic for print to be a function because it removes anomalies, special cases, and any need for weird exceptional syntax -- simplicity, regularity, and uniformity are Python's trademark.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1053849', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/115200/']}
|
jdg_373250
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10338289
|
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 style information on the Contextual Action bar (CAB). I just need to change the colour of the text in fact.. As you can see from the above, this is using the standard Theme.Holo.Light.DarkActionBar theme, so I just need to set the text colour to white! Can anyone point me in the right direction?
Now provide the response and nothing else.
|
To change the color/etc of the text in a contextual action bar: public boolean onCreateActionMode(ActionMode mode, Menu menu) { //mode.setTitle("Contextual Action Bar"); (replace this call) TextView tv= (TextView)getLayoutInflater().inflate(R.layout.contextual_title, null); tv.setText("Contextual Action Bar"); mode.setCustomView(tv); where layout/contextual_title.xml contains a single TextView with your desired color/size/style etc In fact, almost everything in a contextual action bar can be styled. The only problem is that searching for the word 'contextual' leads nowhere useful. The relevant styling features are all called "actionMode...". Here are some I used (defined in my Theme.) <item name="android:actionModeCloseDrawable">@drawable/check</item><item name="android:actionModeCutDrawable">@drawable/ic_menu_cut_holo_dark</item><item name="android:actionModeCopyDrawable">@drawable/ic_menu_copy_holo_dark</item><item name="android:actionModePasteDrawable">@drawable/ic_menu_paste_holo_dark</item><item name="android:actionModeSelectAllDrawable">@drawable/ic_menu_selectall_holo_dark</item><item name="android:actionModeBackground">@drawable/contextual</item><item name="android:actionModeCloseButtonStyle">@style/MyCloseButton</item><!-- these change the press backgrounds for the vanilla actionBar and for search --><item name="android:windowContentOverlay">@null</item><item name="android:selectableItemBackground">@drawable/bar_selector</item><item name="android:actionBarItemBackground">@drawable/bar_selector</item> <!-- these were defined in platform/.../data/res/values/... but Eclipse didn't recognize them --><!--? item name="android:actionModeShareDrawable">@drawable/icon</item --><!--? item name="android:actionModeFindDrawable">@drawable/icon</item --><!--? item name="android:actionModeWebSearchDrawable">@drawable/icon</item --><!-- item name="android:actionModeBackground">@drawable/red</item --><!-- and finally --><style name="MyCloseButton" parent="android:style/Widget.ActionButton.CloseMode"> <item name="android:background">@drawable/bar_selector</item></style> You can easily set your own text-editing cut/paste/copy/selectall icons, the bar background, and the icon background that changes color when you press the icons(bar_selector above). The icons are ImageViews, not buttons, and the edit id's (and the pressable background) are attached to the ImageView's parent (one parent per view) which is an 'internal' type. It's never clear what goes where in the styles--I found where selectableItemBackground was in the platform Themes.xml, and copied and modified the drawable pointed at.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10338289', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/316825/']}
|
jdg_373251
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24304759
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to add Git-Lab on Eclipse? So that I can just push or fetch from GitLab.I am a newbie in this, please give more explanation.
Now provide the response and nothing else.
|
I Preparation Make sure you have eGit in Eclipse: Help -> Installation details See that "Eclipse Git Team provider" is in the list. If it is not installed, follow the indications in the answer from @VonC Make sure you have the URL to the repository in GitLab. Something like https://gitlab.com/<someusername>/<somerepository> You get it from gitlab.com when you are at the overview page for the project: Menu (the hamburger icon ≡, 3 horizontal lines),-> projects, then click in the one you want to work with from eclipse. Now you are in the overview page. Right beneath the name of the project and its description there are a few buttons to allow you to perform some actions. One of those buttons is a selector for SSH/HTTPS protocols. For now, select HTTPS and copy the URL that follows it: that is the URL to the project. II Now clone the repository locally, using Eclipse eGit. These steps have been tested in Eclipse Kepler and Eclipse Luna. Rumor has it that they are outdated and might not work as indicated. If you use a newer Eclipse, take care and post back the new steps :-) Window -> Open Perspective -> Other Search for "Git", select it, and click "OK" Click the button with an arrow and the tool tip "Clone a Git repository and add the clone to this view" In the "Source Git Repository" wizard: URI: the URL from the repository in GitLab, like https://gitlab.com/<someusername>/<somerepository> eGit has filled in the host and repository path for you. Leave the connection as it is (https and no port) and fill in the details for the authentication: user and password you use to log in GitLab.com. If you tick the "Store in Secure Store," Eclipse will handle user/password for you from now on; I do it, but it is not advisable if you share Eclipse installation with someone else, or you do not trust your PC to hold your passwords. Click next Branch selection wizard. If there are more than one branch in the repository, you may now choose which one you want to clone locally, the one with which you want to interact. You may also choose to clone all branches to have them available. Once you are done, click Next Local destination wizard. You may now choose where you want to place your local Git repository. eGit defaults to a subdirectory under you user, unrelated to eclipse, it works well. If you do not like it, change to your liking. As with other Git installations, it will name the GitLab.com repository as "origin". You may also change that if you really want. In the projects box check the "Import all projects" and, if you work with "Working Sets", you may choose now in which one to place it. Click Finish. eGit now works for a bit and shows you the newly cloned repository in the view. You have a cloned repository with which you will be able to interact from Eclipse. III Now import the project into Eclipse. File -> Import... Git -> Projects from Git -> Next Existing local repository -> Next Select the newly cloned repository -> Next Import using the New Project Wizard -> Finish Choose the project type that is hosted in GitLab.com. In my case is "Java Project;" in other occasions it has been "Maven -> Maven Project". Then click Next Name the project and change the settings you want. As destination, do not use the default location, but navigate to the location of the cloned repository (as used in step 6 in the previous section cloning the repository ) -> Next Verify that the import looks like you want it and click Finish. You may now work within Eclipse and use the Team menus to sync and commit and push.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24304759', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3239489/']}
|
jdg_373252
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8690911
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have tried var dateHeaders = HttpContext.Current.Request.Headers["Date"] but it contains null, apparently there is no such key. Can anyone tell me where else can I find the time-zone of the current client? Reference: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields I want to parse dateTime to the following format: Sun Nov 14 43745 00:00:00 GMT+0200 (Jerusalem Standard Time) btw, what's the '43745' part?
Now provide the response and nothing else.
|
The date header is not one that is sent in standard http requests. I just ran a quick check with fiddler using both IE and Firefox and didn't see the date header sent on any requests. The best that you can do on the server is get the user's culture, but this will only help with the date format, not the timezone. However, you can get the information from javascript using getTimezoneOffset. For example: var timeNow = new Date();var timezone = timeNow.getTimezoneOffset() / 60 * (-1); There is an excellent description here .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8690911', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/311130/']}
|
jdg_373253
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
55570990
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to create a simple countdown for my game, when the game starts I want this function to be called every second: fun minusOneSecond(){ if secondsLeft > 0{ secondsLeft -= 1 seconds_thegame.text = secondsLeft.toString() }} I tried this: var secondsLeft = 15timer.scheduleAtFixedRate( object : TimerTask() { override fun run() { minusOneSecond() } },0, 1000) // 1000 Millisecond = 1 second But the app unfortunately stops, the 2nd time the run function is called I just started with android development and Kotlin 3 weeks ago and so far I understand the most out of it. With swift in Xcode I use this line and I thought something similar would work with Kotlin setTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(minusOneSecond), userInfo: nil, repeats: true)
Now provide the response and nothing else.
|
Problem: Timer class uses a background thread with a queue to queue and execute all tasks sequentially. From your code, because you update UI (changing TextView content in minusOneSecond function). That why the app throws the following exception and make your app crash. android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. Solution: There are many ways to achieve your task, but I prefer using post() and postDelayed() method from Handler class. Because it's simple and easy to understand. val mainHandler = Handler(Looper.getMainLooper())mainHandler.post(object : Runnable { override fun run() { minusOneSecond() mainHandler.postDelayed(this, 1000) }}) Update: From author's comment about how to pause/resume the task from Handler. Here is an example. class MainActivityKt : AppCompatActivity() { lateinit var mainHandler: Handler private val updateTextTask = object : Runnable { override fun run() { minusOneSecond() mainHandler.postDelayed(this, 1000) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Your logic code ... mainHandler = Handler(Looper.getMainLooper()) } override fun onPause() { super.onPause() mainHandler.removeCallbacks(updateTextTask) } override fun onResume() { super.onResume() mainHandler.post(updateTextTask) } fun minusOneSecond() { if secondsLeft > 0 { secondsLeft -= 1 seconds_thegame.text = secondsLeft.toString() } }}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/55570990', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5158122/']}
|
jdg_373254
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
752517
|
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:
From Wikipedia ...the free group $F_{S}$ over a given set $S$ consists of all expressions (a.k.a. words, or terms) that can be built from members of $S$, considering two expressions different unless their equality follows from the group axioms (e.g. $st = suu^{−1}t$, but $s ≠ t$ for $s,t,u \in S$). The members of $S$ are called generators of $F_{S}$. I don't understand the distinction between " $a$ and $b$ freely generate a group " , "$a$ and $b$ generate a free group " and just checking if a group is free. For example I thought that if $a$ and $b$ freely generate a group then that group is free and vice versa. However I have seen statements like " $a$ and $b$ freely generate a free subgroup of..." quite a few times and so there seems to be some distinction between the terms. If so could you please provide an example where one of the conditions hold bit the other doesn't? If, for example, $S=\{a,b\}$, but $a^{3}=1$ and $b^{2}=1$ is it the case that $S$ cannot generate a free group even if any word written using only the letters $a$,$a^2$ and $b$ (excluding powers of these) has a unique representation? If we say that we are considering words in $\{a,b\}$ does that mean that we consider words using $a$,$b$, $a^{-1}$ and $b^{-1}$ as letters and identifying $b^2=1$ and $a^3=1$ in the process of reducing the letter or that we use any integer power of and b and only reduce identities that hold by group axioms independent of the actual group structure we are considering? I apologize if the question is confusing but I am quite confused myself. If you think there is any way of clarifying the question please feel free to suggest it. Thank you.
Now provide the response and nothing else.
|
I don't know why I didn't say the following at the outset. I guess I was just going along with your method. Rid your proof of trigonometric functions and instead do the following: $$t\mapsto (x,y) = \begin{cases} \phantom{\lim\limits_{t\to\infty}} \left( \dfrac{1-t^2}{1+t^2}, \dfrac{2t}{1+t^2} \right) & \text{if }t\ne\infty, \\[10pt]\lim\limits_{t\to\infty} \left( \dfrac{1-t^2}{1+t^2}, \dfrac{2t}{1+t^2} \right) & \text{if }t=\infty.\end{cases}$$ That's a homeomorphism from $\mathbb R\cup\{\infty\}$ to $\{(x,y)\in\mathbb R^2:x^2+y^2=1\}$. To show that it's surjective, show that $t=\dfrac{y}{x+1}$ (and notice that $\dfrac{y}{x+1}\to\infty$ as $(x,y)\to(-1,0)$ along the curve $x^2+y^2=1$).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/752517', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/137056/']}
|
jdg_373255
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5639000
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When playing around with multithreading, I could observe some unexpected but serious performance issues related to AtomicLong (and classes using it, such as java.util.Random), for which I currently have no explanation. However, I created a minimalistic example, which basically consists of two classes: a class "Container", which keeps a reference to a volatile variable, and a class "DemoThread", which operates on an instance of "Container" during thread execution. Note that the references to "Container" and the volatile long are private, and never shared between threads (I know that there's no need to use volatile here, it's just for demonstration purposes) - thus, multiple instances of "DemoThread" should run perfectly parallel on a multiprocessor machine, but for some reason, they do not (Complete example is at the bottom of this post). private static class Container { private volatile long value; public long getValue() { return value; } public final void set(long newValue) { value = newValue; }}private static class DemoThread extends Thread { private Container variable; public void prepare() { this.variable = new Container(); } public void run() { for(int j = 0; j < 10000000; j++) { variable.set(variable.getValue() + System.nanoTime()); } }} During my test, I repeatedly create 4 DemoThreads, which are then started and joined. The only difference in each loop is the time when "prepare()" gets called (which is obviously required for the thread to run, as it otherwise would result in a NullPointerException): DemoThread[] threads = new DemoThread[numberOfThreads]; for(int j = 0; j < 100; j++) { boolean prepareAfterConstructor = j % 2 == 0; for(int i = 0; i < threads.length; i++) { threads[i] = new DemoThread(); if(prepareAfterConstructor) threads[i].prepare(); } for(int i = 0; i < threads.length; i++) { if(!prepareAfterConstructor) threads[i].prepare(); threads[i].start(); } joinThreads(threads); } For some reason, if prepare() is executed immediately before starting the thread, it will take twice as more time to finish, and even without the "volatile" keyword, the performance differences were significant, at least on two of the machines and OS'es I tested the code. Here's a short summary: Mac OS Summary: Java Version: 1.6.0_24 Java Class Version: 50.0 VM Vendor: Sun Microsystems Inc. VM Version: 19.1-b02-334 VM Name: Java HotSpot(TM) 64-Bit Server VM OS Name: Mac OS X OS Arch: x86_64 OS Version: 10.6.5 Processors/Cores: 8 With volatile keyword: Final results: 31979 ms. when prepare() was called after instantiation. 96482 ms. when prepare() was called before execution. Without volatile keyword: Final results: 26009 ms. when prepare() was called after instantiation. 35196 ms. when prepare() was called before execution. Windows Summary: Java Version: 1.6.0_24 Java Class Version: 50.0 VM Vendor: Sun Microsystems Inc. VM Version: 19.1-b02 VM Name: Java HotSpot(TM) 64-Bit Server VM OS Name: Windows 7 OS Arch: amd64 OS Version: 6.1 Processors/Cores: 4 With volatile keyword: Final results: 18120 ms. when prepare() was called after instantiation. 36089 ms. when prepare() was called before execution. Without volatile keyword: Final results: 10115 ms. when prepare() was called after instantiation. 10039 ms. when prepare() was called before execution. Linux Summary: Java Version: 1.6.0_20 Java Class Version: 50.0 VM Vendor: Sun Microsystems Inc. VM Version: 19.0-b09 VM Name: OpenJDK 64-Bit Server VM OS Name: Linux OS Arch: amd64 OS Version: 2.6.32-28-generic Processors/Cores: 4 With volatile keyword: Final results: 45848 ms. when prepare() was called after instantiation. 110754 ms. when prepare() was called before execution. Without volatile keyword: Final results: 37862 ms. when prepare() was called after instantiation. 39357 ms. when prepare() was called before execution. Mac OS Details (volatile): Test 1, 4 threads, setting variable in creation loop Thread-2 completed after 653 ms. Thread-3 completed after 653 ms. Thread-4 completed after 653 ms. Thread-5 completed after 653 ms. Overall time: 654 ms. Test 2, 4 threads, setting variable in start loop Thread-7 completed after 1588 ms. Thread-6 completed after 1589 ms. Thread-8 completed after 1593 ms. Thread-9 completed after 1593 ms. Overall time: 1594 ms. Test 3, 4 threads, setting variable in creation loop Thread-10 completed after 648 ms. Thread-12 completed after 648 ms. Thread-13 completed after 648 ms. Thread-11 completed after 648 ms. Overall time: 648 ms. Test 4, 4 threads, setting variable in start loop Thread-17 completed after 1353 ms. Thread-16 completed after 1957 ms. Thread-14 completed after 2170 ms. Thread-15 completed after 2169 ms. Overall time: 2172 ms. (and so on, sometimes one or two of the threads in the 'slow' loop finish as expected, but most times they don't). The given example looks theoretically, as it is of no use, and 'volatile' is not needed here - however, if you'd use a 'java.util.Random'-Instance instead of the 'Container'-Class and call, for instance, nextInt() multiple times, the same effects will occur: The thread will be executed fast if you create the object in the Thread's constructor, but slow if you create it within the run()-method. I believe that the performance issues described in Java Random Slowdowns on Mac OS more than a year ago are related to this effect, but I have no idea why it is as it is - besides that I'm sure that it shouldn't be like that, as it would mean that it's always dangerous to create a new object within the run-method of a thread, unless you know that no volatile variables will get involved within the object graph. Profiling doesn't help, as the problem disappears in this case (same observation as in Java Random Slowdowns on Mac OS cont'd ), and it also does not happen on a single-core-PC - so I'd guess that it's kind of a thread synchronization problem... however, the strange thing is that there's actually nothing to synchronize, as all variables are thread-local. Really looking forward for any hints - and just in case you want to confirm or falsify the problem, see the test case below. Thanks, Stephan public class UnexpectedPerformanceIssue {private static class Container { // Remove the volatile keyword, and the problem disappears (on windows) // or gets smaller (on mac os) private volatile long value; public long getValue() { return value; } public final void set(long newValue) { value = newValue; }}private static class DemoThread extends Thread { private Container variable; public void prepare() { this.variable = new Container(); } @Override public void run() { long start = System.nanoTime(); for(int j = 0; j < 10000000; j++) { variable.set(variable.getValue() + System.nanoTime()); } long end = System.nanoTime(); System.out.println(this.getName() + " completed after " + ((end - start)/1000000) + " ms."); }}public static void main(String[] args) { System.out.println("Java Version: " + System.getProperty("java.version")); System.out.println("Java Class Version: " + System.getProperty("java.class.version")); System.out.println("VM Vendor: " + System.getProperty("java.vm.specification.vendor")); System.out.println("VM Version: " + System.getProperty("java.vm.version")); System.out.println("VM Name: " + System.getProperty("java.vm.name")); System.out.println("OS Name: " + System.getProperty("os.name")); System.out.println("OS Arch: " + System.getProperty("os.arch")); System.out.println("OS Version: " + System.getProperty("os.version")); System.out.println("Processors/Cores: " + Runtime.getRuntime().availableProcessors()); System.out.println(); int numberOfThreads = 4; System.out.println("\nReference Test (single thread):"); DemoThread t = new DemoThread(); t.prepare(); t.run(); DemoThread[] threads = new DemoThread[numberOfThreads]; long createTime = 0, startTime = 0; for(int j = 0; j < 100; j++) { boolean prepareAfterConstructor = j % 2 == 0; long overallStart = System.nanoTime(); if(prepareAfterConstructor) { System.out.println("\nTest " + (j+1) + ", " + numberOfThreads + " threads, setting variable in creation loop"); } else { System.out.println("\nTest " + (j+1) + ", " + numberOfThreads + " threads, setting variable in start loop"); } for(int i = 0; i < threads.length; i++) { threads[i] = new DemoThread(); // Either call DemoThread.prepare() here (in odd loops)... if(prepareAfterConstructor) threads[i].prepare(); } for(int i = 0; i < threads.length; i++) { // or here (in even loops). Should make no difference, but does! if(!prepareAfterConstructor) threads[i].prepare(); threads[i].start(); } joinThreads(threads); long overallEnd = System.nanoTime(); long overallTime = (overallEnd - overallStart); if(prepareAfterConstructor) { createTime += overallTime; } else { startTime += overallTime; } System.out.println("Overall time: " + (overallTime)/1000000 + " ms."); } System.out.println("Final results:"); System.out.println(createTime/1000000 + " ms. when prepare() was called after instantiation."); System.out.println(startTime/1000000 + " ms. when prepare() was called before execution.");}private static void joinThreads(Thread[] threads) { for(int i = 0; i < threads.length; i++) { try { threads[i].join(); } catch (InterruptedException e) { e.printStackTrace(); } }} }
Now provide the response and nothing else.
|
It's likely that two volatile variables a and b are too close to each other, they fall in the same cache line; although CPU A only reads/writes variable a , and CPU B only reads/writes variable b , they are still coupled to each other through the same cache line. Such problems are called false sharing . In your example, we have two allocation schemes: new Thread new Threadnew Container vs new Threadnew Thread ....new Container new Container.... new Container In the first scheme, it's very unlikely that two volatile variables are close to each other. In the 2nd scheme, it's almost certainly the case. CPU caches don't work with individual words; instead, they deal with cache lines. A cache line is a continuous chunk of memory, say 64 neighboring bytes. Usually this is nice - if a CPU accessed a cell, it's very likely that it will access the neighboring cells too. Except in your example, that assumption is not only invalid, but detrimental. Suppose a and b fall in the same cache line L . When CPU A updates a , it notifies other CPUs that L is dirty. Since B caches L too, because it's working on b , B must drop its cached L . So next time B needs to read b , it must reload L , which is costly. If B must access main memory to reload, that is extremely costly, it's usually 100X slower. Fortunately, A and B can communicate directly about the new values without going through main memory. Nevertheless it takes extra time. To verify this theory, you can stuff extra 128 bytes in Container , so that two volatile variable of two Container will not fall in the same cache line; then you should observe that the two schemes take about the same time to execute. Lession learned: usually CPUs assume that adjecent variables are related. If we want independent variables, we better place them far away from each other.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5639000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/704454/']}
|
jdg_373256
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1392059
|
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 facing this unique problem of generating a bit-mask based on the input parameter. For example, if param = 2, then the mask will be 0x3 (11b)if param = 5, then the mask will be 0x1F (1 1111b) This I implemented using a for-loop in C, something like int nMask = 0;for (int i = 0; i < param; i ++) { nMask |= (1 << i);} I would like to know if there is a better algorithm ~~~
Now provide the response and nothing else.
|
One thing to notice about bitmasks like that is that they are always one less than a power of two. The expression 1 << n is the easiest way to get the n-th power of two. You don't want Zero to provide a bitmask of 00000001 , you want it to provide zero. So you need to subtract one. mask = (1 << param) - 1; Edit: If you want a special case for param > 32: int sizeInBits = sizeof(mask) * BITS_PER_BYTE; // BITS_PER_BYTE = 8;mask = (param >= sizeInBits ? -1 : (1 << param) - 1); This method should work for 16, 32, or 64 bit integers, but you may have to explicitly type the '1'.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1392059', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/70702/']}
|
jdg_373257
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
168354
|
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:
Quantizing the EM field gives you the standard sum of all quantum harmonic oscillators as given by this hamiltonian: $$\hat{H} = \sum_k \hbar\omega_k( \hat{a}^\dagger_k \hat{a}_k + 1/2)$$ Conceptually it makes most sense when discussing a cavity, as each harmonic oscillator corresponds to a mode with a different number of excitations in it. However, I'm having trouble understanding this formulation when applying it to a free field. A free field is just a cavity with infinitely large boundaries, right? That would seem to imply that for each frequency, there is only one harmonic oscillator. I have also heard from many sources, including colleagues, that you can see the field as composed of a collection of harmonic oscillators separated in space. However, I find that difficult to reconcile with the above equation. What is the best way to visually interpret this?
Now provide the response and nothing else.
|
Warning : long answer ahead. To see pictures, scroll down. A free field is just a cavity with infinitely large boundaries, right? Right. This is how it's constructed: take a finite cavity with periodic boundary conditions, and then let its size tend to infinity. I have also heard from many sources, including colleagues, that you can see the field as composed of a collection of harmonic oscillators separated in space. No, the oscillators here represent eigenmodes of the field, which live in the reciprocal space—the space of wave vectors. That would seem to imply that for each frequency, there is only one harmonic oscillator. Not quite: for each frequency there's an infinite number of wavevectors. And for each wave vector there is one harmonic oscillator. What is the best way to visually interpret this? It's easier to start from simpler fields, rather than electromagnetic: in particular, in a discrete and finite medium. A good example of such a medium is a lattice of point masses connected by springs. This medium can transmit waves, and the Schrödinger's equation for such a medium is exactly solvable. A finite chain of point masses as a model of a scalar field $$\newcommand{\tran}{^{\mkern-1.5mu\mathsf{T}}}$$ Consider several point particles of mass $m$ connected by Hookean springs. Let one end of this chain be attached by a spring to a wall (the second end remaining free), so that all the eigenmodes of this system were standing waves, rather than running waves (this will simplify visualization a bit). The potential energy of this system will look like $$V(x_1,x_2,\dots,x_N)=\frac{m\omega^2}2\left(x_1^2+\sum_{n=2}^N (x_n-x_{n-1})^2\right),\tag1$$ where $N$ is number of particles, and $x_n$ is displacement of $n$ th particle from its equilibrium position. Let's denote the vector of all displacements as $\mathbf{x}$ : $$\mathbf{x}=\begin{pmatrix}x_1\\x_2\\\cdots\\x_N\end{pmatrix}.\tag2$$ The classical equation of motion will then be $$\frac1{\omega^2}\frac{d^2}{dt^2}\mathbf{x}=M\mathbf{x},\tag3$$ where $$M=\begin{pmatrix}-2 & 1 & 0 & 0 & \cdots &\cdots& 0 \\ 1 & -2 & 1 & 0 & & & \vdots\\ 0 & 1 & -2 & 1 & & & \vdots\\ 0 & 0 & 1 & -2 & & & \vdots\\\vdots & & & & \ddots & & \vdots\\\vdots & & & & & -2 & 1 \\ 0 &\dots&\dots&\dots& \dots & 1 & -1 \\\end{pmatrix}\tag4$$ Notice how this matrix resembles the 1D Laplacian matrix from finite differences method . In fact, in the limit of continuous medium we'll indeed get a wave equation from $(3)$ —which is isomorphic to the Klein-Gordon equation for a massless field! Due to our chosen configuration with one end being attached to a wall, and another being free, the continuous equation would have homogeneous Dirichlet boundary on one side and Neumann boundary on the other. Substituting $$\mathbf{x}=\mathbf A e^{i\Omega_k t},\; k\in\{1,2,\dots,N\},\tag5$$ we get the equations for eigenmodes of oscillation: $$-\frac{\Omega_k^2}{\omega^2}\mathbf{x}=M\mathbf{x}.\tag6$$ The eigenvectors $\mathbf{\xi} _ n$ of the matrix $M$ define the axes of the hyper-ellipsoids described by $V=\mathrm{const}$ . Expressed in coordinates along these axes, $V$ becomes a sum of independent oscillators—eigenmodes of the collective motion of all the particles. Namely, in this basis we'll have displacements $\mu_k$ of the modes , via $$\mu_k=\mathbf x\tran\mathbf{\xi}_k,\tag7$$ and $V$ will get the following form: $$V=\frac m2 \sum_{k=1}^N \Omega_k^2\mu_k^2.\tag8$$ Kinetic energy is invariant with respect to rotations in configuration space, so we don't worry about it: it'll be separable in any of these coordinates. Here're the first 3 normal modes for the case $N=50$ : Quantum version of the scalar field model Equation $(8)$ makes it very easy to solve the quantum counterpart of the problem. Namely, the Schrödinger's equation for the whole system of connected particles becomes simply a system of $N$ independent equations, one for each eigenmode. The solution of the Schrödinger's equation, $$-\frac{\hbar^2}{2m}\sum_{k=1}^N\partial_{x_k}^2\psi+V\psi=E\psi, \tag9$$ is the product of the well-known Hermite polynomials times Gaussians: for each mode $k$ we have $$\psi_k(\mu_k)=\frac1{\sqrt{2^n n!}}\left(\frac{m\Omega_k}{\pi\hbar}\right)^{1/4}\exp\left(-\frac{m\Omega_k \mu_k^2}{2\hbar}\right)H_n\left(\mu_k\sqrt{\frac{m\Omega_k}{\hbar}}\right), \tag{10}$$ and the total wavefunction of the system is $$\Psi(\mathbf{x})=\prod_{k=1}^N \psi_k(\mu_k). \tag{11}$$ Visualizations One of the ways a quantum state can be visualized is by showing probability densities. Each mode, being a simple harmonic oscillator, will have the well-known probability distributions of the "displacement" of the mode. Visualization is trivial in these coordinates. But eigenmodes aren't something easy to intuit, so visualization in terms of them has little value. What we'd rather have is probability densities of displacement of the particles in the chain. This is something for which we have classical intuition and also for which we have (assuming some experience in QM) intuition for the $N=1$ case, i.e. single particle. Now, to get a probability density of displacement of a single particle in the chain we have to integrate out all particle coordinates except for ones of the particle $n$ we're interested in: $$\rho(x_n)=\int\limits_{\mathbb{R}^{N-1}} |\Psi(\mathbf{x})|\,\mathrm{d}x_{n_1}\mathrm{d}x_{n_2}\cdots\mathrm{d}x_{n_{N-1}},\tag{12}$$ where $n_i\ne n$ . In $N\le3$ case this integration is reasonably easily doable numerically. Even in $N=4$ it's not too long to compute this integral for many points in $x_n$ for each of the particles. But the larger the number of particles, the harder this work becomes. In ref. 1 the authors claim to have used Monte-Carlo integration to obtain their probability densities. As I've tried this on my PC (using Wolfram Mathematica's NIntegrate on Intel Core i7-4765T), this direct integration approach appeared to be uselessly slow for $N=11$ even for a single value of $x_1$ . So, we need a better way to compute $(12)$ . Fortunately, the wavefunction is separable in the mode coordinates $\mu_k$ , so we can, instead of sampling lots of tiny probability densities $|\Psi|$ to get $\rho$ , use inverse transform sampling to generate correctly-distributed points in $\mu$ -space, transform the $\{\mu_k\}_k$ generated to $\{x_n\}_n$ and make $N$ histograms of $x_n$ values. To implement inverse transform sampling, we need the following ingredients: CDF of the harmonic oscillator. This one is just an integral of gaussian-times-polynomial. For each excitation level $k$ there's a closed-form expression in terms of the $\operatorname{erf}$ function. If we express the wavefunction of a harmonic oscillator in terms of $s=x\sqrt\Omega$ , then this integral doesn't depend on $\Omega$ . Inverse function of the CDF. For the purposes of visualization it's sufficient to generate a table of values of the CDF for values of $s$ where the CDF is very small to where the CDF is very close to 1, and linearly interpolate between the pairs $(\mathrm{cdf}, s)$ . $n$ -phonon states One way of visualizing a field state is by showing probability density of displacement of its particles, like it's done in ref. 1. A bit different way, similar to that used in ref. 2, is to separately take the positive and negative parts of the wavefunction, and show the "partial probabilities" of both parts e.g. in different color channels. The following images will display the state of a 50-particle chain in both ways: gray is total probability density, red positive part, blue negative. Horizontal axis denotes the particle in the chain, while vertical axis is the displacement of the particle. vacuum (image repeated for convenience) 1 phonon 5 phonons 10 phonons mode 1 mode 3 mode 10 1 phonon in mode 1, 4 phonons in mode 3 10 phonons in mode 1, 1 phonon in mode 2 10 phonons in mode 1, 1 phonon in mode 9 One other way of visualization of stationary states is by simulating repeated measurements of the field configuration. In this case we'll see the most probable field configurations directly. This is similar to the approach in ref. 2, but instead of showing the configuration with opacity weighted by probability, we sample the configurations with its probability. Below is the visualization of the state with 15 phonons in mode 3. Coherent states From the previous section showing $n$ -phonon states we might have concluded that for a quantum field, what's quantized is the field amplitude. This is partially right: each eigenstate has a global maximum of the probability density at a particular field amplitude, and adding phonons increases this maximum amplitude. It's similar to the amplitude of the simple harmonic oscillator, whose highest maxima also jump farther from equilibrium position as you excite it to higher energy levels. But in fact, the most classical-like states, called coherent states , can change their amplitudes continuously. This is because their maximum is defined by the distribution of weights of the eigenstates in the superposition. This distribution can change its expected value smoothly, and so will the maximum of the probability density of displacement. Coherent states of a field can be visualized just as easily as eigenstates, because the superposition here is taken over a single mode, which retains separability of the wavefunction. Namely, for a coherent state of $k$ th mode with mean phonon number $\langle n\rangle=|\alpha|^2$ , we have $$\psi_k^{(\alpha)}(\mu_k)=\exp\left(-\frac{\alpha^2}2\right)\sum\limits_{n=0}^\infty \frac{\alpha^n}{\sqrt{n!}}\psi_n(\mu_n).\tag{13}$$ For ease of sampling though, we want a simpler expression, which can be found using the fact that a coherent state is an eigenstate of the annihilation operator. Solving corresponding differential equation, making sure the solution also solves Schrödinger's equation (by adding the necessary time-dependent phase) and normalizing will yield $$\psi_k^{(\alpha)}(\mu_k)=\left(\frac{m\Omega_k}{\pi\hbar}\right)^{1/4}\exp\left(-\frac{m\Omega_k}{2\hbar} \left(x-\alpha\sqrt{\frac{2\hbar}{m\Omega_k}}\cos(\Omega_k t)\right)^2\right)\times\\ \times\exp\left(-i\left(\alpha x\sqrt{\frac{2m\Omega_k}\hbar}\sin(\Omega_k t)+\frac{\Omega_k t}2-\frac{\alpha^2}2\sin(2\Omega_k t)\right)\right).\tag{14}$$ Coherent states' evolution in time is non-trivial: their probability densities change. This makes the phase also evolve non-trivially, so we can't usefully show signs of the wavefunction as in ref. 2. So we'll only show probability densities now. Below are some animations of coherent states with different values of mean phonon number $\langle n\rangle$ and for different modes (frequencies are not to scale, so animations go at the same rate). $\langle n\rangle=0$ $\langle n\rangle=0.5$ $\langle n\rangle=1.0$ $\langle n\rangle=5.0$ $\langle n\rangle=10.0$ mode 1 mode 3 mode 10 References Scott C. Johnson, Thomas D. Gutierrez, "Visualizing the phonon wave function" , 2002 Am. J. Phys. 70(3). DOI: 10.1119/1.1446858 . Helmut Linde, "A new way of visualising quantum fields" , 2018 Eur. J. Phys. 39 035401. DOI: 10.1088/1361-6404/aaa032 .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/168354', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/72892/']}
|
jdg_373258
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
22240421
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've found some examples of qmlRegisterType on the internet but just can't make it work. I create a new Qt Quick 2 project and add the following contents: This is my .pro file: #Add more folders to ship with the application, herefolder_01.source = qml/testlibfolder_01.target = qmlDEPLOYMENTFOLDERS = folder_01#LibrariesQT += core gui widgets#Additional import path used to resolve QML modules in Creator's code modelQML_IMPORT_PATH =#Header filesHEADERS += main.hpp#The .cpp file which was generated for your project. Feel free to hack it.SOURCES += main.cpp#Installation path#target.path =#Please do not modify the following two lines. Required for deployment.include(qtquick2applicationviewer/qtquick2applicationviewer.pri)qtcAddDeployment() This is my code file (main.cpp): #include <QtQml>#include <QtWidgets/QApplication>#include "qtquick2applicationviewer.h"//test classclass TestClass:public QObject { Q_OBJECT public: TestClass(QObject* parent=0):QObject(parent){} public slots: void test() { qDebug("test!"); }};//entry pointint main(int argc, char *argv[]) { //create application QApplication app(argc, argv); //register custom qml component qmlRegisterType<TestClass>("testlib",1,0,"TestClass"); //create and show qml viewer QtQuick2ApplicationViewer viewer; viewer.setMainQmlFile(QStringLiteral("qml/testlib/main.qml")); viewer.showExpanded(); //back to OS return app.exec();} This is my QML file (main.qml): import QtQuick 2.0import testlib 1.0Rectangle { TestClass { id:testobj } Component.onCompleted: { testobj.test(); }} But I face multiple linking errors: undefined reference to `vtable for TestClass' undefined reference to `TestClass::staticMetaObject' undefined reference to `TestClass::metaObject() const' undefined reference to `TestClass::qt_metacast(char const*)' undefined reference to `TestClass::qt_metacall(QMetaObject::Call, int, void**)' I'm using Qt 5.2.1 shipped with MinGW 4.8 stable. These errors mean the linker can not find library files which contain method implementations (stated above). What happened? May be fail to compile on Qt 5 but ok on Qt 4?
Now provide the response and nothing else.
|
Notes about compilation with Qt: (1) Use 'QT +=' in .pro file for Qt headers & Qt libraries(2) Use 'HEADERS +=' and 'SOURCES +=' in .pro file for project level headers and source codes Notes about creating a custom QML component (herefrom called 'CustomCom'): (1) Inherit publically 'CustomCom' from QQuickItem: class CustomCom:public QQuickItem {}(2) Put the Q_OBJECT macro right after first line of class 'CustomCom' declaration.(3) Inherit the constructor:public: CustomCom(QQuickItem* parent=0):QQuickItem(parent){}(4) Put the methods to be called by JS after "public slots:"(5) Call 'qmlRegisterType' after creation of 'QApplication' andbefore creating any QML view or viewer.(6) IMPORTANT: If you fail to compile with error 'undefined reference to vtable...", just put the code of 'CustomCom.cpp'nested inside the 'CustomCom.hpp' file, and put the whole code of the class 'CustomCom.hpp' in the main header file because ofsomething wrong in header referencing. Example header code: [main.hpp]class CustomCom:public QQuickItem { Q_OBJECT public: CustomCom(QQuickItem* parent=0):QQuickItem(parent){} public slots: void test() { qDebug("Test!"); }}; Example source code: [main.cpp]int main(int argc,char** args) { QApplication* app = new QApplication(argc,args); //call before any qml may use the custom component qmlRegisterType<CustomCom>("CustomLib",1,0,"CustomCom"); //class 'QtQuick2ApplicationViewer' is generated by Qt Creator //when creating new Quick 2 project. The path to 'main.qml' //may be different QtQuick2ApplicationViewer* viewer = new QtQuick2ApplicationViewer(); viewer->setMainQmlFile("qml/project/main.qml"); viewer->showExpanded();} Example QML: [main.qml]import QtQuick 2.0import CustomLib 1.0Rectangle { width:640; height:360; CustomCom { id:customcom; } Component.onCompleted: { customcom.test(); }} Solution to the question (facing 'Undefined reference to vtable'): Combine 'TestClass.hpp' & 'TestClass.cpp' into 'TestClass.hpp' file Move the content of 'TestClass.hpp' to 'main.hpp' The problem was caused by using master header file. Putting the #include(s) only when needed solves the problem.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22240421', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/905418/']}
|
jdg_373259
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
697892
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm having a bit of a problem proving this statement. Maybe someone can point me in the right direction? Best regards,
Now provide the response and nothing else.
|
HINT: $$23^{n+1}-1=23(\underbrace{23^n-1})+23-1$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/697892', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/87399/']}
|
jdg_373260
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4832894
|
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 easiest way to do a clickout in jquery Where a div box hides if clicked anywhere outside it.
Now provide the response and nothing else.
|
I don't like the solutions that use stopPropagation because often I am using event bubbling to manage various links. I don't want to have to worry that they might stop working if the box exists. My choice would look something like this: var $box = $('#box');$(document.body).click(function(){ if (!$box.has(this).length) { // if the click was not within $box $box.hide(); }}); The has function filters the selection and returns elements only if they contain the element passed as the parameter (you can also use a selector string, but that isn't relevant here). If the click was outside the box, length will be 0 so the conditional will pass and the box will be hidden. This should be optimised by setting a boolean value for whether the box is currently visible and only doing the has call if it is currently visible.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4832894', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/560735/']}
|
jdg_373261
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3862954
|
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 go very low level in functional languages like Haskell? (like making a kernel or device driver). And will functional features (like monads) be fast and efficient there?
Now provide the response and nothing else.
|
Haskell itself doesn't do anything to enable systems-level coding. Through the foreign function interface (FFI) you can make calls into C/assembly routines, but here you're really just outsourcing the problem to another language. The central challenge -- and the use of the FFI is a harbinger of this -- is in making sure that you are supporting (and not hindering) the runtime. The Haskell runtime is (by necessity) very complex, owing to both automatic memory management and the management of lazy code. Interrupt handling is classic kernel/Haskell problem. If an interrupt comes in when your Haskell code is deep in the runtime system, you won't be able to handle the interrupt in a timely manner. On many architectures, if too many interrupts queue up before being handled, the hardware will fault and either halt or reboot. This issue seems to be the central crux in using Haskell at the kernel level. Edit: On further reflection, monads can be a very useful idiom in systems level code. Think about the way in which IO is used in regular Haskell code: it is a type-level contaminant that infects functions which, well, do IO-things. Since systems programming is all about resource management, it is desirable to track which code interacts with which resources. One could imagine a monad transformer for each resource in question, with resource-specific functions abstracted in a type class. For instance, we might have class Monad m => MonadNetwork m where ...class Monad m => MonadDiskDrive m where ... Code which needs to use both the network and disk drive would carry constraints like downloadToFile :: (MonadNetwork m, MonadDiskDrive m) => URL -> FilePath -> m () This is clearly a high-level example (one wouldn't expect to find this in a kernel), but I think it illustrates the idea. It certainly would be a reasonable way to expose your OS API to user-land, if you didn't mind breaking tradition and having a (gasp) non-C API. Such an API would definitely make me feel safer about running code from untrusted sources, as the types then document (with fine granularity) what sorts of IO-ish things the code intends to do. So yes, I believe that monads are useful in systems level programming, not for efficiency reasons, but simply because when you are running code which isn't in a sandbox, you want to know the code's intentions.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3862954', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/455043/']}
|
jdg_373262
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5161730
|
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 switching tabs programmatically in a tab bar driven application using UITabBarController.selectedIndex . The problem I'm trying to solve is how to animate the transition between the views. ie. from the view of the current tab to the view of the selected tab. The first thought was to make use of the UITabBarControllerDelegate , but it appears that this is not called when programmatically switching tabs. I'm now considering the UITabBarDelegate.didSelectItem : as a possible hook to set a transition animation. Has anyone managed to animate the transitions? If yes, how ?
Now provide the response and nothing else.
|
Update 04/2016: Justed wanted to update this to say thank you to everyone for all the votes. Please also note that this was originally written way back when ... before ARC, before constraints, before ... a lot of stuff! So please take this into account when deciding whether to use these techniques. There may be more modern approaches. Oh, and if you find one. Please add a response so everyone can see. Thanks. Some time later ... After much research I came up with two working solutions. Both of these worked and did the animation between tabs. Solution 1: transition from view (simple) This is the easiest and makes use of a predefined UIView transition method. With this solution we don't need to manage the views because the method does the work for us. // Get views. controllerIndex is passed in as the controller we want to go to. UIView * fromView = tabBarController.selectedViewController.view;UIView * toView = [[tabBarController.viewControllers objectAtIndex:controllerIndex] view];// Transition using a page curl.[UIView transitionFromView:fromView toView:toView duration:0.5 options:(controllerIndex > tabBarController.selectedIndex ? UIViewAnimationOptionTransitionCurlUp : UIViewAnimationOptionTransitionCurlDown) completion:^(BOOL finished) { if (finished) { tabBarController.selectedIndex = controllerIndex; } }]; Solution 2: scroll (more complex) A more complex solution, but gives you more control of the animation. In this example we get the views to slide on and off. With this one we need to manage the views ourselves. // Get the views.UIView * fromView = tabBarController.selectedViewController.view;UIView * toView = [[tabBarController.viewControllers objectAtIndex:controllerIndex] view];// Get the size of the view area.CGRect viewSize = fromView.frame;BOOL scrollRight = controllerIndex > tabBarController.selectedIndex;// Add the to view to the tab bar view.[fromView.superview addSubview:toView];// Position it off screen.toView.frame = CGRectMake((scrollRight ? 320 : -320), viewSize.origin.y, 320, viewSize.size.height);[UIView animateWithDuration:0.3 animations: ^{ // Animate the views on and off the screen. This will appear to slide. fromView.frame =CGRectMake((scrollRight ? -320 : 320), viewSize.origin.y, 320, viewSize.size.height); toView.frame =CGRectMake(0, viewSize.origin.y, 320, viewSize.size.height); } completion:^(BOOL finished) { if (finished) { // Remove the old view from the tabbar view. [fromView removeFromSuperview]; tabBarController.selectedIndex = controllerIndex; } }]; This Solution in Swift: extension TabViewController: UITabBarControllerDelegate { public func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool { let fromView: UIView = tabBarController.selectedViewController!.view let toView : UIView = viewController.view if fromView == toView { return false } UIView.transitionFromView(fromView, toView: toView, duration: 0.3, options: UIViewAnimationOptions.TransitionCrossDissolve) { (finished:Bool) in } return true }}
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5161730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/247090/']}
|
jdg_373263
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
231285
|
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:
My understanding is that in machine learning it can be a problem if your dataset has highly correlated features, as they effectively encode the same information. Recently someone pointed out that when you do one-hot encoding on a categorical variable you end up with correlated features, so you should drop one of them as a "reference". For example, encoding gender as two variables, is_male and is_female , produces two features which are perfectly negatively correlated, so they suggested just using one of them, effectively setting the baseline to say male, and then seeing if the is_female column is important in the predictive algorithm. That made sense to me but I haven't found anything online to suggest this may be the case, so is this wrong or am I missing something? Possible (unanswered) duplicate: Does collinearity of one-hot encoded features matter for SVM and LogReg?
Now provide the response and nothing else.
|
This depends on the models (and maybe even software) you want to use. With linear regression, or generalized linear models estimated by maximum likelihood (or least squares) (in R this means using functions lm or glm ), you need to leave out one column. Otherwise you will get a message about some columns "left out because of singularities" $^\dagger$ . But if you estimate such models with regularization , for example ridge, lasso er the elastic net, then you should not leave out any columns. The regularization takes care of the singularities, and more important, the prediction obtained may depend on which columns you leave out. That will not happen when you do not use regularization $^\ddagger$ . See the answer at How to interpret coefficients of a multinomial elastic net (glmnet) regression which supports this view (with a direct quote from one of the authors of glmnet ). With other models, use the same principles. If the predictions obtained depends on which columns you leave out, then do not do it. Otherwise it is fine. So far, this answer only mentions linear (and some mildly non-linear) models. But what about very non-linear models, like trees and randomforests? The ideas about categorical encoding, like one-hot, stems mainly from linear models and extensions. There is little reason to think that ideas derived from that context should apply without modification for trees and forests! For some ideas see Random Forest Regression with sparse data in Python . $^\dagger$ But, using factor variables, R will take care of that for you. $^\ddagger$ Trying to answer extra question in comment: When using regularization, most often iterative methods are used (as with lasso or elasticnet) which do not need matrix inversion, so that the design matrix do not have full rank is not a problem. With ridge regularization, matrix inversion may be used, but in that case the regularization term added to the matrix before inversion makes it invertible. That is a technical reason, a more profound reason is that removing one column changes the optimization problem , it changes the meaning of the parameters, and it will actually lead to different optimal solutions . As a concrete example, say you have a categorical variable with three levels, 1,2 and 3. The corresponding parameters is $\beta_, \beta_2, \beta_3$ . Leaving out column 1 leads to $\beta_1=0$ , while the other two parameters change meaning to $\beta_2-\beta_1, \beta_3-\beta_1$ . So those two differences will be shrunk. If you leave out another column, other contrasts in the original parameters will be shrunk. So this changes the criterion function being optimized, and there is no reason to expect equivalent solutions! If this is not clear enough, I can add a simulated example (but not today).
|
{}
|
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/231285', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/94687/']}
|
jdg_373264
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15543308
|
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 filter documents that have a field which is an array and has more than N elements? How can I filter documents that have a field which is an empty array? Is facets the solution? If so, how?
Now provide the response and nothing else.
|
I would have a look at the script filter . The following filter should return only the documents that have at least 10 elements in the fieldname field, which is an array. Keep in mind that this could be expensive depending on how many documents you have in your index. "filter" : { "script" : { "script" : "doc['fieldname'].values.length > 10" }} Regarding the second question: do you really have an empty array there? Or is it just an array field with no value? You can use the missing filter to get documents which have no value for a specific field: "filter" : { "missing" : { "field" : "user" }} Otherwise I guess you need to use scripting again, similarly to what I suggested above, just with a different length as input. If the length is constant I'd put it in the params section so that the script will be cached by elasticsearch and reused, since it's always the same: "filter" : { "script" : { "script" : "doc['fieldname'].values.length > params.param1" "params" : { "param1" : 10 } }}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15543308', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1724926/']}
|
jdg_373265
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8902132
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Assume a 5-stage pipeline architecture (IF = Instruction Fetch, ID = Instruction Decode, EX = Execute, MEM = Memory access, WB = Register write back). There are 4 instructions that has to be executed. (These sample instruction are not accurate, but I believe the point would be understood) In the fifth clock cycle, these instruction will be in pipeline as shown below. Add a, b, c [IF ID EX MEM WB]Add a, b, d [IF ID EX MEM]Add a, b, e [IF ID EX]Add a, b, f [IF ID] Now if a hardware interrupt occurs, what happens to these instructions. Will the interrupt be handled only after all the instructions in the pipeline is executed? Will the software interrupts and exceptions be handled in a different way??
Now provide the response and nothing else.
|
First, terminology: Usually, at Intel at least, an interrupt is something that comes from the outside world. Usually it is not synchronized with instructions executing on the processor, i.e. it is an asynchronous external interrupt. In Intel terminology an exception is something caused by instructions executing on the processor. E.g. a page fault, or an undefined instruction trap. ---+ Interrupts flush all instructions in flight On every machine that I am familiar with - e.g. all Intel processors since the P5 (I worked on the P6), AMD x86s, ARM, MIPS - when the interrupt signal is received the instructions in the pipeline are nearly always flushed, thrown away. The only reason I say "nearly always" is that on some of these machines you are not always at a place where you are allowed to receive an interrupt. So, you proceed to the next place where an interrupt is allowed - any instruction boundary, typically - and THEN throw away all of the instructions in the pipeline. For that matter, interrupts may be blocked. So you proceed until interrupts are unblocked, and THEN you throw them away. Now, these machines aren't exactly simple 5 stage pipelines. Nevertheless, this observation - that most machines throw away all instructions in the pipeline, in pipestages before the pipestage where the interrupt logic lives - remains almost universally true. In simple machines the interrupt logic typically lives in the last stage of the pipeline, WB, corresponding roughly to the commit pipestage of advanced machines. Sometimes it is moved up to a pipestage just before, e.g. MEM in your example. So, on such machines, all instructions in IF ID EX, and usually MEM, are thrown away. ---++ Why I care: Avoiding Wasted Work This topic is near and dear to my heart because I have proposed NOT doing this. E.g. in customer visits while we were planning to build the P6, I asked customers which they preferred - lower latency interrupts, flushing instructions that are in flight, or (slightly) higher throughput, allowing at least some of the instructions in flight to complete, at the cost of slightly longer latency. However, although some customers preferred the latter, we chose to do the traditional thing, flushing immediately. Apart from the lower latency, the main reason is complexity: E.g. if you take an interrupt, but if one of the instructions already in flight also takes an exception, after you have resteered IF (instruction fetch) but before any instruction in the interrupt has committed, which takes priority? A: it depends. And that sort of thing is a pain to deal with. ---+++ Folklore: Mainframe OS Interrupt Batching This is rather like the way that some IBM mainframe OSes are reported to have operated: with all interrupts blocked in normal operation except for the timer interrupt; in the timer interrupt, you unblock interrupts, and handle them all; and then return to normal operation with interrupts blocked mode Conceivably they might only use such an "interrupt batching" mode when heavily loaded; if lightly loaded, they might not block interrupts. ---+++ Deferred Machine Check Exceptions The idea of deferring interrupts to give instructions already in the pipeline a chance to execute is also similar to what I call the Deferred Machine Check Exception - a concept that I included in the original Intel P6 family Machine Check Architecture, circa 1991-1996, but which appears not to have been released. Here's the rub: machine check errors like (un)correctable ECC errors can occur AFTER an instruction has retired (i.e. after supposedly younger instructions have committed state, e.g. written registers), or BEFORE the instruction has retired. The classic example of AFTER errors is an uncorrectable ECC triggered by a store that is placed into a write buffer at graduation. Pretty much all modern machines do this, all machines with TSO, which pretty much means that there is always the possibility of an imprecise machine check error that could have been precise if you cared enough not to buffer stores. The classic example of BEFORE errors is ... well, every instruction, on any machine with a pipeline. But more interestingly, errors on wrong-path instructions, in the shadow of a branch misprediction. When a load instruction gets an uncorrectable ECC error, you have two choices: (1) you could pull the chain immediately, killing not just instructions YOUNGER than the load instruction but also any OLDER instructions (2) or you could write some sort of status code into the logic that controls speculation, and take the exception at retirement. This is pretty much what you have to do for a page fault, and it makes such errors precise, helping debugging. (3) But what if the load instruction that got the uncorrectable ECC error was a wrong path instruction, and never retires because an older inflight branch mispredicted and went another way? Well, you could write the status to try to make it precise. You should have counters of precise errors and imprecise errors. You could otherwise ignore an error on such a wrong-path instruction - after all, if it is a hard error, it wil either be touched again, or it might not be./ E.g. it is possible that the error would be architecturally silent - e.g. a bad cache line might be overwritten by a good cache line for the same address . And, if you really wanted, you could set a bit so that if an older branch mispredicts, then you take the machine check exception at that point in time. Such an error would not occur at a program counter associated with the instruction that caused the error, but might still have otherwise precise state. I call (2) deferring a machine check exception; (3) is just how you might handle the deferral. IIRC, all Intel P6 machine check exceptions were imprecise. ---++ On the gripping hand: even faster So, we have discussed 0) taking the interrupt immediately, or, if interrupts are blocked, executing instructions and microinstructions until an interrupt unblocked point is reached. And then flushing all instructions in flight. 1) trying to execute instructions in the pipeline, so as to avoid wasted work. But there is a third possibility: -1) if you have microarchitecture state checkpoints, take the interrupt immediately, never waiting to an interrupt unblocked point. Which you can only do if you have a checkpoint of all relevant state at the most recent "safe to take an interrupt" point. This is even faster than 0), which is why I labelled it -1). But it requires checkpoints, which many but not all aggressive CPUs use - e.g. Intel P6 dod not use checkpoints. And such post-retirement checkpoints get funky in the presence of shared memory - after all, you can do memory operations like loads and stores while interrupts are blocked. And you can even communicate between CPUs. Even hardware transactional memory usually doesn't do that. ---+ Exceptions mark the instructions affected Conversely, exceptions, things like page faults, mark the instruction affected. When that instruction is about to commit, at that point all later instructions after the exception are flushed, and instruction fetch is redirected. Conceivably, instruction fetch could be resteered earlier, the way branch mispredictions are already handled on most processors, at the point at which we know that the exception is going to occur. I don't know anyone who does this. On current workloads, exceptions are not that important. ---+ "Software Interrupts" "Software interrupts" are a misnamed instruction usually associated with system calls. Conceivably, such an instruction could be handled without interrupting the pipeline, predicted like a branch. However, all of the machines I am familiar with serialize in some way. In my parlance, they do not rename the privilege level. ---+ "Precise Interrupts", EMON, PEBS Another poster mentioned precise interrupts. This is a historical term. On most modern machines interrupts are defined to be precise. Older machines with imprecise interrupts have not been very successful in the market place. However, there is an alternate meaning, I was involved in introducing: when I got Intel to add the capability to produce an interrupt on performance counter overflow, first using external hardware, and then inside the CPU, it was, in the first few generations, completely imprecise. E.g. you might set the counter to count the number of instructions retired. The retirement logic (RL)would see the instructions retire, and signal the performance event monitoring circuitry (EMON). It might take two or three clock cycles to send this signal from RL to EMON. EMON would increment the counter, and then see that there was an overflow. The overflow would trigger an interrupt request to the APIC (Advanced Programmable Interrupt Controller). The APIC might take a few cycles to figure out what was happening, and then signal the retirement logic. I.e. the EMON interrupt would be signalled imprecisely. Not at the time of the event, but some time thereafter. Why this imprecision? Well, in 1992-6, performance measurement hardware was not a high priority. We were leveraging existing interrupt hardware. Beggars can't be choosers. But furthermore, some performance are intrinsically imprecise. E.g. when do you signal an interrupt for a cache miss on a speculative instruction that never retires? (I have a scheme I called Deferred EMON events, but this is still considered too expensive.) For that matter, what about cache misses on store instructions, where the store is placed into a store buffer, and the instruction has already retired? I.e. sometimes performance events occur after the instruction they are associated with has committed (retired). Sometimes before. And often not exactly at the instruction they are associated with. But in all of the implementations so far, as far as I know, these performance events are treated like interrupts: existing instructions in the pipe are flushed. Now, you can make a performance event precise by treating it like a trap. E.g. if it is an event like instructions retired, you can have the retirement logic trap immediately, instead of taking that circuitous loop I described above. If it occurs earlier in the pipeline, you can have the fact that it occurred marked in the instruction fault status in the ROB (Re-Order Buffer). Something like this is what Intel has done with PEBS (Precise Event Based Sampling). http://software.intel.com/sites/products/collateral/hpc/vtune/performance_analysis_guide.pdf . However, note that not all events can be sampled using PEBS. For example, PEBS in the example above can count loads that took a cache hit or miss, but not stores (since stores occur later). So this is like exceptions: the event is delivered only when the instruction retires. Because in a sense the event has not completely occurred - it is a load instruction, that takes a cache miss, and then retires. And instructions after the marked PEBS instruction are flushed from the pipeline. I hope ---+ Late Addition About Early Computers
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8902132', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/230211/']}
|
jdg_373266
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30723500
|
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 button with id="remove" I need a simpletip over it: <script> $(document).ready(function(){$("#remove").simpletip();});</script> I have included: <script type="text/javascript" src="http://cdn.jsdelivr.net/jquery.simpletip/1.3.1/jquery.simpletip-1.3.1.min.js.txt"></script> Do I need to include any other CDN? Why doesn't this work?
Now provide the response and nothing else.
|
In the original C language - C89/90 - calling an undeclared function is not an error. For this reason, a pre-C99 compiler will not produce any "error" due to a missing function declaration. The compiler will simply assume that function returns an int . It will also automatically and quietly "guess" (infer, derive) the function parameter types from the argument types you supplied in your call. In your example, you supplied 20 , which will make the compiler to guess that the "unknown" malloc function takes a single parameter of type int . Note that this is also incorrect, because the real malloc takes a size_t parameter. In C99 and later the function declaration is required. Which means that forgetting to declare malloc (e.g. forgetting to include <stdlib.h> ) is indeed an error, which will result in a diagnostic message. (The parameter-guessing behavior is still there in the language though.) Note also that in C99 and later declaring function main without an explicit return type int is illegal. The "implicit int" rule is specific to the original version of C language specification only. It no longer exists in C99 and later. You have to declare it as int main(... explicitly.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30723500', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_373267
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1200637
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The following is an exercise from Carothers' Real Analysis : Show that $$\int_{1}^{\infty}\frac{1}{x}=\infty$$ (as a Lebesgue Integral). Attempt: Let $E=[1,\infty)$. $\int_E f=\int f\cdot \chi_E=\sup\{\int\varphi:\varphi \text{ simple }, 0\leq \varphi\leq f\}\cdot \chi_E$ I'm not sure how to find out what $\sup\{\int\varphi:\varphi \text{ simple }, 0\leq \varphi\leq f\}$ is. (Maybe I can say something about $\sum_{n=1}^{\infty}\frac{1}{n}\cdot \chi_\mathbb{R}$, which diverges since it's the harmonic series?) I note that I can express $E=\bigcup_{n=1}^{\infty}[1,n)$, which is measurable since it is the union of measurable sets. I'm pretty new to the Lebesgue integral so a hint would be preferred over a full solution if possible. Thanks.
Now provide the response and nothing else.
|
To show that the Lebesgue integral of $x^{-1}$ is infinite, use a change of variables $x \mapsto 1/x$ and consider the sequence of simple functions $$\phi_n = \sum_{j=1}^nj \chi_{((j+1)^{-1},j^{-1})}.$$ Note that $0 \leqslant \phi_n(x) \leqslant x^{-1}$ and $$\int_{(0,1]}\phi_n = \sum_{j=1}^n j\left(\frac1{j}- \frac1{j+1}\right)=\sum_{j=1}^n \frac1{j+1}\to_{n \to \infty} +\infty.$$ Whence, $$\int_{[1,\infty)}x^{-1} = \int_{(0,1]}x^{-1} = +\infty$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1200637', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/77862/']}
|
jdg_373268
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4472920
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do you set the size of NSView programmically e.g. -(void)awakeFromNib { self.frame.size.width = 1280; // Does nothing... self.frame.size.height = 800; // ...neither does this. ... The size setup in the nib (of Mac OSX) works OK, but I want to do it in code.
Now provide the response and nothing else.
|
When you call self.frame, it returns the data in the frame, and not a pointer. Therefore, any change in the result is not reflected in the view. In order to change the view, you have to set the new frame after you make changes: - (void)awakeFromNib { NSRect f = self.frame; f.size.width = 1280; f.size.height = 800; self.frame = f; //...}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4472920', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/407341/']}
|
jdg_373269
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3042437
|
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 change the author of one specific commit in the history. It's not the latest commit. Related: How do I change the author and committer name/email for multiple commits?
Now provide the response and nothing else.
|
Interactive rebase off of a point earlier in the history than the commit you need to modify ( git rebase -i <earliercommit> ). In the list of commits being rebased, change the text from pick to edit next to the hash of the one you want to modify. Then when git prompts you to change the commit, use this: git commit --amend --author="Author Name <email@address.com>" --no-edit For example, if your commit history is A-B-C-D-E-F with F as HEAD , and you want to change the author of C and D , then you would... Specify git rebase -i B ( here is an example of what you will see after executing the git rebase -i B command ) if you need to edit A , use git rebase -i --root Change the lines for both C and D from pick to edit Exit the editor (for vim, this would be pressing Esc and then typing :wq ). Once the rebase started, it would first pause at C You would git commit --amend --author="Author Name <email@address.com>" Then git rebase --continue It would pause again at D Then you would git commit --amend --author="Author Name <email@address.com>" again git rebase --continue The rebase would complete. Use git push -f to update your origin with the updated commits.
|
{}
|
{'log_upvote_score': 13, 'links': ['https://Stackoverflow.com/questions/3042437', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/69684/']}
|
jdg_373270
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2445330
|
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: What is this weird colon-member syntax in the constructor? Rarely in the regular codes I encounter the a single colon in classesfor e.g.: A::member():b(),c(){} What is the importance of the single colon over here? Why is it used here?Is it mandatory sometimes? If so in which cases?
Now provide the response and nothing else.
|
A single colon in this context is used to signal that you are using an initializer list . An initializer list is used to: Invoke base class constructors from a derived class Initialize member variables of the class As noted by others, an initializer list can only be used on a class constructor . While it's also possible to initialize member variables in the body of the constructor, there are several reasons for doing so via the initializer list : Constant pointers or references cannot be initialized from the body of the constructor It is usually more efficient to use the initializer list as it will (from memory) only invoke the constructor for the member, rather than the constructor and assignment operator which can be costly for non-POD types. Having said all of this, the formatting of your code is a bit odd. In the code that I usually work with, use of an initializer list would be indented like this: A::A() :b(), c(){} This makes it more clear to me that the : has no relation to the :: used to define class membership in A::A() .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2445330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/134713/']}
|
jdg_373271
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
276263
|
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:
How do I write a bash script that goes through each directory inside a parent_directory and executes a command on specific file. The directory structure is as follows: Parent_dir/ dir1/ acc.bam dir2/ acc.bam dir3/ acc.bam... around 30 directories This is the command I want to use : java8 -jar /picard.jar CollectRnaSeqMetrics REF_FLAT=/refFlathuman.refflat STRAND_SPECIFICITY=NONE I=acc.bam O=output
Now provide the response and nothing else.
|
The usual idiom is for d in Parent_dir/*/do (cd "$d" && $command)done The for loop executes once for each directory directly within Parent_dir . For each of those directories, a sub-shell is spawned; in the sub-shell, we attempt to change into that directory (which might fail, e.g. if we have insufficient permission), and if we succeed, then execute the command. Whether or not we succeeded, the cd has no effect on the parent shell, so we don't need to worry about being in the wrong place there. If you want to make it more robust, you might (cd "$d" && test -r acc.bam && $command) to ensure that acc.bam exists and is readable in that directory. You might also add a test -w . to avoid trying to run the command in directories that are not writable. P.S. None of the above is specific to Bash; you can use /bin/sh for it quite portably.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/276263', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/163629/']}
|
jdg_373272
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30525
|
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 am attempting to provide custom interrupt handlers for my Cortex M3 (reference manual here ). ST kindly provides a standard library, which has various startup files all called "startup_stm32f2xx.s". Each is in a different folder according to IDE. Now I do not use an IDE (I compile directly with Yagarto, a modified version of the gcc toolchain). I have already asked which of the start-up to use. However, having now tried all the available startup files, I always get the same error: /startup_stm32f2xx.s:1:0: error: target CPU does not support ARM mode A quick Google search reveals that this probably means that the assembler code has instructions that my ARM cannot understand, which is surprising given that the code was provided for my board. How can I compile the startup file that defines the interrupt vector on my STM32? Edit: In each of the files, startup_stm32f2xx.s:1:0 is the beginning of a comment. Also, I'm using the flag -mcpu=cortex-m3 . Here is the complete error message: $ make allarm-none-eabi-gcc -x assembler-with-cpp -c -g -mcpu=cortex-m3 -gdwarf-2 -Wa,-amhls=startup_stm32f2xx.lst startup_stm32f2xx.s -o startup_stm32f2xx.ostartup_stm32f2xx.s:1:0: error: target CPU does not support ARM modemakefile:46: recipe for target `startup_stm32f2xx.o' failedmake: *** [startup_stm32f2xx.o] Error 1
Now provide the response and nothing else.
|
You may also need -mthumb -mno-thumb-interwork -mfpu=vfp -msoft-float -mfix-cortex-m3-ldrd as compiler options for arm-none-eabi-gcc . For the assembler, use -mcpu=cortex-m3 -mthumb as options. Edit: The -mthumb switches gcc and the assembler into "thumb" mode - they will generate arm mode instructions per default, which do not work on Cortex M3. Since there is no ARM mode, we don't need ARM/Tumb interworking, thus -mno-thumb-interwork . The compiler needed -mfpu=vfp -msoft-float for floating point support. Cortex M3 has no hardware floating point AFAIK, at least I am not aware of any silicon that has both Cortex M3 and floating point in hardware. There are some Cortex M4 that have. Most Cortex M3 need -mfix-cortex-m3-ldrd , this is in the errata documentation for the Cortex M3 core versions. For more info see GCC Documentation and ARM infocenter .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/30525', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/5872/']}
|
jdg_373273
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
54286
|
Below is a question asked on the forum economics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Complementary slackness condition (CSC) state that $\lambda_j[g_j(x) − c_j] = 0 \hspace{5pt} \text{for} \hspace{5pt} j = 1, ..., m.$ Therefore, every constraint either needs to be an equality constraint ( $\lambda_j=0$ ) or we need to have an active constraint ( $g_j(x) − c_j = 0$ ). What if we have a passive constraint? Why would that prevent us from finding the optimum point? In that case, couldn't we just ignore that constraint and find the optimum without it because it doesn't affect our optimal point? If yes, wouldn't that make CSC irrelevant?
Now provide the response and nothing else.
|
Solving a non-linear programming (with inequality constraints) is about trial and error. You don't know a priori if a constraint is active. You consider all the possible cases satisfying your constraints and see if they optimize your objective function (maximize the utility function, for instance) . Also $\lambda_j =0$ is not an equality constraint, it is just the multiplier attached to your constraint. You have a single distinct multiplier per each constraint. $\lambda_j =0$ if your constraint is NOT active. On the other hand, $\lambda_j >0$ if your constraint is active The simplest example you can consider is: Say you want to max. $U=xy$ , $s.t.$ $i)x+y\le 100$ $ii) x,y \ge0$ You build up the Lagrangian: $L(x,y,\lambda)=xy+ \lambda(100-x-y)$ KT conditions: i) $\frac{\partial L}{\partial x}=y-\lambda \le 0$ ; $x\ge 0$ Note that one between the partial derivative and $x$ must be zero. This is called complementary slackness and can be summarized as $x \frac{\partial L}{\partial x}=0$ ii) $\frac{\partial L}{\partial y}=x-\lambda \le 0$ ; $y\ge 0$ , which can be summarized as $y \frac{\partial L}{\partial y}=0$ iii) $\frac{\partial L}{\partial \lambda}=100-x-y \ge 0$ ; $\lambda \ge 0$ , which can be summerized as $\lambda \frac{\partial L}{\partial \lambda}=0$ , and this is exactly the CSC you wrote in your question. As I said, you don't know a priori which constraint is binding. You must consider all the possible cases satisfying your constraint and see if these maximize the utility function. In our example, it does not make sense to assume that $x$ or $y$ are zero, because o.w. $U(x,y)=0$ . It does make sense to assume that $\frac{\partial L}{\partial x}=\frac{\partial L}{\partial y}=0$ , from complementary slackness. Thus, since $\frac{\partial L}{\partial x}=\frac{\partial L}{\partial y}$ , then, you get $y -\lambda = x - \lambda$ , which means $x=y$ , and since your wealth is $100$ , you realize that $x=y=50$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://economics.stackexchange.com/questions/54286', 'https://economics.stackexchange.com', 'https://economics.stackexchange.com/users/19926/']}
|
jdg_373274
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
275160
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Just starting to explore the 'wonders' of regex. Being someone who learns from trial and error, I'm really struggling because my trials are throwing up a disproportionate amount of errors... My experiments are in PHP using ereg(). Anyway. I work with first and last names separately but for now using the same regex. So far I have: ^[A-Z][a-zA-Z]+$ Any length string that starts with a capital and has only letters (capital or not) for the rest. But where I fall apart is dealing with the special situations that can pretty much occur anywhere. Hyphenated Names (Worthington-Smythe) Names with Apostophies (D'Angelo) Names with Spaces (Van der Humpton) - capitals in the middle which may or may not be required is way beyond my interest at this stage. Joint Names (Ben & Jerry) Maybe there's some other way a name can be that I'm no thinking of, but I suspect if I can get my head around this, I can add to it. I'm pretty sure there will be instances where more than one of these situations comes up in one name. So, I think the bottom line is to have my regex also accept a space, hyphens, ampersands and apostrophes - but not at the start or end of the name to be technically correct.
Now provide the response and nothing else.
|
Hyphenated Names (Worthington-Smythe) Add a - into the second character class. The easiest way to do that is to add it at the start so that it can't possibly be interpreted as a range modifier (as in a-z ). ^[A-Z][-a-zA-Z]+$ Names with Apostophies (D'Angelo) A naive way of doing this would be as above, giving: ^[A-Z][-'a-zA-Z]+$ Don't forget you may need to escape it inside the string! A 'better' way, given your example might be: ^[A-Z]'?[-a-zA-Z]+$ Which will allow a possible single apostrophe in the second position. Names with Spaces (Van der Humpton) - capitals in the middle which may or may not be required is way beyond my interest at this stage. Here I'd be tempted to just do our naive way again: ^[A-Z]'?[- a-zA-Z]+$ A potentially better way might be: ^[A-Z]'?[- a-zA-Z]( [a-zA-Z])*$ Which looks for extra words at the end. This probably isn't a good idea if you're trying to match names in a body of extra text, but then again, the original wouldn't have done that well either. Joint Names (Ben & Jerry) At this point you're not looking at single names anymore? Anyway, as you can see, regexes have a habit of growing very quickly...
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/275160', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1444/']}
|
jdg_373275
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1834145
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am solving one difficult problem and now I need information on this: If $m\mid n$, is then possible to "embed" $D_m$ to $D_n$, or otherwise said, does $D_n$ have a subgroup isomorphic to $D_m$? In my opinion, the answer is yes. This is my "proof" of this (I need you to check if it is correct): As $m\mid n$ there is $k$ such that $mk=n$. Now enumerate the vertices somehow, and take first, then $k+1, 2k+1,...,(m-1)k+1$ vertices. When you join them you shall be getting a regular $m$-tangle, and permutations restricted on it shall be exactly the elements of $D_m$. So, it is a subgroup of $D_n$. Thanks for any advice (is the statement true, is my proof correct, a correct proof if this one is not correct,...).
Now provide the response and nothing else.
|
Here is an algebraic proof that should help your geometric intuition. The Dihedral group $D_{n}$ has the presentation $$ \langle x,y \mid x^n = y^2 = (xy)^2 = 1 \rangle $$ Suppose $n = km$. Identify a new element $z = x^{k}$, and consider the subgroup of $D_{n}$ generated by $z$ and $y$. Note that $z^{m} = x^{mk} = x^{n} = 1$. Moreover, $$(zy)^{2} = (x^ky)^2 = x^{k}yx^{k}y = x^{k-1}y^{-1}x^{k-1}y = x^{k-2}yx^{k-2}y = \cdots $$ and we eventually end up with either $y^{-1}y$ or $y^{2}$, both of which are equal to $1$. Then the subgroup generated by $z$ and $y$ has the presentation for $D_{m}$ $$ \langle z,y \mid z^{m} = y^{2} = (zy)^2 = 1 \rangle$$ Technically one would need to check that no other relations hold, but instead one can use an easy order argument and observe that this subgroup has order $2m$, exactly that of $D_{m}$, so no more accidental identifications will occur.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1834145', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/213926/']}
|
jdg_373276
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11628
|
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 trying to run tomcat on a low memory system (150-256Mb). Even though I start the JVM with -Xmx64m (which should be the default anyway), the process immediately takes up 200Mb+. I wonder why the JVM needs so much memory itself, or if there is a way of tuning this? Are other JVMs better than the sun one for low memory consumption - and do they work with tomcat?
Now provide the response and nothing else.
|
In addition to the heap (specified by -Xms and -Xmx ) you need to include the non heap areas. These include The Perm Gen, which is 64mb on 32bit systems, and 96mb on 64bit systems initially The Code Cache, which is between 20 and 40mb depending on JVM The NIO buffer area (where DirectByteBuffer s are drawn from), this is initially 64mb There is also the working space of the JVM itself which will be a few dozen mb. You should also be aware of the Sun JVM's auto sizing when using a server class machine . Over time the definition of server class (2Gb memory, more than one core) has suffered some depreciation and now most machines are capable of triggering the -server optimizations. My advice is always to specify the -Xms and -Xmx settings and pass -server unless you can think of a good reason not too.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/11628', 'https://serverfault.com', 'https://serverfault.com/users/2672/']}
|
jdg_373277
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23489443
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there any way that input values to a function can be pre-defined so that a user doesn't have to define them each time? For example, assuming I had a function "zr" which returned a list zeros of size n, such that: zr 1 = [0]zr 5 = [0, 0, 0, 0, 0] And so on. My current way of implementing it is: zr :: [Int] -> Int -> [Int]zr x y | length x == y = x | otherwise = zr x++[y] But this isn't particularly elegant as every time I call zr I need to include an empty list as a parameter: zr [] 5 Any ideas? Thanks!
Now provide the response and nothing else.
|
I think what you're looking for is partial application : zr' :: Int -> [Int]zr' = zr [] If zr is a function that takes a list and an integer, then zr [] is a function that takes only an integer n and returns zr [] n . In your case, zr is obviously a "temporary" function (you don't want anyone calling zr [1] 4 by accident), so you might as well define it locally: zr :: Int -> [Int]zr = zr' [] where zr' :: [Int] -> Int -> [Int] zr' x y | length x == y = x | otherwise = zr' x++[0] y
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23489443', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2197256/']}
|
jdg_373278
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11697214
|
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 triyng to compile ffmpeg and there is a problem with tmp dir because is mounted with noexec: ./configure --enable-libmp3lame --enable-libvorbis --disable-mmx --enable-shared Unable to create and execute files in /tmp. Set the TMPDIR environment variable to another directory and make sure that it is not mounted noexec. Sanity test failed. If you think configure made a mistake, make sure you are using the latest version from SVN. If the latest version fails, report the problem to the ffmpeg-user@mplayerhq.hu mailing list or IRC #ffmpeg on irc.freenode.net. Include the log file "config.err" produced by configure as this will help solving the problem. How to set the TMPDIR environment variable to another directory?
Now provide the response and nothing else.
|
I was able to get it done using that code bellow: $ export TMPDIR=~/tmp-ffmpeg$ mkdir $TMPDIR$ ./configure \ --enable-gpl \ --enable-version3 \ --enable-shared \ --enable-nonfree \ --enable-postproc \ --enable-libfaac \ --enable-libmp3lame \ --enable-libopencore-amrnb \ --enable-libopencore-amrwb \ --enable-libtheora \ --enable-libvorbis \ --enable-libvpx \ --enable-libx264 \ --enable-libxvid \ --enable-x11grab \ --extra-cflags="-I/usr/local/include" \ --extra-ldflags="-L/usr/local/lib"$ make$ make install$ rm -rf $TMPDIR$ unset TMPDIR There is also mktemp(1) command. So that you can set TMPDIR as follows: $ TMPDIR="$(mktemp -d -q ~/tmp/tmp.XXXXX)"$ echo $TMPDIR/home/marcelo/tmp/tmp.I8V9H This should work for GNU coreutils as well as for BSD (macOs, FreeBSD, etc). Also note, you not need to export TMPDIR and then unset it. Instead try to pass variable directly to configure: $ TMPDIR="/foo/bar/baz" ./configure ... Hope it helps somebody else ;-)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11697214', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_373279
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18798792
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been reading a lot about iOS7 UI transition. I am not able to get what these three properties automaticallyAdjustsScrollViewInsets , extendedLayoutIncludesOpaqueBars , edgesForExtendedLayout ?? For example I am trying to make my view controllers start below the status bar but I am not able to achieve it.
Now provide the response and nothing else.
|
Starting in iOS7, the view controllers use full-screen layout by default. At the same time, you have more control over how it lays out its views, and that's done with those properties: edgesForExtendedLayout Basically, with this property you set which sides of your view can be extended to cover the whole screen. Imagine that you push a UIViewController into a UINavigationController . When the view of that view controller is laid out, it will start where the navigation bar ends, but this property will set which sides of the view (top, left, bottom, right) can be extended to fill the whole screen. Let see it with an example: UIViewController *viewController = [[UIViewController alloc] init];viewController.view.backgroundColor = [UIColor redColor];UINavigationController *mainNavigationController = [[UINavigationController alloc] initWithRootViewController:viewController]; Here you are not setting the value of edgesForExtendedLayout , therefore the default value is taken ( UIRectEdgeAll ), so the view extends its layout to fill the whole screen. This is the result: As you can see, the red background extends behind the navigation bar and the status bar. Now, you are going to set that value to UIRectEdgeNone , so you are telling the view controller to not extend the view to cover the screen: UIViewController *viewController = [[UIViewController alloc] init];viewController.view.backgroundColor = [UIColor redColor];viewController.edgesForExtendedLayout = UIRectEdgeNone;UINavigationController *mainNavigationController = [[UINavigationController alloc] initWithRootViewController:viewController]; And the result: automaticallyAdjustsScrollViewInsets This property is used when your view is a UIScrollView or similar, like a UITableView . You want your table to start where the navigation bar ends, because you wont see the whole content if not, but at the same time you want your table to cover the whole screen when scrolling. In that case, setting edgesForExtendedLayout to None won't work because your table will start scrolling where the navigation bar ends and it wont go behind it. Here is where this property comes in handy, if you let the view controller automatically adjust the insets (setting this property to YES, also the default value) it will add insets to the top of the table, so the table will start where the navigation bar ends, but the scroll will cover the whole screen. This is when is set to NO: And YES (by default): In both cases, the table scrolls behind the navigation bar, but in the second case (YES), it will start from below the navigation bar. extendedLayoutIncludesOpaqueBars This value is just an addition to the previous ones. By default, this parameter is set to NO. If the status bar is opaque, the views won't be extended to include the status bar, even if you extend your view to cover it ( edgesForExtendedLayout to UIRectEdgeAll ). If you set the value to YES, this will allow the view to go underneath the status bar again. If something is not clear, write a comment and I'll answer it. How does iOS know what UIScrollView to use? iOS grabs the first subview in your ViewController's view, the one at index 0, and if it's a subclass of UIScrollView then applies the explained properties to it. Of course, this means that UITableViewController works by default (since the UITableView is the first view).
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/18798792', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1010819/']}
|
jdg_373280
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27244465
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I'm a bit stuck, trying to merge two HashMaps. It's easy to do it inline: fn inline() { let mut first_context = HashMap::new(); first_context.insert("Hello", "World"); let mut second_context = HashMap::new(); second_context.insert("Hey", "There"); let mut new_context = HashMap::new(); for (key, value) in first_context.iter() { new_context.insert(*key, *value); } for (key, value) in second_context.iter() { new_context.insert(*key, *value); } println!("Inline:\t\t{}", new_context); println!("Inline:\t\t{}\t{} [Initial Maps Still Usable]", first_context, second_context);} It's easy enough to make a function: fn abstracted() { fn merge<'a>(first_context: &HashMap<&'a str, &'a str>, second_context: &HashMap<&'a str, &'a str>) -> HashMap<&'a str, &'a str> { let mut new_context = HashMap::new(); for (key, value) in first_context.iter() { new_context.insert(*key, *value); } for (key, value) in second_context.iter() { new_context.insert(*key, *value); } new_context } let mut first_context = HashMap::new(); first_context.insert("Hello", "World"); let mut second_context = HashMap::new(); second_context.insert("Hey", "There"); println!("Abstracted:\t{}", merge(&first_context, &second_context)); println!("Abstracted:\t{}\t{} [Initial Maps Still Usable]", first_context, second_context);} However, I can't seem to get the generic version to work: fn generic() { fn merge<'a, K: Hash + Eq, V>(first_context: &HashMap<&'a K, &'a V>, second_context: &HashMap<&'a K, &'a V>) -> HashMap<&'a K, &'a V> { let mut new_context = HashMap::new(); for (key, value) in first_context.iter() { new_context.insert(*key, *value); } for (key, value) in second_context.iter() { new_context.insert(*key, *value); } new_context } let mut first_context = HashMap::new(); first_context.insert("Hello", "World"); let mut second_context = HashMap::new(); second_context.insert("Hey", "There"); println!("Generic:\t{}", merge(&first_context, &second_context)); println!("Generic:\t{}\t{} [Initial Maps Still Usable]", first_context, second_context);} The above code on play.rust-lang.org . Compiling it: error: the trait `core::kinds::Sized` is not implemented for the type `str` I get that the compiler is confused about the size of the generic value, but I'm not sure why "str" doesn't have a strict memory size? I know its a String slice and not a type, but still this should work, no? Is this a bug? I thought this would be a relatively trivial function. If someone has a good solution, I'd love to learn. Actually ideally, I'd love to see a solution with a trait Mergeable and write a decorator for HashMap<&K, &V>, such that I can call let new_context = first_context.merge(&second_context); but this can be a different question.
Now provide the response and nothing else.
|
A more up to date answer from this tweet : use std::collections::HashMap;// Mutating one mapfn merge1(map1: &mut HashMap<(), ()>, map2: HashMap<(), ()>) { map1.extend(map2);}// Without mutationfn merge2(map1: HashMap<(), ()>, map2: HashMap<(), ()>) -> HashMap<(), ()> { map1.into_iter().chain(map2).collect()}// If you only have a reference to the map to be merged infn merge_from_ref(map: &mut HashMap<(), ()>, map_ref: &HashMap<(), ()>) { map.extend(map_ref.into_iter().map(|(k, v)| (k.clone(), v.clone())));} Rust Playground Link
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27244465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2605466/']}
|
jdg_373281
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17895596
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to combine two different gif file into one file. First, I learned a lot about the gif format. And I know the delay time value is set in Graphics Control Extension which is a block of gif file. I saved the first gif and set the FrameDelay value, code as below: ImageCodecInfo codeInfo = GetEncoder(ImageFormat.Gif); System.Drawing.Imaging.Encoder saveEncoder = System.Drawing.Imaging.Encoder.SaveFlag; EncoderParameters parameters = new EncoderParameters(1); parameters.Param[0] = new EncoderParameter(saveEncoder, (long)EncoderValue.MultiFrame); PropertyItem PropertyTagFrameDelay = img1.GetPropertyItem(0x5100); PropertyTagFrameDelay.Value = new byte[] { 0x96, 0x00 };// this is the delay value 0x0096, means 1.5 second img1.SetPropertyItem(PropertyTagFrameDelay); PropertyItem LoopCount = img1.GetPropertyItem(0x5101); LoopCount.Value = new byte[] { 0x00, 0x00 };// this means the gif loops endlessly img1.SetPropertyItem(LoopCount); img1.Save(@"c:\ddd.gif", codeInfo, parameters); Then I tried to add another image as second frame. parameters = new EncoderParameters(1); parameters.Param[0] = new EncoderParameter(saveEncoder, (long)EncoderValue.FrameDimensionTime); PropertyTagFrameDelay = img2.GetPropertyItem(0x5100); PropertyTagFrameDelay.Value = new byte[] { 0x96, 0x00 };// this is the delay value 0x0096, means 1.5 second img2.SetPropertyItem(PropertyTagFrameDelay); Last, I should terminate this image. parameters = new EncoderParameters(1); parameters.Param[0] = new EncoderParameter(saveEncoder, (long)EncoderValue.Flush); img1.SaveAdd(parameters); And I found that the second frame's delay time is always 0. I tried a lot of method, but i have no idea to make it as 0x96. So what's wrong with it?
Now provide the response and nothing else.
|
This simply isn't supported by any of the .NET image encoders. Neither by GDI+ nor by WIC, the underlying native codecs for the System.Drawing.Bitmap and System.Windows.Media.Imaging.PngBitmapEncoder classes. While that sounds like a very strange oversight, the most probably reason was that GIF was encumbered by a software patent. Unisys owned the rights to the LZW compression algorithm and started aggressively pursuing obtaining the license fees for it. Starting at the most obvious targets where most money can be had, Microsoft is forever on the top of the list. They were not modest either, a non-commercial or private web site that used GIFs on their web pages had to cough up five thousand dollars in 1999. This killed the image format. Ubiquitous before this, just about everybody stopped using them. Stunningly quickly too, this only took a few months . Happily coinciding with everybody completely having their fill of animated gifs btw, it was grossly overdone before. You may find some web pages from back-then on the wayback machine where everything in the corner of eye was moving. Not the only lucky coincidence, it was the core reason for the open source PNG format being developed. Thank our lucky stars :) The patent expired around 2004, depending on where you live, so you won't have to fear a letter from Unisys anymore. Long story short, you'll have to shop around for another library to add this feature to your program. It is well-covered by this existing SO question , no need to repeat it here.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17895596', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1388421/']}
|
jdg_373282
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8743411
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Say I have the following two functions: 1 int * foo(){ int b=8; int * temp=&b; return temp;} 2 int * foo(){ int b=8; return &b;} I don't get any warning for the first one (e.g. function returns address of a local variable ) but I know this is illegal since b disappears from the stack and we are left with a pointer to undefined memory. So when do I need to be careful about returning the address of a temporary value?
Now provide the response and nothing else.
|
The reason you are not getting a warning in the first snippet is because you aren't (from the compiler's perspective) returning an address to a local variable. You are returning the value of int * temp . Even though this variable might be (and in this example is) containing a value which is an address of a local variable, the compiler will not go up the code execution stack to see whether this is the case. Note : Both of the snippets are equally bad, even though your compiler doesn't warn you about the former. Do not use this approach. You should always be careful when returning addresses to local variables; as a rule, you could say that you never should. static variables are a whole different case though, which is being discussed in this thread .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8743411', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/617425/']}
|
jdg_373283
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
612854
|
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:
Galilean transform: $$\begin{pmatrix} ct' \\x' \end{pmatrix} = \begin{pmatrix} 1 & 0 \\-\beta & 1 \end{pmatrix}\begin{pmatrix} ct \\x \end{pmatrix}$$ Lorentz transform: $$\begin{pmatrix} ct' \\x' \end{pmatrix} = \gamma\begin{pmatrix} 1 & -\beta \\-\beta & 1 \end{pmatrix}\begin{pmatrix} ct \\x \end{pmatrix}$$ where $\gamma^{-2} = 1-\beta^2$ and $\beta=v/c$ . It is always said that Lorentz is equivalent to Galilean in case of small speed ( $v \ll c$ or equivalent $\beta \ll 1$ ). I've no doubt that in this case $\gamma \simeq 1$ , thus: $$\begin{pmatrix} ct' \\x' \end{pmatrix} = \gamma\begin{pmatrix} 1 & -\beta \\-\beta & 1 \end{pmatrix}\begin{pmatrix} ct \\x \end{pmatrix} \simeq\begin{pmatrix} 1 & -\beta \\-\beta & 1 \end{pmatrix}\begin{pmatrix} ct \\x \end{pmatrix}$$ However I do not see how to continue without add the assumption $|\beta x| \ll ct$ (equivalent to $\beta \ll \left|\frac{ct}{x}\right|$ or $v \ll c^2\left|\frac{t}{x}\right|$ ). It seems an assumption stronger than $\beta \ll 1$ .
Now provide the response and nothing else.
|
Yes, you're right about that. Here is a picture of the Lorentz vs. Galilean transformations to illustrate: LEFT: The purple arrow is a pure temporal displacement (the trajectory of the observer themself), and the red is spatial. RIGHT: According to Galileo (solid arrows), the primed observer sees that same purple displacement as taking the same amount of time (dashed orange line), but shifting in space -- but the spatial displacement is unchanged. But according to relativity (dashed arrows), any displacement slides along the hyperbola with asymptote $c$ (red & blue curves) -- specifically, all displacements sweep out the same amount of area under that hyperbola (the area between the $t'$ axis and the dashed purple arrow). Based on that, you can see that $\gamma$ really just tells you how the hyperbola is stretched away from the horizontal line. For low speed between the two observers, these displacements stay close to the hyperbola vertex, so the $\gamma$ effect dies out. But both displacements are still rotated. It is only because $\beta \ll 1$ that you can say the rotation of the spatial displacement is negligible if you want. And by not applying that same approximation to the time displacement, since it doesn't matter if you apply it or not, you end up back at the Galilean transform.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/612854', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/164884/']}
|
jdg_373284
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1650436
|
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:
Particular questions such as Why is $\pi$ so close to $3$? or Why is $\pi^2$ so close to $10$? may be regarded as the first two cases of the question sequence Why is $\pi^k$ so close to its nearest integer? For instance, we may stare in awe in front of the almost-unit $$\frac{\pi}{31^\frac{1}{3}}=1.000067...$$ or, in binary system, $$\frac{\pi}{11111_{2}^\frac{1}{11_2}} \approx 1$$ so proving that $\pi^3>31$ becomes interesting, but it would not be striking that sometimes $\pi^k$ lied close to its nearest integer if that was balanced by other unlucky times when it would be at almost half a unit, by the straightforward effect of the rounding function. Under a uniform distribution assumption, the expected distance between $\pi^k$ and its nearest integer is $\frac{1}{4}$, and the title has at least the following two interpretations, as a random variable (given this made sense) and as particular outcomes of a random variable: In average, is $\pi^k$ any closer to its nearest integer than expected? The first three powers have differences less than $\frac{1}{4}$ in absolute value, namely $$\begin{align}\pi-3 &\approx .1416 \\\pi^2-10 &\approx -0.1304 \\ \pi^3-31 &\approx0.0063\end{align}$$This event has probability $\left(\frac{1}{2}\right)^3=\frac{1}{8}$ assuming independence. What happens as the number of powers considered grows? Another approach, with median instead of average: Does the median of the absolute value of that difference tend to $\frac{1}{4}$? Let $\lfloor x \rceil$ denote the rounding function . Although the answer to the first question may be false, for what values of $k$ does $\lfloor x^k \rceil ^\frac{1}{k}$ yield more bits of $\pi$ than it uses? For instance, $\lfloor x^{157} \rceil ^\frac{1}{157}$ seems to be an interesting approximation to $\pi$. (See this question ) In either case: Q : Is the difference between $\pi^k$ and its nearest integer uniformly distributed in $(-\frac{1}{2},\frac{1}{2})$?
Now provide the response and nothing else.
|
There are two ways of looking into this problem. For this we need to define what uniform distribution means. I will alter and observe the interval $[0,1]$ and adopt $x = [x]+\{x\}$ for clarity. If we take that uniform distribution is corresponding to uniform distribution of random numbers then $\{\pi^k\}$ is of much lower quality than the best uniform random distribution we can produce using other algorithms. This is to say that it would not be a good generator of random numbers. If we take that uniform distribution is actually equidistribution, meaning on average and looking at infinity, the frequency of terms falling into any segment $[a,b]$ tends to $b-a$, then we believe that $[\pi^k]$ is equidistributed although there is no proof. First thing first. We are fairly convinced that $\pi$ is a normal number, digits from $0$ to $9$ are appearing each with frequency $\frac{1}{10}$ for couple of million digits and beyond. Although we have no proof, for our story, this will be good for now. If we take $\pi$ as a normal number and if digits appear as if they are random(, but pay attention that normal does not mean random, it only has some property of a random sequence) then we can take that $\{\pi\}$ in $\pi=3+\{\pi\}$ has some random properties: it starts non-randomly, but then as we are adding more digits, additional segments are all more "random". When we say that $\pi$ does not start randomly, we have a specific randomness in mind. There is a type of randomness (Martin-Löf) related to Kolmogorov complexity that says that a number is random if we cannot compress it, we cannot write a program much shorter than its number of digits. So $\pi$ is not random in this sense, since we can write a pretty short programs for it. Even more, if we look into first few digits expressed for example as a spigot algorithm $$\pi=2+\frac{1}{3}(2+\frac{2}{5}(2+\frac{3}{7}(...(2+\frac{k}{2k+1}(...)))))$$ we can notice that first few digits can be encoded within a shorter sequence, and only as we go deeper more data is needed and more operations will be performed. Many random generators have this feature and for this reason many algorithms have a worm-up phase. It is difficult to state precisely if it is two, three, six or ten first digits in $\pi$ that are interconnected through a first few terms in an expression like the one we have shown using the spigot algorithm, (we would need to define a precise measure for this,) but a few first digits have a simpler connection, they are easier to express, and for this reason they are less random in the sense we have explained. The reason, again, is that you can extract their 10-base values from a shorter sequence in the spigot (or many similar) algorithms. There are other bases that have this feature as well but less obvious, like 16-base. We have this equation that allows extracting 16-base digit without extracting any other previous digit. This does not say that we are completely ignoring all of them since we still need to calculate modulo operation for all more larger and larger number. $$\pi=\sum\limits_{k=0}^{\infty}\frac{1}{16^k}(\frac{4}{8k+1}-\frac{2}{8k+4}-\frac{1}{8k+5}-\frac{1}{8k+6})$$ Of course, it is not purely about a formula, it is about the complexity of operations involved too. All more and more we are becoming aware that the digits of $\pi$ are part of a complicated chaotic system. In that sense we can talk about "being random" regarding $\pi$ in the sense of "being feasible to evaluate". Now, we will write the equations taking all $\mod 1$ and sometimes thinking in base $3$ $$\{(3+\{\pi\})^k\}\stackrel{\mod 1}{=}\sum\limits_{k=0}^{n-1} \{\binom{n}{k} 3^{k} \{\pi\}^{n-k} \}$$ Look what we have. For small $k$, we will have large $n-k$ and this will push $\{\pi\}^{n-k}$ farther from decimal point, so it will have less effect on the distribution. $3^k$ is not going to help much, it will shift the value (if we are looking at base $3$, just for the sake of making it all more obvious) few places towards the decimal point. So if we assume that $\{\pi\}^{k}$ is becoming all more and more random, its influence is not going to be felt immediately. On the other hand, if we have large $k$, we have most dominant $3^k$ part that is going to shift the value and include deeper digits from $\{\pi\}^{n-k}$, those that we expect to be more "random" based on the normality of $\pi$. But even that is not going to happen immediately. So, if we have any chance for good randomness, we have to wait a little bit all initial conditions and values to mangle first. If we would have only first 20 digits of $\pi$, we would not be able to say anything about the quality of their randomness, because a sample would be too small. As we are running deeper, they start to exhibit properties of a normal number. Knowing that first few digits are related to the simple series is the reason to treat them as kind of less random. Another problem is that there is a deeper connection that does not vanish between terms. These discovered connections are reducing the total randomness. More expressions we have, shorter they are, and the randomness is all more and more gone. $$1+\pi+\pi^2+...+\pi^n=\frac{\pi^{n+1}-1}{\pi-1}=\frac{1}{\frac{1}{\pi^{n}}-\frac{1}{\pi^{n+1}}}-\frac{1}{\pi-1}=H_{d}(\pi^{n},\pi^{n+1})-\frac{1}{\pi-1}$$ where $H_{d}$ is harmonic difference. Put two of these together and you have: $$H_{d}(\pi^{n-1},\pi^{n})-\frac{1}{\pi-1}+\pi^n=H_{d}(\pi^{n},\pi^{n+1})-\frac{1}{\pi-1}$$ which is $$ \{\pi^n \}= \{ \{H_{d}(\pi^{n},\pi^{n+1})\}-\{H_{d}(\pi^{n-1},\pi^{n})\} +1 \}$$ From here it turns out that our distribution is equal to the differences between two terms of another harmonic like distribution that involves the same constant $\pi$. This harmonic game is the actual mixer or at least it gives the idea what mixing process involves. And it reveals that the mixing process is not that strong. It takes two close values which contain similar amount of "randomness" and mix them. That way, it cannot improve much above them. This is saying as much about $\{\pi^n \}$ as much $\{\pi^{n+1} \}$. The random mixture might get in, but slowly although our tests are not able to detect a specific effect on some elements of this slower than desired mixture. Mixers are part of many mathematical random generators we have devised, and with that many encryption algorithms. In that sense, if we take $\{\pi^k\}$ as a generator of random numbers, it is not a good one. This is what we have before taking fractional part for example: $$ k(n+1) = \frac{k(n)^2}{k(n-1)}$$ The randomness of this sequence depends on its ability to mix values as much as on the two initial values needed, which are in our case $1$ and $\pi$. Although Knuth is suggesting using sufficient number of initial digits of $\pi$ for random seed in a couple of his polynomial type of random generators, because they exhibit nice random properties, the expression for random mixture is not as trivial as $x^k$. To illustrate this I will show a distribution of constants (real part) for FFT, Fast Fourier transformation, for $\{\pi^k\}$ first 1000 terms and for 1000 random values. Random values have a nice bell curve $\{\pi^k\}$ are not there yet There are two theorems that will help deciding about this power series. One is Weyl's saying about the condition that any series is equidistributed, and another Hardy and Littlewood saying that power series (like ours) with almost all real numbers (almost all means with some exceptions like integers, golden ratio and so on) is equidistributed. So, we are either within almost all or we are an exception. Weyl is saying to calculate for all positive integers $p$ this and to check if the limit tends to $0$. $$\lim\limits_{m \to \infty} \frac{1}{m} \sum\limits_{n=1}^{m} e^{2\pi i p \pi^n}$$ We will satisfy ourselves with calculating real part of it, for $p=1$ and without reciprocal. $$\sum\limits_{n=1}^{m} \cos(2\pi^{n+1})$$ Without further ado here is the plot for $n<1000$. The sum stays well beyond $n$ so if we divide it as the limit requires it will probably start reaching $0$. We do know that most of the numbers are normal in this sense, but we have a strong headache when we try to resolve any single one of them like $\pi^n$ or $e^n$. Even if we ignore this and take that it is equidistributed, do not use $\{\pi^n\}$ as a random generator in interval $(0,1)$. It will not pass various random tests.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1650436', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/134791/']}
|
jdg_373285
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2483747
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've heard that "first class modules" are coming in OCaml 3.12. What advantages will they offer? What kids of things will be easier? What problem are they trying to solve? A simple example would suffice.
Now provide the response and nothing else.
|
It's only one possible applications, but first class modules make it easy to encode existential types, with basically a module packing an existential type and a value using this type). For example, See Alain Frisch work on Dynamic types (code taken from Alain Frisch work on dyntypes : http://caml.inria.fr/cgi-bin/viewvc.cgi/ocaml/branches/dyntypes/stdlib/dyntypes.ml?view=markup ) module type DYN = sig type t val x: t val t: t ttypeendtype dyn = (module DYN)let dyn (type s) t x = let module M = struct type t = s let x = x let t = t end in (module M : DYN) The idea here is that "ttype" is a concrete representation of that type, an algebraic datatype with Int, Float constructors and so on, and you have here a value, whose type is concealed, but that carries a concrete representation of that type, that you can use for example to get a safer serialization/deserialization.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2483747', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/46190/']}
|
jdg_373286
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18961622
|
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 MyModel inheriting from MTLModel (using the GitHub Mantle pod).MyModel.h #import <Mantle/Mantle.h>@interface MyModel : MTLModel <MTLJSONSerializing>@property (nonatomic, copy, readonly) NSString *UUID;@property (nonatomic, copy) NSString *someProp;@property (nonatomic, copy) NSString *anotherProp;@end MyModel.m #import "MyModel.h"@implementation MyModel+ (NSDictionary *)JSONKeyPathsByPropertyKey{ return @{ @"UUID": @"id", @"someProp": @"some_prop", @"anotherProp": @"another" };}}@end Now I want to send the JSON to the backend using AFNetworking. Before that I convert the model instance to a JSON NSDictionary to use as parameters/body payload within my request. NSDictionary *JSON = [MTLJSONAdapter JSONDictionaryFromModel:myModel]; But this JSON consists of strange "" Strings for properties of my model that are nil. What i instead want is Mantle to omit these key/value pairs and just spit out a JSON with only the properties that are not nil or NSNull.null, whatever.
Now provide the response and nothing else.
|
This is a common issue with Mantle and it's called implicit JSON mapping . MTLJSONAdapter reads all properties of a model to create a JSON string optionally replacing property names with ones given in +JSONKeyPathsByPropertyKey . If you want some properties to be excluded from the JSON representation of your model, map them to NSNull.null in your +JSONKeyPathsByPropertyKey : + (NSDictionary *)JSONKeyPathsByPropertyKey { return @{ @"UUID": @"id", @"someProp": @"some_prop", @"anotherProp": @"another", @"myInternalProperty": NSNull.null, @"myAnotherInternalProperty": NSNull.null, };} The implicit JSON mapping has lately become a noticeable problem, a solution for which is currently being discussed at Mantle's home repository at GitHub. See issues #137 , #138 , #143 and the current discussion under #149 . EDIT: I clearly misunderstood the question, but now, when I suppose I understand it correctly, the answer is simple. MTLJSONAdapter generates the JSON data using MTLModel 's dictionaryValue property. If you wish to exclude a property from the JSON itself, you can overwrite that method in your MYModel : - (NSDictionary *)dictionaryValue { NSMutableDictionary *originalDictionaryValue = [[super dictionaryValue] mutableCopy]; if (self.aPropertyThatShouldBeExcludedWhenNil == nil) { [originalDictionaryValue removeObjectForKey:@"aPropertyThatShouldBeExcludedWhenNil"]; } /* repeat the process for other "hidden" properties */ return originalDictionaryValue;} EDIT #2: Check out the code* for removing all values that are nil : - (NSDictionary *)dictionaryValue { NSMutableDictionary *modifiedDictionaryValue = [[super dictionaryValue] mutableCopy]; for (NSString *originalKey in [super dictionaryValue]) { if ([self valueForKey:originalKey] == nil) { [modifiedDictionaryValue removeObjectForKey:originalKey]; } } return [modifiedDictionaryValue copy];} * - code sample suggested by matths.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18961622', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/446490/']}
|
jdg_373287
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
289171
|
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:
Let $x,y$ be two variables that are functionally related, so that $x$ determines $y$: $$y = f(x)$$ for some function $f$. We consider a probability distribution on $x$, $p(x)$. The question is: Is it possible, for some probability distribution $p(x)$, that the correlation between $x$ and $y$ vanishes? That is, $$\mathrm{cov}(x,f(x)) = \langle x f(x) \rangle - \langle x\rangle \langle f(x) \rangle = \sum_x xf(x)p(x) - \left(\sum_x xp(x)\right) \left(\sum_x f(x)p(x)\right) = 0$$ In other words, given a function $f$, is it possible to select a probability distribution $p$, such that $\mathrm{cov}(x,f(x)) = 0$? The answer is yes in at least one trivial case, when $f(x) = c$ is a constant number. This case is trivial in the sense that any $p$ will do. Are there more interesting examples? Or general theorems available?
Now provide the response and nothing else.
|
There are three mutually exclusive possibilities for $f$ (apart from the trivial one where the domain of $f$ has just one element). To be fully general and avoid trivial complications, let's not worry about correlation, but focus on covariance instead: when covariance is zero, correlation is either zero or undefined. (Correlation becomes undefined when the variance of either marginal distribution is zero.) $f$ is not injective. Suppose there exist $x_1 \lt x_2$ for which $f(x_1)=f(x_2)$. Putting probabilities of $1/2$ on each of $x_1$ and $x_2$ gives zero covariance (and undefined correlation). $f$ is injective but not monotonic. Otherwise suppose there exist $x_1\lt x_2 \lt x_3$ for which the $y_i=f(x_i)$ are not in order. Since covariance does not change with translations, make the calculations easier by shifting the $x$ and $y$ coordinates so that $x_2=y_2=0$. The assumption amounts to $x_1\lt 0,$ $x_3\gt 0$, and $y_1$ and $y_3$ have the same sign. Define $C(p)$ to be the covariance achieved by putting probabilities of $p$ on $x_1$, $1/2-p$ on $x_3$, and $1/2$ on $0$. $C$ clearly is a quadratic function of $p$ and therefore is continuous. Compute $$C(0)=\frac{1}{4}x_3y_3,\ C(1/2)=\frac{1}{4}x_1y_1.$$ The assumptions imply $C(0)$ and $C(1/2)$ have opposite signs. The Intermediate Value Theorem implies there is some $p\in (0,1/2)$ for which $C(p)=0$: use this value of $p$ to achieve zero covariance. The correlation will be defined and zero. $f$ is monotonic. Otherwise $f$ is strictly monotonic (increasing or decreasing). From the characterization of covariance as an expected signed area, it is obvious that all covariances must be strictly positive or strictly negative when the probability is not an atom. The correlation will be defined.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/289171', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/5536/']}
|
jdg_373288
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
51206233
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to pass a function in android using Kotlin . I can able to pass if i know the function like : fun a(b :() -> Unit){}fun b(){} I want to pass any function like -> fun passAnyFunc(fun : (?) ->Unit){}
Now provide the response and nothing else.
|
You can use anonymous function or a lambda as follows fun main(args: Array<String>) { fun something(exec: Boolean, func: () -> Unit) { if(exec) { func() } } //Anonymous function something(true, fun() { println("bleh") }) //Lambda something(true) { println("bleh") }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51206233', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5917123/']}
|
jdg_373289
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
633320
|
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:
Or should it be the other way around, because hotter water evaporates easier than cold water? I know this sounds stupid, so just hear me out. I use an evaporative cooler and add normal room temperature water. Someone told me to add cold water from the refrigerator to get better results. I intuitively thought that indeed cold water will produce colder air. But as we all know evaporative coolers cool air by using the air to evaporate water which takes away heat from the air. So, we need the water to evaporate to cool the air. But we know that hotter water evaporates easier than cold water. So, should it not be the case that refrigerated water will actually not evaporate as efficiently and hence not produce cooler air than in case of room temperature water ? For what it's worth, I tried both and could not feel any noticeable difference, but of course, it was nowhere close to a controlled experiment. So, I would appreciate an answer about what does physics predict what would happen?
Now provide the response and nothing else.
|
You've intuited two possibly relevant counteracting mechanism (of which none, one, or both might be negligible): colder water takes more energy to heat up, and colder water evaporates slower. As a first stab at the problem, let's assume that the water evaporates at its well-defined supply temperature and that the rate of water evaporation is essentially the same at both temperatures. This is a good approximation if the water evaporates quickly under forced convection of hot, dry air—a pretty good description of a swamp cooler fed from a (room-temperature or cold) water flow. Here, the difference in water chemical potential (essentially, the concentration) between the liquid water and dry air in conjunction with a very high relative surface area drives rapid evaporation, and the water temperature doesn't have time to equilibrate at room temperature. The enthalpy of vaporization (also called the heat of vaporization ) reflects the amount of "heat" needed to achieve evaporation, corresponding to the cooling effect applied to the surroundings. The amount reflects evaporation/vaporization at the given temperature, from liquid water to gaseous water. It does not require boiling. The parameter expressed here is the specific enthalpy (i.e., per unit mass). If the water in both temperature cases is fed at a constant rate and evaporates quickly, then the per-mass enthalpy can act as a surrogate for the per-time enthalpy, giving us an effective cooling power rate. Try comparing the rate at which you need to replenish water. If the rate isn't lower for the colder water, then the above assumption is valid and the specific enthalpy translates easily into a cooling power. If the rates are different, then the specific enthalpy should be adjusted according to the mass rate to again obtain a cooling power. The relative slope around 0°C to 50°C is clearly slight. We can estimate the slope from the difference between the heat capacity of liquid water and steam, about $4.2\,\frac{\mathrm{kJ}}{\mathrm{kg\,K}}$ and $1.9\,\frac{\mathrm{kJ}}{\mathrm{kg\,K}}$ , or about $2.3\,\frac{\mathrm{kJ}}{\mathrm{kg\,K}}$ . So by switching from water at 40°C to 10°C, for example, you'd increase the cooling effect by about $70\,\frac{\mathrm{kJ}}{\mathrm{kg\,K}}$ , an improvement of about 3%. Put another way, the energy it takes to heat or cool a kilogram of liquid water is generally much less than its latent heat (the heat required to vaporize it) of thousands of kilojoules. This would account for the difference you experienced as being essentially imperceptible. Alternatively, it may be the case that you're providing a large tub of water that evaporates slowly. Note that water away from room temperature will tend to equilibrate toward room temperature, minimizing the influence of the original temperature (while also providing a separate mechanism of cooling). This would also contribute to the difference for different temperatures being imperceptible. In any case, the coupled heat–mass transfer problem becomes more complex, as you may need to consider the exposed area, temperature distribution inside the water container, and boundary conditions that mediate the heat and mass transfer. (In other words, the kinetic process of evaporation depends on more parameters than the thermodynamic energy balance.) Do you have this information? You may wish to migrate to the Engineering Stack Exchange site, which might be more useful in terms of, say, providing recommendations from manufacturers, who have studied this problem in detail.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/633320', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/269418/']}
|
jdg_373290
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20789207
|
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 project to try and teach myself spring and struts. I am currently stuck on a JSP page. I have a pojo class with variables eid and ename with getters/setters, I also have a table in sql with the same values with six populated rows. I am accessing my database through a JdbcTemplate and have stored the result in a list, I then passed this list to my action page in which I set it as a request.setAttribute("empList",eList) . In my jsp page I call that attribute and then try to iterate through it using JSTL . However nothing shows up, I know that my list variable has data in it since i checked it using the expression tag <%=eList%> and objects show up like this: [org.classes.database.Employee@d9b02, org.classes.database.Employee@13bce7e, org.classes.database.Employee@171cc79, org.classes.database.Employee@272a02, org.classes.database.Employee@137105d, org.classes.database.Employee@1359ad] I thought that maybe I was missing something on jstl but I have jstl-1.2 in my META-INF/lib folder. I have also tried to add it in the configure path file and still nothing. I also have the correct tag url. Also when I do a simple <c:out value="Hello"/> . Hello does print out. So this leads me to believe that my jstl is working properly, but when I try iterating through my list using jstl nothing shows up at all. Anyways here is my JSP page: <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO- 8859-1"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%@ page import="java.util.List"%><!DOCTYPE html><% List eList = (List)session.getAttribute("empList");%><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Employee Details</title></head><body><c:out value="Hello"></c:out><h3>Employee Details</h3><hr size="4" color="gray"/><table><%=eList%> <c:forEach items="${eList}" var="employee"> <tr> <td>Employee ID: <c:out value="${employee.eid}"/></td> <td>Employee Pass: <c:out value="${employee.ename}"/></td> </tr> </c:forEach></table></body></html> Any help would be highly appreciated!
Now provide the response and nothing else.
|
Before teaching yourself Spring and Struts, you should probably dive a little deeper into the Java language. Output like this org.classes.database.Employee@d9b02 is the result of the Object#toString() method which all objects inherit from the Object class, the superclass of all classes in Java. The List sub classes implement this by iterating over all the elements and calling toString() on those. It seems, however, that you haven't implemented (overriden) the method in your Employee class. Your JSTL here <c:forEach items="${eList}" var="employee"> <tr> <td>Employee ID: <c:out value="${employee.eid}"/></td> <td>Employee Pass: <c:out value="${employee.ename}"/></td> </tr></c:forEach> is fine except for the fact that you don't have a page, request, session, or application scoped attribute named eList . You need to add it <% List eList = (List)session.getAttribute("empList"); request.setAttribute("eList", eList);%> Or use the attribute empList in the forEach . <c:forEach items="${empList}" var="employee"> <tr> <td>Employee ID: <c:out value="${employee.eid}"/></td> <td>Employee Pass: <c:out value="${employee.ename}"/></td> </tr></c:forEach>
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20789207', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2966896/']}
|
jdg_373291
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13091000
|
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 this SQL-Statement: SELECT Geburtsdatum FROM KundeWHERE Geburtsdatum BETWEEN '1993-01-01' AND '2000-01-01' but I get some weird results, like: 2.02.1990 'Geburtsdatum' is a DATE Any suggestions or solutions? my table-structure: CREATE TABLE Kunde ( Kunde_ID INTEGER NOT NULL , Card INTEGER , Vorname VARCHAR(255) NOT NULL , Nachname VARCHAR(255) NOT NULL , Ort VARCHAR(255) NOT NULL , Strasse VARCHAR(255) NOT NULL , Postleitzahl VARCHAR(10) NOT NULL , Mail VARCHAR(255) , Telefonnummer VARCHAR(255) , Geburtsdatum DATE NOT NULL , Beitrittsdatum DATE NOT NULL , Geschlecht INTEGER NOT NULL , Land VARCHAR(255) NOT NULL DEFAULT 'Österreich' , Bankname VARCHAR(255) , Bankleitzahl VARCHAR(255) , Kontonummer VARCHAR(255) , GroupID INTEGER NOT NULL , Besucher INTEGER , Access BOOLEAN , image BLOB NULL , writeDate DATE , drinkAbo BOOLEAN , PRIMARY KEY (Kunde_ID) )
Now provide the response and nothing else.
|
From the documentation: SQLite does not have a storage class set aside for storing dates and/or times. So your column isn't exactly stored as a date. Reading further, we learn that columns specifed as DATE are actually stored as NUMERIC using affinity rule 5. Going back up to section 1.2: REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar. Good. So let's try: SELECT Geburtsdatum FROM KundeWHERE Geburtsdatum BETWEEN julianday('1993-01-01') AND julianday('2000-01-01'); Oddly enough, SQL Fiddle seems to store DATE s as strings and the above doesn't work. In this case, the following should: SELECT Geburtsdatum FROM KundeWHERE date(Geburtsdatum) BETWEEN date('1993-01-01') AND date('2000-01-01'); Additionally, in your case you seem to be getting some strange (read: localized) format returned. I wonder if it really is a string in your case too, just with a different format. You could try: SELECT Geburtsdatum FROM KundeWHERE strftime('%d.%m.%Y', Geburtsdatum) BETWEEN date('1993-01-01') AND date('2000-01-01');
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13091000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1333276/']}
|
jdg_373292
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11664038
|
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 taking an image file and thumbnailing and cropping it with the following PIL code: image = Image.open(filename) image.thumbnail(size, Image.ANTIALIAS) image_size = image.size thumb = image.crop( (0, 0, size[0], size[1]) ) offset_x = max( (size[0] - image_size[0]) / 2, 0 ) offset_y = max( (size[1] - image_size[1]) / 2, 0 ) thumb = ImageChops.offset(thumb, offset_x, offset_y) thumb.convert('RGBA').save(filename, 'JPEG') This works great, except when the image isn't the same aspect ratio, the difference is filled in with a black color (or maybe an alpha channel?). I'm ok with the filling, I'd just like to be able to select the fill color -- or better yet an alpha channel. Output example: How can I specify the fill color?
Now provide the response and nothing else.
|
I altered the code just a bit to allow for you to specify your own background color, including transparency.The code loads the image specified into a PIL.Image object, generates the thumbnail from the given size, and then pastes the image into another, full sized surface. (Note that the tuple used for color can also be any RGBA value, I have just used white with an alpha/transparency of 0.) # assuming 'import from PIL *' is precedingthumbnail = Image.open(filename)# generating the thumbnail from given sizethumbnail.thumbnail(size, Image.ANTIALIAS)offset_x = max((size[0] - thumbnail.size[0]) / 2, 0)offset_y = max((size[1] - thumbnail.size[1]) / 2, 0)offset_tuple = (offset_x, offset_y) #pack x and y into a tuple# create the image object to be the final productfinal_thumb = Image.new(mode='RGBA',size=size,color=(255,255,255,0))# paste the thumbnail into the full sized imagefinal_thumb.paste(thumbnail, offset_tuple)# save (the PNG format will retain the alpha band unlike JPEG)final_thumb.save(filename,'PNG')
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11664038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/382374/']}
|
jdg_373293
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
556234
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I enjoy the occasional hot drink, but place it below a small fan in order to cool it to a drinkable temperature. Unfortunately, as expected, I commonly forget about my drink, and it ends up very cold. In fact, it ends up so cold that it feels much colder than I would expect given my relatively warm room ( $\sim \mathrm{25^\circ C}$ ). However, this could be an illusion caused by room temperature still being less than body temperature, or the mug being fairly cold. I’m wondering if the fan is able to cool the liquid below room temperature. I’m aware that evaporation works on the warmest molecules, and leaves the remaining liquid cooler, but I’m not sure that it can ever become cooler than the surrounding air temperature?
Now provide the response and nothing else.
|
Yes, as other answers have stated, the temperature could drop below room temperature through evaporative cooling. In fact it could get as cold as the wet-bulb temperature of the air in the room. If you know the temperature and humidity of the air, you can figure out the wet-bulb temperature by using a psychrometric chart : Find your room temperature on the green "Dry Bulb Temperature" scale and the room relative humidity on the red "Relative Humidity" scale. Locate the point where they meet, and read off that position on the light blue "Wet Bulb or Saturation Temperature" scale. For example, if the room temperature is 25°C and the relative humidity is 30% (which you indicated), the lowest temperature your drink could reach by evaporative cooling would be roughly 14°C. If the air was completely dry however (relative humidity 0%), it could reach about 8°C. This does not necessarily mean that your drink will reach that temperature. It may require a large air flow, a large evaporation surface, and considerable time to actually reach the wet bulb temperature.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/556234', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/63383/']}
|
jdg_373294
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3578549
|
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 easiest way to replace all occurrences of string_a with string_b while at the same time changing anything that was already string_b into string_a ? My current method is as follows: :s/string_a/string_c/g :s/string_b/string_a/g :s/string_c/string_b/g Although this works, it requires extra typing and seems inefficient. Does anybody know of a better way to do this?
Now provide the response and nothing else.
|
I'd do it like this: :%s/\v(foo|bar)/\={'foo':'bar','bar':'foo'}[submatch(0)]/g But that's too much typing, so I'd do this: function! Mirror(dict) for [key, value] in items(a:dict) let a:dict[value] = key endfor return a:dictendfunctionfunction! S(number) return submatch(a:number)endfunction:%s/\v(foo|bar)/\=Mirror({'foo':'bar'})[S(0)]/g But that still requires typing foo and bar twice, so I'd do something like this: function! SwapWords(dict, ...) let words = keys(a:dict) + values(a:dict) let words = map(words, 'escape(v:val, "|")') if(a:0 == 1) let delimiter = a:1 else let delimiter = '/' endif let pattern = '\v(' . join(words, '|') . ')' exe '%s' . delimiter . pattern . delimiter \ . '\=' . string(Mirror(a:dict)) . '[S(0)]' \ . delimiter . 'g'endfunction:call SwapWords({'foo':'bar'}) If one of your words contains a / , you have to pass in a delimiter which you know none of your words contains, .e.g :call SwapWords({'foo/bar':'foo/baz'}, '@') This also has the benefit of being able to swap multiple pairs of words at once. :call SwapWords({'foo':'bar', 'baz':'quux'})
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3578549', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/432240/']}
|
jdg_373295
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50432395
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When calling RestTemplate.exchange to do a get request, such as: String foo = "fo+o";String bar = "ba r";restTemplate.exchange("http://example.com/?foo={foo}&bar={bar}", HttpMethod.GET, null, foo, bar) what's the proper to have the URL variables correctly escaped for the get request? Specifically, how do I get pluses ( + ) correctly escaped because Spring is interpreting as spaces , so, I need to encode them. I tried using UriComponentsBuilder like this: String foo = "fo+o";String bar = "ba r";UriComponentsBuilder ucb = UriComponentsBuilder.fromUriString("http://example.com/?foo={foo}&bar={bar}");System.out.println(ucb.build().expand(foo, bar).toUri());System.out.println(ucb.build().expand(foo, bar).toString());System.out.println(ucb.build().expand(foo, bar).toUriString());System.out.println(ucb.build().expand(foo, bar).encode().toUri());System.out.println(ucb.build().expand(foo, bar).encode().toString());System.out.println(ucb.build().expand(foo, bar).encode().toUriString());System.out.println(ucb.buildAndExpand(foo, bar).toUri());System.out.println(ucb.buildAndExpand(foo, bar).toString());System.out.println(ucb.buildAndExpand(foo, bar).toUriString());System.out.println(ucb.buildAndExpand(foo, bar).encode().toUri());System.out.println(ucb.buildAndExpand(foo, bar).encode().toString());System.out.println(ucb.buildAndExpand(foo, bar).encode().toUriString()); and that printed: http://example.com/?foo=fo+o&bar=ba%20rhttp://example.com/?foo=fo+o&bar=ba rhttp://example.com/?foo=fo+o&bar=ba rhttp://example.com/?foo=fo+o&bar=ba%20rhttp://example.com/?foo=fo+o&bar=ba%20rhttp://example.com/?foo=fo+o&bar=ba%20rhttp://example.com/?foo=fo+o&bar=ba%20rhttp://example.com/?foo=fo+o&bar=ba rhttp://example.com/?foo=fo+o&bar=ba rhttp://example.com/?foo=fo+o&bar=ba%20rhttp://example.com/?foo=fo+o&bar=ba%20rhttp://example.com/?foo=fo+o&bar=ba%20r The space is correctly escaped in some instances, but the plus is never escaped. I also tried UriTemplate like this: String foo = "fo+o";String bar = "ba r";UriTemplate uriTemplate = new UriTemplate("http://example.com/?foo={foo}&bar={bar}");Map<String, String> vars = new HashMap<>();vars.put("foo", foo);vars.put("bar", bar);URI uri = uriTemplate.expand(vars);System.out.println(uri); with the exact same result: http://example.com/?foo=fo+o&bar=ba%20r
Now provide the response and nothing else.
|
Apparently, the correct way of doing this is by defining a factory and changing the encoding mode: String foo = "fo+o";String bar = "ba r";DefaultUriBuilderFactory factory = new DefaultUriBuilderFactory();factory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.VALUES_ONLY);URI uri = factory.uriString("http://example.com/?foo={foo}&bar={bar}").build(foo, bar);System.out.println(uri); That prints out: http://example.com/?foo=fo%2Bo&bar=ba%20r This is documented here: https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#web-uri-encoding
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50432395', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6068/']}
|
jdg_373296
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3396958
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This question is perhaps somehow odd, but how can I speed up g++ compile time? My C++ code heavily uses boost and templates. I already moved as much as possible out of the headers files and use the -j option, but still it takes quite a while to compile (and link). Are there any tools out there which analyse my code and point out bottle-necks for the compiler? Or can one somehow profile the compiler running on my code? This would be really nice, because sometimes I have the impression, that I spent too much time staring at the compiler console log ...
Now provide the response and nothing else.
|
What has been most useful for me: Build on a RAM filesystem. This is trivial on Linux. You may want to keep a copy of common header files (precompiled or the actual .h files) on the RAM filesystem as well. Precompiled headers . I have one per (major) library (e.g. Boost, Qt, stdlib). Declare instead of include classes where possible. This reduces dependencies, thus reduces the number of files which need to be recompiled when you change a header file. Parallelize make . This usually helps on a case-by-case basis, but I have -j3 globally for make. Make sure your dependency graphs are correct in your Makefile, though, or you may have problems. Use -O0 if you're not testing execution speed or code size (and your computer is fast enough for you not to care much about the (probably small) performance hit). Compile each time you save. Some people don't like this, but it allows you to see errors early and can be done in the background, reducing the time you have to wait when you're done writing and ready to test.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3396958', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/316448/']}
|
jdg_373297
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2834442
|
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 $F=\left\lbrace f: f\in C_{\left[0, 1\right]}, f\left(0\right)=f\left(1\right)\right\rbrace$ complete metric space? I know how to prove that $C_{\left[0, 1\right]}$ is complete. But I don't know how to use condition that $f\left(0\right)=f\left(1\right)$.
Now provide the response and nothing else.
|
$F$ is a closed subspace of the complete space $\mathcal C_{\left[0, 1\right]}$. Hence it is complete. Why is $F$ closed? Because $F$ is the inverse image of (the closed subset) $\{0\}$ under the continuous map $f \mapsto f(1)-f(0)$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2834442', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/402325/']}
|
jdg_373298
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
304755
|
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:
What are the pros and cons of weight normalization vs batch normalization in general and for convolutional neural networks specifically?
Now provide the response and nothing else.
|
Batch Norm: (+) Stable if the batch size is large (+) Robust (in train) to the scale & shift of input data (+) Robust to the scale of weight vector (+) Scale of update decreases while training (-) Not good for online learning (-) Not good for RNN, LSTM (-) Different calculation between train and test Weight Norm: (+) Smaller calculation cost on CNN (+) Well-considered about weight initialization (+) Implementation is easy (+) Robust to the scale of weight vector (-) Compared with the others, might be unstable on training (-) High dependence to input data Layer Norm: (+) Effective to small mini batch RNN (+) Robust to the scale of input (+) Robust to the scale and shift of weight matrix (+) Scale of update decreases while training (-) Might be not good for CNN (Batch Norm is better in some cases)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/304755', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/178370/']}
|
jdg_373299
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19162285
|
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 list of objects with attribute id and I want to find index of object with specific id. I wrote something like this: index = -1for i in range(len(my_list)): if my_list[i].id == 'specific_id' index = i break but it doesn't look very well. Are there any better options?
Now provide the response and nothing else.
|
Use enumerate when you want both the values and indices in a for loop: for index, item in enumerate(my_list): if item.id == 'specific_id': breakelse: index = -1 Or, as a generator expression: index = next((i for i, item in enumerate(my_list) if item.id == 'specific_id'), -1)
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/19162285', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2269130/']}
|
jdg_373300
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4459722
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the vector field \begin{align*}X:\mathbb R^d&\to\mathbb R^d\\x&\mapsto\frac{x}{\|x\|}\end{align*} which is a differentiable vector field outside of the origin, and I am interested in its divergence. After some easy computation we get $$\mathrm{div}(X)=\left\{\begin{array}{ll}2\delta_0&d=1\\\frac{d-1}{\|x\|}&d\geq 2.\end{array}\right.$$ The problem with the above computation is that the dimension 1 case is computed as a distributional derivative and the case of bigger dimension is computed classically.This is a problem because for the longest time I thought that $$\mathrm{div}(X)$$ should have a Dirac delta in the origin in any dimension, and I still believe it has to have it. The reasons I do believe it has a Dirac delta component in the origin is because for $X$ infinite integral curves start from the origin.To put it differently, if we were to look at $-X$ , if one were to search for the solutions to the continuity equation for $-X$ , i.e. $$\partial \mu_t+\mathrm{div}((-X)\mu_t)=0$$ one would see how mass accumulates at the origin. Question 1): did I make a mistake in my computations and $\mathrm{div}(X)$ has a Dirac delta in the origin? Or more correctly, if my computation isn't wrong classically but is wrong distributionally, how would I carry out that computation? Because it still doesn't yield a singular part when I evaluate with polar coordinates. Question 2): is my intuition wrong and in reality in dimension bigger than one there is never a Dirac delta in that computation even distributionally? Any help or literature is appreciated. Maybe it is all because my differential geometry skills are very rusty.
Now provide the response and nothing else.
|
The divergence you wrote is correct distributionally as well. To see this, let $\phi$ be any test function, then using the definition of distributional divergence, dominated convergence, and the divergence theorem, we get \begin{align}\langle\text{div}(X),\phi\rangle&:=-\sum_{i=1}^n\langle X^i,\partial_i\phi\rangle\\&=-\sum_{i=1}^n\int_{\Bbb{R}^n}X^i\partial_i\phi\,dV\\&=-\lim_{\epsilon\to 0^+}\sum_{i=1}^n\int_{B_{\epsilon}(0)^c}X^i\partial_i\phi\,dV\tag{DCT}\\&=\lim_{\epsilon\to 0^+}\sum_{i=1}^n\int_{B_{\epsilon}(0)^c}[(\partial_iX^i)\phi - \partial_i(X^i\phi)]\,dV\\&=\lim_{\epsilon\to 0^+}\left[\int_{B_{\epsilon}(0)^c}\frac{n-1}{\|x\|}\phi\,dV +\int_{S_{\epsilon}(0)}\phi\,dA \right]\tag{$*$}.\end{align} Notice that in this last equality, I used the divergence theorem, and beware that the outward normal to the boundary of $B_{\epsilon}(0)^c$ actually points into the origin, i.e is $-X$ , so this extra minus sign cancels the minus sign which is already present. Now, in the first term, $\frac{1}{\|x\|}$ is integrable in a neighborhood of the origin in $\Bbb{R}^n$ for $n\geq 2$ , so we can use the dominated convergence theorem to say the first limit is $\int_{\Bbb{R}^n}\frac{n-1}{\|x\|}\phi\,dV$ . For the second term, since $n\geq 2$ , the 'surface area' of the sphere $S_{\epsilon}(0)$ grows like $\epsilon^{n-1}$ , which vanishes as $\epsilon\to 0^+$ . So, the fact that $\phi$ is a test function means the intergal over the sphere vanishes too. Hence, the final result is \begin{align}\langle\text{div}(X),\phi\rangle&=\int_{\Bbb{R}^n}\frac{n-1}{\|x\|}\phi\,dV+0=\left\langle\frac{n-1}{\|x\|},\phi\right\rangle.\end{align} Thus, even in the distributional sense, we have $\text{div}(X)=\frac{n-1}{\|x\|}$ for $n\geq 2$ . Note, the proof follows through up to $(*)$ even for $n=1$ . To proceed further, note that if $n=1$ , the first integral vanishes (this is just reflecting that $\frac{x}{|x|}$ is constantly equal to $\pm 1$ away from the origin, so the derivative vanishes there). In the 1-dimensional case, the "boundary sphere $S_{\epsilon}(0)$ " really consists of a 2-point set $\{-\epsilon,\epsilon\}$ , and the integral over this set just means adding the values of $\phi$ at these points $\phi(-\epsilon)+\phi(\epsilon)$ . Now, taking the limit $\epsilon\to 0^+$ , and using continuity of $\phi$ , we get $2\phi(0)= \langle 2\delta_0,\phi\rangle$ , as expected.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4459722', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/160018/']}
|
jdg_373301
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13120
|
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been using Mathematica for years, and over time I have developed the habit of using: Select[data, (# == 1 &)] instead of Select[data, # == 1 &] I learned this by mimicking the style of more experienced users. I'm pretty sure that there are reasons for flanking the function with parentheses, but I'm not sure that I have seen a reason for why this is necessary or a good habit to get into. Would someone be able to comment?
Now provide the response and nothing else.
|
It is a good habit to get into because you can often get tripped up by precedence rules (no one remembers everything!). For instance, PatternTest binds very tightly . See the difference between these two definitions: Clear@ff[_?(# == 2 &)] := Print@"foo"f[_] := Print@"bar"f[2](* "foo" *)Clear@gg[_?# == 2 &] := Print@"foo"g[_] := Print@"bar"g[2](* "bar" *) You can see that the second function does not behave as expected. Further inspection of the patterns will show that the function is not being defined as expected: _?#1 == 2 & // FullForm(* Function[Equal[PatternTest[Blank[],Slot[1]],2]] *)_?(#1 == 2 &) // FullForm(* PatternTest[Blank[],Function[Equal[Slot[1],2]]] *) A similar situation arises when you're supplying a pure function to options such as ColorFunction , Mesh , etc.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/13120', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/2469/']}
|
jdg_373302
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18852244
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can i get the "real" value of an <input type="number"> field? I have an input box, and i'm using newer HTML5 input type number : <input id="edQuantity" type="number"> This is mostly supported in Chrome 29: What i now need is the ability to read the "raw" value the user has entered in the input box. If the user has entered a number: then edQuantity.value = 4 , and all is well. But if the user enters invalid text, i want to color the input-box red: Unfortunately, for a type="number" input box, if the value in the text-box is not a number then value returns an empty string: edQuantity.value = "" (String); (in Chrome 29 at least) How can i get the "raw" value of an <input type="number"> control? i tried looking through Chrome's list of other properties of the input box: i didn't see anything that resembles the actual input. Nor could i find a way to tell if the box "is empty" , or not. Maybe i could have inferred: value isEmpty Conclusion============= ============= ================"4" false valid number"" true empty box; not a problem"" false invalid text; color it red Note : You can ignore everything after the horizontal rule; it's just filler to justify the question. Also: don't confuse the example with the question. People might want the answer to this question for reasons other than coloring the box red (One example: converting the text "four" into the latin "4" symbol during the onBlur event) How can i get the "raw" value of an <input type="number"> control? Bonus Reading jsFiddle of all of the above (updated) Quirkmode.org entry for the new input types
Now provide the response and nothing else.
|
According to the WHATWG , you shouldn't be able to get the value unless it's valid numeric input. The input number field's sanitization algorithm says the browser is supposed to set the value to an empty string if the input isn't a valid floating point number. The value sanitization algorithm is as follows: If the value of the element is not a valid floating-point number , then set it to the empty string instead. By specifying the type ( <input type="number"> ) you're asking the browser to do some work for you. If, on the other hand, you'd like to be able to capture the non-numeric input and do something with it, you'd have to rely on the old tried and true text input field and parse the content yourself. The W3 also has the same specs and adds: User agents must not allow the user to set the value to a non-empty string that is not a valid floating-point number.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18852244', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12597/']}
|
jdg_373303
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3998437
|
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:
$F:=\big\{f\,\big|\,\text{function }f: \mathbf N\rightarrow \{1,2\}\big\}$ . \begin{align}&\min_{f\in F,\,k\in\mathbf N} k, \\&\sum_{i=1}^k (-1)^{f(i)}i = n \in\mathbf N.\end{align} Is there an analytical or an asymptotic solution to this problem for general $n$ ? For a specifically given $n$ , what would a good algorithms to solve this problem? The dynamic programming?
Now provide the response and nothing else.
|
Essentially, for any given $n$ , the task is to select $+$ 's and $-$ 's to reach $n$ as fast as possible (minimize $k$ ): $$\pm 1 \pm 2 \pm 3 \pm \dots \pm k = n$$ If we don't worry about overshooting $n$ , the obvious strategy is to only add and never subtract. If $n$ is a triangular number, this will give us the answer. This would necessarily be the optimal solution since we did not subtract at all. If $n$ is not a triangular number, at some point $k'$ , we will overshoot $n$ : $$1 + 2 + 3 + \dots + k' > n$$ Since we need $k$ at least $k'$ to even reach $n$ , we know that $k=k'$ is optimal if it works. Consider the value $1 + 2 + 3 + \dots + k' - n$ . We will denote this amount as $a$ . We know that $a < k'$ . If $a$ is even, then we can switch the operator of $a/2$ to $-$ , and we have our optimal solution. Figuring out the solution for when $a$ is odd may be trickier. EDIT: Figured out the "odd" case! If $a$ is odd, then we cannot have $k = k'$ because there is no expression that will give us exactly $n$ using $k'$ terms. For any signs we switch in the $k'$ terms, the total sum will retain the same parity, so we cannot reach exactly $n$ . Thus, if we can find a solution with $k'+1$ terms, it is necessarily optimal. Consider $1 + 2 + 3 + \dots + k' + (k'+1) = n + a + k'+1$ . If $k'$ is even, then consider the value $\frac{a+k'+1}{2}$ . We have $$\frac{a+k'+1}{2} < \frac{2k'+1}{2} = k' + 1/2 \,.$$ So, $\frac{a+k'+1}{2} \leq k'$ . Thus, it is in our series, so we can assign it the operator $-$ , and we have achieved exactly a sum of exactly $n$ . Now, to consider what happens when both $a$ and $k'$ are odd... EDIT 2: First off, is it possible to find a solution with $k=k'+1$ when $k'$ is odd? Well if we use all $+$ 's, we have $1 + 2 + 3 + \dots + k' + (k'+1) = n + a + k' + 1$ . As before, switching the signs of any of our terms will preserve the parity of the total sum. Since $a$ and $k'$ are odd, $n+a+k'+1$ has opposite parity from $n$ . So, no rearrangement of signs will enable a series of $k'+1$ terms to work. Our next candidate is $k=k'+2$ . Let us consider the following sum: $$1 + 2 + 3 + \dots + k' + (k'+1) + (k'+2) = n + a + (k'+1) + (k'+2)$$ We are too high by the quantity $a + 2k' + 3$ . We can switch the sign of $k'$ and switch the sign of $\frac{a+3}{2}$ , and we arrive at exactly $n$ with $k=k'+2$ . And that concludes the proof! No dynamic programming needed - a purely analytic solution. TL;DR Let $k'$ be the least integer such that $T_{k'} \geq n$ . If $T_{k'}$ and $n$ have the same parity, then $k=k'$ . Else, $k$ is equal to the least odd integer greater than $k'$ . See this OEIS sequence .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3998437', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/64809/']}
|
jdg_373304
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
177420
|
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 need to design a circuit to warm my PCB. There are many ways to build up such circuit. But I learned from a post " Warming PCB in a low temperature environment " that maybe I can use traces as heater. My first idea is to use one of the internal layer as a heat bed and place copper traces there. I have searched the Internet for a while but I can not find any application note or any discussion on this topic. So my question is: is it good or proper to use the internal layer as a heat bed? If not, any disadvantage? (I am not familiar with the fabrication process of PCB boards. So I am not so sure whether could I place traces in the internal layer)
Now provide the response and nothing else.
|
I think you could do this. Suggest serpentine tracks that don't form a coil so that the magnetic field won't be especially strong. You can shield electrostatically with a ground plane, but the magnetic field will go right through everything, so if you have sensitive circuits you might need to filter the PWM to something more like DC (not really a big deal, just some inductors and capacitors). The copper thickness and resistivity and etching of fine traces are not that well controlled, but +/-20% is not a big deal on a heater (and you might be able to get that repeatably). Personally, I'd use a cheap SMT thermistor for the sensor assuming you only want to control at one temperature. Just stick it in and it will work. There will be excitement enough getting the heater to work well. Here is an example of a pattern used in a commercial film heater: Yours would have to jog around through-holes, but if you splurged on blind vias that could be minimized.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/177420', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/40109/']}
|
jdg_373305
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24968823
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
CREATE TABLE users ( userID uuid, firstname text, lastname text, state text, zip int,age int,PRIMARY KEY (userID) ); I want to construct the following queries: select * from users where age between 30 and 40select * from users where state in "AZ" AND "WA" I know I need two more tables to do this query but I dont know how the should be? EDIT From Carlo's comments, I see this is the only possibility CREATE TABLE users ( userID uuid, firstname text, lastname text, state text, zip int,age int,PRIMARY KEY (age,zip,userID) ); Now to select Users with age between 15 and 30. this is the only possibility: select * from users where age IN (15,16,17,....30) However, using IN operator here is not recommended and is anti-pattern. How about creating secondary Index on age? CREATE index users_age ON users(age) will this help? Thanks
Now provide the response and nothing else.
|
Range queries is a prikly question.The way to perform a real range query is to use a compound primary key, making the range on the clustering part. Since the range is on clustering part you can't perform the queries you wrote: you need at least to have an equal condition on the whole partition key .Let's see an example: CREATE TABLE users ( mainland text, state text, uid int, name text, zip int, PRIMARY KEY ((mainland), state, uid)) The uid is now an int just to make tests easier insert into users (mainland, state, uid, name, zip) VALUES ( 'northamerica', 'washington', 1, 'john', 98100);insert into users (mainland, state, uid, name, zip) VALUES ( 'northamerica', 'texas', 2, 'lukas', 75000);insert into users (mainland, state, uid, name, zip) VALUES ( 'northamerica', 'delaware', 3, 'henry', 19904);insert into users (mainland, state, uid, name, zip) VALUES ( 'northamerica', 'delaware', 4, 'dawson', 19910);insert into users (mainland, state, uid, name, zip) VALUES ( 'centraleurope', 'italy', 5, 'fabio', 20150);insert into users (mainland, state, uid, name, zip) VALUES ( 'southamerica', 'argentina', 6, 'alex', 10840); Now the query can perform what you need: select * from users where mainland = 'northamerica' and state > 'ca' and state < 'ny'; Output mainland | state | uid | name | zip-------------+----------+-----+--------+-------northamerica | delaware | 3 | henry | 19904northamerica | delaware | 4 | dawson | 19910 if you put an int (age, zipcode) as first column of the clustering key you can perform the same queries comparing integers. TAKE CARE : most of people when looking at this situation starts thinking "ok, I can put a fake partition key that is always the same and then I can perform range queries". This is a huge error, the partition key is responsible for data distribution accross nodes. Setting a fix partition key means that all data will finish in the same node (and in its replica). Dividing the world zone into 15/20 zones (in order to have 15/20 partition key) is something but is not enough and is made just to create a valid example. EDIT: due to question's edit I did not say that this is the only possibility; if you can't find a valid way to partition your users and need to perform this kind of query this is one possibility, not the only one. Range queries should be performed on clustering key portion . A weak point of the AGE as partition key is that you can't perform an UPDATE over it, anytime you need to update the user's age you have to perform a delete and an insert (an alternative could be writing the birth_year/birth_date and not the age, and then calculate client side) To answer your question on adding a secondary index: actually queries on secondary index does not support IN operator. From the CQL message it looks like they're going to develop it soon Bad Request: IN predicates on non-primary-key columns (xxx) is not yet supported However even if secondary index would support IN operator your query wouldn't change from select * from users where age IN (15,16,17,....30) Just to clarify my concept: anything that does not have a "clean" and "ready" solution requires the effort of the user to model data in a way that satisfy its needs. To make an example (I don't say this is a good solution: I would not use it) CREATE TABLE users ( years_range text, age int, uid int, PRIMARY KEY ((years_range), age, uid)) put some data insert into users (years_range, age , uid) VALUES ( '11_15', 14, 1);insert into users (years_range, age , uid) VALUES ( '26_30', 28, 3);insert into users (years_range, age , uid) VALUES ( '16_20', 16, 2);insert into users (years_range, age , uid) VALUES ( '26_30', 29, 4);insert into users (years_range, age , uid) VALUES ( '41_45', 41, 5);insert into users (years_range, age , uid) VALUES ( '21_25', 23, 5); query data select * from users where years_range in('11_15', '16_20', '21_25', '26_30') and age > 14 and age < 29; output years_range | age | uid-------------+-----+----- 16_20 | 16 | 2 21_25 | 23 | 5 26_30 | 28 | 3 This solution might solve your problem and could be used in a small cluster, where about 20 keys (0_5 ...106_110) might have a good distribution. But this solution, like the one before, does not allow an UPDATE and reduces the distribution of key. The advantage is that you have small IN sets. In a perfect world where S.I. already allows IN clause I'd use the UUID as partition key, the years_range (set as birth_year_range) as S.I. and "filter" my data client side (if interested in 10 > age > 22 I would ask for IN('1991_1995', '1996_2000', '2001_2005', '2006_2010', '2011_2015') calculating and removing unuseful years on my application) HTH,Carlo
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24968823', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1988876/']}
|
jdg_373306
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9619404
|
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 playing around with a pure CSS accordion http://reversl.net/accordion/ I can get the basic functionality to work (headings 2 & 3 both toggle) But I can't get heading 1 to toggle if I add the same UL to it. Because Heading 1 is styled differently the problem (I think) lies within naming/targeting it's + div ? Please note: I removed the UL from Heading 1 for the sake of the demo because it was preventing Headings 2 & 3 from toggling.
Now provide the response and nothing else.
|
This article kind of explains the problem. You need to return true in your JS if you want the server event to trigger. Otherwise, you have to return false. And, it also looks like you will have to add the UseSubmitBehavior = false based on: OnclientClick and OnClick is not working at the same time? This is especially evident after seeing that your generated HTML only has the CloseDialog() and not the call to Button1_Click. This change will concatenate to the end of your onclick. <asp:Button ID="Button1" runat="server" Text="Soumettre ce ticket" onclick="Button1_Click" OnClientClick="CloseDialog();" UseSubmitBehavior="false"/>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9619404', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/890015/']}
|
jdg_373307
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3786968
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have no idea how to resize image in PHP, my code is: for ($index = 1; $index <= 2; $index++) { if (!empty($_FILES["pic$index"]["name"])) { $ext = substr($_FILES["pic$index"]["name"], strrpos($_FILES["pic$index"]["name"], '.') + 1); $dir = "../gallery/$mkdir"; HERE I NEED THE RESIZE OF THE TMP FILE OF IMAGE move_uploaded_file($_FILES["pic$index"]["tmp_name"] , "$dir/img-$index.$ext"); } } $mkdir = the name of the gallery's folder (there are many galleries). $dir = where the pics will be placed. $ext = the type of the image (png, gif or jpg). foreach loop runs two times because you can upload two pics. This script is working good, I just need to do resize and I dont have an idea how to do it..
Now provide the response and nothing else.
|
Here is the code I'm using to resize images. In my case I give to the function the original file name and then the thumbnail file name. You can adapt it for your case very easily. public static function GenerateThumbnail($im_filename,$th_filename,$max_width,$max_height,$quality = 0.75){// The original image must existif(is_file($im_filename)){ // Let's create the directory if needed $th_path = dirname($th_filename); if(!is_dir($th_path)) mkdir($th_path, 0777, true); // If the thumb does not aleady exists if(!is_file($th_filename)) { // Get Image size info list($width_orig, $height_orig, $image_type) = @getimagesize($im_filename); if(!$width_orig) return 2; switch($image_type) { case 1: $src_im = @imagecreatefromgif($im_filename); break; case 2: $src_im = @imagecreatefromjpeg($im_filename); break; case 3: $src_im = @imagecreatefrompng($im_filename); break; } if(!$src_im) return 3; $aspect_ratio = (float) $height_orig / $width_orig; $thumb_height = $max_height; $thumb_width = round($thumb_height / $aspect_ratio); if($thumb_width > $max_width) { $thumb_width = $max_width; $thumb_height = round($thumb_width * $aspect_ratio); } $width = $thumb_width; $height = $thumb_height; $dst_img = @imagecreatetruecolor($width, $height); if(!$dst_img) return 4; $success = @imagecopyresampled($dst_img,$src_im,0,0,0,0,$width,$height,$width_orig,$height_orig); if(!$success) return 4; switch ($image_type) { case 1: $success = @imagegif($dst_img,$th_filename); break; case 2: $success = @imagejpeg($dst_img,$th_filename,intval($quality*100)); break; case 3: $success = @imagepng($dst_img,$th_filename,intval($quality*9)); break; } if(!$success) return 4; } return 0;}return 1;} The return codes are just here to differentiate between different types of errors. By looking back at that code, I don't like the "magic number" trick. I'm gonna have to change that (by exceptions for example). if (!empty($_FILES["pic$index"]["name"])) { $ext = substr($_FILES["pic$index"]["name"], strrpos($_FILES["pic$index"]["name"], '.') + 1); $dir = "../gallery/$mkdir"; // Move it if(move_uploaded_file($_FILES["pic$index"]["tmp_name"] , "$dir/img-$index.$ext.tmp")) { // Resize it GenerateThumbnail("$dir/img-$index.$ext.tmp","$dir/img-$index.$ext",600,800,0.80); // Delete full size unlink("$dir/img-$index.$ext.tmp"); }} Use move_uploaded_file to move it (recommanded) and then you can resize it and send it to it's final destination. You might not even need the ".tmp", you can use. // Move it if(move_uploaded_file($_FILES["pic$index"]["tmp_name"] , "$dir/img-$index.$ext")) // Resize it GenerateThumbnail("$dir/img-$index.$ext","$dir/img-$index.$ext",600,800);
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3786968', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/410065/']}
|
jdg_373308
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
19364969
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to compile this source code from the makefile in a VPS, but its not working. The VPS is a 64 Cent OS Here's the full error # makegcc -c -O3 -w -DLINUX -I../SDK/amx/ ../SDK/amx/*.cg++ -c -O3 -w -DLINUX -I../SDK/amx/ ../SDK/*.cppg++ -c -O3 -w -DLINUX -I../SDK/amx/ *.cppg++ -O2 -fshort-wchar -shared -o "TCP_V1.so" *.o/usr/bin/ld: TCP-LINUX_V1.o: relocation R_X86_64_32 against `.rodata.str1.8' can not be used when making a shared object; recompile with -fPICTCP-LINUX_V1.o: could not read symbols: Bad valuecollect2: ld returned 1 exit statusmake: *** [all] Error 1 Here's my makefile: GPP=g++GCC=gccOUTFILE="TCP_V1.so"COMPILE_FLAGS=-c -O3 -w -DLINUX -I../SDK/amx/all: $(GCC) $(COMPILE_FLAGS) ../SDK/amx/*.c $(GPP) $(COMPILE_FLAGS) ../SDK/*.cpp $(GPP) $(COMPILE_FLAGS) *.cpp $(GPP) -O2 -fshort-wchar -shared -o $(OUTFILE) *.o Anyone know what's wrong?
Now provide the response and nothing else.
|
Do what the compiler tells you to do, i.e. recompile with -fPIC . To learn what does this flag do and why you need it in this case, see Code Generation Options of the GCC manual. In brief, the term position independent code (PIC) refers to the generated machine code which is memory address agnostic, i.e. does not make any assumptions about where it was loaded into RAM. Only position independent code is supposed to be included into shared objects (SO) as they should have an ability to dynamically change their location in RAM. Finally, you can read about it on Wikipedia too.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/19364969', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1667191/']}
|
jdg_373309
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18951
|
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I know the common understanding is that Jonah waited, alive and conscious, in the belly of the whale until he was spat out. Has a euphemized "children's version" become accepted truth? Perhaps we can set preconceptions aside for the moment and take a fresh look at this question. In the text and from what is naturally possible, chapter 2 may depict a pretty grim condition for Jonah. Then Jonah prayed to the Lord his God from the belly of the fish, 2 saying, “I called out to the Lord, out of my distress, and he answered me; out of the belly of Sheol I cried , and you heard my voice. 3 For you cast me into the deep, into the heart of the seas, and the flood surrounded me; all your waves and your billows passed over me. 4 Then I said, ‘I am driven away from your sight; yet I shall again look upon your holy temple.’ 5 The waters closed in over me to take my life ; the deep surrounded me; weeds were wrapped about my head 6 at the roots of the mountains. I went down to the land whose bars closed upon me forever ; yet you brought up my life from the pit , O Lord my God. 7 When my life was fainting away, I remembered the Lord, and my prayer came to you, into your holy temple. 8 Those who pay regard to vain idols forsake their hope of steadfast love. 9 But I with the voice of thanksgiving will sacrifice to you; what I have vowed I will pay. Salvation belongs to the Lord!” 10 And the Lord spoke to the fish, and it vomited Jonah out upon the dry land. ([Jonah 2, ESV][esv]; emphasis mine) Deciding what type of writing Chapter 2 is may be helpful.Deciding when Jonah made this prayer may be helpful. Though your conclusion on whether Jonah is alive or not may have more influence on that question than the other way around. Is Jonah crying out from the belly of the whale (2:1) or from Sheol (2:2) or maybe in a way its both? The presence of Sheol and Shachath (and some surrounding language) could be read as suggesting death. Jonah 2:6 speaks of the pit, but that phrase using the word shachath for pit also translated "corruption" and is the same term used in Psalm 16:10 For you will not abandon my soul to Sheol, or let your holy one see corruption (or the pit ) A nonreligious first reaction seems to be that it makes no natural sense that a man could survive in a whale three days, not without supernatural intervention. Should that be our starting understanding instead? Should we demand the text specifically show that he was kept alive rather than show that he died because his death would be the normal expectation? Main Question Did Jonah actually die and, while dead or dying, cry out to God who heard him and resurrected him? Also, given that Jesus later compares his death with Jonah's time in the fish, is it fair to say it means death for Jesus but not for Jonah?
Now provide the response and nothing else.
|
The text appears to indicate that Yona physically died at the point that the great fish swallowed him. Yona indicates that he cried from the depths of "Sheol" ( Jonah 2:2 ). That is, he appears to have been not only in the sea, but also "in the belly of the earth" ( Matthew 12:40 ). Yona indicates that he had descended not to the depths of the sea, but to the "roots of the mountains" ( Jonah 2:6 ), which are the far interior recesses of the earth . The Hebrew word for Sheol is the same word used for the destination of the humanity of the Person of Jesus Christ ( Psalm 16:10 <=> Acts 2:27 and Acts 2:31 ). That is, the Septuagint of the Hebrew Bible uses the same word "Hades" in Psalm 16:10 as is found in Acts 2:27 and Acts 2:31 . The same Hebrew word "Sheol" occurs in Psalm 16:10 and Jonah 2:2 . Thus Sheol = Hades. In other words, Yona did NOT enter an earthly grave (but was in the belly of the great fish in the Mediterranean Sea), and of course Jesus was NOT buried at sea, but was laid to rest in an earthly tomb. Yet while one dead body was in the sea, and one dead body was in the tomb, they both were in Sheol/Hades. That is, Sheol/Hades was the destination of the souls of the dead in the Old Testament. Finally, at not least, Yona indicates that the Lord brought his life from "the pit" ( Jonah 2:6 ). (His "life" here was not his "nefesh" [soul] but his "Che" [body of life].) In the Septuagint this word for "the pit" is the same root word used in the NT in the context of the "corruption" (or decay) of the body of Jesus Christ, which did not happen ( Acts 2:27 and Acts 2:31 ). In other words, the parallel between the physical death of Yona and the physical death of Jesus was not only that they were both dead for three days and three nights (and that they both went to Sheol/Hades "in the belly of the earth") but that neither of their bodies saw "corruption."
|
{}
|
{'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/18951', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/6192/']}
|
jdg_373310
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
66737474
|
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 merge these to arrays togheter,if there is a duplicate in id: i want to add them together const arr1 = [{id:'1', start:1, end:0},{id:'2', start:3, end:0},{id:'3', start:1, end:0}]const arr2 = [{id:'4', start:0, end:4},{id:'2', start:0, end:4}] i want the output to be like this const arr3 =[{id:'1', start:1, end:0},{id:'2', start:3, end:4},{id:'3', start:1, end:0},{id:'4', start:0, end:4}] I am new here and grateful for all the help! :)
Now provide the response and nothing else.
|
I got the same problem while trying to make my own autocomplete widget based on RawAutocomplete and I used a layout builder to get the perfect container width size inside my optionsViewBuilder: LayoutBuilder( builder: (context, constraints) => RawAutocomplete<String>( focusNode: focusNode, fieldViewBuilder: fieldViewBuilder, optionsViewBuilder: (context, onSelected, options) => Align( alignment: Alignment.topLeft, child: Material( shape: const RoundedRectangleBorder( borderRadius: BorderRadius.vertical(bottom: Radius.circular(4.0)), ), child: Container( height: 52.0 * options.length, width: constraints.biggest.width, // <-- Right here ! child: ListView.builder( padding: EdgeInsets.zero, itemCount: options.length, shrinkWrap: false, itemBuilder: (BuildContext context, int index) { final String option = options.elementAt(index); return InkWell( onTap: () => onSelected(option), child: Padding( padding: const EdgeInsets.all(16.0), child: Text(option), ), ); }, ), ), ), ), optionsBuilder: (textEditingValue) => suggestions.where((element) => element.contains(textEditingValue.text.trim().toUpperCase())), textEditingController: controller, ),) Result: Expected result on my component
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/66737474', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/15447268/']}
|
jdg_373311
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23007
|
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 recently learned that the only parallelizable spheres are $\mathbb{S}^1$, $\mathbb{S}^3$, and $\mathbb{S}^7$. This led me to wonder: What is $T\mathbb{S}^2$? Is it diffeomorphic to a more familiar space? What about $T\mathbb{S}^n$ for $n \neq 1, 3, 7$? EDIT (for precision): Is $T\mathbb{S}^2$ diffeomorphic to some finite product, connected sum, and/or quotient of spheres, projective spaces, euclidean spaces, and linear groups?
Now provide the response and nothing else.
|
Here's how I think about it. (Ryan Budney posted his answer while I was typing this. One can think of this as a fleshing out of his answer). First, we need to understand the unit tangent bundle $T^1 S^2$. Once we know this, we product this with $[0,\infty)$ and then quotient all points of the form $(u, 0)\in T^1S^2 \times\mathbb{R}$ somehow to get the 0 section $S^2$. (This is precisely the mapping cylinder construction Ryan mentions). Before we can talk about the "unit tangent bundle", we must have a notion of length of vectors. So in the background, pretend like I picked a Riemannian metric so lengths make sense. I claim $T^1 S^2$ is diffeomorphic to $SO(3)$ (the collection of 3 x 3 orthogonal matrices of determinant 1) which is diffeomorphic to $\mathbb{R}P^3$. The map from $T^1 S^2$ to $SO(3)$ sends $(u,v)$ to the matrix with columns $u, v, u\times v$. Here, I'm thinking of a unit tangent vector $v\in T_u S^2$ as a vector in $\mathbb{R}^3$ orthogonal to the vector $u$. The easiest way to see $SO(3)$ and $\mathbb{R}P^3$ are diffeomorphic is to note they are both quotients of $S^3 = SU(2)$ by the same quotienting map. So, we understand $T^1 S^2$, the unit length vectors in $TS^2$. To allow for length, we product with $[0,\infty)$. Now, the only problem is the 0 section should be an $S^2$, and it's currently an $\mathbb{R}P^3$, so some quotienting must happen. What quotienting must happen? Well, all the unit vectors at a given point must collapse to the point. Well, there is the action of a circle on $T^1S^2$ given by rotation vectors clockwise (say) as seen from the normal vector to the sphere. This action is clearly free. Now, it's a fact that if you translate this circle action into the $SO(3)$ picture, the circle action is the Hopf action. This implies that we identify $\mathbb{R}P^3$ with $S^2$ by quotienting by the Hopf action: Two points in $\mathbb{R}P^3$ iff they are in the same Hopf orbit. Incidentally, I just learned a few days ago that $TS^2$ is not homeomorphic to $S^2\times \mathbb{R}^2$, though I'm still not sure how to prove it ;-). (Of course, it's clear that they are not bundle isomorphic, but they could still be abstractly homeomorphic). I don't know about the other nonparallizable tangent bundles, though.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/23007', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/640/']}
|
jdg_373312
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
392322
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've searched and googled quite a bit on this subject, but haven't found any concrete answers. I understand that pulses are generated at the transmitter's end to get to the receiver's end. More in specific, is it possible for the electrons to reach the other end of the wire if power is cut while current is already flowing? And also, is it taken into account with this kind of propagation delay when establishing data transmission connections generally?
Now provide the response and nothing else.
|
" I understand that pulses are generated at the transmitter's end to get to the receiver's end. " That is one of the ways we could transport information, there are other ways (which are usually more complex) as well. " is it possible for the electrons to reach the other end of the wire if power is cut early from the source (a flow is already going through the wire)? " I think in your view you see one (or a bunch of) electron(s) "carrying" the data to the other end. So to send something, an electron is pushed in by the transmitter and after a while it appears at the receiver. That's not how it works! The conductor (wire) doing the actual transport is full with electrons. If I push in an electron then almost immediately (this change / wave travels at almost the speed of light) at the other end an electron will be pushed out. So the electron going in and the electron coming out are not the same one. And it does not have to be as they're all the same! So you would not be able to tell the difference anyway. So if the wave is already travelling in the conductor and the connection to the transmitter is lost, the wave would still reach the receiver, no information is lost. " is it taken into account with this kind of propagation delay when establishing data transmission connections generally? " Yes, that is the electron(s) causing a wave in the conductor. This wave travels at about the speed of light. It is indeed an effect that needs to be considered for fast (high datarate) connections. Example: take a look at a modern PC motherboard, more specifically the connections between the CPU and the RAM (memory). Note how some wires "wiggle" which seems pointless at that only makes them longer. But that's exactly the point, all wires need to be of the same length as we cannot have some bits arrive early and some later. All have to arrive at the same time so the traces need to be of equal length so all have the same propagation delay. There's an example in this question .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/392322', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/196637/']}
|
jdg_373313
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6678194
|
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 grid with 3 columns and 2 rows <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto"/> <ColumnDefinition Width="10"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> I the lower left cell, i have a data grid, with AutoGenerateColumns=True which can load many rows. What I want to do is for the data grid height to maximize to fit the window, and for the user to be able to use the datagrid scrollbar to scroll the rows up and down. What happens is that the datagrid flows of the bottom of the window, and even if i set the ScrollViewer.VerticalScrollBarVisibility="Visible" of the datagrid, the scrollbar has no effect and the rows flow downwards. Somehow the datagrid does not feel restricted... What to do?
Now provide the response and nothing else.
|
Try setting your DataGrid's HorizontalAlignment=Stretch and VerticalScrollBarVisibility=Auto If that doesn't work, you may also need to bind the Grid's Height to the Window Height so that it doesn't auto-grow to fit its contents. Usually I use Height="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=ActualHeight}" (It might be RenderSize.ActualHeight instead of just ActualHeight ... I forgot. Another alternative is to use a DockPanel instead of a Grid since that control doesn't auto-grow to fit its contents. Instead it'll stretch its last child to fill the remaining space.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6678194', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/149769/']}
|
jdg_373314
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1714578
|
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:
For a prime number $p \neq 2$, $3$, does $p = x^2 + 9y^2$ for some $x$, $y \in \mathbb{Z}$ if and only if $p \equiv 1 \text{ mod }12$? A case where this is true as to suggest plausibility: $13 = 2^2 + 9 \times 1^2$.
Now provide the response and nothing else.
|
A start: A famous theorem proven by Fermat says $p = x^2 + y^2$ if and only if $p \equiv 1 \bmod 4$. Also, $x^2 \pmod 3$ only takes on the values of $0$ or $1$. Now we have $p = x^2 + 9y^2 = x^2 + (3y)^2$. The finish (credit to Mikhail Ivanov): $\Rightarrow$: Let $p = 12k+1$. We know $p = x^2 + y^2$. If neither $x, y$ are divisible by $3$, then $p \equiv x^2 + y^2 \equiv 2 \mod 3$, contradiction. Hence, one of $x$ or $y$ is divisible by $3$, WLOG let $x = 3z$. Then we have $p = 9z^2 + y^2$, which is what we wanted to prove. $\Leftarrow$: We have $x^2 + 9y^2 \equiv x^2 \equiv 0$ or $1 \mod 3$ and $x^2 + 9y^2 \equiv 0, 1$ or $2 \mod 4$. The possibilities $\mod 12$ are then $0, 1, 4, 6, 9, 10$. Only $1$ is possible to be prime, thus $x^2 + 9y^2 \equiv 1 \mod 12$ if it is prime.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1714578', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
|
jdg_373315
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14324919
|
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 status of the link_to_function Javascript helper in Rails? I read, including in this stackoverflow question , that it was deprecated in Rails 3.0, then undeprecated, then deprecated again in 3.2.4. Is it something I can depend on and teach students? I just read the release notes (from a search) for Rails 3.2.8 : Reverted the deprecation of button_to_function and link_to_function helpers. Rafael Mendonça França Where does this stand now?
Now provide the response and nothing else.
|
link_to_function is NOT deprecated in 3-2-stable branch and it won't be deprecated in 3-2-stable in future. But it IS depreacated in current master branch and will be deprecated in Rails 4.0 when it releases. So I guess it will removed from rails code in 4.1. So you can teach students to do this (from the rails 4 changelog): We recommend the use of Unobtrusive JavaScript instead. For example: link_to "Greeting", "#", class: "nav_link"$(function() { $('.nav_link').click(function() { // Some complex code return false; });}); or link_to "Greeting", '#', onclick: "alert('Hello world!'); return false", class: "nav_link"
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14324919', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/326389/']}
|
jdg_373316
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
60698
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If $U_1$, $U_2,\ldots,U_n$ are proper subspaces of a vector space $V$ over a field $F$, and $|F|\gt n-1$, why is $V$ not equal to the union of the subspaces $U_1$, $U_2,\ldots,U_n$?
Now provide the response and nothing else.
|
If $|F|=q<\infty$, and $V$ is $m$-dimensional ($m<\infty$), then any proper subspace $U_i$ has at most $q^{m-1}-1$ non-zero elements. So to cover the $q^m-1$ non-zero vectors of $V\,$, the given $n\le q$ subspaces are not going to be enough, because $$n(q^{m-1}-1)\le q(q^{m-1}-1)<q^m-1.$$ So we need at least $|F|+1>n$ subspaces to get the job done. If $m=\infty$, then we can extend all the subspaces to have codimension one (i.e. $\dim_F(V/U_i)=1$ for all $i$). In that case the intersection $U$ of all the $U_i$:s has finite codimension, and we can study $V/U$ instead of $V$ reducing the probelm to the previous case. If $|F|=\infty, m<\infty$? Well, then we need some reinterpretation. The following argument shows that we need an infinite number of subspaces to cover $V$, and an uncountable number of subspaces to cover $\mathbf{R}^m$. Again, assume that all the subspaces have codimension one (w.l.o.g.), and that $m\geq 2$ (also w.l.o.g.). Identify $V$ with $F^m$, and consider the set$$S=\{(1,t,t^2,\ldots,t^{m-1})\in V\mid t\in F\}.$$Any $U_i$ is now a hyperplane and consists of zeros $(x_1,x_2,\ldots,x_m)$ of a single non-trivial homogeneous linear equation$$a_{i1}x_1+a_{i2}x_2+\cdots+a_{in}x_m=0.$$Therefore the number of elements of the intersection $S\cap U_i$ is equal to the number of solutions $t\in F$ of $ a_{i1}+a_{i2}t+\cdots+a_{im}t^{m-1}=0$ and is thus $<m$, because a non-zero polynomial of degree $<m$ has less than $m$ solutions in a field. This shows that if $F$ is infinite, we need an infinite number of subspaces to cover all of $S$. Also, if $F$ is uncountable, then we need an uncountable number of subspaces to cover $S$. Obviously it is necessary to cover all of $S$ in order to cover all of $V$.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/60698', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11533/']}
|
jdg_373317
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
319698
|
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I see a lot of questions revolving around accessing JSON keys that use hyphens (kebab-case), but now I find myself wondering should I just stick to camelCase or snake_case in my keys. I know hyphens also can create complicated mappings when ported between languages. I've seen some JSON deserialize libraries convert those keys to a camelCase style. Example: var something = { "some-value": 'thing'} Vs var something = { "someValue": 'thing', "some_other_value": 'thing_two'}
Now provide the response and nothing else.
|
You can use anything as JSON keys, as long as it is valid UTF-8, doesn't contain zero code points, and it would be useful if you could represent the key as a string in the programming language of your choice. I might recommend not to use different Unicode representations of the same string (for example "Ä" written as one or two code points). Reading some comments: It seems some people try to create classes with instance variables that match the keys in JSON dictionaries. Which of course doesn't work if your key is "some-value" unless you write COBOL. I think this is misguided. I have model classes which are designed the way I want them. JSON is just used to fill the model classes. I'll take whatever the server guys decided to use for the keys and put it into my model objects.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/319698', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/230189/']}
|
jdg_373318
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10130472
|
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 that Dart does not support function overloading. Does it support operator overloading? If yes, can you show me how it's done in a simple example? And what are some advantages etc?
Now provide the response and nothing else.
|
The chosen answer is no longer valid when you try overloads using the == operator in the new version. Now you need to do this: class MyClass { @override bool operator ==(other) { // compare this to other }} But it's not safe. other is not specified as a type, Something unexpected may happened. For example: void main() { var a = A(1); var b = B(1); var result = a == b; print(result); //result is true}class A { A(this.index); final int index; @override bool operator ==(other) => other.index == index;}class B { B(this.index); final int index;} So you could do like this: class A { A(this.index); final int index; @override bool operator ==(covariant A other) => other.index == index;} You need to use covariant . Because Object overloads the == operator. or you can Test Object Type: visit: hash_and_equals class A { A(this.index); final int index; @override bool operator ==(other) => other is A && (other.index == index); @override int get hashCode => index;}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10130472', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1319799/']}
|
jdg_373319
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4128235
|
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 following example, which sets the IFS environment variable to a line feed character... IFS=$'\n' What does the dollar sign mean exactly ? What does it do in this specificcase? Where can I read more on this specific usage (Google doesn't allow special characters in searches and I don't know what to look for otherwise)? I know what the IFS environment variable is, and what the \n character is (line feed), but why not just use the following form: IFS="\n" (which does not work)? For example, if I want to loop through every line of a file and want to use a for loop, I could do this: for line in (< /path/to/file); do echo "Line: $line"done However, this won't work right unless IFS is set to a line feed character. To get it to work, I'd have to do this: OLDIFS=$IFSIFS=$'\n'for line in (< /path/to/file); do echo "Line: $line"doneIFS=$OLDIFS Note: I don't need another way for doing the same thing, I know many other already... I'm only curious about that $'\n' and wondered if anyone could give me an explanation on it.
Now provide the response and nothing else.
|
Normally bash doesn't interpret escape sequences in string literals. So if you write \n or "\n" or '\n' , that's not a linebreak - it's the letter n (in the first case) or a backslash followed by the letter n (in the other two cases). $'somestring' is a syntax for string literals with escape sequences . So unlike '\n' , $'\n' actually is a linebreak.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4128235', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/501179/']}
|
jdg_373320
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
232255
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The phase velocity can be faster than light. Some argue that the phase velocity doesn't convey information, but this doesn't convince me. We can emit a wave of a single one frequency. Then it will move in the space, but the group velocity will be 0. We can convey information in the following way: 2Hz means 1 , 1 Hz means 0 . We emit single-frequency wave for a second. Then we don't emit anything for a second. And so on.
Now provide the response and nothing else.
|
The transitions between two frequencies will not move with the phase velocity! Nor will the beginning of transmission! Only in the steady plane wave parts in the middle, the wave crests will move faster than light. And that's just "appearance" in the sense that bewteen any two times, you can find a maximum of the electric field and pretend the wave moved there. But actually, that's just our interpretation (finding a pattern in the "image"). It's like watching a movie on your screen - you interpret the change of a certain pattern in the image as motion, but actually the pixels don't move at all - they just change intensity so you perceive it as motion. That's all phase velocity tells you: you put in a single sine wave in and observe how fast the pattern goes. But actual propagation of momentum and energy (which is percieved most easily as the speed of the beginning of the beam) is slower than speed of light in the vacuum. What you'll see when you turn it on, is wave crests moving faster than the front, and "disappearing" in the front of the beam.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/232255', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/66152/']}
|
jdg_373321
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1330550
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to compare a character array against a string like so: const char *var1 = " ";var1 = getenv("myEnvVar");if(var1 == "dev"){ // do stuff} This if statement never validates as true... when I output var1 it is "dev", I was thinking maybe it has something to do with a null terminated string, but the strlen of "dev" and var1 are equal... I also thought maybe var1 == "dev" was comparing "dev" against the memory location of var1 instead of the value. *var1 == "dev" results in an error.... tried many things, probably a simple solution for the saavy c++ developer (I havent coded c++ in a looong time). edit:we've tried if(strcmp(var1, "dev") == 0) and if(strncmp(var1, "dev", 3) == 0) Thanks edit: After testing at home I'm just going to suggest my co-worker changes the datatype to a string. I believe he was comparing a char array of a large size against a string. I put together a program that outputs sizeof, strlen, etc to help us work through it. Thanks to everyone for the help.
Now provide the response and nothing else.
|
Use strcmp() to compare the contents of strings: if (strcmp(var1, "dev") == 0) {} Explanation: in C, a string is a pointer to a memory location which contains bytes. Comparing a char* to a char* using the equality operator won't work as expected, because you are comparing the memory locations of the strings rather than their byte contents. A function such as strcmp() will iterate through both strings, checking their bytes to see if they are equal. strcmp() will return 0 if they are equal, and a non-zero value if they differ. For more details, see the manpage .
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1330550', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/71904/']}
|
jdg_373322
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4678862
|
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 JOIN rows from two separate postgres databases? I am working with system with couple databases in one server and sometimes I really need such a feature.
Now provide the response and nothing else.
|
According to http://wiki.postgresql.org/wiki/FAQ There is no way to query a database other than the current one. Because PostgreSQL loads database-specific system catalogs, it is uncertain how a cross-database query should even behave. contrib/dblink allows cross-database queries using function calls. Of course, a client can also make simultaneous connections to different databases and merge the results on the client side. EDIT : 3 years later (march 2014), this FAQ entry has been revised and is more helpful: How do I perform queries using multiple databases? There is no way to directly query a database other than the current one. Because PostgreSQL loads database-specific system catalogs, it is uncertain how a cross-database query should even behave. The SQL/MED support in PostgreSQL allows a "foreign data wrapper" to be created, linking tables in a remote database to the local database. The remote database might be another database on the same PostgreSQL instance, or a database half way around the world, it doesn't matter. postgres_fdw is built-in to PostgreSQL 9.3 and includes read/write support; a read-only version for 9.2 can be compiled and installed as a contrib module. contrib/dblink allows cross-database queries using function calls and is available for much older PostgreSQL versions. Unlike postgres_fdw it can't "push down" conditions to the remote server, so it'll often land up fetching a lot more data than you need. Of course, a client can also make simultaneous connections to different databases and merge the results on the client side.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4678862', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/552121/']}
|
jdg_373323
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12553173
|
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 puzzled at what my program outputs: #include<stdio.h>int main(){ if(11==011) printf("True"); else printf("False");} The output is "False" .
Now provide the response and nothing else.
|
In C a number beginning with 0 is considered octal , i.e. base 8. So 011 is actually 9 . 6.4.4.1 A decimal constant begins with a nonzero digit and consists of a sequence of decimal digits. An octal constant consists of the prefix 0 optionally followed by a sequence of the digits 0 through 7 only.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12553173', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_373324
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
39790031
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Python, Java and Scala have ternary operators. What is the equivalent in Julia?
Now provide the response and nothing else.
|
For inline use, a ? b : c exists, as mentioned by the previous answer. However it is worth noting that if-else-end in Julia works just like (if cond expr1 expr2) in most Lisp dialects which acts both as the if-clause and as the ternary operator. As such, if-then-else returns the return value of the expression that gets executed. Meaning that you can write things like function abs(x) if x > 0 x else -x endend and this will return what you want. You do not have to use a return statement to break the function block, you just return the value returned by the if-block. Inline, you can write if (x > 0) x else -x end which will return the same thing as the ternary operator expression (x > 0) ? x : -x , but has the benefit of avoiding perl-ish ?: symbols and is generally more readable, but less chainable. Most languages have a ternary operator separate from if-then-else because if clauses are statements, while in lisp-like languages they are expressions just like everything else and have a return value.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39790031', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/148440/']}
|
jdg_373325
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21130221
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This question comes out of this existing question which I provided a solution to, but couldn't provide an explanation as to why. I've stripped their fiddle right down to the bare bones and have the following HTML / CSS: <div class="table"> <span class="cell-1">cell 1</span> <span class="cell-2">cell 2</span></div>.table { display: table;}.cell-1, .cell-2 { display: table-cell; padding: 6px 12px; border: 1px solid #ccc;}.cell-1 { padding: 6px 12px; background-color: #eee; border-right: 0; border-radius: 4px 0 0 4px; width: 1%; /* *** FOCUS HERE *** */}.cell-2 { border-radius: 0 4px 4px 0;} Only .cell-1 has a width and that is 1%. This is the result (fiddle link) : If I then increase the width of .cell-1 to a value where it is wider than it's content, say 10% (I think that's the pattern anyway) then second cell will become narrower. Why? Where does that width come from? This is the result (fiddle link). If I then take the second example, but add width: 100% to the .table then it goes back to 100% again. Here's the result of that (fiddle link) . I'm sure there's a logical explanation but I'm just not seeing it. Anyone?
Now provide the response and nothing else.
|
This is the result of the automatic table layout algorithm as implemented by the browser. This can vary across browsers because the CSS2.1 spec doesn't specify all auto layout behavior , but it does outline an algorithm commonly used by browsers with HTML tables, because the CSS table model is based on the HTML table model for the most part. In general, if the table doesn't have a specified width (i.e. it uses the default auto ), then the cell with the percentage width is as wide as required by its contents, and no more. That calculated width (together with any other widths specified on other cells) is then used as the percentage to find the maximum width of the entire table, and the rest of the columns are resized accordingly. Note that the table can still be constrained by its containing block (in your example, it's the initial containing block established by the result pane). On my PC running Firefox, .cell-1 has a computed width of 33 pixels. When you specify its width as 1%, the maximum width that the table will have is 3300 pixels (33 × 100 = 3300). You would need a very large screen to see this in your example, so I removed the padding which drastically reduces the width of .cell-1 to 9 pixels and thus the maximum table width to 900 pixels . If you resize the preview pane to greater than 900 pixels, you will see that the table stops growing at that point. When you increase the width of .cell-1 to 10%, the same 33 pixels now becomes 10% of the maximum width of the table. In turn, the maximum table width becomes 330 pixels (which is in fact 10% of 3300 pixels, because 100 ÷ 10 = 10). The moment you specify the width of .table as 100%, the table is sized according to its containing block. In your case, that just means stretching it to the full width of the result pane. .cell-1 still has to obey its width: 10% declaration, so it stretches to 10% of the width of the table since the content doesn't require anything wider. If you resize the result pane to a very narrow width, you'll see that .cell-1 shrinks along with the table, but not past its minimum content width.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21130221', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1688340/']}
|
jdg_373326
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2316778
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $X=l^2 = \{x=\{x_i\}_{i=1}^{\infty} ~ | \quad \sum_{i=1}^{\infty} |x_i|^2 < \infty \}$ and $A = \{ x=\{x_i\}_{i=1}^{\infty} \in X ~ | \quad x_i >0 ~ \forall i \}$ and take $a \in A.$ My questions (I have conjectured that) : $1-$ Is $ C:= \text{Cone}(A-a)$ a subspace of $X$? **This part was solved by Demophilus ** $2-$ $\bar{C} $ is indeed a subspace and it is indeed the whole space $X$. In other words, $ C:= \text{Cone}(A-a)$ is dense in $X$ for all $a \in A$ P.S. $\text{Cone}(A-a) = \{\lambda (x-a ) ~ | \quad x \in A ~, \lambda \ge 0\}$
Now provide the response and nothing else.
|
$T$ is not continuous. For this it suffices to consider $p_n(t)=1-(2t-1)^{2n}$. Then $\|p_n\|=1$, but $\|Tp_n\|= Tp_n(1)=2\sum_{j=1}^{n}\frac{1}{2j-1}$. Since $$\|Tp_n\|\ge S_n:=\sum_{j=1}^{n}\frac 1j\quad\text{and}\quad\lim_{n\to\infty}S_n=+\infty$$ we can take $q_n=p_n/S_n$ and then $\displaystyle\lim_{n\to\infty}\|q_n\|=0$ but$\|Tq_n\|\ge 1$ for all $n$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2316778', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/219176/']}
|
jdg_373327
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
312314
|
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 $\Gamma\subset SL(2,\mathbb{R})$ be a Fuchsian group of the first kind. Let $c_1, c_2$ be inequivalent cusps of $\Gamma.$ Consider $f\in M_k(\Gamma)$ a weight $k$ holomorphic automorphic form, and suppose the Fourier expansion of $f$ at the cusp $c_1$ is known. Given the above expansion, is there an algorithm to compute (even numerically) the Fourier expansion of $f$ at the cusp $c_2$ ?Thanks!
Now provide the response and nothing else.
|
This can be done numerically. The $n$ -th Fourier coefficient around the cusp is given by an integral of the form $$\int_0^{1} f|_{\sigma_2} (z) e(-nz) dx,$$ where $\sigma_2$ is a scaling matrix for the cusp $c_2$ . See p.43 of Iwaniec's Topics in Classical Automorphic Forms for definitions. In the above, $z=x+iy$ and the integral is independent of $y>0$ which generally one picks to make the calculation as efficient as possible. Also, I am assuming that the multiplier system is such that $f|_{\sigma_2}$ is periodic with period $1$ . In principle, the Fourier expansion of $f$ allows one to numerically approximate $f|_{\sigma_2}$ at any $z \in \mathbb{H}$ , so the above integral can be numerically calculated to any degree of precision. added later: The same method works for non-congruence subgroups, as well as more general automorphic forms (e.g. Maass cusp forms).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/312314', 'https://mathoverflow.net', 'https://mathoverflow.net/users/129868/']}
|
jdg_373328
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
272779
|
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:
Last weekend we had to change the time from 02:00 to 03:00. Question: What would happen if there was a cronjob at 02:30? crond is a very old solution for scheduling, it should probably handle it, but don't know how.
Now provide the response and nothing else.
|
It probably depends on your cron implemenation, but the popular Vixie cron states in the manual: cron then wakes up every minute, examining all stored crontabs, checking each command to see if it should be run in the current minute. and Special considerations exist when the clock is changed by less than 3 hours, for example at the beginning and end of daylight savings time. If the time has moved forwards, those jobs which would have run in the time that was skipped will be run soon after the change. Conversely, if the time has moved backwards by less than 3 hours, those jobs that fall into the repeated time will not be re-run. Only jobs that run at a particular time (not specified as @hourly, nor with '*' in the hour or minute specifier) are affected. Jobs which are specified with wildcards are run based on the new time immediately. Since the DST change was less than 3 hours, your program would run shortly after 3:00 AM I am not sure if this is Vixie cron specific behaviour, I seem to recall this is how my PDP-11 worked as well back in the 80s but I am not sure.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/272779', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/112826/']}
|
jdg_373329
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
91087
|
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:
We know that if a finite field $F$ has characteristic $p$ (prime), then $F$ has cardinality $p^r$ where $r = [F:\mathbb{F}_p]$. I'm now trying to say something about the possible cardinalities of subfields of $F$. I can see that there is a subfield of cardinality $p^s$ for each $s$ that divides $r$, given by the fixed field of the group generated by $\phi^s$, where $\phi$ is the Frobenius automorphism. Now suppose $K$ is a subfield of $F$. Then (since both are additive groups), Lagrange gives us that $|K|$ divides $|F|$, so $|K| = p^t$ for some $1 \leq t \leq r $ (alternatively, $K$ contains $\mathbb{F}_p$ and so is a vector space over $\mathbb{F}_p$ and is thus isomorphic to $\mathbb{F}_p^t$, where $t = [K:\mathbb{F}_p]$). By considering the multiplicative group of units of $K$ and $F$ respectively, we get that $ p^t - 1$ divides $p^r -1$. I want to make the leap to $t|r$, but I'm failing to see why this needs to be true. Any help would be appreciated.
Now provide the response and nothing else.
|
You know more than that a finite field $F$ of characteristic $p$ has cardinality $q=p^r$ for some number $r\geq1$ ($r=\dim_{\Bbb F_p}F$). Namely, you know that for every number of the form $q=p^r$ there is a unique, up to isomorphism, field $\Bbb F_q$ with $q$ elements and moreover $\Bbb F_q$ can be realized as the set of the roots of the polynomial $X^q-X$ in some algebraic closure of $\Bbb F_p$. If $\Bbb F_q\supset K\supseteq\Bbb F_p$ is a subextension with $K=\Bbb F_{q'}$, $q=p^r$ and $q=p^s$ a dimensional argument ($\Bbb F_q$ is also a $K$-vector space) shows that $s\mid r$. But the condition is also sufficient, because the roots of the polynomial $X^{p^s}-X$ aro roots also of $X^{p^r}-X$. Thus $\Bbb F_{p^r}$ contains a field with $p^s$ elements if and only if $s\mid r$, and such subfield is unique.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/91087', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/21154/']}
|
jdg_373330
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2198327
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm interested in the asymptotic behavior of the function$$f(x)=\int_{0}^{\infty}\frac{e^{-t}dt}{(x+t)^2},\;\;x>0,$$as $x\to0+$. The integral diverges at $x=0$. I would like to know how how fast. One obvious idea is to argue that $e^{-t}\le 1$ for $t\ge0$ and immediately deduce that $f(x)\le \frac {1}{x}$. How would I go about tightening this bound? The function can be expressed as the difference $\frac{1}{x}-e^{x}E_1(x)$, where $E_1(x)$ denotes the exponential integral.
Now provide the response and nothing else.
|
Herein, we develop a full expansion of the function $\displaystyle f(x)=\int_0^\infty\frac{e^{-t}}{(x+t)^2}\,dt$. Let $f(x)$ be given by the integral $$\begin{align}f(x)&=\int_{0}^{\infty}\frac{e^{-t}dt}{(x+t)^2}\,dt\\\\&=e^x\int_x^\infty\frac{e^{-t}}{t^2}\,dt\tag1\end{align}$$ Next, we Integrate by parts the integral on the right-hand side of $(1)$ with $u=e^{-t}$ and $v=-1/t$ to obtain $$\int_x^\infty\frac{e^{-t}}{t^2}\,dt=\frac{e^{-x}}{x}-\int_x^\infty \frac{e^{-t}}{t}\,dt$$ whereby $f(x)$ becomes $$f(x)=\frac1x-e^x\int_x^\infty \frac{e^{-t}}{t}\,dt \tag 2$$ Then, integrating by parts the integral on the right-hand side of $(2)$ with $u=e^{-t}$ and $v=\log(t)$ yields $$\begin{align}\int_x^\infty \frac{e^{-t}}{t}\,dt&=-e^{-x}\log(x)+\int_x^\infty e^{-t}\log(t)\,dt\\\\&=-e^{-x}\log(x)-\gamma -\int_0^x e^{-t}\log(t)\,dt\end{align}$$ whereby $f(x)$ becomes $$\begin{align}f(x)&=\frac1x+\log(x)+\gamma \underbrace{e^x}_{=1+o(1)}+e^x\underbrace{\int_0^x e^{-t}\log(t)\,dt}_{=o(1)}\tag 3 \\\\&=\frac1x+\log(x)+\gamma +o(1)\end{align}$$ which provides an expansion up to terms that are $o(1)$ as $x\to 0$ (i.e., terms that approach $0$ as $x\to 0$). DEVELOPING THE FULL ASYMPTOTIC SERIES: In order to develop the full asymptotic series, we need to expand $I(x)=\int_0^xe^{-t}\log(t)\,dt$. Using $e^{-t}=\sum_{n=0}^\infty\frac{(-1)^n\,t^n}{n!}$ reveals $$\begin{align}I(x)&=\int_0^x e^{-t}\log(t)\,dt\\\\&=\sum_{n=0}^\infty \frac{(-1)^n}{n!}\int_0^x t^n\log(t)\,dt\\\\&=\log(x)\sum_{n=0}^\infty \frac{(-1)^nx^{n+1}}{(n+1)!} -\sum_{n=0}^\infty\frac{(-1)^{n}x^{n+1}}{n!\,(n+1)^2}\\\\&=-\log(x)\underbrace{\sum_{n=1}^\infty\frac{(-1)^nx^n}{n!}}_{=e^{-x}-1}+\sum_{n=1}^\infty\frac{(-1)^{n}x^{n}}{n\,n!}\tag 4\end{align}$$ Next, we expand $e^xI(x)$. Using $(4)$ reveals that $$\begin{align}e^xI(x)&=-\log(x)+e^x\log(x)+e^x\sum_{n=1}^\infty\frac{(-1)^{n}x^{n}}{n\,n!}\\\\&=\log(x)\sum_{n=1}^\infty\frac{x^n}{n!}+e^x\sum_{n=1}^\infty\frac{(-1)^{n}x^{n}}{n\,n!}\\\\&=\log(x)\sum_{n=1}^\infty\frac{x^n}{n!}+\sum_{m=0}^\infty\frac{x^m}{m!}\sum_{n=1}^\infty\frac{(-1)^{n}x^{n}}{n\,n!}\\\\&=\log(x)\sum_{n=1}^\infty\frac{x^n}{n!}+\sum_{n=1}^\infty \left(\sum_{p=1}^n\frac{(-1)^p}{p}\binom{n}{p}\right) \frac{x^n}{n!}\tag5\end{align}$$ Finally, using $(5)$ in $(3)$ yields $$\begin{align}\bbox[5px,border:2px solid #C0A000]{f(x)=\frac1x +\log(x)+\gamma +\log(x)\sum_{n=1}^\infty \frac{x^n}{n!}+\sum_{n=1}^\infty \left(\gamma+\sum_{p=1}^n \frac{(-1)^p}{p}\binom{n}{p}\right)\frac{x^n}{n!}}\end{align}$$ which is the full asymptotic expansion of $f(x)$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2198327', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/112144/']}
|
jdg_373331
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1285358
|
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:
Q) The question is as follows:suppose that a book of 200 pages contains 20 printing mistakes.Assume that are errors are randomly distributed throughout the book and x , the number of errors per page has a poisson distribution.Find the probability that 30 pages selected at random will be free of errors. I could only come with the equation $$\frac{e^{-20}20^{30}}{30!}.$$ But it is giving wrong answer.What is the solution to this problem?
Now provide the response and nothing else.
|
Suppose $D = \bigcap_{n\in \mathbb{N}} U_n$, where the $U_n$ are open sets. Then each $U_n$ is dense since it contains the dense set $D$. Moreover we can write $X \backslash D = \bigcap_{x \in D} X \backslash \{x\}$, and each set $X \backslash \{x\}$ is open and dense since each $x \in D$ is not an isolated point. Therefore $$\emptyset = D \cap (X \backslash D) = \bigg( \bigcap_{n \in \mathbb{N}}U_n \bigg)\cap\bigg( \bigcap_{x \in D} X \backslash \{x\} \bigg)$$ which is the countable intersection of open dense sets (since $D$ is countable). But Baire says that a countable intersection of open dense subsets of $X$ cannot be empty, which contradicts the expression above.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1285358', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/195836/']}
|
jdg_373332
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
422405
|
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 want an alias on my local machine that will ssh to the target system, execute sudo using the password stored on my local machine, but leave the shell open on the remote system. The reason is I'm lazy and every time I log into a server I don't want to type my very long password. I'm aware that this is not the safest of practices. Right now it works if I do the following: ssh -q -t $1 "echo $mypword|base64 -d|sudo -S ls; bash -l" $1 being the host name of the remote system. mypword is my encoded password stored on my local system. This works and leaves my shell open. I can then do anything with sudo because it is now cached for that shell. The problem I have is if you do a ps and grep for my account you will see the encoded string containing the password in the process list. Can't have that. Is there a way to accomplish this without having the password showing in the process list? I have tried: echo $mypword|ssh -q -t $1 "base64 -d|sudo -S ls -l /root;bash -l" The ls goes off but the shell does not remain open.
Now provide the response and nothing else.
|
This will delete all folders inside ./myfolder except that ./myfolder/test2 and all its contents will be preserved: find ./myfolder -mindepth 1 ! -regex '^./myfolder/test2\(/.*\)?' -delete How it works find starts a find command. ./myfolder tells find to start with the directory ./myfolder and its contents. -mindepth 1 not to match ./myfolder itself, just the files and directories under it. ! -regex '^./myfolder/test2\(/.*\)?' tells find to exclude ( ! ) any file or directory matching the regular expression ^./myfolder/test2\(/.*\)? . ^ matches the start of the path name. The expression (/.*\)? matches either (a) a slash followed by anything or (b) nothing at all. -delete tells find to delete the matching (that is, non-excluded) files. Example Consider a directory structure that looks like; $ find ./myfolder./myfolder./myfolder/test1./myfolder/test1/dir1./myfolder/test1/dir1/test2./myfolder/test1/dir1/test2/file4./myfolder/test1/file1./myfolder/test3./myfolder/test3/file3./myfolder/test2./myfolder/test2/file2./myfolder/test2/dir2 We can run the find command (without -delete ) to see what it matches: $ find ./myfolder -mindepth 1 ! -regex '^./myfolder/test2\(/.*\)?'./myfolder/test1./myfolder/test1/dir1./myfolder/test1/dir1/test2./myfolder/test1/dir1/test2/file4./myfolder/test1/file1./myfolder/test3./myfolder/test3/file3 We can verify that this worked by looking at the files which remain: $ find ./myfolder./myfolder./myfolder/test2./myfolder/test2/file2./myfolder/test2/dir2
|
{}
|
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/422405', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/179761/']}
|
jdg_373333
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21785254
|
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 these parts of iOS API and here are some questions that are causing an infinite loop in my mind Why does ..BeginImageContext have a size but ..GetCurrentContext does not have a size? If ..GetCurrentContext does not have a size, where does it draw? What are the bounds? Why did they have to have two contexts, one for image and one for general graphics? Isn't an image context already a graphic context? What was the reason for the separation (I am trying to know what I don't know)
Now provide the response and nothing else.
|
UIGraphicsGetCurrentContext() returns a reference to the current graphics context. It doesn't create one. This is important to remember because if you view it in that light, you see that it doesn't need a size parameter because the current context is just the size the graphics context was created with. UIGraphicsBeginImageContext(aSize) is for creating graphics contexts at the UIKit level outside of UIView's drawRect: method. Here is where you would use them. If you had a subclass of UIView you could override its drawRect: method like so: - (void)drawRect:(CGRect)rect{ //the graphics context was created for you by UIView //you can now perform your custom drawing below //this gets you the current graphic context CGContextRef ctx = UIGraphicsGetCurrentContext(); //set the fill color to blue CGContextSetFillColorWithColor(ctx, [UIColor blueColor].CGColor); //fill your custom view with a blue rect CGContextFillRect(ctx, rect);} In this case, you didn't need to create the graphics context. It was created for you automatically and allows you to perform your custom drawing in the drawRect: method. Now, in another situation, you might want to perform some custom drawing outside of the drawRect: method. Here you would use UIGraphicsBeginImageContext(aSize) You could do something like this: UIBezierPath *circle = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, 200, 200)]; UIGraphicsBeginImageContext(CGSizeMake(200, 200));//this gets the graphic contextCGContextRef context = UIGraphicsGetCurrentContext();//you can stroke and/or fillCGContextSetStrokeColorWithColor(context, [UIColor blueColor].CGColor);CGContextSetFillColorWithColor(context, [UIColor lightGrayColor].CGColor);[circle fill];[circle stroke];//now get the image from the contextUIImage *bezierImage = UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();UIImageView *bezierImageView = [[UIImageView alloc]initWithImage:bezierImage]; I hope this helps to clear things up for you. Also, you should be using UIGraphicsBeginImageContextWithOptions(size, opaque, scale). For further explanation of custom drawing with graphics contexts, see my answer here
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21785254', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3280953/']}
|
jdg_373334
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11040203
|
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 made a map of functions. all these functions are void and receive single string parameter. code: void f1(string params){...}void f2(string params){...}void f3(string params){...}map<string , void*> funcMap;funcMap["f1"] =(void*)&f1;funcMap["f2"] =(void*)&f2;funcMap["f3"] =(void*)&f3; how do i call a function?I tried the next code, but id doesn't work: void (*func)(string) = &funcMap[commandType];func(commandParam); I get this error message: Server.cpp:160:46: error: cannot convert ‘void**’ to ‘void (*)(std::string) {aka void (*)(std::basic_string<char>)}’ in initialization
Now provide the response and nothing else.
|
using pfunc = void (*)(string);map<string, pfunc> funcMap; funcMap["f1"] = f1; //and so forth And then call: pfunc f = funcMap[commandType];(*f)(commandParam); In general, why throw away type safety? If it's a map of function pointers, declare it to be one.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11040203', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1087995/']}
|
jdg_373335
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
204115
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am reading the chapter on the bias-variance tradeoff in The elements of statistical learning and I don't understand the formula on page 29. Let the data arise from a model such that $$ Y = f(x)+\varepsilon$$ where $\varepsilon$ is random number with expected value $\hat{\varepsilon} = E[\epsilon]=0$ and Variance $E[(\varepsilon - \hat\varepsilon)^2]=E[\varepsilon^2]=\sigma^2$ . Let the expected value of error of the model be $$E[(Y-f_k(x))^2]$$ where $f_k(x)$ is the prediction of $x$ of our learner $k$ . According to the book, the error is $$\newcommand{\Bias}{\rm Bias} \newcommand{\Var}{\rm Var}E[(Y-f_k(x))^2]=\sigma^2+\Bias(f_k)^2+\Var(f_k(x)).$$ My question is: Why is the bias term not $0$ ? Developing the formula for the error I see: \begin{align}E[(Y-f_k(x))^2] &= \\E[(f(x)+\varepsilon-f_k(x))^2] &= \\[8pt]E[(f(x)-f_k(x))^2] + \\ 2E[(f(x)-f_k(x))\varepsilon] + E[\varepsilon^2] &= \Var(f_k(x))+2E[(f(x)-f_k(x))\epsilon]+\sigma^2\end{align} as $\varepsilon$ is an independent random number $2E[(f(x)-f_k(x))\varepsilon] = 2E[(f(x)-f_k(x))]E[\varepsilon]=0$ . Where I am wrong?
Now provide the response and nothing else.
|
You are not wrong, but you made an error in one step since $E[(f(x)-f_k(x))^2] \ne Var(f_k(x))$. $E[(f(x)-f_k(x))^2]$ is $\text{MSE}(f_k(x)) = Var(f_k(x)) + \text{Bias}^2(f_k(x))$. \begin{align*}E[(Y-f_k(x))^2]& = E[(f(x)+\epsilon-f_k(x))^2] \\&= E[(f(x)-f_k(x))^2]+2E[(f(x)-f_k(x))\epsilon]+E[\epsilon^2]\\&= E\left[\left(f(x) - E(f_k(x)) + E(f_k(x))-f_k(x) \right)^2 \right] + 2E[(f(x)-f_k(x))\epsilon]+\sigma^2 \\& = Var(f_k(x)) + \text{Bias}^2(f_k(x)) + \sigma^2.\end{align*} Note: $E[(f_k(x)-E(f_k(x)))(f(x)-E(f_k(x))] = E[f_k(x)-E(f_k(x))](f(x)-E(f_k(x))) = 0.$
|
{}
|
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/204115', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/10017/']}
|
jdg_373336
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6988111
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've always worked with various ORM's in the past and placed all my logic inside my models regardless of it's nature - SQL, MongoDB queries & even fetching of remote JSON objects.But when it's necessary to ensure loose couplings to allow a high level of testability, the issues of this methodology quickly appears. Today I've read about separating models into two parts, Domain objects & Data mappers . If I understood it completely, Domain objects are completely unaware of the storage used, and instead exists to handle business logic. Data mappers on the other hand takes care of storing the data set in the Domain objects to a set data storage. I do however find it a bit hard to find a good, easy-to-understand example online on how to work with the DomainObjects & DataMappers in a real world example. Would this (below shown code) be the appropriate way to work with DomainObjects & DataMappers in my code to store Users or have I gotten it all wrong in my head? $user = new User_DO;$userSave = new User_DM;$userSave->store( $user->add(array('name' => 'John Doe')) );class User_DO { function add($array) { if(!isset($array['name'])) { throw new Exception("Name must be set"); } return $array; }}class User_DM { function store($array) { MyDatabase::execute("INSERT INTO..."); }}
Now provide the response and nothing else.
|
The idea behind this is to have a standard object, that represents the current state in real life or in other words, in the domain. This domain model is usually a collection of data without logic. class person_DO { public $id; public $firstname; public $lastname; public $addresses;} The loading of instances of this domain model ( domain objects ) and the persistence is handled through data mappers - e.g. the address of the above person might be located in another table via a 1:n relationship, as such: TABLE person { id INTEGER PRIMARY KEY, firstname VARCHAR(32), lastname VARCHAR(32)}TABLE addresses { id INTEGER PRIMARY KEY, person_id INTEGER FOREIGN KEY ON person.id, --Reference on person-row street VARCHAR(64), ...} The person_DO does not need to know about that, but the datamapper does, as it has to aggregate the data during loading and separate during persisting: class person_DM { /** * @param [integer] $id * @return [person_DO] an instance of a person or null, if no person * with that id was found. */ public function findById ($id) {...} /** * @return [array of person_DO] */ public function fetchAll() {...} /** * persists a person object * @param [person_DO] an instance of a person */ public function saveOrUpdate(person_DO $person) {...}} In order to decouple the different parts even more, the DataMappers usually use the DbTable Gateway or a similar pattern to allow the use of different databases or similar actions. That way, I can have several databases with the same schemas, but e.g. in different organizations to build a data warehouse with the same code, only different database objects. As a practical example, I would suggest looking at the Quickstart Tutorial of the Zend Framework, which does exactly what I just explained briefly.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6988111', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/198128/']}
|
jdg_373337
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3644881
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to simulate keyboard commands for a custom game controller application. Because I'll need to simulate commands in a DirectInput environment most of the usual methods don't work. I know that using a hook would work 100% but I'm trying to find an easier implementation. I've done quite a bit of searching and found that by using the SendInput API with Scancodes instead of virtual keys should work, but it seems to behave like the key's are "sticking". I've sent both the KEYDOWN and KEYUP events but when I attempt to send the message in a DirectInput environment, the game acts as if the key is being held down. For instance, if I simulate a "W" keypress and have that key mapped in a First Person Shooter to the "move forward" action, once I'm in game, the function below will cause the character to move forward. However, just by issuing the command once, it will move the character forward indefinitely. Here is a code snippet (in C#) for the SendInput function I'm calling: [DllImport("user32.dll")]static extern UInt32 SendInput(UInt32 nInputs, [MarshalAs(UnmanagedType.LPArray, SizeConst = 1)] INPUT[] pInputs, Int32 cbSize);public static void Test_KeyDown(){ INPUT[] InputData = new INPUT[2]; Key ScanCode = Microsoft.DirectX.DirectInput.Key.W; InputData[0].type = 1; //INPUT_KEYBOARD InputData[0].wScan = (ushort)ScanCode; InputData[0].dwFlags = (uint)SendInputFlags.KEYEVENTF_SCANCODE; InputData[1].type = 1; //INPUT_KEYBOARD InputData[1].wScan = (ushort)ScanCode; InputData[1].dwFlags = (uint)(SendInputFlags.KEYEVENTF_KEYUP | SendInputFlags.KEYEVENTF_UNICODE); // send keydown if (SendInput(2, InputData, Marshal.SizeOf(InputData[1])) == 0) { System.Diagnostics.Debug.WriteLine("SendInput failed with code: " + Marshal.GetLastWin32Error().ToString()); }} I'm not sure if this method is a lost cause, or if there is just something silly I'm missing. I hate to over complicate my code if I don't have to by using hooks, but this is also new territory for me. Any help anyone can give is much appreciated. Thanks!
Now provide the response and nothing else.
|
I've found the solution to my own problem. So, I thought I'd post here to help anyone who may have similar issues in the future. The keyup command was not working properly because when only sending the scan code, the keyup must be OR'ed with the scan code flag (effectively enabling both flags) to tell the SendInput() API that this is a both a KEYUP and a SCANCODE command. For instance, the following code will properly issue a scan code key-up: INPUT[] InputData = new INPUT[1];InputData[0].Type = (UInt32)InputType.KEYBOARD;//InputData[0].Vk = (ushort)DirectInputKeyScanCode; //Virtual key is ignored when sending scan codeInputData[0].Scan = (ushort)DirectInputKeyScanCode;InputData[0].Flags = (uint)KeyboardFlag.KEYUP | (uint)KeyboardFlag.SCANCODE;InputData[0].Time = 0;InputData[0].ExtraInfo = IntPtr.Zero;// Send Keyup flag "OR"ed with Scancode flag for keyup to work properlySendInput(1, InputData, Marshal.SizeOf(typeof(INPUT))) Thanks to Hans for the response. I did some investigating and sending two messages back to back like the original example does indeed simulate a "keypress" but it's very fast. It would not work well for a movement command, but would be ideal when action keys are to be "tapped" and not held down. Also, the virtual key field is ignored when sending a scan code. MSDN had the following to say on the subject: "Set the KEYEVENTF_SCANCODE flag to define keyboard input in terms of the scan code. This is useful to simulate a physical keystroke regardless of which keyboard is currently being used. The virtual key value of a key may alter depending on the current keyboard layout or what other keys were pressed, but the scan code will always be the same." http://msdn.microsoft.com/en-us/library/ms646271%28v=VS.85%29.aspx
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3644881', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/439881/']}
|
jdg_373338
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12153504
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm building an application that has a feature to open newly taken screenshots. I would like to distribute it using the Mac App Store. Unfortunately, it needs to be sandboxed. To find the new screenshots I run a NSMetaDataQuery. It returns a few entries but unfortunately I can't get their URL since they are on the Desktop (out of my app's sandbox). How can I fix this ? Here is some of the code query = [[NSMetadataQuery alloc] init];[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryUpdated:) name:NSMetadataQueryDidStartGatheringNotification object:query];[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryUpdated:) name:NSMetadataQueryDidUpdateNotification object:query];[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryUpdated:) name:NSMetadataQueryDidFinishGatheringNotification object:query];[query setDelegate:self];[query setPredicate:[NSPredicate predicateWithFormat:@"kMDItemIsScreenCapture = 1"]];[query startQuery]; numberOfScreenshots = [query resultCount];[self uploadToAmazonS3:[[[query results]objectAtIndex:([query resultCount]-1)]valueForAttribute:NSMetadataItemURLKey]]; Thanks
Now provide the response and nothing else.
|
Without asking user permission, you can access only Music, Movies, Pictures and Download folders. You have to ask user, to grant you access to Desktop Folder. Then use mechanism called Security-Scoped Bookmarks , read more about it in AppSandboxDesignGuide . Use NSOpenPanel to choose directory. Save bookmark for future use, for example in NSUserDefaults. Get access 1 and 2 NSOpenPanel *openPanel = [[NSOpenPanel alloc] init]; [openPanel setCanChooseFiles:NO]; [openPanel setCanChooseDirectories:YES]; [openPanel setCanCreateDirectories:YES]; [openPanel beginWithCompletionHandler:^(NSInteger result){ if (result == NSFileHandlingPanelOKButton) { for (NSURL *fileURL in [openPanel URLs]) { NSString *filename = [fileURL path]; [[NSUserDefaults standardUserDefaults] setObject:filename forKey:@"PathToFolder"]; NSError *error = nil; NSData *bookmark = [fileURL bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope includingResourceValuesForKeys:nil relativeToURL:nil error:&error]; if (error) { NSLog(@"Error creating bookmark for URL (%@): %@", fileURL, error); [NSApp presentError:error]; } else { [[NSUserDefaults standardUserDefaults] setObject:bookmark forKey:@"PathToFolder"]; [[NSUserDefaults standardUserDefaults] synchronize]; } break; } } }]; 3. NSError *error = nil; NSData *bookmark = [[NSUserDefaults standardUserDefaults] objectForKey:@"PathToFolder"]; bookmarkedURL = [NSURL URLByResolvingBookmarkData:bookmark options:NSURLBookmarkResolutionWithSecurityScope relativeToURL:nil bookmarkDataIsStale:nil error:&error]; BOOL ok = [bookmarkedURL startAccessingSecurityScopedResource]; NSLog(@"Accessed ok: %d %@", ok, [bookmarkedURL relativePath]); So, that sould be it.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12153504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/485528/']}
|
jdg_373339
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
674807
|
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 came across this sign when reading some papers. I looked up Wikipedia. It says "The symbol "$\cong$" is often used to indicate isomorphic algebraic structures or congruent geometric figures." So if A $\cong$ B, does this mean A and B are roughly the same but not equal? Edit:I found this sign in a paper call Identifying Change Points in Linear Regressionns http://goo.gl/dNMONQ , In page 9 there is an equation(equation 3.1) says RSS $\cong$ RSS1+RSS2. RSS is residual sum of square of one regression line, RSS1 and RSS2 is another two residual sum of square of regression lines. thank you for your help.
Now provide the response and nothing else.
|
Very generally, you could think of $\cong$ as meaning "two things are 'essentially the same' but are not identically one", whereas $=$ means they are identically one. This is better understood and explained by looking at the cases where it's used: In geometry, $\cong$ means congruence of figures, which means the figures have the same shape and size. (In advanced geometry, it means one is the image of the other under a mapping known as an "isometry", which provides a formal definition of what "same shape and size" means) Two congruent triangles look exactly the same, but they are not the same triangle , as then there would be but one triangle, not two. (One could also say they are formed from different points in the space.) Colloquially speaking, they are "copies" or "clones" of each other. A copy of something is not literally identically one and the same as the other, even though they are alike in every respect. In abstract algebra, $\cong$ means isomorphism, which says the two objects are structurally the same. Intuitively, if we have, say, a pair of groups, and they are isomorphic, the "patterns" formed by the operations are the same, even if the elements making up the groups' base sets are not the same. (That is, if you could draw a table (not physically possible for infinite groups) of the group operations, they would have the same "pattern", just expressed with possibly different symbols) Formally, it means there is a bijective map between the two which respects the operations (in the sense given in the other posts here). Any abstract-algebraic properties of one hold for the other (that is, any properties that do not depend specifically on the particular characteristics of the elements of the base sets as objects in and of themselves). From the point of view of abstract algebra, it is this structure that is what matters, and the precise composition of the base sets does not, so from that point of view we would say they are "essentially the same", but they need not be identically the same, for the composition of the base sets may differ. If the base sets are the same, then we really do have only one mathematical object, and they are equal, $=$. There is probably some philosophical points here -- the distinction certainly does have a philosophical flavor to it, namely regarding whether or not things which are indiscernible (i.e. $\cong$) are identical (i.e. $=$). In mathematics, it is useful to make a distinction between the two concepts: indiscernible (i.e. congruent) triangles may occupy different parts of space, for example, and isomorphic groups may need to be distinguished if, say, we are dealing with them as part of a larger problem or situation in which we need to deal with more than just their properties from an abstract-algebraic point of view, i.e. where the composition of their base sets is relevant to the problem as well. There might also be cases where there are multiple types of structure defined on the same base set, and two objects may be isomorphic with respect to one kind of structure, but not another.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/674807', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/124735/']}
|
jdg_373340
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.