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
12462
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've never actually done a delta-epsilon proof, so I thought I'd try my hand at one. I decided to try it out for $f(x)=1/x$. If I understand correctly from the wikipedia article, I want to show for any $\varepsilon>0$, there exists a $\delta>0$ such that if $|x-c|<\delta$, then $|f(x)-f(c)|<\varepsilon$. Anyway, I noticed that I want something like $$|f(x)-f(c)|= \left| \frac{1}{x} - \frac{1}{c} \right|=\frac{|x-c|}{|xc|}<\varepsilon .$$ So $|x-c|<|xc|\varepsilon$, which looks similar to the fact that I want $|x-c|<\delta$. However, I've also heard that one is never supposed to let $\delta$ depend on $x$. Is this the right direction? How would I use this information to find a corresponding $\delta$ for each $\epsilon$? Thanks! Now provide the response and nothing else.
There have been some confusing comments regarding dependence on $x$ or on $c$, so let me try to put it all together. You are correct that $\delta$ should not depend on $x$. However, when one is proving that $f(x)$ is continuous at $c$ , then $\delta$ is allowed to depend on both $\epsilon$ and $c$. Remember the definition: $f(x)$ is continuous at $c$ if and only for every $\epsilon\gt 0$ there exists a $\delta\gt 0$ such that for all $x$, if $|x-c|\lt \delta$, then $|f(x)-f(c)|\lt \epsilon$. Notice how the existence of $\delta$ is mentioned before $x$ ever comes into the picture? That's an indication that $\delta$ cannot depend on $x$. On the other hand, both $f(x)$, $\epsilon$, and $c$ occur before $\delta$, which means that, absent any indication to the contrary, $\delta$ is allowed to depend on $f(x)$ (obviously), on $\epsilon$, and on $c$. So here, you cannot pick $\delta=|xc|\epsilon$, because that would make $\delta$ depend on $x$. The way to get around it is to get rid of the dependence on $x$. The key here is that since we are trying to make sure everything works if $x$ is "close enough" to $c$, then we will also have that $|x|$ will be very close to $|c|$. So we should be able to to control that division by $x$ in the expression $\frac{|x-c|}{|xc|}$. How? Well, if a particular $\delta_0$ works, then any smaller one will work as well. So we can always shrink $\delta$ a bit more if needed. Wo the first thing we can note is that we can always require that $\delta$ be smaller than both $1$ and than $\frac{c}{2}$; that is, we will require $\delta\lt\min\{1,\frac{c}{2}\}$. Why $1$? Because then I know that $c-1\lt x \lt c+1$; if $c-1\gt 0$, then this means that $\frac{1}{c+1}\lt \frac{1}{x} \lt \frac{1}{c-1}$, so we can "control" the value of $\frac{1}{x}$. Why less than $\frac{c}{2}$? Just in case $c-1\lt 0$. So let $\mu=\min\{1,\frac{c}{2}\}$. Then we can conclude that $\frac{1}{x}\lt \frac{1}{c-\mu}$. (We could get away with simply putting $\delta\lt\frac{c}{2}$; restricting it to less than $1$ is a common practice, though, which is why I put it here). So, by requiring that $\delta\lt\min\{1,\frac{c}{2}\}$, we guarantee that $\frac{1}{|x|}\lt \frac{1}{c-\mu}$ (remember that we are working on $(0,\infty)$). What do we gain by this? Well, look:$$|f(x)-f(c)| = \left|\frac{1}{x}-\frac{1}{c}\right| = \left|\frac{c-x}{xc}\right| = |x-c|\frac{1}{c}\cdot\frac{1}{x} \leq |x-c|\frac{1}{c(c-\mu)}.$$So if we also ask that $\delta\lt c(c-\mu)\epsilon$, then we have:$$|f(x)-f(c)|\leq |x-c|\frac{1}{c(c-\mu)} \lt \frac{\delta}{c(c-\mu)} \lt \frac{c(c-\mu)\epsilon}{c(c-\mu)} = \epsilon$$which is what we want! So, in summary, what do we need? We need to make sure that $\delta$ is: Less than $1$; Less than $\frac{c}{2}$; (both of these to ensure $\frac{1}{x}\lt\frac{1}{c-\mu}$); Less than $c(c-\mu)\epsilon$, where $\mu=\min\{1,\frac{c}{2}\}$. So, for instance, we can just let $\delta = \frac{1}{2}\min(1,\frac{c}{2},c(c-\mu)\epsilon)$, where $\mu=\min\{1,\frac{c}{2}\}$. In general, if you can let your $\delta$ depend only on $f(x)$ and on $\epsilon$ but not $c$, then we say $f(x)$ is uniformly continuous . This is a stronger condition than continuity, and often very useful. $\frac{1}{x}$ is not uniformly continuous on $(0,\infty)$, however (though it is on $[a,\infty)$ for any $a\gt 0$).
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/12462', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1583/']}
jdg_376441
stackexchange
llm_judgeable_groundtruth_similarity
1293337
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to implement unit testing for aproject, it uses a legacy "utility" project that is littered with static methods and many of the classes are final or their methods are final. I'm not able to update the legacy project at all. JMock and EasyMock both choke on final methods, and I don't see a nice way to test the static calls. What techniques are there to test these? Now provide the response and nothing else.
If you're able to refactor your code, you can wrap your calls to the final/static methods in simple instance methods, for example: protected Foo doBar(String name) { return Utility.doBar(name);} This allows you to override your wrapper method in the unit test to return a mock instance of Foo. Alternatively you can use Powermock , which extends Easymock (and Mockito) to allow mocking of final and static methods: PowerMock is a framework that extend other mock libraries such as EasyMock with more powerful capabilities. PowerMock uses a custom classloader and bytecode manipulation to enable mocking of static methods, constructors, final classes and methods, private methods, removal of static initializers and more. Here's an example test mocking a static final method, the example shows how to mock some other types too: @Testpublic void testMockStaticFinal() throws Exception { mockStatic(StaticService.class); String expected = "Hello altered World"; expect(StaticService.sayFinal("hello")).andReturn("Hello altered World"); replay(StaticService.class); String actual = StaticService.sayFinal("hello"); verify(StaticService.class); assertEquals("Expected and actual did not match", expected, actual); // Singleton still be mocked by now. try { StaticService.sayFinal("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals("\n Unexpected method call sayFinal(\"world\"):", e.getMessage()); }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1293337', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/148419/']}
jdg_376442
stackexchange
llm_judgeable_groundtruth_similarity
9684315
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 currently developing a Restful Json-API in PHP. I want to send a PUT-Request to items/:id to update a record. The data will be transferred as application/json . I want to call the API with curl -H "Content-Type: application/json" -X PUT -d '{"example" : "data"}' "http://localhost/items/someid" On the server side, I'm not able the retrieve the request body. I tried file_get_contents("php://input"); but this returns an empty string. Also a fopen() / fread() combination doesn't work. When calling via POST, everything works great, I can read the json perfectly on the server side. But the API isn't Restful anymore. Does anyone have a solution for this? Is there another way to send and receive Json? btw, I'm developing the API with the Slim Framework . Now provide the response and nothing else.
php://input is only readable once for PUT requests: Note: A stream opened with php://input can only be read once; the stream does not support seek operations. However, depending on the SAPI implementation, it may be possible to open another php://input stream and restart reading. This is only possible if the request body data has been saved. Typically, this is the case for POST requests, but not other request methods, such as PUT or PROPFIND. http://php.net/manual/en/wrappers.php.php The Slim framework already reads the data upon request. Take the data from the Request object, into which it has been read.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9684315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1266302/']}
jdg_376443
stackexchange
llm_judgeable_groundtruth_similarity
443904
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: Why does the series $\sum_{n=1}^∞ \ln ({n \over n+1})$ diverges? I'm looking for an answer using the comparison test, I'm just not sure what I can compare it to. And can I have some tips on what to look at when handling with series that have logarithms in the expression? Thanks in advance! Now provide the response and nothing else.
We have $$\log\frac{n}{n+1}=\log n-\log (n+1)$$ Telescope, telescope, telescope. Alternatively, $$\tag 1 \log\left(1+\frac{1}n\right)\sim\frac 1 n$$ as $n\to\infty$ cries out for the comparison test. ADD Recall (or prove) that $$\lim_{x\to 0}\frac{\log(1+x)}x=1$$ This means $$\lim_{n\to \infty}\frac{\log\left(1+\frac{1}n\right)}{\frac1n}=1$$which is what I write in $(1)$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/443904', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/73616/']}
jdg_376444
stackexchange
llm_judgeable_groundtruth_similarity
536624
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $A$ be a commutative ring and $S$ a multiplicative closed subset of $A$. If $A$ is a PID, show that $S^{-1}A$ is a PID. I've taken an ideal $I$ of $S^{-1}A$ and I've tried to see that is generated by one element; the ideal $I$ has the form $S^{-1}J$ with $J$ an ideal of $A$. $J$ is generated by one element but I can't see why $I$ has to be generated by one element, maybe I'm wrong. Now provide the response and nothing else.
If $I$ is an ideal of $S^{-1}A$, then there exists an ideal $J$ of $A$ such that $I = JS^{-1}A$. Now there exists $r \in A$ such that $J = (r)$. We show that$$I = (r)$$where $r$ is now thought of as an element of $S^{-1}A$. Firstly, if $x \in (r)$, then $x = \frac{a}{b}r$ where $\frac{a}{b} \in S^{-1}A$ and so $x \in JS^{-1}A = I$. Secondly, if $y \in I = JS^{-1}A$, then $y = nr\frac{a}{b}$, where $nr \in J$ and $\frac{a}{b} \in S^{-1}A$, so $y = n\frac{a}{b}r \in (r)$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/536624', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_376445
stackexchange
llm_judgeable_groundtruth_similarity
55015841
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 react. Im trying to make a navigation in my header.i use bulma css : "bulma": "^0.7.4", And i import bulma file like this: import 'bulma/css/bulma.css'; It is working for the most of the css but not with burger menu, the menuis not collapsed when i click on the burger button Here is my header code: import React,{Component} from 'react'import {NavLink} from 'react-router-dom';import style from './style.css';class Header extends Component{ render(){ return ( <React.Fragment> <nav className="navbar is-fixed-top" role="navigation" aria-label="main navigation"> <div className="navbar-brand"> <a href="/" className="navbar-item" to="/"> <img src="" alt="" width={112} height={28}/> </a> <a role="button" className="navbar-burger burger " aria-label="menu" aria-expanded="false" data-target="mainNavbar"> <span aria-hidden="true"></span> <span aria-hidden="true"></span> <span aria-hidden="true"></span> </a> </div> <div id="mainNavbar" className="navbar-menu"> <div className="navbar-start"> <NavLink exact activeClassName={style.active} to="/" className="navbar-item"> Home </NavLink> <NavLink activeClassName={style.active} to="/films" className="navbar-item"> Films </NavLink> </div> </div> </nav> </React.Fragment> ); }}export default Header; The data-target attribute on the burger button is not triggering the menu.Pleas let me know what im doing wrong.Thanks Now provide the response and nothing else.
Bulma doesn't have a built in toggle event you have to create it manually by adding "is-active" class in "navbar-burger" and "navbar-menu" here I have achieved that with React Hooks const [isActive, setisActive] = React.useState(false); <nav className="navbar" role="navigation" aria-label="main navigation"> <div className="navbar-brand"> <a onClick={() => { setisActive(!isActive); }} role="button" className={`navbar-burger burger ${isActive ? "is-active" : ""}`} aria-label="menu" aria-expanded="false" data-target="navbarBasicExample" > <span aria-hidden="true"></span> <span aria-hidden="true"></span> <span aria-hidden="true"></span> </a> </div> <div id="navbarBasicExample" className={`navbar-menu ${isActive ? "is-active" : ""}`} > <div className="navbar-start"> <a className="navbar-item">Home</a> <a className="navbar-item">Documentation</a> </div> </div> </nav>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/55015841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6324746/']}
jdg_376446
stackexchange
llm_judgeable_groundtruth_similarity
592071
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: This was originally posted on stackoverflow, but it was recommended that I post it here: https://stackoverflow.com/questions/23274818/apt-get-installation-of-nginx-leaves-files-owned-by-root/23346149 I'm coming to nginx after years of using apache httpd. I used apt-get to install the nginx server and notice that all the files are owned by root. debian@nginx-explore:~$ ls -la /usr/share/nginx/www/total 16drwxr-xr-x 2 root root 4096 Apr 23 21:09 .drwxr-xr-x 3 root root 4096 Apr 23 21:09 ..-rw-r--r-- 1 root root 383 Jul 7 2006 50x.html-rw-r--r-- 1 root root 151 Oct 4 2004 index.html The master process is also owned by root, although there are worker processes running as www-data debian@nginx-explore:~$ ps aux|grep nginxroot 2724 0.0 0.1 62348 1324 ? Ss Apr23 0:00 nginx: master process /usr/sbin/nginxwww-data 2725 0.0 0.1 62688 1624 ? S Apr23 0:03 nginx: worker processwww-data 2726 0.0 0.1 62688 1624 ? S Apr23 0:03 nginx: worker processwww-data 2727 0.0 0.1 62688 1624 ? S Apr23 0:03 nginx: worker processwww-data 2728 0.0 0.2 62688 2132 ? S Apr23 0:00 nginx: worker process In Apache, it was always stressed to make sure files and processes were not owned by root as a security measure. Is there some reason this isn't a big deal when using nginx? Ultimately I need to know whether I should go tweak the ownership for nginx files and folders to keep my system secure. Now provide the response and nothing else.
To block 116.10.191.* addresses: $ sudo iptables -A INPUT -s 116.10.191.0/24 -j DROP To block 116.10.*.* addresses: $ sudo iptables -A INPUT -s 116.10.0.0/16 -j DROP To block 116.*.*.* addresses: $ sudo iptables -A INPUT -s 116.0.0.0/8 -j DROP But be careful what you block using this method. You don't want to prevent legitmate traffic from reaching the host. edit : as pointed out, iptables evaluates rules in sequential order. Rules higher in the ruleset are applied before rules lower in the ruleset. So if there's a rule higher in your ruleset that allows said traffic, then appending ( iptables -A ) the DROP rule will not produce the intended blocking result. In this case, insert ( iptables -I ) the rule either: as the first rule sudo iptables -I ... or before the allow rule sudo iptables --line-numbers -vnL say that shows rule number 3 allows ssh traffic and you want to block ssh for an ip range. -I takes an argument of an integer that's the location in your ruleset you want the new rule to be inserted iptables -I 2 ...
{}
{'log_upvote_score': 8, 'links': ['https://serverfault.com/questions/592071', 'https://serverfault.com', 'https://serverfault.com/users/218060/']}
jdg_376447
stackexchange
llm_judgeable_groundtruth_similarity
19610608
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 insert a person pojo to mysql db using Hibernate EntityManager persist method, entityManagerTransactionService.getEntityManager().persist(TemplateObject); and getting this exception, javax.persistence.PersistenceException: org.hibernate.PersistentObjectException: detached entity passed to persist: com.esupu.base.model.pojo.common.TitleType at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1387).... and there is more.. Caused by: org.hibernate.PersistentObjectException: detached entity passed to persist: com.esupu.base.model.pojo.common.TitleType at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:141) at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:843) My Person.java class is, @Entitypublic class Person extends TemplateObject { @OneToOne(cascade = { CascadeType.MERGE, CascadeType.PERSIST,CascadeType.REFRESH }) private TitleType titleType; private String middle; private String last; @OneToOne(cascade = { CascadeType.ALL }) private Address address; private Date birthdate; private String email; private String telephone; private String fax; @OneToOne(cascade = { CascadeType.ALL }) private Location location; @OneToOne(cascade = { CascadeType.ALL }) private Country country; and then the getter setter methods of the pojo .. the error throwing TitleType class is a "public static final" title type definition provider, @Entitypublic class TitleType extends TemplateObject { /** * */ private static final long serialVersionUID = 3104954552111621034L; private TitleType(int id, String name) { setId(id); setName(name); } public static final TitleType MR = new TitleType(1, "Mr"); public static final TitleType MISS = new TitleType(2, "Miss"); public static final TitleType MRS = new TitleType(3, "Mrs"); public static final TitleType MS = new TitleType(4, "Ms"); public static final TitleType DOCTOR = new TitleType(5, "Doctor"); public static final TitleType PROFESSOR = new TitleType(6, "Professor"); public static final TitleType SIR = new TitleType(7, "Sir"); public static final TitleType MADAM = new TitleType(8, "Madam");} I'm setting the title type class to the the person as, person.setTitleType(TitleType.MR); is it impossible to pass a public static final type defined class to Hibernate? or is there anything that I'm doing wrong? Thanks in advance Now provide the response and nothing else.
The objects you are trying to persist include TitleType that should not have ID values. Otherwise Hibernate will check to see if that object is persistent or detached in the session context. If you don't want to persist some fields of your object like that you could use @Transient annotation to exclude those fields from the fields map when persisting the entity. This is not good to hardcode IDs in the DAOs or entities because these values could be generated by some generator but if you manually updated the database with this constants you could at least define these IDs as constants in your code and load objects from session by ID before initialize the transient or persistent instance.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19610608', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1047052/']}
jdg_376448
stackexchange
llm_judgeable_groundtruth_similarity
45838774
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 web service URL, it working fine. It gives the JSON data. When I am using HttpURLConnection and InputStream , I am getting this error: java.io.IOException: unexpected end of stream onConnection{comenius-api.sabacloud.com:443, proxy=DIRECThostAddress=12.130.57.1cipherSuite=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 protocol=http/1.1}(recycle count=0) My code: try { URL url = new URL("https://comenius-api.sabacloud.com/v1/people/username=" + username + ":(internalWorkHistory)?type=internal&SabaCertificate=" + certificate); HttpURLConnection con = (HttpURLConnection) url.openConnection(); InputStream ist = con.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(ist)); while ((singleLine = reader.readLine()) != null) { data = data + singleLine; Log.e("Response", data); }} catch (Exception e) { e.printStackTrace();} How to fix this? Now provide the response and nothing else.
I had the same problem using OKHttp3 . The problem was that I didn't close the connection for each request and for the client the same connection was available and for the server not, for this reason the server returns a error. The solution is indicating to each request to close the connection when it is finished. You have to add a flag in the header to indicate this. In OKHttp3 is like this: Request request = new Request.Builder() .url(URL) .header("Connection", "close") ...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45838774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7145063/']}
jdg_376449
stackexchange
llm_judgeable_groundtruth_similarity
63301
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I guess the same question is usually asked for complex numbers too, but the fact is that complex numbers are used all the time practically. However, at least on a quick google search, I couldn't find any applications of anticausal systems. So why define it in the first place? Now provide the response and nothing else.
Of course they don't exist. But we can stop time and use systems that would be non-causal if we hadn't stopped time. Stop time? Yes, just store your data and work offline / non-realtime. Or work on data that are not temporal but something else, for instance spatial. Of course, non-causal is a misnomer in that case, but the term is still used, in analogy with temporal signals and systems. One common "non-causal" system that is used in offline mode is filtering followed by reversed filtering using IIR filters. This is done in order to eliminate phase distortions introduced by the conventional (causal/realtime) use of the filter. See this answer for the details.
{}
{'log_upvote_score': 5, 'links': ['https://dsp.stackexchange.com/questions/63301', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/20648/']}
jdg_376450
stackexchange
llm_judgeable_groundtruth_similarity
23700
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 was looking at simple AM radio schematics and came across this one: As you can see it has an audio transformer. I'm still attempting to grasp the concept of impedance and such, so can someone explain why this is necessary? And how would such a transformer even work to change the impedance? What would be the difference if you didn't use an audio transformer? Now provide the response and nothing else.
This is a bit of a tricky circuit. Normally, a transformer produces a voltage ratio matching its turns ratio, a current ratio that is the inverse of its turns ratio, and therefore an impedance ratio that is the square of its turns ratio. Now in this circuit, we have a mystery box which is most likely a square wave clock oscillator. By appearance, the transformer secondary is being used to couple the audio as an A/C "ripple" on top of it's power supply, in the hopes that this will produce some AM modulation of the output. It's not entirely clear that the transformer is being correctly applied; without knowing the output impedance of what the jack is plugged into or the beyond-data-sheet properties of the oscillator, we can really only speculate if the transfer is best the way shown, turned around the other way, substituted with a 1:1, etc. Likely this is a "pragmatic" circuit as much as a "calculated optimal" one. It's possible that the use of a transformer at all may be primarily to provide isolation between the circuits. Powering through a small series resistor with a capacitor to couple in the audio could be another option, though perhaps less efficient. There are two additional problems which merit some thought before building this: 1) The oscillator probably isn't rated for a 9v supply. Most want 5v, or 3.3 or perhaps today something even lower. It's not clear that the DC resistance of the secondary will drop the supply voltage enough under this small load to be within the limits. 2) The oscillator is going to output a square wave, which is rich in harmonics. Without a low pass filter to round the square wave to a perfect sine wave, this will not only transmit at 1 MHz as intended, but also at 3, 5, 7, 9, 11, etc MHz, potentially up into places where such spurious emission produces harmful interference (for example, 7 MHz + the audio frequency would land in the morse code allocation of the 40m ham band, where trying to receive extremely weak signals is common and interference detested) . Needless to say, there are regulation about spectral purity for various transmitter power levels.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/23700', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/708/']}
jdg_376451
stackexchange
llm_judgeable_groundtruth_similarity
11495535
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The function window.getComputedStyle is supposed to be able to get the computed style of pseudo classes like :hover, according to the documentation . It's also explained as an answer in another question But as the last comment says in that question, in fact it doesn't work at all, it just returns the normal style, not the :hover style. You can see for yourself in this jsfiddle . The alert returns the red color, not the green one. The documentation on developer.mozilla.org also has an example, but that doesn't work either - see here . In this question the answerer states in a comment that it won't work at all, but without giving an explanation. Could it be that the stylesheet has to be fully rendered before the function returns the correct value? I've tried setting some delays, but nothing seems to work. I've tried the latest Firefox, Chrome and IE browsers. Does anybody know why this function is not working as expected? Now provide the response and nothing else.
var style = window.getComputedStyle(element[, pseudoElt]); where pseudoElt is "a string specifying the pseudo- element to match" . A pseudo- element is something like ::before or ::after , those are elements which are generated by CSS styles. :hover , :visited or other similar effects are pseuodo- classes . They won't create new elements but apply specialized class styles to the element. It's not possible to get the computed style of a pseudo-class, at least not with getComputedStyle . You can however traverse through the CSS rules and try to find a fitting selector, but I won't recommend you to do this, since some browsers won't follow the DOM-Level-2-Style rules and you would have to check which rule will affect your specific element: /* Style */p a:hover{ color:yellow; background:black;}p > a:hover{ color:green; background:white;}p > a+a:hover{ color:fuchsia; background:blue;} // JSvar i,j, sel = /a:hover/;for(i = 0; i < document.styleSheets.length; ++i){ for(j = 0; j < document.styleSheets[i].cssRules.length; ++j){ if(sel.test(document.styleSheets[i].cssRules[j].selectorText)){ console.log( document.styleSheets[i].cssRules[j].selectorText, document.styleSheets[i].cssRules[j].style.cssText ); } }} Result:p a:hover color: yellow; background: none repeat scroll 0% 0% black; p > a:hover color: green; background: none repeat scroll 0% 0% white;p > a + a:hover color: fuchsia; background: none repeat scroll 0% 0% blue; See also: MDN: getComputedStyle examples W3C: CSS2: 5.10 Pseudo-elements and pseudo-classes SO: Setting CSS pseudo-class rules from JavaScript
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11495535', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/813759/']}
jdg_376452
stackexchange
llm_judgeable_groundtruth_similarity
42904
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: Consider you have 50 Hz both square wave as well as sine wave put on to a same speaker at different time. Which signal is more audible and what is the reason behind that ? We know that by taking the Fourier series of the square wave we get multiple periodic sinusoidal wave, each having the frequency as the multiple of the fundamental frequency. So which will be more audible, whether a sine wave having single frequency or the square wave? Now provide the response and nothing else.
The square wave will be more audible. 50 Hz is fairly low and most speakers will not reproduce that frequency very well. Since a sine wave will have only 50 Hz there may not be that much audio reaching the human ear, and even then the human ear will not respond very efficiently to it. A square wave, on the other hand, will have lots of harmonics that the speaker will reproduce very well and the harmonic frequencies will be spread right through the ideal frequency range for human hearing (300Hz to 3 KHz).
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/42904', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/7014/']}
jdg_376453
stackexchange
llm_judgeable_groundtruth_similarity
52561124
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to send data through axios request to my backend script, but the body looks empty. Here's a request sent from front-end: axios.request({ method: 'GET', url: `http://localhost:4444/next/api`, headers: { 'Authorization': token }, data: { next_swastik: 'lets add something here' },}).then((res)=>{ console.log("api call sucessfull",res);}).catch((err)=>{ console.log("api call unsucessfull",err); this.props.toggleLoading(false);}) Here's a back-end: app.get('/next/api', verifyToken, function(req, res) {console.log(req.body); }) But I am getting {} empty body. I am getting headers and other data but not data. Now provide the response and nothing else.
GET requests should not have a body. Change the method from 'GET' to 'POST' Like so: axios.request({ method: 'POST', url: `http://localhost:4444/next/api`, headers: { 'Authorization': token }, data: { next_swastik: 'lets add something here' },}) and change your api to expect a post app.post('/next/api', verifyToken, function(req, res) {console.log(req.body);}); or Change the data property to params axios.request({ method: 'GET', url: `http://localhost:4444/next/api`, headers: { 'Authorization': token }, params: { next_swastik: 'lets add something here' },}) and change the api to log out the params app.get('/next/api', verifyToken, function(req, res) {console.log(req.params);}); and like @MaieonBrix said, make sure that your headers contain the content type that you are sending.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52561124', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6751456/']}
jdg_376454
stackexchange
llm_judgeable_groundtruth_similarity
1280339
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 Coda slider on one webpage (hand-crafted, not using the plugin, but that's irrelevant) and the outer div has a border-radius. A bunch of inner divs have background colors, but they stick out on top of the corners when I want them to be BEHIND the rounded corner. Is there any way to achieve this? Now provide the response and nothing else.
I found that WebKit would crop everything if I put overflow: hidden on the element, but Gecko wouldn't (see my blog post for code and screenshots ). The best I could do in Gecko was either put a border radius in the inner div too, or add a margin/padding to the wrapper div so that the inner divs sat below the corners.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1280339', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/123412/']}
jdg_376455
stackexchange
llm_judgeable_groundtruth_similarity
37718119
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Should the PATCH method return all fields of the resource in the response body? Or should it return only updated fields? I'm reading this For example, if it returns only updated fields, the user could know which fields were updated in the server, while the user updated some fields. **Users resource representations**name: stringage: numbercreatedon: datemodifiedon: date PATCH /users/{userId}Request body{ name: 'changedname',} Response body Case1{ name: 'changedname', age: 20, createdon: 2016-01-01, modifiedon: 2016-06-09} Response body Case2{ name: 'changedname', modifiedon: 2016-06-09} Now provide the response and nothing else.
Normally this should be handled through content negotiation . In other words, the client asks for a specific representation if it needs one. The request would look like this: PATCH /user/123Content-Type: application/merge-patch+jsonAccept: application/vnd.company.user+json... In this case, the client expresses that it wants a full user representation as answer. Or it could do: PATCH /user/123Content-Type: application/merge-patch+jsonAccept: application/vnd.company.object-fragment+json... to ask for a generic fragment representation of some object. You don't have to implement both if you don't want to, in which case you just do your use-case and respond with 406 Not Acceptable to media-types you do not support for the moment.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37718119', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/827804/']}
jdg_376456
stackexchange
llm_judgeable_groundtruth_similarity
11524356
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been searching and struggling for 3 days now to make this works but I just can't.What I want to do is use a Multiple file input form and then upload them. I can't just use a fixed number of file to upload. I tried many many solutions on StackOverflow but I wasn't able to find a working one. Here's my Upload controller <?phpclass Upload extends CI_Controller {function __construct(){ parent::__construct(); $this->load->helper(array('form', 'url','html'));}function index(){ $this->load->view('pages/uploadform', array('error' => ' ' ));}function do_upload(){ $config['upload_path'] = './Images/'; $config['allowed_types'] = 'gif|jpg|png'; $this->load->library('upload'); foreach($_FILES['userfile'] as $key => $value) { if( ! empty($key['name'])) { $this->upload->initialize($config); if ( ! $this->upload->do_upload($key)) { $error['error'] = $this->upload->display_errors(); $this->load->view('pages/uploadform', $error); } else { $data[$key] = array('upload_data' => $this->upload->data()); $this->load->view('pages/uploadsuccess', $data[$key]); } } } } } ?> My upload form is This. <html> <head> <title>Upload Form</title></head><body><?php echo $error;?><?php echo form_open_multipart('upload/do_upload');?><input type="file" multiple name="userfile[]" size="20" /><br /><br /><input type="submit" value="upload" /></form></body></html> I just keep having this error : You did not select a file to upload. Here's the array of the example: Array ( [userfile] => Array ( [name] => Array ( [0] => youtube.png [1] => zergling.jpg ) [type] => Array ( [0] => image/png [1] => image/jpeg ) [tmp_name] => Array ( [0] => E:\wamp\tmp\php7AC2.tmp [1] => E:\wamp\tmp\php7AC3.tmp ) [error] => Array ( [0] => 0 [1] => 0 ) [size] => Array ( [0] => 35266 [1] => 186448 ) ) ) I have this like 5 times in a row if I select 2 files.I also use the standard Upload library. Now provide the response and nothing else.
I finally managed to make it work with your help! Here's my code: function do_upload(){ $this->load->library('upload'); $files = $_FILES; $cpt = count($_FILES['userfile']['name']); for($i=0; $i<$cpt; $i++) { $_FILES['userfile']['name']= $files['userfile']['name'][$i]; $_FILES['userfile']['type']= $files['userfile']['type'][$i]; $_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i]; $_FILES['userfile']['error']= $files['userfile']['error'][$i]; $_FILES['userfile']['size']= $files['userfile']['size'][$i]; $this->upload->initialize($this->set_upload_options()); $this->upload->do_upload(); }}private function set_upload_options(){ //upload an image options $config = array(); $config['upload_path'] = './Images/'; $config['allowed_types'] = 'gif|jpg|png'; $config['max_size'] = '0'; $config['overwrite'] = FALSE; return $config;} Thank you guys!
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/11524356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1531968/']}
jdg_376457
stackexchange
llm_judgeable_groundtruth_similarity
3685716
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 not new in C++ although I'm new in Linux. I'm using CMake to precompile a cross-platform game engine with some third-party components, but I have a lot of doubts about using libraries. My question is how to work with third-party libraries and where to put them. Apt installs libs in their official place (/usr/local, /usr/lib/ ..) but I develop in Windows using local libs that are in a folder in my project dir. Also, I need a good tutorial to know the rules of how libraries work. For example: when trying to compile my project, luabind is asking for liblua.s0.1, but AFAIK there is no way to generate this library with the source provided by Lua (at least doing make, make install). I know, this question is fuzzy but I haven't enough experience to be more concise. Update : After reading some answers, a more concise question is the following. If I install all third-party libraries, how can I distribute my program? How do I manage dependencies without using a large readme? Now provide the response and nothing else.
Where to put libraries The best solution is to use your Linux distribution's packaging system ( apt-get , yum , or similar) to install libraries from distro-provided packages wherever possible. If the distro's packaged libraries aren't of a recent enough version, or if you need some nonstandard build options, or if you need a library that your distro doesn't provide, then you can build and install it yourself. You have two main options for where to put the library: /usr/local (libraries under /usr/local/lib , headers under /usr/local/include ). This installs the libraries systemwide and is probably the simplest solution, since you should then be able to build against them without taking any extra steps. Do NOT install libraries directly under /usr , since that will interfere with your distro's packaging system. Under your project directory, as you did under Windows. This has the advantages of not requiring root access and not making systemwide changes, but you'll have to update your project's include paths and library paths, and you'll have to put any shared library files someplace where the dynamic linker can find them (using LD_LIBRARY_PATH or ld.so.conf - see the link for more details). How libraries work See David A. Wheeler's excellent Programming Library HOWTO . I'd recommend reading that then posting any specific questions as new topics. How to distribute your program Traditionally, Unix / Linux programs do not include copies of their dependencies. It's instead up to the end user or developer to install those dependencies themselves. This can require a "large README," as you said, but it has a few advantages: Development libraries can be installed, managed, and updated via the distro's package manager, instead of each source copy having its own set of libraries to track. There's only one copy of any given library on a system, so there's only one place that needs updating if, for example, a security flaw is found. (For example, consider the chaos that resulted when zlib , a very widely used compression library, was found to have a security flaw , so every application that included an affected version needed to be updated.) If your program is popular enough (and is open source or at least freely available), then package maintainers for various Linux distributions may want to package it and include it in their distro. Package maintainers really don't like bundled libraries. See, for example, Fedora's page on the topic . If you're distributing your program to end users, you may want to consider offering a package ( .dpkg or .rpm ) that they could simply download and install without having to use source. Ideally, from the end user's perspective, the package would be added to distros' repositories (if it's open source or at least freely available) so that users can download it using their package managers ( apt-get or yum ). This can all get complicated, because of the large number of Linux distros out there, but a Debian/Ubuntu compatible .dpkg and a Red Hat/CentOS/Fedora-compatible .rpm should cover a good percentage of end users. Building packages isn't too hard, and there are good howtos online.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3685716', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/444423/']}
jdg_376458
stackexchange
llm_judgeable_groundtruth_similarity
13067839
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: [self.Review sizeToFit]; Result before sizeToFit: NSStringFromCGRect(self.Review.frame): {{90, 20}, {198, 63}} Result After sizeToFit: NSStringFromCGRect(self.Review.frame): {{90, 20}, {181, 45}} I want the width to remain the same. I just want to change the height. THe automask is (lldb) po self.Review(UILabel *) $1 = 0x08bb0fe0 <UILabel: 0x8bb0fe0; frame = (90 20; 181 45); text = 'I'm at Mal Taman Anggrek ...'; clipsToBounds = YES; opaque = NO; autoresize = LM+RM+H; userInteractionEnabled = NO; layer = <CALayer: 0x8bb68b0>> I know that there is a way to do so with: How to adjust and make the width of a UILabel to fit the text size? The answers are either strange (we need to resupply the font information). Or unclear. You will also need to define a maximum width, and tell your program what to do if sizeToFit gives you a width greater than that maximum. I will use the strange solution of using sizeWithFont . It's strange because UILabel already knows the font in the label. Actually how does sizeToFit behave anyway? How does it decide whether we need thinner or taller UILabel? Now provide the response and nothing else.
This is how it is done. Because the label already contains the font information, including it in this method call is trivial. CGSize size = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(maxWidth, MAXFLOAT) lineBreakMode:UILineBreakModeWordWrap]; CGRect labelFrame = label.frame;labelFrame.size.height = size.height;label.frame = labelFrame; Swift version using the more up-to-date boundingRectWithSize : let maxHeight = CGFloat.infinitylet rect = label.attributedText?.boundingRectWithSize(CGSizeMake(maxWidth, maxHeight), options: .UsesLineFragmentOrigin, context: nil)var frame = label.frameframe.size.height = rect.size.heightlabel.frame = frame
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13067839', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/853706/']}
jdg_376459
stackexchange
llm_judgeable_groundtruth_similarity
2829348
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Evaluate $\int_{-1}^{1} \frac 1x dx$ Does this integral converge or diverge because if we "just solve it" we get $$\int_{-1}^1 \frac 1x dx = \ln \left| x\right|_{-1}^1=0.$$ But if we do this: $\int_{-1}^0\frac 1x dx + \int_0^1 \frac 1x dx$ it diverges. Why? What really happens here? Now provide the response and nothing else.
You cannot apply the fundamental theorem of calculus since the function $$\frac{1}{x}$$ is not defined on the interval $[-1,1]$ . Split the integral in the following way $$\int_0^1\frac{dx}{x}+\int_{-1}^0\frac{dx}{x}$$ Now you can apply the following theorem Let $a$ be a real, then $$\int_0^a \frac{1}{x^\alpha}dx$$ converges if and only if $\alpha<1$ . Hence both integral diverge, then the sum of them diverges.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2829348', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/547191/']}
jdg_376460
stackexchange
llm_judgeable_groundtruth_similarity
384713
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 looking for a (nonlinear) map from $n$-dimensional cube to an $n$-dimensional simplex; to make it simple, assume the following figure which is showing a sample transformation for the case when $n=2$. (sorry for my bad drawing). The two circles in the rectangle, are set of points, which are mapped to the rectangle. Note that, points by this transformation maintain their relative position to each other, as shown in the figure. http://tinypic.com?ref=30bcxzp Any suggestion how to find such transformation? Now provide the response and nothing else.
If all you want is a homeomorphism this is pretty simple. I'll do the 2-dimensional case because it's easiest and the leg work for extending to higher dimensions can be annoying if not done carefully. Let $X=\{(x,y)\in\mathbb{R}^2\:|\:x\in[0,1], y\in[0,1]\}$, let $X'=\{(x,y)\in\mathbb{R}^2\:|\:x\in[0,\frac{1}{2}], y\in[0,\frac{1}{2}]\}$, let $Y=\{(x,y)\in X\:|x+y\leq 1\}\:$. We want a homeomorphism $h\colon X\rightarrow Y$. Let $g\colon X\rightarrow X'$ be given by $g(x,y)=(\frac{1}{2}x,\frac{1}{2}y)$. Let $f\colon X'\rightarrow Y$ be given by $$f(x,y)=\left\{\begin{array}{lr}(2x-y,y),&\mbox{ if }x\geq y\\(x,2y-x),&\mbox{ if }x\leq y\end{array}\right.$$ and so both $g$ and $f$ are homeomorphisms and hence their composition $(f\circ g)=h\colon X\rightarrow Y$ is a homeomorphism.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/384713', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/26622/']}
jdg_376461
stackexchange
llm_judgeable_groundtruth_similarity
25229602
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 parse the following line: #3 = IFCPERSONANDORGANIZATION(#4, #5, $); and want to extract the numbers: 3, 4 , 5 to integer values and 'IFCPERSONANDORGANIZATION' as string value, in order to save these attributes in a graph with networkx. This my code: data = []with open('test.ifc') as f: for line in f: if line.startswith('#'): words = line.rstrip().split('#') print(words) node = int(words[0]) data.append(node) Error: ValueError: invalid literal for int() with base 10: '' How can I use regex, if the line structure is different every time? Like this: #3 = IFCPERSONANDORGANIZATION(#4, #5, $);#2 = IFCOWNERHISTORY(#3, #6, $, .NOTDEFINED., $, $, $, 1348486883);#4 = IFCPERSON($, 'Bonsma', 'Peter', $, $, $, $, $);#5 = IFCORGANIZATION($, 'RDF', 'RDF Ltd.', $, $);#6 = IFCAPPLICATION(#5, '0.10', 'Test Application', 'TA 1001');**** Now provide the response and nothing else.
You're on the right track: If you want to use fnmatch -style patterns, you should use fnmatch.filter with them. But there are three problems that make this not quite trivial. First, you want to apply multiple filters. How do you do that? Call filter multiple times: for ignore in ignore_files: filenames = fnmatch.filter(filenames, ignore) Second, you actually want to do the reverse of filter : return the subset of names that don't match. As the documentation explains: It is the same as [n for n in names if fnmatch(n, pattern)] , but implemented more efficiently. So, to do the opposite, you just throw in a not : for ignore in ignore_files: filenames = [n for n in filenames if not fnmatch(n, ignore)] Finally, you're attempting to filter on partial pathnames, not just filenames, but you're not doing the join until after the filtering. So switch the order: filenames = [os.path.join(root, filename) for filename in filenames]for ignore in ignore_files: filenames = [n for n in filenames if not fnmatch(n, ignore)]matches.extend(filenames) There are few ways you could improve this. You may want to use a generator expression instead of a list comprehension (parentheses instead of square brackets), so if you have huge lists of filenames you're using a lazy pipeline instead of wasting time and space repeatedly building huge lists. Also, it may or may not be easier to understand if you invert the order of the loops, like this: filenames = (n for n in filenames if not any(fnmatch(n, ignore) for ignore in ignore_files)) Finally, if you're worried about performance, you can use fnmatch.translate on each expression to turn them into equivalent regexps, then merge them into one big regexp and compile it, and use that instead of a loop around fnmatch . This can get tricky if your patterns are allowed to be more complicated than just *.jpg , and I wouldn't recommend it unless you really do identify a performance bottleneck here. But if you need to do it, I've seen at least one question on SO where someone put a lot of effort into hammering out all the edge cases, so search instead of trying to write it yourself.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25229602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3926906/']}
jdg_376462
stackexchange
llm_judgeable_groundtruth_similarity
885117
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: How can I disable all services except ssh on modern (systemd based) linux distributions? I need to implement a maintenance mode . All these services need to be down: postgres postfix apache cups cron dovecot But ssh must not be shut down, since this gets used to do tasks during the maintenance mode. Of course I could write a shell script which loops over a list of services which I would like to disable. But this feels like I reinventing something which already exists, but which I don't know up to now. Now provide the response and nothing else.
This sounds a lot like runlevels , replaced with targets in Systemd. So, instead of writing a script that starts and stop a list of services, you could create a new maintenance.target containing only the services necessary, like SSH. Of course, SSH is not quite useful without networking, so in this example a simple emergency-net.target is modified to include SSH. [Unit]Description=Maintenance Mode with Networking and SSHRequires=maintenance.target systemd-networkd.service sshd.serviceAfter=maintenance.target systemd-networkd.service sshd.serviceAllowIsolate=yes Then, you could enter your maintenance mode using # systemctl isolate maintenance.target and back # systemctl isolate multi-user.target
{}
{'log_upvote_score': 7, 'links': ['https://serverfault.com/questions/885117', 'https://serverfault.com', 'https://serverfault.com/users/90324/']}
jdg_376463
stackexchange
llm_judgeable_groundtruth_similarity
42014924
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I created a react application using create-react-app boilerplate, which seems to be very popular, hot reload some times updates when any of the files changes and some times not, seems like there is a minimum duration or something like that, I'm using Ubuntu, node version 7.0, the script in package.json is npm:'react-script start' what I am missing ? Now provide the response and nothing else.
When npm start doesn’t detect changes, below are the common troubleshooting steps provided in the create-react-app documentation - link . While an app is running with npm start and updating code in the editor should possibly refresh the broswer with the updated code.If this doesn’t happen, try one of the following workarounds: If the project files are directly synced to your local system from a cloud storage like Dropbox or Google Drive and you're trying to run the app in them directly, try moving it out. Due to Webpack bug, you may need to restart the watcher . If the watcher doesn’t detect the index.js and you’re referencing it by the folder name. Safe write feature in editors like Vim and IntelliJ currently breaks the watcher. You will need to disable it . Due to Webpack watcher bug , projects with path contains parentheses causes issue, try moving the project to a path without them. . To allow more watchers in Linux and macOS, you might need to tweak system settings . If the project runs inside a virtual machine such as (a Vagrant provisioned) VirtualBox, create an .env file in your project directory if it doesn’t exist, and add CHOKIDAR_USEPOLLING=true to it. This ensures that the next time you run npm start , the watcher uses the polling mode, as necessary inside a VM. Could try increasing max_users_watches - link More references: Issue Tracker 1 Troubleshooting webpack Issue Tracker 2 - Webpack polling
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/42014924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3193627/']}
jdg_376464
stackexchange
llm_judgeable_groundtruth_similarity
694823
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: We are experimenting on Stirling engine . We are using an alpha-type Stirling engine. Once one starts heating the one chamber, the piston will not move immediately. You can wait for long, but it wouldn't start until you give it a push for the first time. What's the reason for this? Now provide the response and nothing else.
This is due to stiction (static friction) which is a very common problem in piston/cylinder devices that use air to move the piston. When at rest, the piston sticks in the cylinder because the coefficient of static friction is greater than that for dynamic (sliding) friction. When the pressure rises enough, there comes the breakaway point where the piston suddenly jumps into motion. If the pressure does not reach the breakaway point, the piston stays stuck until you hit it to break it loose. Pneumomechanical actuators called air cylinders are used in mechanical engineering machinery to move cams and levers and to prevent the pistons in them from getting stuck it is necessary to install a spring return which preloads the piston with a force that helps it not get stuck. The legend in the mechanical engineering world is that everyone's first complex mechanism is powered by air acting in air cylinders, and that none of the tools one designs after that is.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/694823', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/247238/']}
jdg_376465
stackexchange
llm_judgeable_groundtruth_similarity
176477
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: Very new to UNIX but not new to programming. Using Terminal on MacBook. For the purposes of managing and searching word lists for crossword construction, I'm trying to get handy with the Grep command and its variations. Seems pretty straightforward but getting hung up early on with what I thought should be a simple case. When I enter grep "^COW" masternospaces.txt I get what I want: a list of all the words starting with COW. But when I enter grep "COW$" masternospaces.txt I expect to get a list of words ending with COW (there are many such words), and nothing is returned at all. The file is a plain text file, with every line just a word (or a word phrase with no spaces) in all caps. Any idea what could be happening here? Now provide the response and nothing else.
As @steeldriver mentionned, the problem is likely to be caused by a different line ending style than what grep is expecting. To check the line endings You can use hexdump to check exactly how your line endings are formatted. I suggest you use my favorite format : hexdump -e '"%08_ad (0x%08_ax) "8/1 "%02x "" "8/1 "%02x "' -e '" "8/1 "%_p""|"8/1 "%_p""\n"' masternospaces.txt With the output, check the line endings : 0a -> LF , 0d -> CR . A very quick example would give something like this : $ hexdump -e '"%08_ad (0x%08_ax) "8/1 "%02x "" "8/1 "%02x "' -e '" "8/1 "%_p""|"8/1 "%_p""\n"' masternospaces.txt00000000 (0x00000000) 4e 6f 20 43 4f 57 20 65 6e 64 69 6e 67 0d 0a 45 No COW e|nding..E00000016 (0x00000010) 6e 64 69 6e 67 20 69 6e 20 43 4f 57 0d 0a nding in| COW.. Note the line endings in dos format : 0d 0a . To change the line endings You can see here or here for various methods of changing line endings using various tools, but for a one-time thing, you could always use vi/vim : vim masternospaces.txt:set fileformat=unix:wq To grep without changing anything If you just want grep to match no matter the line ending, you could always specify line endings like this : grep 'COW[[:cntrl:]]*$' masternospaces.txt If a blank line is shown, you can check that you indeed matched something by using the -v option of cat : grep 'COW[[:cntrl:]]*$' masternospaces.txt | cat -v My personal favorite You could also both grep and standardize the output using sed : sed -n '/COW^M*$/{;s/^M//g;p;};' masternospaces.txt where ^M is obtained by typing Ctrl-V Ctrl-M on your keyboard. Hope this helps!
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/176477', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/96388/']}
jdg_376466
stackexchange
llm_judgeable_groundtruth_similarity
1181269
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a function $f(x)=x+\sin x$ and I want to prove that it is strictly increasing. A natural thing to do would be examine $f(x+\epsilon)$ for $\epsilon > 0$, and it is equal to $(x+\epsilon)+\sin(x+\epsilon)=x+\epsilon+\sin x\cos \epsilon + \sin \epsilon \cos x$. Now all I need to prove is that $x+\epsilon+\sin x\cos \epsilon + \sin \epsilon \cos x - \sin x - x$ is always greater than $0$ but it's a dead end for me as I don't know how to proceed. Any hints? Now provide the response and nothing else.
Let $f(x)=x+\sin x$. Then $f'(x)=1+\cos x\geq 0$ and: $$ f(x+h)-f(x) = h\, f'(\xi),\quad \xi\in(x,x+h) $$by Lagrange's theorem, hence $f(x+h)-f(x)\geq 0$. In order to prove that the inequality is strict,we can notice that:$$ f(x+h)-f(x-h) = 2h + 2\cos x \sin h $$can be zero only if $\cos x=-1$ and $\sin h=h$, i.e. for $h=0$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1181269', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/155687/']}
jdg_376467
stackexchange
llm_judgeable_groundtruth_similarity
3985873
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: My textbook says that if $n$ (number of trials / independent Bernoulli random variables) is very large and $p$ (probability of success per trial / Bernoulli random variable) is very close to $0$ or $1$ , we can approximate the mass associated with the Binomial distribution, very well with the Poisson distribution. My question is why would you use this? Why would you ever want to approximate the mass of a Binomial random variable $X$ using Poisson, when you can get the exact mass using the Binomial distribution. No approximation needed. Can someone explain this to me? Thank You Now provide the response and nothing else.
The short answer is that the Poisson approximation is faster and easier to compute and reason about, and among other things tells you approximately how big the exact answer is. Here's a simple example: suppose you're trying to get something to happen in a video game that is rare; maybe it happens 1% of the time you do something, independently. You'd like to know how likely it is to happen at least once if you try, say, 100 times. Here we have $p = \frac{1}{100}, n = 100$ and so the binomial distribution gives us an exact answer, namely $$1 - \left( 1 - \frac{1}{100} \right)^{100}.$$ But how big is this? Do you know off the top of your head? Is it, say, bigger or less than 50%? The Poisson approximation answers this question quickly and easily: in this special case, it amounts to the approximation $$\left( 1 - \frac{1}{100} \right)^{100} \approx e^{-1} \approx 0.368 \dots $$ which gives $$1 - \left( 1 - \frac{1}{100} \right)^{100} \approx 1 - e^{-1} \approx 0.632 \dots $$ so we get that the odds are about 63% that we'll succeed at least once, which is bigger than 50% but maybe smaller than you might hope. We learn something else too: the Poisson approximation tells us more generally that the odds of success are approximately a function of the product $np = \lambda$ only (which is the expected number of successes), so that e.g. if we had $p = \frac{1}{1000}$ and $n = 1000$ the answer would still be about 63%. This is valuable information and not entirely obvious from the exact answer, and knowing it saves you from having to recompute a bunch of binomials. Sometimes $n$ can get large enough that it would actually be infeasible to calculate the exact binomial answer. For example, suppose $n = 10^{25}, p = 10^{-25}$ ; numbers this big regularly appear in physics or chemistry since Avogadro's number is so large. I can confidently say that the answer is still about 63% even though it is no longer feasible to exactly calculate $(1 - p)^n$ (just try it!). The funny thing here is that the larger $n$ gets the harder it becomes to exactly compute the binomials, but the more accurate the Poisson approximation gets; for numbers this large it is for all intents and purposes basically exact.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3985873', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_376468
stackexchange
llm_judgeable_groundtruth_similarity
172014
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Importance of differential forms is obvious to any geometer and some analysts dealing with manifolds, partly because so many results in modern geometry and related areas cannot even be formulated without them: for example if you want to learn the definition of symplectic manifold, you must first learn what is differential form. However I have heard another opinion from people with non-geometric background (say, functional analysis, probability) that differential forms are probably used only in problems where they already appear in basic definitions (like symplectic geometry). When I taught an undergraduate course "Analysis on manifold" I had a feeling that my students might have got the same impression at the end: in the second half of the semester I developed calculus of differential forms with rather few concrete applications. Personally I am completely convinced in usefulness of differential forms, but find it not so easy to explain this to people who are not used to them. I would like to make a list of concrete applications of differential forms. Also it would be interesting to know historical reasons to introduce them. To start the list, below are some examples which come to my mind. 1) The general Stokes formula $\int_M d\omega=\pm \int_{\partial M}\omega$ generalizes all classical formulas of Green, Gauss, Stokes. 2) The Haar measure on a Lie group can be easily constructed as a translation invariant top differential form. (Some experts often prefer to consider this as a special case of a more general and more difficult fact of existence of Haar measure on locally compact groups. In that generality there is no such a simple and relatively explicit description of Haar measure as there is no language similar to differential forms.) 3) The cohomology of the de Rham complex of differential forms on a manifold is canonically isomorphic to singular cohomology (with real coefficients) of the manifold. One use of this isomorphism is that even Betti numbers of a symplectic manifold are non-zero. Another non-trivial use of this fact is the Hodge decomposition of the cohomology (with complex coefficients) of a compact Kahler manifold which makes it, in particular, a bi-graded algebra (rather than just graded) and provides new information on the Betti numbers, say $\beta_{2k+1}$ must be even. Now provide the response and nothing else.
In Chern-Weil Theory, characteristic classes appear as certain closed differential forms associated to vector bundles with connections (constructed via the curvature form of the connection). When you deal with Clifford bundles, e.g. spinors (which are an interesting thing to study from the physics perspective, I hear), there is Getzler's symbol map that sends Clifford elements to differential forms; in this sense, the Clifford Algebra appears as a "quantized version" of the Grassmann Algebra. When you follow the Heat Kernel Proof of the Atiyah-Singer Index Theorem, differential forms jump out of the semiclassical asymptotics of the heat kernel using Getzler's symbol mapping, and by some miracle, these are exactly the $\hat{A}$ genus and the Chern character, defined by Chern-Weil theory.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/172014', 'https://mathoverflow.net', 'https://mathoverflow.net/users/16183/']}
jdg_376469
stackexchange
llm_judgeable_groundtruth_similarity
835878
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We are developing a UI Control in WPF to be consumed within an existing Windows Forms / MFC application engine (Rhino 3D). The application engine exposes the ability create a "Dockbar" which essentially lets you put Windows Forms controls inside a child window which can dock to the Engines Interface. I am attempting to put a simple WPF TextBox inside an ElementHost control, which is added to the Dockbar. This appears to work fine at first glance; but after attempting to type into the TextBox only certain sequences actually show up in the TextBox. The DELETE , BACKSPACE , COPY , PASTE , and SELECTING TEXT work. If you type A-Z, 1-9, etc. those keys do not show up. I have SCOURED the net, and have heard about the ElementHost.EnableModelessKeyboardInterop() but this only applies to WPF Windows being created from the form. I am only creating WPF UserControls and hosting them in the ElementHost control. I saw a post which talked about the Dispatcher.Run(), and it sort of works but breaks the rest of the form: System.Windows.Threading.Dispatcher.Run(); The PreviewKeyUp , PreviewKeyDown , KeyUp , and KeyDown events all fire on the TextBox, but alas no text shows up in the TextBox. I don't know much about Windows Messages, but using WinSpector I noticed that no WM_GETTEXT messages were coming from the TextBox (if they even should be I don't know). I also create a new Windows Forms project and did the same thing in there and it works fine, so it must be an issue with how the windows are created and docked within the Rhino 3D engine. Here is the sample code which doesn't work: ElementHost el = new ElementHost();System.Windows.Controls.TextBox t = new System.Windows.Controls.TextBox();t.Width = 100;t.Text = "TEST";el.Child = t;panel1.Controls.Add(el); Now provide the response and nothing else.
I finally figured it out after 2 days of head scatching... The MFC Dialog window was taking the WM_CHAR messages and preventing the control from handling the input. So in order to prevent this, I hook the HwndSource and whenever I receive the WM_GETDLGCODE message I respond back with the types of input to accept, and then mark the event as handled. I created my own TextBox in order to prevent having to fix every textbox (see Below): /// <summary> /// Interop Enabled TextBox : This TextBox will properly handle WM_GETDLGCODE Messages allowing Key Input /// </summary> class IOTextBox : TextBox { private const UInt32 DLGC_WANTARROWS = 0x0001; private const UInt32 DLGC_WANTTAB = 0x0002; private const UInt32 DLGC_WANTALLKEYS = 0x0004; private const UInt32 DLGC_HASSETSEL = 0x0008; private const UInt32 DLGC_WANTCHARS = 0x0080; private const UInt32 WM_GETDLGCODE = 0x0087; public IOTextBox() : base() { Loaded += delegate { HwndSource s = HwndSource.FromVisual(this) as HwndSource; if (s != null) s.AddHook(new HwndSourceHook(ChildHwndSourceHook)); }; } IntPtr ChildHwndSourceHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (msg == WM_GETDLGCODE) { handled = true; return new IntPtr(DLGC_WANTCHARS | DLGC_WANTARROWS | DLGC_HASSETSEL); } return IntPtr.Zero; } }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/835878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13368/']}
jdg_376470
stackexchange
llm_judgeable_groundtruth_similarity
419051
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: It is always said that forward voltage drop in the diode is around 0.7 volts. LED also being a diode, why does it have a greater forward voltage drop of around 3 Volts? What is the model of LED that explains this higher voltage drop? Now provide the response and nothing else.
Different semiconductor junctions have different forward voltages (and reverse leakage currents, and reverse breakdown voltages, etc.) The forward drop of a typical small-signal silicon diode is around 0.7 volts. Same thing only germanium, around 0.3V. The forward drop of a PIN (p-type, intrinsic, n-type) power diode like a 1N4004 is more like a volt or more. The forward drop of a typical 1A power Schottky is something like 0.3V at low currents, higher for their design working currents. Band gap has a lot to do with it -- germanium has a lower band gap than silicon, which has a lower band gap than GaAs or other LED materials. Silicon carbide has a higher band gap yet, and silicon carbide Schottky diodes have forward drops of something like 2V (check my number on that). Aside from band gap, the doping profile of the junction has a lot to do with it, too -- a Schottky diode is an extreme example, but a PIN diode will generally have a higher forward drop (and reverse breakdown voltage) than a PN junction. LED forward drops range from about 1.5V for red LEDs to 3 for blue -- this makes sense because the LED mechanism is basically to generate one photon per electron, so the forward drop in volts has to be equal to or more than the energy of the emitted photons in electron-volts.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/419051', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/176095/']}
jdg_376471
stackexchange
llm_judgeable_groundtruth_similarity
237377
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a better way to do this? string[] s = {"zero", "one", "two", "three", "four", "five"};var x = s.Select((a,i) => new {Value = a, Index = i}).Where(b => b.Value.StartsWith("t")).Select(c => c.Index); i.e. I'm looking for a more efficient or more elegant way to get the positions of the items matching the criteria. Now provide the response and nothing else.
You could easily add your own extension method: public static IEnumerable<int> IndexesWhere<T>(this IEnumerable<T> source, Func<T, bool> predicate){ int index=0; foreach (T element in source) { if (predicate(element)) { yield return index; } index++; }} Then use it with: string[] s = {"zero", "one", "two", "three", "four", "five"};var x = s.IndexesWhere(t => t.StartsWith("t"));
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/237377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1463/']}
jdg_376472
stackexchange
llm_judgeable_groundtruth_similarity
24413088
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This is a question regarding how Storm's max spout pending works. I currently have a spout that reads a file and emits a tuple for each line in the file (I know Storm is not the best solution for dealing with files but I do not have a choice for this problem). I set the topology.max.spout.pending to 50k to throttle how many tuples get into the topology to be processed. However, I see this number not having any effect in the topology. I see all records in a file being emitted every time. My guess is this might be due to a loop I have in the nextTuple() method that emits all records in a file. My question is: Does Storm just stop calling nextTuple() for the Spout task when topology.max.spout.pending is reached? Does this mean I should only emit one tuple every time the method is called? Now provide the response and nothing else.
Exactly! Storm can only limit your spout with the next command, so if you transmit everything when you receive the first next, there is no way for Storm to throttle your spout. The Storm developers recommend emitting a single tuple with a single next command. The Storm framework will then throttle your spout as needed to meet the "max spout pending" requirement. If you're emitting a high number of tuples, you can batch your emits to at most a tenth of your max spout pending, to give Storm the chance to throttle.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24413088', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2375963/']}
jdg_376473
stackexchange
llm_judgeable_groundtruth_similarity
17100137
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 not really sure whether the format of this question is good for this site. Basically, does anyone know what has convinced Apple to make the design decision that NSManagedObjectID changes whenever you save the data to the persistent store? I might be wrong, but that decision sounds quite questionable to me.There is no clear advantage (it's an UUID! It is unique!), and yet it makes passing objectID's --- it can change under your feet at any time when the object is saved. It is a big problem for me because I use three MOC system (background MOC -> UI MOC -> Persistent MOC), objects are inserted into the background MOC and propagated upwards with a save. The save is asynchronous, as it has to propagate over three different MOCs and returning objects after they were created, yet before they are saved to the persistent store is quite painful, as I can't rely on passing objectID around. Am I doing something particularly wrong? Does anyone know what is the advantage of UUID being mutable anytime with no notification? My biggest question is why temporary managedObjectID is offered at all. Is there any point in it at all? Is it just to confuse people into attempting to use it? Now provide the response and nothing else.
I'm a little confused why you keep saying the NSManagedObjectID is specifically a UUID. The URI representation may have a similar appearance to the UUID format, but I don't see anywhere in the docs that it says that "a NSManagedObjectID is a UUID" (and as I'll discuss below, it is more than that). Why exactly Apple designed it this way is beyond the scope of StackOverflow, so hopefully your question is really "what is Core Data's design, and how do I work with it?" What the docs say (in Managed Object IDs and URIs ) is that if you want to do this kind of object tracking, you should add your own UUID as a property: You can sometimes benefit from creating your own unique ID (UUID) property which can be defined and set for newly inserted objects. This allows you to efficiently locate specific objects using predicates (though before a save operation new objects can be found only in their original context). The reason that the NSManagedObjectID changes can be seen from the immutable data structure. It includes a persistentStore property. This cannot be known for certain until you actually save the object (you might call assignObject:toPersistentStore: for instance). Again, don't think of the NSManagedObjectID in terms of its URI representation; that's just a serialization format. The real ID includes the persistent store, as indicated in the docs: Like the primary key in the database, an identifier contains the information needed to exactly describe an object in a persistent store , although the detailed information is not exposed. That identifier cannot be finalized until the object is inserted.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17100137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/429546/']}
jdg_376474
stackexchange
llm_judgeable_groundtruth_similarity
242762
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: In [FSIT] and [OIMT] it is claimed that there is a surjection from $P(\kappa)\cap J^{\vec E}_{\nu(E_\alpha)}\times[\nu(E_\alpha)]^{<\omega}$ onto $\alpha$, and that this surjection lies in $J_{\alpha+1}^{\vec E}$. It is stated as a rather trivial fact, but I'm having trouble with seeing how this map should look like. Here $\nu(E_\alpha)$ is the natural length of the $(\kappa,\alpha)$ pre-extender $E_\alpha$ and $\vec E$ is a fine extender sequence, the definition of which can be found in [OIMT] at page 11. Since $E_\alpha$ is the trivial completion of $E_\alpha\upharpoonright\nu(E_\alpha)$ I can see that $\nu(E_\alpha)$ somehow "carries enough information" to determine $\alpha$, but this vague analogy just doesn't give me anything concrete. Of course, if a given surjection is found and is shown to be definable over $J_\alpha^{\vec E}$, then it's in $J_{\alpha+1}^{\vec E}$. Thanks in advance! References: [FSIT] "Fine structure and iteration trees" by Steel and Mitchell [OIMT] "Outline of inner model theory" in the handbook, by Steel (preprint at https://math.berkeley.edu/~steel/papers/steel1.pdf ) Now provide the response and nothing else.
We know that $\alpha = (\nu^{+})^{Ult(J^{\vec{E}}_{\alpha}, E_{\alpha})}$ and that $i_{E_{\alpha}} (\kappa) > \nu$, where $i_{E_{\alpha}}$ denotes the ultrapower embedding. Thus working in $Ult(J^{E_{\alpha}}_{\alpha}, E_{\alpha})$ any $\beta <\nu^{+}=\alpha$ can be represented in the ultrapower $Ult(J^{\vec{E}}_{\alpha}, E_{\alpha})$ using a function $f: [\kappa]^{|a|} \rightarrow \kappa$, for some $a \in [\nu]^{<\omega}$ and $f \in J^{E_{\alpha}}_{\alpha}$. Thus we have a surjection from $(P(\kappa) \cap J^{E_{\alpha}}_{\alpha}) \times [\nu]^{<\omega}$ onto $\alpha$, via just looking at the representatives of ordinals less than $\alpha$ in the ultrapower.But the ultrapower can be constructed in $J^{\vec{E}}_{\alpha +1}$ as it has all the information. So $\alpha$ can not be a cardinal in $J^{\vec{E}}_{\alpha +1}$.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/242762', 'https://mathoverflow.net', 'https://mathoverflow.net/users/38602/']}
jdg_376475
stackexchange
llm_judgeable_groundtruth_similarity
478021
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: Source: p. 69. How to Prove It by Daniel Velleman. I already read 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 & 12 . $\exists \, x \, \in \, \emptyset : P(x) \tag{1}$ will be false no matter what the statement $P(x)$ is. There can be nothing in $\emptyset$ that, when plugged in for $x$, makes $P(x)$ come out true, because there is nothing in $\emptyset$ at all! It may not be so clear whether $\forall \, x \, \in \,\emptyset : P(x) $ should be considered true or false ... I then paused reading to conjecture the truth value of: $2. \; \forall \, x \, \in \,\emptyset : P(x). $ $\boxed{\text{Conjecture :}}$ Because $\emptyset$ contains nothing, ergo $x \, \in \,\emptyset$ is false $\implies \forall \, x \, \in \,\emptyset $ is false. Since the Truth Value of $P(x)$ is unknown, ergo 2 is false. $\blacksquare$ Then I continued reading and was stupefied to learn that 2 is true: After expanding the abbreviation of the quantifiers, $\forall \, x \, \in \,\emptyset : P(x) \quad \equiv \quad \forall \, x \, \left[\, x \, \in \,\emptyset \Longrightarrow P(x)\right]. \tag{*}$ Now according to the truth table for the conditional connective, the only way this can be false is if there is some value of $x$ such that $x \, \in \,\emptyset $ is true but $P(x)$ is false. But there is no such value of $x$, simply because there isn’t a value of $x $ for which $x \, \in \,\emptyset $ is true. Thus, (*) is (vacuously) true. Though I understand this proof and the Principle of Explosion, I still do not understand why my intuition failed. How can I correct my intuition? Supplement to mercio's Answer I understand $\forall x \in \emptyset,P(x). \; \stackrel{dfn}{\equiv} \; \forall x, \color{#B22222}{x\in \emptyset}\implies P(x). \quad \equiv \; \forall x,\color{#B22222}{false}\implies P(x)$. Consider $3. \forall\;\bbox[5px,border:2px solid #32CD32]{\, \color{#B22222}{\underbrace{{x\in\emptyset}}_{false}} \;,P(x)} \;$. 3. Is 3 vacuously true because the green box is vacuously true? I consider the green box above a statement, because though the comma is not a Logical Connective, $ \forall \; \color{#B22222}{\underbrace{{x\in\emptyset}}_{false}} \; \;P(x) \quad \equiv \quad \forall \; \color{#B22222}{\underbrace{{x\in\emptyset}}_{false}} \; \color{#0073CF}{\huge{,}} \;P(x) \quad \equiv \quad \forall \; \color{#B22222}{\underbrace{{x\in\emptyset}}_{false}} \; \color{#0073CF}{{\huge{\text{,}}} \text{we have that}} \; P(x). \tag{**}$ Now provide the response and nothing else.
You are right when you say that $\forall x$, the statement $x \in \emptyset$ is false. This means that $\forall x, \neg (x \in \emptyset)$, which is equivalent to $\forall x, x \notin \emptyset$. Perfectly true. Then you say "the statement $\forall x \in \emptyset$ is false". $\forall x \in \emptyset$ is NOT a statement, it's an incomplete sentence. Either you write "$\forall x, P(x)$", either you write "$\forall x \in X, P(x)$", which is a shorthand for "$\forall x, (x \in X \implies P(x))$". "$\forall x \in \emptyset$" is not a statement. It can't be true or false. $\forall x \in \emptyset, P(x)$ is a shorthand for $\forall x, (x \in \emptyset \implies P(x))$, which is equivalent (since $x \in \emptyset$ is always false) to $\forall x, ~\textrm{false} \implies P(x)$. After looking at the truth table for $\implies$, this is equivalent to $\forall x, ~\textrm{true}$ (whatever $P(x)$ may be), which is $\textrm{true}\;.$ If you want to disprove $\forall x \in \emptyset, P(x)$ you have to show me an $x \in \emptyset$ such that $P(x)$ is false. Well you will never find an $x \in \emptyset$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/478021', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_376476
stackexchange
llm_judgeable_groundtruth_similarity
5203150
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an Excel 2007 spreadsheet that I edit with the OpenXML SDK 2.I remove some rows etc.I would like to know how to save that Spreadsheetdocument to another filename. Now provide the response and nothing else.
To my knowledge there is no built in way to change the filename, but since one way to edit the file is to use streams you can easily give the name of the file you want when writing out the contents of a stream: byte[] byteArray = File.ReadAllBytes("C:\\temp\\oldName.xltx");using (MemoryStream stream = new MemoryStream()){ stream.Write(byteArray, 0, (int)byteArray.Length); using (SpreadsheetDocument spreadsheetDoc = SpreadsheetDocument.Open(stream, true)) { // Do work here } File.WriteAllBytes("C:\\temp\\newName.xlsx", stream.ToArray()); } There are other ways to change the name as well, like when returning the file to a user in an ASP.NET MVC web application, but it depends on what you are trying to do.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5203150', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/143540/']}
jdg_376477
stackexchange
llm_judgeable_groundtruth_similarity
9986734
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The android documentation has the following options below but does not explain what circumstances each is best for. What are the pros and cons of each method? e.g. Under what conditions would SQL be better than Shared Preferences? Shared Preferences Internal Storage External Storage SQLite Databases Network Connection Now provide the response and nothing else.
Different Storage options in Android Content Providers Consider the structured data added to the device from application1 isnot accessible to another application2 present in the same device butthe profile photo added to the device by application1 is available tothe application2 running in the same device Consider android device as a city, the applications in it are thehouses in the city, people in the houses(application) are the data.Now content provider is like an broker in the city(android device).This broker provide access for the people in the city for findingdifferent houses referring as the content provider in the androiddevice provide access for the data in the device for differentapplications. Shared Preferences Consider I have an App say a Face book App which I use to log in tomy account. Now the very first time I enter my username and password to getaccess to my account. Say I log out of the application an hour lateragain I use the same Face book App to login again to my application. I have to enter username and password again to login to my accountand I set a theme to my application and other settings on how my applooks in my current phone This is un-necessary because consider I am using my phone to login tothe application. So I will always use my phone to login again andagain, thus entering my credentials again and again is more workshows it’s not a user friendly app Shared Preferences is very handy in such scenarios where I can useits feature to share my data in a xml file Which physically exists inthe Android app installed in my phone which is not destroyed even ifthe app is closed. Here we can save user preferences data of thecurrent application. As a result next time I open my app in my phone I can see the dataautomatically filled in the necessary fields and the settings are File Storage In Android we can use the device storage space to store the data init for the applications. The type of data involves things such as atext file, image file, video file, audio file etc. As seen in the figure as we can see that there are two places we cando this. One way is to write the raw files into primary /secondarystorage. Another way is to write the cache files into theprimary/secondary storage. There is also difference between storing raw data and the cache data,the raw data once stored in memory by user has to be explicitlydeleted by the user explicitly otherwise it would exist till then.Cache data stored in memory is not a permanent data because thesystem automatically deletes it if it feels there is shortage ofmemory. Internal Storage: Consider a user in an application has stored data in internalstorage, then only that user of that application has access to thatdata on the mobile and that data is automatically deleted when theuser uninstalls the application. Speaking of which internal memory isprivate. The apps internal storage directory is stored using the name packagename in a special place in the android file system. Other apps or users of current app have no access to the file set bya particular user and a particular app unless it is explicitly madeavailable to the user for readable/writable access. SQLite Sqlite is used to store more structured data locally in a mobilewhere the android app is running. Structured data involves as ofwhich shown in the figure like a student’s information in the form ofrows and columns. Sqlite offers similar functionality like Mysql and oracle but withlimited functional features. Some of the things involve performingquery operations on tables. There are features though like creatingviews but also some features are not available like stored procedure. Sqlite is very helpful in storing complex and large data which can bedownloaded once and can be used again and again until the applicationis running. When the application is closed the sqlite database isalso destroyed. Putting all the pieces together
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9986734', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/957245/']}
jdg_376478
stackexchange
llm_judgeable_groundtruth_similarity
52240972
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 tried to implement the Stringer interface on my type as follow: package mainimport ( "fmt")type IPAddr [4]byte// TODO: Add a "String() string" method to IPAddr.func (o IPAddr) String() string { return fmt.Sprintf("%v.%v.%v.%v", o[0], o[1], o[2], o[3])}func main() { hosts := map[string]IPAddr{ "loopback": {127, 0, 0, 1}, "googleDNS": {8, 8, 8, 8}, } for name, ip := range hosts { fmt.Printf("%v: %v\n", name, ip) fmt.Printf("%v\n", ip.String()) }} In the code above, I used a value receiver to implement the String() method. The Printf recognised my implementation and called the correct String function on my type. Output: googleDNS: 8.8.8.88.8.8.8loopback: 127.0.0.1127.0.0.1 Then I updated my code to use pointer receiver: func (o *IPAddr) String() string { return fmt.Sprintf("%v.%v.%v.%v", o[0], o[1], o[2], o[3])} The output of the updated code: loopback: [127 0 0 1]127.0.0.1googleDNS: [8 8 8 8]8.8.8.8 The Printf method didn't call my String method anymore. The output told me that Printf use the default String method of the type. However, when I called ip.String() , my method was used. Can someone explain to me this behaviour, please? As far as I know, we can implement methods of interfaces by both value and pointer receivers. Thank you. Now provide the response and nothing else.
The %v conversion specifier will read any method satisfying the Stringer interface. For this to happen, however, that method must exist in the method set of the value. For a value of type T , its method set contains any methods that receive a value of that type T : func (t T) Foo() // in the method set of Tfunc (t *T) Bar() // not in the method set of T For a pointer of type *T , its method set contains both methods that receive a value of type T and a pointer of type *T : func (t T) Foo() // in the method set of *Tfunc (t *T) Bar() // in the method set of *T In main , you have a value identified as ip with type IPAddr , so the first set of commented code above applies. Your first example will work because the method receiver of the String method has type IPAddr . In the second example, the method receiver of the String method has type *IPAddr , which means it's not in the method set of ip , which has type IPAddr . In summary: | String() Method | fmt.Print, fmt.Printf, etc. Input Type | Receiver | calls String() implicitly ========== | =============== | =========================== *IPAddr | IPAddr | Yes | *IPAddr | Yes ---------- + --------------- + --------------------------- IPAddr | IPAddr | Yes | *IPAddr | No You might be wondering why this occurs. It turns out that some values might not be addressable, so a method receiver with type *IPAddr can't receive a value that has no address. For example, try executing IPAddr{}.String() with an *IPAddr method receiver. It will fail to compile because a literal value has no address. If you instead used (&IPAddr{}).String() , it would work because now you have a pointer *IPAddr created using &IPAddr{} , and if you used a non-pointer receiver IPAddr , then it would work whether the IPAddr was addressable or not.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52240972', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1399505/']}
jdg_376479
stackexchange
llm_judgeable_groundtruth_similarity
20933509
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 c++ and Qt and I am trying to initialize a QVector, which is a class member in a class initialization list like: MyClass::MyClass(QWidget *parent) : QMainWindow(parent) , myVector(QVector<double>(100)) I was expecting the QVector to have already 100 indexes alocated, but when I try to read myVector[0] I get an assertion error saying "Unhandled exception at 0x0143bf77 in test.exe: 0xC0000005: Access violation reading location 0x00000004." and the program stops at this line of Qt: inline T &QVector<T>::operator[](int i){ Q_ASSERT_X(i >= 0 && i < d->size, "QVector<T>::operator[]", "index out of range"); return data()[i]; } Which I believe shows that I am trying to access members that arent allocated yet, so I guess I am not using the initialization list properly. I could make it a pointer and make a new QVector(100) in the constructor but I want to learn what's wrong and how may I make it correct. Now provide the response and nothing else.
You are probably doing something wrong unshown because the following code works fine for me, and it should by design . Note that for the first element, you could use the convenience first method . main.cpp #include <QVector>#include <QDebug>int main(){ QVector<double> myVector(QVector<double>(100)); qDebug() << "TEST FIRST:" << myVector.first(); return 0;} main.pro TEMPLATE = appTARGET = mainSOURCES += main.cpp Output TEST FIRST: 0 As I noted in the comment, you could use the reserve method . void QVector::reserve(int size) Attempts to allocate memory for at least size elements. If you know in advance how large the vector will be, you can call this function, and if you call resize() often you are likely to get better performance. If size is an underestimate, the worst that will happen is that the QVector will be a bit slower. The sole purpose of this function is to provide a means of fine tuning QVector's memory usage. In general, you will rarely ever need to call this function. If you want to change the size of the vector, call resize(). So, you would be writing something like this: MyClass::MyClass(QWidget *parent) : QMainWindow(parent){ myVector.reserve(100);} However, as I also noted later in the comment, the simple constructor should also work like: MyClass::MyClass(QWidget *parent) : QMainWindow(parent) , myVector(100){} What you are doing is invoking the copy constructor (although for an implicitly shared class), so it may be negligibly slower. It is at least more code than you need.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20933509', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1227166/']}
jdg_376480
stackexchange
llm_judgeable_groundtruth_similarity
40959275
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 getting the following error message <faultcode>soap-env:Client.InvalidSecurityToken</faultcode><faultstring>Invalid or Expired binary security token: null</faultstring><detail><StackTrace>com.sabre.universalservices.base.security.AuthenticationException: errors.session.USG_INVALID_SECURITY_TOKEN</StackTrace></detail></soap-env:Fault></soap-env:Body></soap-env:Envelope> The following is my request to the hotels availability API. <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header> <eb:MessageHeader xmlns:eb="http://www.ebxml.org/namespaces/messageHeader" SOAP-ENV:mustUnderstand="0"> <eb:From> <eb:PartyId eb:type="urn:x12.org:IO5:01">client</eb:PartyId> </eb:From> <eb:To> <eb:PartyId eb:type="urn:x12.org:IO5:01">ws</eb:PartyId> </eb:To> <eb:CPAId>'.$pcc.'</eb:CPAId> <eb:ConversationId>YourConversationId</eb:ConversationId> <eb:Service eb:type="sabreXML"></eb:Service> <eb:Action>OTA_HotelAvailLLSRQ</eb:Action> </eb:MessageHeader> <Security xmlns:ns6="http://schemas.xmlsoap.org/ws/2002/12/secext" SOAP-ENV:mustUnderstand="0"> <BinarySecurityToken>'.$sabreKey.'</BinarySecurityToken> </Security> </SOAP-ENV:Header> <SOAP-ENV:Body> <eb:OTA_HotelAvailRQ xmlns:eb="http://webservices.sabre.com/sabreXML/2003/07" TimeStamp="2011-01-26T12:30:00-06:00" Version="1.10.1"> <eb:POS> <eb:Source PseudoCityCode="'.$pcc.'" /></eb:POS> <eb:AvailRequestSegments> <eb:AvailRequestSegment> <eb:StayDateRange Start="12-10" End="12-15" /> <eb:RoomStayCandidates> <eb:RoomStayCandidate> <eb:GuestCounts> <eb:GuestCount Count="1" /></eb:GuestCounts> </eb:RoomStayCandidate> </eb:RoomStayCandidates> <eb:HotelSearchCriteria xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="eb:HotelSearchCriteria_type0"> <eb:Criterion> <eb:HotelRef HotelCityCode="DFW" /></eb:Criterion> </eb:HotelSearchCriteria> </eb:AvailRequestSegment> </eb:AvailRequestSegments> </eb:OTA_HotelAvailRQ> </SOAP-ENV:Body></SOAP-ENV:Envelope> Here's What I did before making the request to the hotel availability API. I received my wsse:BinarySecurityToken from SessionCreateRQ stored the variable containing the token into. <BinarySecurityToken>'.$sabreKey.'</BinarySecurityToken> Why am I getting this error message my credentials are correct. BTW I have production credentials. Thanks I'm looking forward to some help Now provide the response and nothing else.
As already mentioned in the comments, a Double cannot storethe value 1.1 exactly. Swift uses (like many other languages)binary floating point numbers according to the IEEE 754 standard. The closest number to 1.1 that can be represented as a Double is 1.100000000000000088817841970012523233890533447265625 and the closest number to 2.3 that can be represented as a Double is 2.29999999999999982236431605997495353221893310546875 Printing that number means that it is converted to a string witha decimal representation again, and that is done with differentprecision, depending on how you print the number. From the source code at HashedCollections.swift.gyb one can see that the description method of Dictionary uses debugPrint() for both keys and values, and debugPrint(x) prints the value of x.debugDescription (if x conforms to CustomDebugStringConvertible ). On the other hand, print(x) calls x.description if x conformsto CustomStringConvertible . So what you see is the different output of description and debugDescription of Double : print(1.1.description) // 1.1print(1.1.debugDescription) // 1.1000000000000001 From the Swift source code one can seethat both use the swift_floatingPointToString() function in Stubs.cpp , with the Debug parameter set to false and true , respectively.This parameter controls the precision of the number to string conversion: int Precision = std::numeric_limits<T>::digits10;if (Debug) { Precision = std::numeric_limits<T>::max_digits10;} For the meaning of those constants, see std::numeric_limits : digits10 – number of decimal digits that can be represented without change, max_digits10 – number of decimal digits necessary to differentiate all values of this type. So description creates a string with less decimal digits. Thatstring can be converted to a Double and back to a string givingthe same result. debugDescription creates a string with more decimal digits, so thatany two different floating point values will produce a different output.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40959275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4967393/']}
jdg_376481
stackexchange
llm_judgeable_groundtruth_similarity
223750
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 pretty sure stackoverflow.com is created with ASP.NET, but no matter where I click I see no .aspx extension in the address bar.How it is done and is there a particular reason for this? Now provide the response and nothing else.
In the case of stackoverflow, they use ASP.NET MVC rather than ASP.NET web forms. With web forms, the url is pointing to a file on your disk, while MVC is pointing to a controller action. If you're using webforms, you'd want to use URL rewriting. Scott Guthrie has a good article on doing URL rewriting.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/223750', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/28098/']}
jdg_376482
stackexchange
llm_judgeable_groundtruth_similarity
45456428
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an excel macro used to manage button visibility in Excel in the "Worksheet_Change" function based from another SO question here . The problem is the although the macro works it makes updating the Excel sheet rather laggy. I have managed to pin down the slowness to a single line: Set rUpdated = Range(Target.Dependents.Address) This sets the range of cells updated to a variable to be iterated through later in the script. If I call a script with just this line I found this is where all the delay is. It seems a rather simple line, but is there a better way to do it? Full disclosure: Private Sub Worksheet_Change(ByVal Target As Range) Dim rUpdated As Range Dim shp As Shape Dim rCell As Range Set rUpdated = Range(Target.Dependents.Address) If Not rUpdated Is Nothing Then For Each rCell In rUpdated If rCell.Column = 1 Then 'Look at each shape in the sheet and cross-reference with rCell. For Each shp In Target.Parent.Shapes If shp.TopLeftCell.Row = rCell.Row Then shp.Visible = (rCell.Value <> "") Exit For 'Exit the loop - the correct button has been found. End If Next shp End If Next rCell End IfEnd Sub Now provide the response and nothing else.
It looks like inputs suffers from the same issue as slurp. I don't know how to accomplish this with jq on huge files, but sed can do it: sed '1s/^/[/; $!s/$/,/; $s/$/]/' in.json > out.json Output: [{"Header":{"AssetClass":"Commodities","InstrumentType":"Forward","UseCase":"Forward","Level":"InstRefDataReporting"},"Attributes":{"NotionalCurrency":"EUR","ExpiryDate":"2018-01-01","ReturnorPayoutTrigger":"Contract for Difference (CFD)","DeliveryType":"CASH","BaseProduct":"AGRI","TransactionType":"FUTR","FinalPriceType":"ARGM","ReferenceRate":"10PPM ULTRA LOW SULPHUR DIESEL-CARGOES CIF NWE/BASIS ARA-PLATTS EUROPEAN","SubProduct":"GROS","AdditionalSubProduct":"FWHT"},"ISIN":{"ISIN":"EZX27M86B860","Status":"New"},"TemplateVersion":1,"Derived":{"CommodityDerivativeIndicator":"TRUE","UnderlyingAssetType":"Agriculture","IssuerorOperatoroftheTradingVenueIdentifier":"NA","PriceMultiplier":1,"FullName":"Commodities Forward AGRI GROS FWHT EUR 20180101","ShortName":"NA/Fwd AGRI FWHT EUR 20180101","ClassificationType":"JTAXCC"}},{"Header":{"AssetClass":"Commodities","InstrumentType":"Swap","UseCase":"Basis_Swap","Level":"InstRefDataReporting"},"Attributes":{"NotionalCurrency":"SOS","ExpiryDate":"2208-12-10","ReturnorPayoutTrigger":"Total Return","DeliveryType":"OPTL","TransactionType":"ORIT","FinalPriceType":"IHSM","ReferenceRate":"NATURAL GAS-MONTHLY INDEX S. TEXAS (TETCO)-GAS DAILY PRICE GUIDE","OtherReferenceRate":"NATURAL GAS-MONTHLY INDEX W. LOUISIANA (TETCO)-GAS DAILY PRICE GUIDE","BaseProduct":"OTHR","OtherBaseProduct":"OTHR","SubProduct":"","AdditionalSubProduct":"","OtherSubProduct":"","OtherAdditionalSubProduct":""},"ISIN":{"ISIN":"EZBBH1XR9GV6","Status":"New"},"TemplateVersion":1,"Derived":{"CommodityDerivativeIndicator":"TRUE","UnderlyingAssetType":"Multi Commodity","IssuerorOperatoroftheTradingVenueIdentifier":"NA","PriceMultiplier":1,"FullName":"Commodities Swap Basis_Swap OTHR OTHR SOS 22081210","ShortName":"NA/Swap OTHR SOS 22081210","ClassificationType":"STQTXE"}},{"Header":{"AssetClass":"Commodities","InstrumentType":"Swap","UseCase":"Multi_Exotic_Swap","Level":"InstRefDataReporting"},"Attributes":{"NotionalCurrency":"LRD","ExpiryDate":"2200-01-31","ReturnorPayoutTrigger":"Contract for Difference (CFD)","DeliveryType":"CASH","TransactionType":"TAPO","FinalPriceType":"EXOF","UnderlyingInstrumentIndex":["BCOMF6","BCOMNG3"]},"ISIN":{"ISIN":"EZ286HJVY4Q2","Status":"New"},"TemplateVersion":1,"Derived":{"CommodityDerivativeIndicator":"TRUE","IssuerorOperatoroftheTradingVenueIdentifier":"NA","PriceMultiplier":1,"UnderlyingAssetType":"Multi Commodity","BaseProduct":"MCEX","SubProduct":"","AdditionalSubProduct":"","FullName":"Commodities Multi_Exotic_Swap MCEX LRD 22000131","ShortName":"NA/Swap MCEX LRD 22000131","ClassificationType":"STQCXC"}},{"Header":{"AssetClass":"Commodities","InstrumentType":"Option","UseCase":"Option","Level":"InstRefDataReporting"},"Attributes":{"NotionalCurrency":"TND","ExpiryDate":"2209-10-18","OptionType":"OPTL","OptionExerciseStyle":"AMER","ValuationMethodorTrigger":"Asian","DeliveryType":"CASH","TransactionType":"OTHR","FinalPriceType":"IHSM","ReferenceRate":"NATURAL GAS-NGPL (NICOR, NIPSCO, PGLC CITYGATE), NBPL-NICOR-ICE/10X MONTHLY","BaseProduct":"OTHR","SubProduct":"","AdditionalSubProduct":""},"ISIN":{"ISIN":"EZ2TK5CWL9Y4","Status":"New"},"TemplateVersion":1,"Derived":{"CommodityDerivativeIndicator":"TRUE","UnderlyingAssetType":"Other","IssuerorOperatoroftheTradingVenueIdentifier":"NA","PriceMultiplier":1,"FullName":"Commodities Option OTHR TND 22091018","ShortName":"NA/O OTHR OPTL TND 22091018","ClassificationType":"HTMHAC"}},{"Header":{"AssetClass":"Commodities","InstrumentType":"Option","UseCase":"Multi_Exotic_Option","Level":"InstRefDataReporting"},"Attributes":{"NotionalCurrency":"SOS","ExpiryDate":"2209-10-18","UnderlyingInstrumentIndex":["BCOMSI2","BCOMPR3T"],"OptionType":"CALL","OptionExerciseStyle":"AMER","ValuationMethodorTrigger":"Other Path Dependent","DeliveryType":"CASH","TransactionType":"ORIT","FinalPriceType":"BLTC"},"ISIN":{"ISIN":"EZ82L36B6225","Status":"New"},"TemplateVersion":1,"Derived":{"CommodityDerivativeIndicator":"TRUE","IssuerorOperatoroftheTradingVenueIdentifier":"NA","PriceMultiplier":1,"UnderlyingAssetType":"Multi Commodity","BaseProduct":"MCEX","SubProduct":"","AdditionalSubProduct":"","FullName":"Commodities Multi_Exotic_Option MCEX SOS 22091018","ShortName":"NA/O MCEX Call SOS 22091018","ClassificationType":"HTQBPC"}}] Explanation The sed script consists of three separate substitutions. Here they are on separate lines: 1 s/^/[/ # Insert a left bracket at the beginning of the first line$! s/$/,/ # On all but the last line append a comma$ s/$/]/ # Append a right bracket to the last line
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45456428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2135406/']}
jdg_376483
stackexchange
llm_judgeable_groundtruth_similarity
4009439
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking for a simple example for camera access in Linux using V4L2.Where I can find it? As simple, as possible. Thanks, Now provide the response and nothing else.
Try the uvccapture code here -> http://staticwave.ca/source/uvccapture/ It is very small yet very concrete example which makes use of all the V4l2 concepts (open,set format, allocate memory, Request Buffer, Dqbuffer and Query-buffer - all intems of ioclts). uvcgrab () function is the one to look for which makes use of Dqbuffer and Query-buffer. ioctl (vd->fd, VIDIOC_DQBUF, &vd->buf);ioctl (vd->fd, VIDIOC_QBUF, &vd->buf) While Studying it you can keep looking for the ioctl definition in this link which will ease your understanding.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4009439', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/136834/']}
jdg_376484
stackexchange
llm_judgeable_groundtruth_similarity
473980
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 know that for uniformly distributed random variables $X_1,X_2,\dots,X_n$ $\in \mathcal{R}$ , the p.d.f. is given by: $f(x_i) = 1/θ$ ; if $0≤x_i≤θ$ $f(x) = 0$ ; otherwise If the uniformly distributed random variables are arranged in the following order $0≤X_1≤X_2≤X_3\dots ≤X_n≤θ$ , I understand that the likelihood function is given by $L(θ)=\prod_{i=1}^{n}f(x_i)=θ^{−n}$ The log-likelihood is: $\ln L(θ)=−n\ln(θ)$ Setting its derivative with respect to parameter $\theta$ to zero, we get: $\frac{\mathrm d}{\mathrm d\theta}\ln L(\theta)=-n\theta$ which is $< 0$ for $θ > 0$ Hence, $L(θ)$ is a decreasing function and it is maximized at $θ = X_{(n)}$ The maximum likelihood estimate is thus $\hat{θ} = X_{(n)}$ My question is:—what if I find the supremum to solve this? Now provide the response and nothing else.
The result is correct, but the reasoning is somewhat inaccurate. You need to keep track of the property that the density is zero outside $[0,\theta]$ . This implies that the likelihood is zero to the left of the sample maximum, and jumps to $\theta^n$ in the maximum. It indeed decreases afterwards, so that the maximum is the MLE. This also entails that the likelihood is not differentiable in this point, so that finding the MLE via the "canonical" route of the score function is not the way to go here. A more detailed formal derivation is, e.g., given here
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/473980', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/288616/']}
jdg_376485
stackexchange
llm_judgeable_groundtruth_similarity
100380
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Maybe a noob question. I've tried searching but maybe my search terms were too specific. I've just conducted a pen test on a client's site. The site allowed me to download .htaccess just by simply browsing to directory where it was stored; www.example.com/dir/.htaccess What causes this and how can it be remediated? Now provide the response and nothing else.
It depends on the type of the webserver in question.If it's Apache 2.2, it should contain something like this in the config file (usually in the "main" apache.conf): <Files ~ "^\.ht"> Order allow,deny Deny from all Satisfy all</Files> If it's missing, that can cause the problem you described. The other typical cause of this is that the client have used Apache in the past, but switched to something else (e.g. Nginx) which does not use .htaccess and hence doesn't treat it in a special way. The solution in this case is webserver-specific, but it usually boils down to restricting access to files beginning with ".ht", or - if they are really not used - you can simply delete them.
{}
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/100380', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/86895/']}
jdg_376486
stackexchange
llm_judgeable_groundtruth_similarity
41965793
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After we are moving over to html5 and many browsers like Google chrome bans VLC web plugin. ... Is there any way to play h.264 / h.265 Rtsp streams in browsers this days? Now provide the response and nothing else.
Direct RTSP streaming is still not supported by browsers, if you have to play an RTSP stream in the browser then you need a proxy server that will convert RTSP to HTTP stream. Many open source projects are there that will do the work of RTSP to HTTP conversion or you can use FFmpeg (used by VLC) to convert RTSP to HTTP and then can stream it on the browser.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41965793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2837987/']}
jdg_376487
stackexchange
llm_judgeable_groundtruth_similarity
870634
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This may be more of an OOP concept question, but here's what I'd like to do. I have an application that outputs debug information using System.Diagnostics.Trace.WriteLine so it can be viewed with DebugView. I'd like to override/extend (not sure of the proper terminology) this method to log the text to a file instead, or maybe in addition to the Trace output. This would allow me to write a new WriteLine method for my app, and I could leave all my other System.Diagnostics.Trace.WriteLine statements unchanged throughout the rest of the application. So how would I go about changing the behavior of this method within my VB.Net app? Now provide the response and nothing else.
Are you absolutely committed to still using Trace? If not, I'd use a more fully-featured logging system such as Log4Net . However, if you really want to use Trace then you can reconfigure the TraceListener s used with an app.config file. The TraceListener MSDN docs give an example somewhat like this: <configuration> <system.diagnostics> <trace autoflush="false" indentsize="4"> <listeners> <add name="fileLogger" type="System.Diagnostics.TextWriterTraceListener" initializeData="LogFile.log" /> <remove name="Default" /> </listeners> </trace> </system.diagnostics></configuration> TextWriterTraceListener will dump logs to the given file. (There are other options available too.) Alternatively, you can do this programmatically: Trace.Listeners.Add(new TextWriterTraceListener("foo.log")); Note that you may need to explicitly flush the traces before your app exits, either with: Trace.Flush(); or the more complicated: foreach (TraceListener listener in Trace.Listeners){ listener.Flush();} (I only mention it because I had to when testing this!) EDIT: As noted in comments, if you're happy for the listener to be flushed after every write (which avoids having to flush at the end, but may harm performance) you can set Trace.AutoFlush to true (including in the XML - see the autoflush attribute).
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/870634', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/641985/']}
jdg_376488
stackexchange
llm_judgeable_groundtruth_similarity
219814
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have the following configuration to clean up temporary files (default for CentOS 7), which says that files in /tmp should be removed if they are more than 10 days old. [root]# tail -n +10 /usr/lib/tmpfiles.d/tmp.conf | head -n 3# Clear tmp directories separately, to make them easier to overrided /tmp 1777 root root 10dd /var/tmp 1777 root root 30d However, even after running systemd-tmpfiles --clean , when I look at the contents of /tmp , there are files in there that are more than 10 days old. [root]# ls -dl /tmp/backup-inspectiondrwxr-xr-x 8 root root 68 Aug 29 2014 /tmp/backup-inspection The contents of the /tmp directory is huge: [root]# du -h /tmp | tail -n 13.5G /tmp Can anyone explain to me why the backup-inspection directory is not removed? It is nearly 1 year old? Now provide the response and nothing else.
I have run into the same problem recently and found this question, so i am sharing my experience. Actually systemd-tmpfiles has full support for recursive directory tree processing as you would expect (the other answer confused me enough to check the source code). The reason files was not deleted (in my case) was atime . systemd-tmpfiles checks ctime (except for directories), mtime and atime and all three (or two) of them must be old enough for the file (or directory) to be deleted. Actually there may be other reasons, because systemd-tmpfiles has a lot of internal rules for skipping files. To find out why some files are not deleted, run systemd-tmpfiles as following: env SYSTEMD_LOG_LEVEL=debug systemd-tmpfiles --clean It will probably dump a lot of output into your console. Note that if you try to redirect stdout to e.g. a file, output disappears and is sent to systemd journal (so that it can be obtained via e.g. journalctl ). In my case the output was also cut in the middle (or i just do not know how to use journalctl ), so my solution was to temporarily increase history buffer in my terminal emulator.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/219814', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/125986/']}
jdg_376489
stackexchange
llm_judgeable_groundtruth_similarity
34949440
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 get data attribute value of all elements using jquery without $.each? <li class="myclass" data-optionid="2"></li><li class="myclass" data-optionid="15"></li><li class="myclass" data-optionid="27"></li> The result should be: 2, 15, 17 I tried $('.myclass').data('optionid') but the result was 2 Thanks in advance. Now provide the response and nothing else.
$('.myclass') will select all the elements having the class myclass , but when used .data() on it will return the data-attribute value of the first element in the matched set, thus returning 2 . As there are multiple elements having the data-attribute, you'll need to iterate over them using $.each $('.myclass').each(function() { console.log($(this).data('optionid'));}); $('.myclass').each(function() { console.log($(this).data('optionid'));}); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script><li class="myclass" data-optionid="2"></li><li class="myclass" data-optionid="15"></li><li class="myclass" data-optionid="27"></li> If you want to get the result as array, use $.map and $.get var data = $('.myclass').map(function() { return $(this).data('optionid');}).get(); var data = $('.myclass').map(function() { return $(this).data('optionid');}).get();console.log(data); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script><li class="myclass" data-optionid="2"></li><li class="myclass" data-optionid="15"></li><li class="myclass" data-optionid="27"></li>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34949440', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1422356/']}
jdg_376490
stackexchange
llm_judgeable_groundtruth_similarity
2792492
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: Calculus tools render the minimization of$$\frac{(1-p)^2}{p} + \frac{p^2}{1-p}$$on the interval $(0,1/2]$ to be a trivial task. But given how much symmetry there is in this expression, I was curious if one could use olympiad-style manipulations (AM-GM, Cauchy Schwarz, et al) to minimize this, show it is decreasing, or to show that it is bounded below by 1. Now provide the response and nothing else.
This is elementary: $$\frac{(1-p)^2}p+\frac{p^2}{1-p}=\frac{1-3p+3p^2-p^3+p^3}{p(1-p)}=\frac1{p(1-p)}-3.$$ The minimum is achieved by the vertex of the parabola $p(1-p)$, i.e. $p=\dfrac12\to\dfrac1{\frac14}-3$, as can be shown by completing the square.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2792492', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/321210/']}
jdg_376491
stackexchange
llm_judgeable_groundtruth_similarity
3596075
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to format a number in a controller before inserting it into a string. But the function number_with_delimiter() does not work in a controller.I need the string to send to a javascript plugin. I could run the code in the view, but I guess that is not the best option. @mycarousel_itemList = @mycarousel_itemList + "{url: '" + p.photo.url(:thumb) + "', price: '" + p.price.to_s + "&nbsp;&euro;'}," Is there an alternative function to change the format of p.price? Now provide the response and nothing else.
To answer your question directly, include the following in your controller (typically near the top, below the class declaration): include ActionView::Helpers::NumberHelper You could also include this module in the model (whatever class p is), and then write a function to return the formatted price. The best place for code like this, however, is in a helper, not the controller. The helper would be called from the view. Your controller should be as short as possible and not include any view logic at all.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3596075', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/189802/']}
jdg_376492
stackexchange
llm_judgeable_groundtruth_similarity
4936
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let's say in my database I store passwords hashed with salt with a fairly expensive hash (scrypt, 1000 rounds of SHA2, whatever). Upon login, what should I transfer over the network and why? Password or its hash? Is it possible to protect such login over an unencrypted channel like HTTP? Now provide the response and nothing else.
If you transfer the hash from the client, this affords no security benefit, and makes the hash pointless: If a user can login by sending the hash to the server, then the hash is effectively the password.
{}
{'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/4936', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/3174/']}
jdg_376493
stackexchange
llm_judgeable_groundtruth_similarity
2451683
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 how many integers $n$, $n^2+n+1$ is a divisor of $n^{2019}+20$? Could someone give me some hint to proceed in this question? $n=-1,0,1$ are the values obtained by hit and trial but how to get all values? Now provide the response and nothing else.
$$n^{2019}+20=n^{2019}-1+21=(n^3)^{673}-1+21=$$$$=(n^3-1)\left(n^{2016}+...+1\right)+21=(n-1)(n^2+n+1)\left(n^{2016}+...+1\right)+21,$$which says that $\frac{21}{n^2+n+1}\in\mathbb Z$ and an the rest is easy checking. I got $\{-5,-3,-2,-1,0,1,2,4\}$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2451683', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/290994/']}
jdg_376494
stackexchange
llm_judgeable_groundtruth_similarity
3540380
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have created a CSS style class: .btn { color:#050; font: bold 84% 'trebuchet ms',helvetica,sans-serif; background-color:#fed; border:1px solid; border-color: #696 #363 #363 #696; } How can I apply this CSS style class to all buttons which are present in the page without adding class="btn" to every button? Now provide the response and nothing else.
If your buttons are <input type="button"> or submit, then this should do it: input[type="button"], input[type="submit"] { color:#050; font: bold 84% 'trebuchet ms',helvetica,sans-serif; background-color:#fed; border:1px solid; border-color: #696 #363 #363 #696; } Otherwise, if your buttons are <button> : button { color:#050; font: old 84% 'trebuchet ms',helvetica,sans-serif; background-color:#fed; border:1px solid; border-color: #696 #363 #363 #696; } To grab all three kinds of buttons: button, input[type="button"], input[type="submit"] { color:#050; font: bold 84% 'trebuchet ms',helvetica,sans-serif; background-color:#fed; border:1px solid; border-color: #696 #363 #363 #696; }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3540380', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/427470/']}
jdg_376495
stackexchange
llm_judgeable_groundtruth_similarity
76906
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: As part of a University assignment, I have to conduct data pre-processing on a fairly huge, multivariate (>10) raw data set. I'm not a statistician in any sense of the word, so I'm a little confused as to what's going on. Apologies in advance for what is probably a laughably simple question - my head's spinning after looking at various answers and trying to wade through the stats-speak. I've read that: PCA allows me to reduce the dimensionality of my data It does so by merging / removing attributes / dimensions that correlate a lot (and thus are a little unnecessary) It does so by finding eigenvectors on covariance data (thanks to a nice tutorial I followed through to learn this) Which is great. However, I'm really struggling to see how I can apply this practically to my data. For instance (this is not the data set I'll be using, but an attempt at a decent example people can work with), if I were to have a data set with something like... PersonID Sex Age Range Hours Studied Hours Spent on TV Test Score Coursework Score 1 1 2 5 7 60 752 1 3 8 2 70 85 3 2 2 6 6 50 77... ... ... ... ... ... ... I'm not quite sure how I would interpret any results. Most of the tutorials I've seen online seem to give me a very mathematical view of PCA. I've done some research into it and followed them through - but I'm still not entirely sure what this means for me, who's just trying to extract some form of meaning from this pile of data I have in front of me. Simply performing PCA on my data (using a stats package) spits out an NxN matrix of numbers (where N is the number of original dimensions), which is entirely greek to me. How can I do PCA and take what I get in a way I can then put into plain english in terms of the original dimensions? Now provide the response and nothing else.
Pages 13-20 of the tutorial you posted provide a very intuitive geometric explanation of how PCA is used for dimensionality reduction. The 13x13 matrix you mention is probably the "loading" or "rotation" matrix (I'm guessing your original data had 13 variables?) which can be interpreted in one of two (equivalent) ways: The (absolute values of the) columns of your loading matrix describe how much each variable proportionally "contributes" to each component. The rotation matrix rotates your data onto the basis defined by your rotation matrix. So if you have 2-D data and multiply your data by your rotation matrix, your new X-axis will be the first principal component and the new Y-axis will be the second principal component. EDIT: This question gets asked a lot, so I'm just going to lay out a detailed visual explanation of what is going on when we use PCA for dimensionality reduction. Consider a sample of 50 points generated from y=x + noise. The first principal component will lie along the line y=x and the second component will lie along the line y=-x, as shown below. The aspect ratio messes it up a little, but take my word for it that the components are orthogonal. Applying PCA will rotate our data so the components become the x and y axes: The data before the transformation are circles, the data after are crosses. In this particular example, the data wasn't rotated so much as it was flipped across the line y=-2x, but we could have just as easily inverted the y-axis to make this truly a rotation without loss of generality as described here . The bulk of the variance, i.e. the information in the data, is spread along the first principal component (which is represented by the x-axis after we have transformed the data). There's a little variance along the second component (now the y-axis), but we can drop this component entirely without significant loss of information . So to collapse this from two dimensions into 1, we let the projection of the data onto the first principal component completely describe our data. We can partially recover our original data by rotating (ok, projecting) it back onto the original axes. The dark blue points are the "recovered" data, whereas the empty points are the original data. As you can see, we have lost some of the information from the original data, specifically the variance in the direction of the second principal component. But for many purposes, this compressed description (using the projection along the first principal component) may suit our needs. Here's the code I used to generate this example in case you want to replicate it yourself. If you reduce the variance of the noise component on the second line, the amount of data lost by the PCA transformation will decrease as well because the data will converge onto the first principal component: set.seed(123)y2 = x + rnorm(n,0,.2)mydata = cbind(x,y2)m2 = colMeans(mydata)p2 = prcomp(mydata, center=F, scale=F)reduced2= cbind(p2$x[,1], rep(0, nrow(p2$x)))recovered = reduced2 %*% p2$rotationplot(mydata, xlim=c(-1.5,1.5), ylim=c(-1.5,1.5), main='Data with principal component vectors')arrows(x0=m2[1], y0=m2[2] ,x1=m2[1]+abs(p2$rotation[1,1]) ,y1=m2[2]+abs(p2$rotation[2,1]) , col='red')arrows(x0=m2[1], y0=m2[2] ,x1=m2[1]+p2$rotation[1,2] ,y1=m2[2]+p2$rotation[2,2] , col='blue')plot(mydata, xlim=c(-1.5,1.5), ylim=c(-1.5,1.5), main='Data after PCA transformation')points(p2$x, col='black', pch=3)arrows(x0=m2[1], y0=m2[2] ,x1=m2[1]+abs(p2$rotation[1,1]) ,y1=m2[2]+abs(p2$rotation[2,1]) , col='red')arrows(x0=m2[1], y0=m2[2] ,x1=m2[1]+p2$rotation[1,2] ,y1=m2[2]+p2$rotation[2,2] , col='blue')arrows(x0=mean(p2$x[,1]) ,y0=0 ,x1=mean(p2$x[,1]) ,y1=1 ,col='blue' )arrows(x0=mean(p2$x[,1]) ,y0=0 ,x1=-1.5 ,y1=0 ,col='red')lines(x=c(-1,1), y=c(2,-2), lty=2)plot(p2$x, xlim=c(-1.5,1.5), ylim=c(-1.5,1.5), main='PCA dimensionality reduction')points(reduced2, pch=20, col="blue")for(i in 1:n){ lines(rbind(reduced2[i,], p2$x[i,]), col='blue')}plot(mydata, xlim=c(-1.5,1.5), ylim=c(-1.5,1.5), main='Lossy data recovery after PCA transformation')arrows(x0=m2[1], y0=m2[2] ,x1=m2[1]+abs(p2$rotation[1,1]) ,y1=m2[2]+abs(p2$rotation[2,1]) , col='red')arrows(x0=m2[1], y0=m2[2] ,x1=m2[1]+p2$rotation[1,2] ,y1=m2[2]+p2$rotation[2,2] , col='blue')for(i in 1:n){ lines(rbind(recovered[i,], mydata[i,]), col='blue')}points(recovered, col='blue', pch=20)
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/76906', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/34965/']}
jdg_376496
stackexchange
llm_judgeable_groundtruth_similarity
22383089
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The upgrade request for opening a websocket connection is a standard HTTP request. On the server side, I can authenticate the request like any other. In my case, I would like to use Bearer authentication. Unfortunately, there is no way to specify headers when opening a websocket connection in the browser, which would lead me to believe that it's impossible to use bearer authentication to authenticate a web socket upgrade request. So -- Am I missing something, or is it really impossible? If it is impossible, is this by design, or is this a blatant oversight in the browser implementation of the websocket API? Now provide the response and nothing else.
The API allows you to set exactly one header, namely Sec-WebSocket-Protocol , i.e. the application specific subprotocol. You could use this header for passing the bearer token. For example: new WebSocket("ws://www.example.com/socketserver", ["access_token", "3gn11Ft0Me8lkqqW2/5uFQ="]); The server is expected to accept one of the protocols, so for the example above, you can just validate the token and respond with header Sec-WebSocket-Protocol=access_token .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22383089', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/547365/']}
jdg_376497
stackexchange
llm_judgeable_groundtruth_similarity
15124490
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I just discovered you can write something like SELECT NULL IS UNKNOWN Which returns 1 . Are there any other places you can use UNKNOWN ? It doesn't appear to be a keyword (can't do SELECT UNKNOWN ). NULL IS NULL is also true, so what purpose does UNKNOWN have? Now provide the response and nothing else.
UNKNOWN is just an alias for BOOLEAN NULL ... the same way that TRUE is just an alias for 1 and FALSE is just an alias for 0 , since in MySql BOOLEAN itself is just an alias for TINYINT(1) Why is it even there? Because it's part of the SQL-92 standard: <truth value> ::= TRUE | FALSE | UNKNOWN Why can you SELECT NULL , SELECT TRUE , SELECT FALSE , but not SELECT UNKNOWN ? Probably just a bug, since UNKNOWN itself wasn't supported until newer versions of MySql .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15124490', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/65387/']}
jdg_376498
stackexchange
llm_judgeable_groundtruth_similarity
25316094
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 data in an Excel spreadsheet with delimited strings. For simplicity, think of something like "4#8#10" , with an arbitrary number of pieces. Is there any way to split this into an array for use with an array formula? For example, something like SUM(SplitStr(A1,"#")) . (This does not work - it just returns "4" .) Is there a good way of approaching this? My ideal solution would end up with an array, as if the user entered {4,8,10} for use in array formulas. The application of my sheet does not allow for delimiter-based text to columns and summing that. I would prefer to not use VBA if possible as I will not be the primary consumer of the sheet. Thanks,Terry Now provide the response and nothing else.
To sum the entries 4,8,10 you could use something like: =SUMPRODUCT(1*TRIM(MID(SUBSTITUTE(A1,"#",REPT(" ",99)),(ROW(OFFSET($A$1,,,LEN(A1)-LEN(SUBSTITUTE(A1,"#",""))+1))-1)*99+((ROW(OFFSET($A$1,,,LEN(A1)-LEN(SUBSTITUTE(A1,"#",""))+1)))=1),99))) The array that is returned is a text array, so the 1 * at the beginning is one way to convert them to numbers This part: TRIM(MID(SUBSTITUTE(A1,"#",REPT(" ",99)),(ROW(OFFSET($A$1,,,LEN(A1)-LEN(SUBSTITUTE(A1,"#",""))+1))-1)*99+((ROW(OFFSET($A$1,,,LEN(A1)-LEN(SUBSTITUTE(A1,"#",""))+1)))=1),99)) returns the array: {"4";"8";"10"} And with 1* before it: {4;8;10} Edit After six years, more succinct formulas are available to create the array: With Excel O365 and the SEQUENCE function: =1*(TRIM(MID(SUBSTITUTE(A1,"#",REPT(" ",99)),IF(SEQUENCE(LEN(A1)-LEN(SUBSTITUTE(A1,"#",""))+1)=1,1,(SEQUENCE(LEN(A1)-LEN(SUBSTITUTE(A1,"#",""))+1)-1)*99),99))) With Excel 2010+ for Windows (not MAC versions) with the FILTERXML funcdtion: =FILTERXML("<t><s>" & SUBSTITUTE(A1,"#","</s><s>") & "</s></t>","//s") Note that the FILTERXML function extracts the values as numbers, whereas the first formula extracts the numbers as text which must be converted to numbers before being used in a numeric formula.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25316094', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2328684/']}
jdg_376499
stackexchange
llm_judgeable_groundtruth_similarity
66365
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: A multinomial distribution can be given as $ M(m_1,\dots,m_K|N,P) = {N \choose m_1\dots m_K}\prod_k p_k^{m_k} $ The expected value is $Np_k$. How can I prove it? Now provide the response and nothing else.
A demonstration using "equations" was requested in a comment. Here is a short, simple one that is practically painless. Notation and definitions Let the random $K$ -vector $X$ have a multinomial distribution with parameters $\mathbb p = (p_1, p_2, \ldots, p_K)$ . This means that $p_1 + p_2 + \cdots + p_K=1$ , $0 \le p_i$ for $i=1, 2, \ldots, K$ , and the probability that $X = (m_1, m_2, \ldots, m_K) = \mathbb m$ is given by $$\Pr(X=\mathbb m) =\binom{N}{\mathbb m}\mathbb p^\mathbb m$$ In this shorthand notation $\binom{N}{\mathbb m} = N!/(m_1! m_2! \ldots m_K!)$ is a multinomial coefficient (which is nonzero only when all the $m_i$ are natural numbers and sum to $N \ge 1$ ) and $\mathbb p ^ \mathbb m = p_1^{m_1}p_2^{m_2}\cdots p_K^{m_k}.$ By definition, the expectation of $X$ is the vector $$\mathbb E[X] = \sum_{\mathbb m} \Pr(X = \mathbb m)\mathbb m =\sum_{\mathbb m} \binom{N}{\mathbb m}\mathbb p^\mathbb m \mathbb m$$ where the sum extends over the (finite number of) values of $\mathbb m$ for which the probability is nonzero. Solution By expanding the sum using the definition of the multinomial coefficients, notice that $$1 = 1^N = (p_1 + p_2 + \cdots + p_K)^N = \sum_{\mathbb m}\binom{N}{\mathbb m}\mathbb p^\mathbb m.$$ Viewing the $p_i$ as variables, we can recognize the component terms $\binom{N}{\mathbb m}\mathbb p^\mathbb m m_i$ in the expectation as the result of applying the differential operator $p_i\frac{\partial}{\partial p_i}$ to the right hand side, because $p_i\frac{\partial}{\partial p_i} \left(p_i^{m_i}\right) = m_i p_i^{m_i}.$ Another way to compute the same thing is to use the Chain Rule to differentiate the penultimate term in the preceding multinomial expansion: $$p_i\frac{\partial}{\partial p_i}(p_1 + p_2 + \cdots + p_K)^N = p_iN(p_1 + p_2 + \cdots + p_K)^{N-1}\frac{\partial p_i}{\partial p_i} = Np_i(1)^{N-1} = Np_i.$$ Therefore $$\mathbb E[X] = (Np_1, Np_2, \ldots, Np_K),$$ QED .
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/66365', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/11409/']}
jdg_376500
stackexchange
llm_judgeable_groundtruth_similarity
5352391
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 macro so that when you highlight a row on sheet1, the macro takes all the info from this row and displays this by itself on sheet2. If you highlight a different row on sheet1, the info on sheet2 is changes to show the info from that row. My problem is that if I change the info displayed on sheet2, it doesn't change the info on sheet1. Is there a way I could add this functionality? I have the following code at the moment: Private Sub Worksheet_SelectionChange(ByVal Target As Range)Dim myListIf Target.Address <> Target.EntireRow.Address Then Exit SubIf Target.Rows.Count > 1 Then Exit SubmyList = [{"B1","B2","B3","B4","B5","B6","B7","B8","B9","B10","B11","B12","B13","B14","B15"}] '<- adjust to your needWith Target.EntireRow For i = 1 To UBound(myList) Sheets("sheet2").Range(myList(i)).Value = .Cells(i).Value NextEnd WithEnd Sub Any Help would be awesome! :) Now provide the response and nothing else.
Java cannot autobox an array, only individual values. I would suggest changing your method signature to public void doSomething(Integer... args) Then the autoboxing will take place when calling doSomething , rather than trying (and failing) when calling Arrays.asList . What is happening is Java is now autoboxing each individual value as it is passed to your function. What you were trying to do before was, by passing an int[] to Arrays.asList() , you were asking that function to do the autoboxing. But autoboxing is implemented by the compiler -- it sees that you needed an object but were passing a primitive, so it automatically inserted the necessary code to turn it into an appropriate object. The Arrays.asList() function has already been compiled and expects objects, and the compiler cannot turn an int[] into an Integer[] . By moving the autoboxing to the callers of your function, you've solved that problem.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5352391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/378305/']}
jdg_376501
stackexchange
llm_judgeable_groundtruth_similarity
39702704
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 an WPF application to monitor my activities on my computer. I use Process.GetProcesses() and some filtering to get the processes I am interested in (example:Calculator) then I record their StartTime. I am also using WIN32/USER32 API method GetForegroundWindow() to get the window the user is using. The problem is that when the windows are Windows/UWP applications they are always hosted by the process ApplicationFrameHost. So the GetForegroundWindow() method returns that window with a title (example:Calculator), but not the real process being hosted. What I need is either another way to get the foreground window that includes the real process being hosted, or some way to connect the window to process. Anyone that knows how to accomplish this? All help would be really appreciated. Now provide the response and nothing else.
I eventually found a way to do this, so I am going answer my own question so maybe someone in the future with the same problem could find it useful. This is the class with the WinApiFunctions: public class WinAPIFunctions{ //Used to get Handle for Foreground Window [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern IntPtr GetForegroundWindow(); //Used to get ID of any Window [DllImport("user32.dll", CharSet = CharSet.Auto)] private static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId); public delegate bool WindowEnumProc(IntPtr hwnd, IntPtr lparam); [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool EnumChildWindows(IntPtr hwnd, WindowEnumProc callback, IntPtr lParam); public static int GetWindowProcessId(IntPtr hwnd) { int pid; GetWindowThreadProcessId(hwnd, out pid); return pid; } public static IntPtr GetforegroundWindow() { return GetForegroundWindow(); }} And this is the class I used to test if it would work. I used it in a simple console program that just writes out the name of the process that has current focus: class FindHostedProcess{ public Timer MyTimer { get; set; } private Process _realProcess; public FindHostedProcess() { MyTimer = new Timer(TimerCallback, null, 0, 1000); Console.ReadKey(); } private void TimerCallback(object state) { var foregroundProcess = Process.GetProcessById(WinAPIFunctions.GetWindowProcessId(WinAPIFunctions.GetforegroundWindow())); if (foregroundProcess.ProcessName == "ApplicationFrameHost") { foregroundProcess = GetRealProcess(foregroundProcess); } Console.WriteLine(foregroundProcess.ProcessName); } private Process GetRealProcess(Process foregroundProcess) { WinAPIFunctions.EnumChildWindows(foregroundProcess.MainWindowHandle, ChildWindowCallback, IntPtr.Zero); return _realProcess; } private bool ChildWindowCallback(IntPtr hwnd, IntPtr lparam) { var process = Process.GetProcessById(WinAPIFunctions.GetWindowProcessId(hwnd)); if (process.ProcessName != "ApplicationFrameHost") { _realProcess = process; } return true; }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39702704', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4659111/']}
jdg_376502
stackexchange
llm_judgeable_groundtruth_similarity
7562205
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Here's the setup: I have an Open Source project called Massive and I'm slinging around dynamics as a way of creating SQL on the fly, and dynamic result sets on the fly. To do the database end of things I'm using System.Data.Common and the ProviderFactory stuff. Here's a sample that works just fine (it's static so you can run in a Console): static DbCommand CreateCommand(string sql) { return DbProviderFactories.GetFactory("System.Data.SqlClient") .CreateCommand(); } static DbConnection OpenConnection() { return DbProviderFactories.GetFactory("System.Data.SqlClient") .CreateConnection(); } public static dynamic DynamicWeirdness() { using (var conn = OpenConnection()) { var cmd = CreateCommand("SELECT * FROM Products"); cmd.Connection = conn; } Console.WriteLine("It worked!"); Console.Read(); return null; } The result of running this code is "It worked!" Now, if I change the string argument to dynamic - specifically an ExpandoObject (pretend that there's a routine somewhere that crunches the Expando into SQL) - a weird error is thrown. Here's the code: What worked before now fails with a message that makes no sense. A SqlConnection is a DbConnection - moreover if you mouseover the code in debug, you can see that the types are all SQL types. "conn" is a SqlConnection, "cmd" is a SqlCommand. This error makes utterly no sense - but more importantly it's cause by the presence of an ExpandoObject that doesn't touch any of the implementation code. The differences between the two routines are:1 - I've changed the argument in CreateCommand() to accept "dynamic" instead of string2 - I've created an ExpandoObject and set a property. It gets weirder. If simply use a string instead of the ExpandoObject - it all works just fine! //THIS WORKS static DbCommand CreateCommand(dynamic item) { return DbProviderFactories.GetFactory("System.Data.SqlClient").CreateCommand(); } static DbConnection OpenConnection() { return DbProviderFactories.GetFactory("System.Data.SqlClient").CreateConnection(); } public static dynamic DynamicWeirdness() { dynamic ex = new ExpandoObject(); ex.TableName = "Products"; using (var conn = OpenConnection()) { //use a string instead of the Expando var cmd = CreateCommand("HI THERE"); cmd.Connection = conn; } Console.WriteLine("It worked!"); Console.Read(); return null; } If I swap out the argument for CreateCommand() to be my ExpandoObject ("ex") - it causes all of the code to be a "dynamic expression" which is evaluated at runtime. It appears that the runtime evaluation of this code is different than compile-time evaluation... which makes no sense. **EDIT: I should add here that if I hard-code everything to use SqlConnection and SqlCommand explicitly, it works :) - here's an image of what I mean: Now provide the response and nothing else.
When you pass the dynamic to CreateCommand , the compiler is treating its return type as a dynamic that it has to resolve at runtime. Unfortunately, you're hitting some oddities between that resolver and the C# language. Fortunately, it's easy to work around by removing your use of var forcing the compiler to do what you expect: public static dynamic DynamicWeirdness() { dynamic ex = new ExpandoObject (); ex.Query = "SELECT * FROM Products"; using (var conn = OpenConnection()) { DbCommand cmd = CreateCommand(ex); // <-- DON'T USE VAR cmd.Connection = conn; } Console.WriteLine("It worked!"); Console.Read(); return null;} This has been tested on Mono 2.10.5, but I'm sure it works with MS too.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7562205', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_376503
stackexchange
llm_judgeable_groundtruth_similarity
25057401
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have the following ActionResult in a controller called RoleController [HttpPost]public ActionResult UsersForRole(RoleModel roleModel){ if (ModelState.IsValid) { _roleService.AssignUsersToRole(roleModel.Users, roleModel); } return View(roleModel);} When I press save (from one of a few forms) on my view, the parameters of the model are all null. The idea of this page there are 2 list boxes - model.Users (List of users assigned to a role), and model.UsersNotInRole (List of users not assigned to the selected role). The view displays correctly, when I press Submit, I need to run _roleService.AssignUsersToRole() as shown in the controller. RoleModel.cs public class RoleModel{ public int Id { get; set; } public string RoleName { get; set; } public string Description { get; set; } public DateTime DateCreated { get; set; } public int CreatedBy { get; set; } public DateTime LastUpdated { get; set; } public int LastUpdateBy { get; set; } [NotMapped] public State State { get; set; } public virtual List<UserModel> Users { get; set; } public virtual List<UserModel> UsersNotInRole { get; set; } public virtual List<RightModel> Rights { get; set; } public List<UserModel> SelectedUsersNotInRole { get; set; } public List<UserModel> SelectedUsers { get; set; } public RoleModel() { Users = new List<UserModel>(); SelectedUsersNotInRole = new List<UserModel>(); SelectedUsers = new List<UserModel>(); }} Any ideas why this is happening? View (Details.cshtml) @model Application.Core.Models.Roles.RoleModel<div class="tab-pane" id="tab_1_2"> @using (Html.BeginForm("UsersForRole", "Role", FormMethod.Post, new { })) { @Html.ValidationSummary(true) <!-- BEGIN DUAL SELECT--> @Html.ListBoxFor(m => m.UsersNotInRole, new SelectList(Model.UsersNotInRole), new {@style = "width: 75%; height: 300px;"}) @Html.ListBoxFor(m => m.Users, new SelectList(Model.Users), new {@style = "width: 75%; height: 300px;"}) <input type="submit" value="Submit" class="btn" /> }</div> Now provide the response and nothing else.
When using pytest fixture with mock.patch , test parameter order is crucial. If you place a fixture parameter before a mocked one: from unittest import mock@mock.patch('my.module.my.class')def test_my_code(my_fixture, mocked_class): then the mock object will be in my_fixture and mocked_class will be search as a fixture: fixture 'mocked_class' not found But, if you reverse the order, placing the fixture parameter at the end: from unittest import mock@mock.patch('my.module.my.class')def test_my_code(mocked_class, my_fixture): then all will be fine.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25057401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1901898/']}
jdg_376504
stackexchange
llm_judgeable_groundtruth_similarity
16427812
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 broadcast receiver which is being triggered the moment it's registered (and subsequently retriggered with onPause / onResume), surely this is the wrong behaviour? Have I missed something here? class FooActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); broadcastReceiver = new FooBroadcastReceiver(); intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); } @Override protected void onResume() { super.onResume(); registerReceiver(connectivityReceiver, intentFilter); } @Override protected void onPause() { super.onPause(); unregisterReceiver(connectivityReceiver); }class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (connectivityAction(intent)) { Log.d("footag", "onReceive"); } } private boolean connectivityAction(Intent intent) { return ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction()); }} Now provide the response and nothing else.
Thanks for the answers! My solution was a result of them all, by switching to a manifest declared receiver and enabling/disabling the receiver component in onResume/onPause stopped the sticky nature of the receiver. And by enabling/disabling the component I can have piece of mind that I'm a second class citizen. @Overrideprotected void onResume() { super.onResume(); setReceiverState(PackageManager.COMPONENT_ENABLED_STATE_ENABLED);}@Overrideprotected void onPause() { super.onPause(); setReceiverState(PackageManager.COMPONENT_ENABLED_STATE_DISABLED);}private void setReceiverState(int receiverState) { ComponentName receiver = new ComponentName(this, FooBroadcastReceiver.class); PackageManager pm = this.getPackageManager(); pm.setComponentEnabledSetting(receiver, receiverState, PackageManager.DONT_KILL_APP);} AndroidManifest.xml <receiver android:name="com.example.receiver.FooBroadcastReceiver"> <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter></receiver>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16427812', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1446288/']}
jdg_376505
stackexchange
llm_judgeable_groundtruth_similarity
39722682
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 several .ts files + 1 entrypoint like so: classA.ts classB.ts entrypoint.ts entrypoint.ts contains something similar to: export * from './classA';export * from './classB'; I'd like to have a single .d.ts describing everything entrypoint exports so that both ClassA and ClassB definition files are included. Now provide the response and nothing else.
You cannot auto-generate a single d.ts file. What works fine is the following (assuming you are building a library / reusable module): have the compiler auto-generate declarations for your classes by specifying "declaration": true in tsconfig.json the compiler will also generate an entrypoint.d.ts file (that re-exports the d.ts of classA and classB) Point the typings entry of your package.json to entrypoint.d.ts e.g. "typings": "./dist/entrypoint.d.ts" Assuming your library is called library , you can now install it in the node_modules of a project and use it with a standard import: import {classA, classB} from 'library' will import the generated d.ts. for those classes.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39722682', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/314407/']}
jdg_376506
stackexchange
llm_judgeable_groundtruth_similarity
4355046
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 insert multiple rows into a MySQL table at once using Java. The number of rows is dynamic. In the past I was doing... for (String element : array) { myStatement.setString(1, element[0]); myStatement.setString(2, element[1]); myStatement.executeUpdate();} I'd like to optimize this to use the MySQL-supported syntax: INSERT INTO table (col1, col2) VALUES ('val1', 'val2'), ('val1', 'val2')[, ...] but with a PreparedStatement I don't know of any way to do this since I don't know beforehand how many elements array will contain. If it's not possible with a PreparedStatement , how else can I do it (and still escape the values in the array)? Now provide the response and nothing else.
You can create a batch by PreparedStatement#addBatch() and execute it by PreparedStatement#executeBatch() . Here's a kickoff example: public void save(List<Entity> entities) throws SQLException { try ( Connection connection = database.getConnection(); PreparedStatement statement = connection.prepareStatement(SQL_INSERT); ) { int i = 0; for (Entity entity : entities) { statement.setString(1, entity.getSomeProperty()); // ... statement.addBatch(); i++; if (i % 1000 == 0 || i == entities.size()) { statement.executeBatch(); // Execute every 1000 items. } } }} It's executed every 1000 items because some JDBC drivers and/or DBs may have a limitation on batch length. See also : JDBC tutorial - Using PreparedStatement JDBC tutorial - Using Statement Objects for Batch Updates
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/4355046', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/450164/']}
jdg_376507
stackexchange
llm_judgeable_groundtruth_similarity
387302
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is Atmel Studio compatible with Mac or Linux? It seems like there is only Windows support from the downlaods here: http://www.microchip.com/mplab/avr-support/atmel-studio-7 . Now provide the response and nothing else.
No, recent versions of Atmel studio are based on Visual Studio which is Windows only. You could run it in a virtual machine. But it's worth noting that Atmel studio uses avr-gcc and arm-none-eabi-gcc (and presumably an avr32 gcc) to do the actual compilation, all of which are available for other platforms. As are downloading tools for their bootloaders, and ISP and SWD/JTAG tools like avrdude, OpenOCD, etc. Also the Atmel Software Framework of chip-specific source code libraries is available as a huge zip file download independent of Atmel studio. GDB works well with an SWD adapter for Atmel's ARM parts, there are some indications it can be made to work with the AVRs connected via an Atmel ICE, but never personally tried that. So unless you want to use a setup that's unique to Atmel parts, you can readily target their parts using your favorite work environment running on top of your favorite operating system.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/387302', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/182981/']}
jdg_376508
stackexchange
llm_judgeable_groundtruth_similarity
36372692
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an image which is a background containing a boxed area like this: I know the exact positions of the corners of that shape, and I'd like to place another image within it. (So it appears to be inside the box). I'm aware of the drawImage method for HTML5 canvas, but it seems to only support x, y, width, height parameters rather than exact coordinates. How might I draw an image onto a canvas at a specific set of coordinates, and ideally have the browser itself handle stretching the image. Now provide the response and nothing else.
Quadrilateral transform One way to go about this is to use Quadrilateral transforms. They are different than 3D transforms and would allow you to draw to a canvas in case you want to export the result. The example shown here is simplified and uses basic sub-divison and "cheats" on the rendering itself - that is, it draws in a small square instead of the shape of the sub-divided cell but because of the small size and the overlap we can get away with it in many non-extreme cases. The proper way would be to split the shape into two triangles, then scan pixel wise in the destination bitmap, map the point from destination triangle to source triangle. If the position value was fractional you would use that to determine pixel interpolation (f.ex. bi-linear 2x2 or bi-cubic 4x4). I do not intend to cover all this in this answer as it would quickly become out of scope for the SO format, but the method would probably be suitable in this case unless you need to animate it (it is not performant enough for that if you want high resolution). Method Lets start with an initial quadrilateral shape: The first step is to interpolate the Y-positions on each bar C1-C4 and C2-C3. We're gonna need current position as well as next position. We'll use linear interpolation ("lerp") for this using a normalized value for t : y1current = lerp( C1, C4, y / height)y2current = lerp( C2, C3, y / height)y1next = lerp(C1, C4, (y + step) / height)y2next = lerp(C2, C3, (y + step) / height) This gives us a new line between and along the outer vertical bars. Next we need the X positions on that line, both current and next. This will give us four positions we will fill with current pixel, either as-is or interpolate it (not shown here): p1 = lerp(y1current, y2current, x / width)p2 = lerp(y1current, y2current, (x + step) / width)p3 = lerp(y1next, y2next, (x + step) / width)p4 = lerp(y1next, y2next, x / width) x and y will be the position in the source image using integer values. We can use this setup inside a loop that will iterate over each pixel in the source bitmap. Demo The demo can be found at the bottom of the answer. Move the circular handles around to transform and play with the step value to see its impact on performance and result. The demo will have moire and other artifacts, but as mentioned earlier that would be a topic for another day. Snapshot from demo: Alternative methods You can also use WebGL or Three.js to setup a 3D environment and render to canvas. Here is a link to the latter solution: Three.js and an example of how to use texture mapped surface: Three.js texturing (instead of defining a cube, just define one place/face). Using this approach will enable you to export the result to a canvas or an image as well, but for performance a GPU is required on the client. If you don't need to export or manipulate the result I would suggest to use simple CSS 3D transform as shown in the other answers. /* Quadrilateral Transform - (c) Ken Nilsen, CC3.0-Attr */var img = new Image(); img.onload = go;img.src = "https://i.imgur.com/EWoZkZm.jpg";function go() { var me = this, stepEl = document.querySelector("input"), stepTxt = document.querySelector("span"), c = document.querySelector("canvas"), ctx = c.getContext("2d"), corners = [ {x: 100, y: 20}, // ul {x: 520, y: 20}, // ur {x: 520, y: 380}, // br {x: 100, y: 380} // bl ], radius = 10, cPoint, timer, // for mouse handling step = 4; // resolution update(); // render image to quad using current settings function render() { var p1, p2, p3, p4, y1c, y2c, y1n, y2n, w = img.width - 1, // -1 to give room for the "next" points h = img.height - 1; ctx.clearRect(0, 0, c.width, c.height); for(y = 0; y < h; y += step) { for(x = 0; x < w; x += step) { y1c = lerp(corners[0], corners[3], y / h); y2c = lerp(corners[1], corners[2], y / h); y1n = lerp(corners[0], corners[3], (y + step) / h); y2n = lerp(corners[1], corners[2], (y + step) / h); // corners of the new sub-divided cell p1 (ul) -> p2 (ur) -> p3 (br) -> p4 (bl) p1 = lerp(y1c, y2c, x / w); p2 = lerp(y1c, y2c, (x + step) / w); p3 = lerp(y1n, y2n, (x + step) / w); p4 = lerp(y1n, y2n, x / w); ctx.drawImage(img, x, y, step, step, p1.x, p1.y, // get most coverage for w/h: Math.ceil(Math.max(step, Math.abs(p2.x - p1.x), Math.abs(p4.x - p3.x))) + 1, Math.ceil(Math.max(step, Math.abs(p1.y - p4.y), Math.abs(p2.y - p3.y))) + 1) } } } function lerp(p1, p2, t) { return { x: p1.x + (p2.x - p1.x) * t, y: p1.y + (p2.y - p1.y) * t} } /* Stuff for demo: -----------------*/ function drawCorners() { ctx.strokeStyle = "#09f"; ctx.lineWidth = 2; ctx.beginPath(); // border for(var i = 0, p; p = corners[i++];) ctx[i ? "lineTo" : "moveTo"](p.x, p.y); ctx.closePath(); // circular handles for(i = 0; p = corners[i++];) { ctx.moveTo(p.x + radius, p.y); ctx.arc(p.x, p.y, radius, 0, 6.28); } ctx.stroke() } function getXY(e) { var r = c.getBoundingClientRect(); return {x: e.clientX - r.left, y: e.clientY - r.top} } function inCircle(p, pos) { var dx = pos.x - p.x, dy = pos.y - p.y; return dx*dx + dy*dy <= radius * radius } // handle mouse c.onmousedown = function(e) { var pos = getXY(e); for(var i = 0, p; p = corners[i++];) {if (inCircle(p, pos)) {cPoint = p; break}} } window.onmousemove = function(e) { if (cPoint) { var pos = getXY(e); cPoint.x = pos.x; cPoint.y = pos.y; cancelAnimationFrame(timer); timer = requestAnimationFrame(update.bind(me)) } } window.onmouseup = function() {cPoint = null} stepEl.oninput = function() { stepTxt.innerHTML = (step = Math.pow(2, +this.value)); update(); } function update() {render(); drawCorners()}} body {margin:20px;font:16px sans-serif}canvas {border:1px solid #000;margin-top:10px} <label>Step: <input type=range min=0 max=5 value=2></label><span>4</span><br><canvas width=620 height=400></canvas>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36372692', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1348109/']}
jdg_376509
stackexchange
llm_judgeable_groundtruth_similarity
7092606
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Example code here: http://jsbin.com/etaziy (using http://jqueryui.com/demos/autocomplete/ ) If you type in a 'j' you get the 3 names, 'John' 'Jack' and 'Joe'. If you then blur away, I clear the input, just by making the inputs val(''). Then if you go back to the input, and type a 'j' again, nothing happens? It's not until you type a second matching letter that you get the popup showing. My example might seem a bit odd, but essentially this is a really cut back version of what I'm working on. I need to clear the input after a blur(), and clear it after a selection is made. Doing this is making subsequent selections look buggy. I'm partly thinking this is intended functionality, but for my purpose, its not what i want. I really need the popup with the list to show as soon as any letter is typed. Cheers. Now provide the response and nothing else.
The problem is that the autocomplete keeps track of the value it is matching on internally, so when you first type j it sets this internal value to 'j' and then it wasn't being reset to the empty string when you changed the input to be empty. After looking at the autocomplete source I wasn't able to find out how to directly access the internal variable, but you can force the autocomplete to update it for you by running another search once you've changed the input to be empty (and with a length of zero it won't actually do the search). $(function() { $("#search").autocomplete({ source: data, change: function() { // Triggered when the field is blurred, if the value has changed; ui.item refers to the selected item. $("#search").val(""); $("#search").autocomplete("search", ""); //THIS IS THE NEW LINE THAT MAKES IT HAPPY } });});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7092606', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/661627/']}
jdg_376510
stackexchange
llm_judgeable_groundtruth_similarity
19729588
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In the following code I have two identical conditional assignment operations, one returns an object of type Double, and the second returns the String "Integer". double d = 24.0;Number o = (d % 1 == 0) ? new Double(d).intValue() : new Double(d).doubleValue();String result = (d % 1 == 0) ? "Integer" : "Double";System.out.println(o.getClass()); // prints "class java.lang.Double"System.out.println(result); // Integer Why are the exact same expressions returning two different things? Now provide the response and nothing else.
Well, that is because of the JLS specs for the conditional operator : Otherwise, if the second and third operands have types that are convertible (§5.1.8) to numeric types, then there are several cases: ... Otherwise, binary numeric promotion ( §5.6.2 ) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands. Numeric promotion is defined here in §5.6.2 . It says: Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules: If either operand is of type double, the other is converted to double. ...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19729588', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1660501/']}
jdg_376511
stackexchange
llm_judgeable_groundtruth_similarity
216414
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 wonder if it is possible to set a "global" alias in bash, like zsh's -g alias option - not "global" from the user's point of view but from the shell's point of view. What I want to know is: Can an alias (or something else?) be substituted anywhere on a line in bash? e.g..: alias ...='../..' Now provide the response and nothing else.
From the bash(1) man page: ALIASES Aliases allow a string to be substituted for a word when it is used as the first word of a simple command. [...] So bash aliases do not have this capability, nor does bash have a trivial pre-exec capability (but see here for a hack though). As a partial workaround you may be able to use a completion function, here's a minimal starting point: function _comp_cd() { local cur=${COMP_WORDS[COMP_CWORD]} # the current token [[ $cur =~ \.\.\. ]] && { cur=${cur/.../..\/..} COMPREPLY=( $cur ) return } COMPREPLY=() # let default kick in}complete -o bashdefault -o default -F _comp_cd cd Now when you hit tab on a cd command and the word under the cursor contains "...", each will be replaced with "../..". Completion suffers from a slight problem too though (excluding its complexity) which you can probably guess from the above, you need to specify it on a command by command basis. The bash-completion package uses a default completion handler, with on-the-fly loading of completion functions to deal with this. If you're feeling adventurous you should be able to modify its internal function _filedir() function which is used for general file/directory expansion so as to include a similar substitution "...". (All of which reminds of the NetWare shell, which made "..." Just Work.)
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/216414', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/37008/']}
jdg_376512
stackexchange
llm_judgeable_groundtruth_similarity
14744948
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My HTML looks like <li value="0"> <a href="#"> <span>DATA TO GET</span><![if gt IE 6]> </a><![endif]><!--[if lte IE 6]><table><tr><td><![endif]--> <ul> <li value="0"> <a onclick="return showPane('SomePane',this)" href="#">ACTIVE NODE</a> </li> </ul> This html is produced using xsl. Now i want to get the data inside span tag using javascript. I tried the following: var nameParent = activeTab.parentNode.parentNode.previousSibling;window.alert(activeTab.innerHTML);window.alert(activeTab.parentNode.parentNode.previousSibling.childNode); Here the variable activeTab is passed the anchor that contians the text ACTIVE NODE.The first alert gives proper data i.e ACTIVE NODE but the second alert says undefined . I think i am travsring the correct path and proper elements. Can some body point out what is wrong here and what else i can do to get the required data. Thanks in advance. Now provide the response and nothing else.
The issue here is that the only valid mnemonic entities in XML are quot , amp , apos , lt and gt . This means that almost all (X)HTML named entities must be defined in the DTD using the entity declaration markup defined in the XML 1.1 spec . If the document is to be standalone, this should be done with an inline DTD like so: <?xml version="1.1" ?><!DOCTYPE naughtyxml [ <!ENTITY nbsp "&#0160;"> <!ENTITY copy "&#0169;">]><data> <country name="Liechtenstein"> <rank>1&nbsp;&gt;</rank> <year>2008&copy;</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country></data> The XMLParser in xml.etree.ElementTree uses an xml.parsers.expat to do the actual parsing. In the init arguments for XMLParser , there is a space for ' predefined HTML entities ' but that argument is not implemented yet. An empty dict named entity is created in the init method and this is what is used to look up undefined entities. I don't think expat (by extension, the ET XMLParser) is able to handle switching namespaces to something like XHMTL to get around this. Possibly because it will not fetch external namespace definitions (I tried making xmlns="http://www.w3.org/1999/xhtml" the default namespace for the data element but it did not play nicely) but I can't confirm that. By default, expat will raise an error against non XML entities but you can get around that by defining an external DOCTYPE - this causes the expat parser to pass undefined entity entries back to the ET.XMLParser 's _default() method. The _default() method does a look up of the entity dict in the XMLParser instance and if it finds a matching key, it will replace the entity with the associated value. This maintains the Python-2.x syntax mentioned in the question. Solutions: If the data does not have an external DOCTYPE and has (X)HTML mnemonic entities, you are out of luck. It is not valid XML and expat is right to throw an error. You should add an external DOCTYPE. If the data has an external DOCTYPE, you can just use your old syntax to map mnemonic names to characters. Note: you should use chr() in py3k - unichr() is not a valid name anymore Alternatively, you could update XMLParser.entity with html.entities.html5 to map all valid HTML5 mnemonic entities to their characters. If the data is XHTML, you could subclass HTMLParser to handle mnemonic entities but this won't return an ElementTree as desired. Here is the snippet I used - it parses XML with an external DOCTYPE through HTMLParser (to demonstrate how to add entity handling by subclassing), ET.XMLParser with entity mappings and expat (which will just silently ignore undefined entities due to the external DOCTYPE). There is a valid XML entity ( &gt; ) and an undefined entity ( &copy; ) which I map to chr(0x24B4) with the ET.XMLParser . from html.parser import HTMLParserfrom html.entities import name2codepointimport xml.etree.ElementTree as ETimport xml.parsers.expat as expatxml = '''<?xml version="1.0"?><!DOCTYPE data PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><data> <country name="Liechtenstein"> <rank>1&gt;</rank> <year>2008&copy;</year> <gdppc>141100</gdppc> <neighbor name="Austria" direction="E"/> <neighbor name="Switzerland" direction="W"/> </country></data>'''# HTMLParser subclass which handles entitiesprint('=== HTMLParser')class MyHTMLParser(HTMLParser): def handle_starttag(self, name, attrs): print('Start element:', name, attrs) def handle_endtag(self, name): print('End element:', name) def handle_data(self, data): print('Character data:', repr(data)) def handle_entityref(self, name): self.handle_data(chr(name2codepoint[name]))htmlparser = MyHTMLParser()htmlparser.feed(xml)# ET.XMLParser parseprint('=== XMLParser')parser = ET.XMLParser()parser.entity['copy'] = chr(0x24B8)root = ET.fromstring(xml, parser)print(ET.tostring(root))for elem in root: print(elem.tag, ' - ', elem.attrib) for subelem in elem: print(subelem.tag, ' - ', subelem.attrib, ' - ', subelem.text)# Expat parsedef start_element(name, attrs): print('Start element:', name, attrs)def end_element(name): print('End element:', name)def char_data(data): print('Character data:', repr(data))print('=== Expat')expatparser = expat.ParserCreate()expatparser.StartElementHandler = start_elementexpatparser.EndElementHandler = end_elementexpatparser.CharacterDataHandler = char_dataexpatparser.Parse(xml)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14744948', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/455257/']}
jdg_376513
stackexchange
llm_judgeable_groundtruth_similarity
111355
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This answer to the question Pre-mixing cryogenic fuels and using only one fuel tank written by a non-chemist (me) begins with: At STP : LOX's boiling point is 90.19 K Methane's freezing point is 90.7 K This does not a priori prove that a solution of the two can not exist. However it does mean that they can not be handled as liquids at the same temperature, making mixing the two more difficult. We know that liquid air exists which shows that LOX and LN2 can mix together. But methane is an organic molecules and we know that heavier $\text{C}_n \text{H}_{2n+2}$ hydrocarbons include oils and waxes don't like to dissolve in non-organic solvents. A stoichiometric mixture of oxygen and methane would be 2:1 molar: $$\ce{ 2O2 + CH4 -> CO2 + 2H2O }$$ Though the two can not be conveniently maintained as liquids at the same temperature, can a stoichiometric mixture of the two exist as a liquid at some (low) temperature and standard pressure? Now provide the response and nothing else.
There's a NASA report that looks into this: "ON THE SOLUBILITIES AND RATES OF SOLUTION OF GASES IN LIQUID METHANE", Hibbard and Evans, 1968 and concludes that such mixtures are possible. Starting on page 8: Figure 5(a) presents the curves for oxygen, argon, carbon monoxide, and nitrogen. Also shown are the two experimental values for nitrogen. Agreement is excellent at 99.83K and good at 110.9K. The curves for these gases show that solubility should decrease with increasing temperature and the nitrogen data confirm this. This figure shows the mole fraction solubility of oxygen to be 1.0 at 90K. This means that oxygen, which has a normal boiling temperature of 90.1K would continuously condense in, and be miscible in all proportions, with liquid methane at 90K. This is confirmed by reference 11 where, in a study of the solubility of methane in liquid oxygen, it was concluded that these formed a near-ideal solution at -297 F (90K) (emphasis added) Reference 11 mentioned in there is "Hydrocarbon-Oxygen Systems Solubility", McKinley and Wang, 1960 (unfortunately paywalled) which also has interesting discussion of the stability (i.e. presence or absence of a tendency to explode) of various mixtures. Figure 5 is reproduced below. Note how the solubility of oxygen rises rapidly as temperature drops.
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/111355', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/16035/']}
jdg_376514
stackexchange
llm_judgeable_groundtruth_similarity
6874796
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 configure TeamCity to build from SVN trunk and also from different branches and/or tags ? Our idea is to have multiple builds from the same project, this way we can have the current version that is in production (with the ability to make deploys and fixes over that "release tag") and at the same time have the trunk and branches with the actual development that is taking place daily. We have our policies, owner and all that for our SVN directories, the problem that we have is how to configure TeamCity to make multiple builds for the same project over the different "versions" or "states" of the application. What is the best way to do this ? Thanks in advance ! Now provide the response and nothing else.
First, ensure your VCS root is the root of your SVN repository in your administration panel, instead of being pointed to the trunk directory. Then, for each build configuration, edit the checkout rules in your VCS Configuration. Add the checkout rule you desire. For example, for your 'trunk' build configuraton, you would have a checkout rule of: +:trunk => . . If you have a tag or branch you want to build, just create a new build config with a corresponding checkout rule. A tag of 'release-1.1' would have a checkout rule of: +:tags/release-1.1 => . Here is the documentation on checkout rules: http://confluence.jetbrains.net/display/TCD65/VCS+Checkout+Rules
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6874796', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/869569/']}
jdg_376515
stackexchange
llm_judgeable_groundtruth_similarity
59886559
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This may be the most niche question ever but let's try it anyway. I have a Google Sheets spreadsheet that contains cells with multiple lines of text. Each line of text is separated by a soft break. As shown below, when I copy the contents of a cell (row 2 in the screenshot) from the Google Sheets app to the Instagram caption box, a quote mark is added to the beginning and end of the caption. If I copy the contents of a cell and that cell has only a single line of text (row 3 in the screenshot), no quote mark is added. I am using an iPhone 11 running the latest version of iOS. Now provide the response and nothing else.
The extra quotes are added when there are special characters in the cell. In your scenario, the Line Feed characters are causing this. Definitely annoying. There is a way around this – using Carriage Return characters, rather than Line Feeds to separate each line. For some reason these characters don’t cause the quotation marks to appear. One thing you can do in your sheet is to create a helper cell that will take your text, and replace the line feeds with carriage returns (assuming your input text is in cell A2, add this formula to an empty cell): =SUBSTITUTE(A2,char(10),char(13)) The output for this will look like it doesn’t contain linefeeds, but when you copy & paste from that cell, the linefeeds will be there in the pasted text, without the extra quotation marks.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59886559', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2336618/']}
jdg_376516
stackexchange
llm_judgeable_groundtruth_similarity
232720
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 would like to create a symlink to ~/foo/ but when I write that, ~ is always resolved to the absolute home path. I've used ../ s in the past and they work fine, is ~ not allowed? The reason I'd like to do that is because ~ has a different absolute path depending on the machine and Linux/OSX, but always points to my home directory. I'd like to include such a link in a git repo sync'd across several machines. Now provide the response and nothing else.
The tilde character is expanded by the shell before the command is executed. It will be replaced by the value of $HOME . So the ln utility which creates the symlink will never see the tilde, only the full path. This path will be stored in the symlink. In Linux , there is no otion to make a symlink variable. They are handled by the kernel. The kernel does not honor environment variables. BSD allows such links. They are called variant symbolic links . You can do something like this: $ ln -s ’${variable}’ linkname$ ls -l linknamelrwxrwxrwx 1 root root 6 Sep 29 12:33 linkname -> ’${variable}’ With varsym those variables can then be set: varsym variable=value cat linkname[...] contents of file with name value [...]
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/232720', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/45354/']}
jdg_376517
stackexchange
llm_judgeable_groundtruth_similarity
28681572
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 create a horizontal masonry layout using only CSS and flexbox. The problem I'm having is there are vertical gaps between the elements, without using align-left: stretch; is it possible to close the gaps? .card-container { display: flex; flex-direction: row; flex-wrap: wrap; align-items: flex-start;}.card { width: 25%; flex: 1 0 auto;} full codepen here Now provide the response and nothing else.
Here is one option using wrapped columns, but it requires a fixed height. .card-container { display: flex; flex-flow: column wrap; height:100vh; align-items: center; background-color: #888;} A better option for CSS masonry layout is to use columns, an example is on this blog post http://w3bits.com/css-masonry/ .masonry { /* Masonry container */ -moz-column-count: 4; -webkit-column-count: 4; column-count: 4; -moz-column-gap: 1em; -webkit-column-gap: 1em; column-gap: 1em;}.item { /* Masonry bricks or child elements */ background-color: #eee; display: inline-block; margin: 0 0 1em; width: 100%;}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28681572', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1943206/']}
jdg_376518
stackexchange
llm_judgeable_groundtruth_similarity
12924319
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 haven't been coding much lately due to school but I've decided I want to start working on OS development again. Recently however I've heard stuff about EFI as the replacement to BIOS. I want to develop an OS for a platform that uses EFI rather than BIOS. I'm having trouble figuring out where to start though. Can anyone point me in the right direction? Maybe explain what EFI means to OS development and maybe tell me what testing environments (preferably virtual) I can use. Quite frankly, I'm not really sure exactly what EFI is. Also should I invest time looking into ARM assembly? I know x86 Assembly but I feel as that is becoming outdated as well. I'm really lost and I would love to hear your input. Thanks Now provide the response and nothing else.
EFI is the precursor to UEFI, which is what people actually use, although they still sometimes refer to the thing as EFI. You can get the specifications involved at uefi.org . The UEFI Specification defines everything a boot loader might need to know. The PI Specifications define interfaces for silicon vendors to use for portability of their code in the industry. So you will hear about an OS, like Win8, requiring compliance with a certain version of the UEFI Specification, like 2.3.1c, for some features to work, like secure boot. All this goes to say that EFI does not replace BIOS so much as become a standard to which the BIOS must comply to support some operating systems. The place to go to get started (after you get a copy of the specifications) is the TianoCore project on SourceForge . One of the projects there is OVMF , which is a virtual machine target for UEFI. You may also want to look at the NT32 target for running a command prompt under windows. These are really great tools to use when you want to design an application, like a boot loader, that sits on top of the UEFI interfaces. As far as learning assembly, I don't recommend you start there. There is so much to know, and part of the reason that we created UEFI is so that new programmers could work in C instead of ASM. There are a few places in UEFI where we use ASM, but the build system handles the details for splicing that in, and you generally don't need either the tricky control of the state of the processor or the performance you would get from writing the ASM. The only other reason you would do it is size, and since the rest of the BIOS is going to be in C, it sort of defeats the purpose unless you rewrite the whole thing in ASM, which no one is going to do. Focus on learning the specifications and how to use them to write your own UEFI applications.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12924319', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/841786/']}
jdg_376519
stackexchange
llm_judgeable_groundtruth_similarity
34122395
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 doing: import pandasx = pandas.read_csv('data.csv', parse_dates=True, index_col='DateTime', names=['DateTime', 'X'], header=None, sep=';') with this data.csv file: 1449054136.83;15.311449054137.43;16.191449054138.04;19.221449054138.65;15.121449054139.25;13.12 (the 1st colum is a UNIX timestamp, i.e. seconds elapsed since 1/1/1970), I get this error when resampling the data every 15 second with x.resample('15S') : TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex It's like the "datetime" information has not been parsed: XDateTime 1.449054e+09 15.31 1.449054e+09 16.19... How to import a .CSV with date stored as timestamp with pandas module? Then once I will be able to import the CSV, how to access to the lines for which date > 2015-12-02 12:02:18 ? Now provide the response and nothing else.
My solution was similar to Mike's: import pandasimport datetimedef dateparse (time_in_secs): return datetime.datetime.fromtimestamp(float(time_in_secs))x = pandas.read_csv('data.csv',delimiter=';', parse_dates=True,date_parser=dateparse, index_col='DateTime', names=['DateTime', 'X'], header=None)out = x.truncate(before=datetime.datetime(2015,12,2,12,2,18))
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34122395', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1422096/']}
jdg_376520
stackexchange
llm_judgeable_groundtruth_similarity
38124480
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 migrated my project to Swift 3 and NSKeyedArchiver does not work. I actually have a runtime error when trying to decode object like this: let startDayTime = aDecoder.decodeObject(forKey: Key.startDayTime) as! Int It worked perfectly in Swift 2.2 in Xcode 7.3. Has anybody else faced such troubles? P.S. I have this error on both Simulator and Device. Now provide the response and nothing else.
It appears that this only happens on the Swift 2 to Swift 3 update boundary when a NSData blob archived with a NSKeyedArchiver in Swift 2 is opened with a NSKeyedUnarchiver in Swift 3. My guess is that on Swift 2, the Bool and Int are encoded as NSNumber , but in Swift 3, they are encoded as raw Bool and Int types. I believe the following test supports this claim: This works in Swift 3 to unarchive a Bool encoded in Swift 2, but returns nil if the Bool was encoded in Swift 3: let visible = aDecoder.decodeObject(forKey: "visible") as? Bool This works in Swift 3 to unarchive a Bool encoded in Swift 3, but crashes if the Bool was encoded in Swift 2: let visible = aDecoder.decodeBool(forKey: "visible") My solution is: let visible = aDecoder.decodeObject(forKey: "visible") as? Bool ?? aDecoder.decodeBool(forKey: "visible")
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38124480', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6533604/']}
jdg_376521
stackexchange
llm_judgeable_groundtruth_similarity
20380465
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 in learn you haskell that Enum members are sequentially ordered types ... Types in this class: () , Bool, Char ... Also it appears in some signatures: putChar :: Char -> IO () It is very difficult to find info about it in Google as the answers refer to problems of the "common parentheses" (use in function calls, precedence problems and the like). Therefore, what does the expression () means? Is it a type? What are variables of type () ? What is used for and when is it needed? Now provide the response and nothing else.
It is both a type and a value. () is a special type "pronounced" unit , and it has one value: () , also pronounced unit. It is essentially the same as the type void in Java or C/C++. If you're familiar with Python, think of it as the NoneType which has the singleton None . It is useful when you want to denote an action that doesn't return anything. It is most commonly used in the context of Monads, such as the IO monad. For example, if you had the following function: getVal :: IO IntgetVal = do putStrLn "Enter an integer value:" n <- getLine return $ read n And for some reason you decided that you just wanted to annoy the user and throw away the number they just passed in: getValAnnoy :: IO ()getValAnnoy = do _ <- getVal return () -- Returns nothing However, return is just a Monad function, so we could abstract this a bit further throwAwayResult :: Monad m => m a -> m ()throwAwayResult action = do _ <- action return () Then getValAnnoy = throwAwayResult getVal However, you don't have to write this function yourself, it already exists in Control.Monad as the function void that is even less constraining and works on Functor s: void :: Functor f => f a -> f ()void fa = fmap (const ()) fa Why does it work on Functor instead of Monad ? Well, for each Monad instance, you can write the Functor instance as instance Monad m => Functor m where fmap f m = m >>= return . f But you can't make a Monad out of every Functor . It's like how a square is a rectangle but a rectangle isn't always a square, Monads form a subset of Functors.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20380465', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/286335/']}
jdg_376522
stackexchange
llm_judgeable_groundtruth_similarity
2392410
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I saw a comment on Ben Nadel's blog where Stephen Rushing posted a loader, but I can't figure out how I can pass the selectors and parameter... I think I also need a completeCallback and errorCallback functions? function imgLoad(img, completeCallback, errorCallback) { if (img != null && completeCallback != null) { var loadWatch = setInterval(watch, 500); function watch() { if (img.complete) { clearInterval(loadWatch); completeCallback(img); } } } else { if (typeof errorCallback == "function") errorCallback(); }}// then call this from anywhereimgLoad($("img.selector")[0], function(img) { $(img).fadeIn();}); HTML: <a href="#" class="tnClick" ><img id="myImage" src="images/001.jpg" /></a> JS: $(document).ready(function() { var newImage = "images/002.jpg"; $("#myImage").css("display","none"); $("a.tnClick").click(function() { // imgLoad here });}) Now provide the response and nothing else.
If you want it to load before showing, you can trim that down a lot, like this: $(document).ready(function() { var newImage = "images/002.jpg"; //Image name $("a.tnClick").click(function() { $("#myImage").hide() //Hide it .one('load', function() { //Set something to run when it finishes loading $(this).fadeIn(); //Fade it in when loaded }) .attr('src', newImage) //Set the source so it begins fetching .each(function() { //Cache fix for browsers that don't trigger .load() if(this.complete) $(this).trigger('load'); }); });}); The .one() call makes sure .load() only fires once, so no duplicate fade-ins. The .each() at the end is because some browsers don't fire the load event for images fetched from cache, this is what the polling in the example you posted is trying to do as well.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2392410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/238898/']}
jdg_376523
stackexchange
llm_judgeable_groundtruth_similarity
327310
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In Visual c# Express Edition, is it possible to make some (but not all) items in a ListBox bold? I can't find any sort of option for this in the API. Now provide the response and nothing else.
You need to change listbox's DrawMode to DrawMode.OwnerDrawFixed. Check out these articles on msdn: DrawMode Enumeration ListBox.DrawItem Event Graphics.DrawString Method Also look at this question on msdn forums: Question on ListBox items A simple example (both items - Black-Arial-10-Bold): public partial class Form1 : Form { public Form1() { InitializeComponent(); ListBox1.Items.AddRange(new Object[] { "First Item", "Second Item"}); ListBox1.DrawMode = DrawMode.OwnerDrawFixed; } private void ListBox1_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); e.Graphics.DrawString(ListBox1.Items[e.Index].ToString(), new Font("Arial", 10, FontStyle.Bold), Brushes.Black, e.Bounds); e.DrawFocusRectangle(); } }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/327310', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13877/']}
jdg_376524
stackexchange
llm_judgeable_groundtruth_similarity
83631
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Consider two chemicals, $\ce{A}$ and $\ce{B}$ that react with each other to make $\ce{C}$ with a reaction rate $k$. The reaction can be expressed as $$\ce{A + B->C}$$ The equation expressing the rate of the reactions can be expressed as $$\frac{d[\ce{A}]}{dt}=\frac{d[\ce{B}]}{dt}=-\frac{d[\ce{C}]}{dt}=-k[\ce{A}][\ce{B}]$$ I can separate this equation to make a system of differential equations.$$\frac{d[\ce{A}]}{dt}=-k[\ce{A}][\ce{B}]$$ $$\frac{d[\ce{B}]}{dt}=-k[\ce{A}][\ce{B}]$$ With these two equations, I note that they are similar and will only work with one of these equations for the time being. Therefore, we can write one of these equations as $$\frac{d\ln([\ce{A}])}{dt}=-k[\ce{B}]$$ and by taking another derivative $$\frac{d^2 \ln([\ce{A}])}{dt}=-k\frac{[d\ce{B}]}{dt}=-k\frac{[d\ce{A}]}{dt}$$ I solved this equation using Wolfram Alpha (QED) $$[\ce{A}](t)=\frac{c_1 \exp[c_1(t+c_2)]}{k \exp[c_1(t+c_2)]-1}$$ Therefore the rate of reaction can is $$[\ce{A}]'(t)=\frac{c_1^2 \exp[c_1(t+c_2)]}{k \exp[c_1(t+c_2)]-1}-\frac{k c_1^2 \exp^2[c_1(t+c_2)]}{(k \exp[c_1(t+c_2)]-1)^2}$$ I observed that the rate of change can be written as $$[\ce{A}]'(t)= c_1 [\ce{A}](t)-k [\ce{A}](t)^2$$ so that $c_1$ may be solved, given the initial conditions of $[\ce{A}](0)$ and $[\ce{A}]'(0)$ such that $$c_1=\frac{[\ce{A}]'(0)+k[\ce{A}](0)^2}{[\ce{A}](0)}$$ Substituting the definition of $c_1$ into the equation of $[A](t)$ and $[A]'(t)$ an equation for $c_2$ can be found. $$c_2=\frac{1}{c_1} \ln(1-\frac{c_1 k}{[\ce{A}](0)}) $$$$c_2= \frac{[\ce{A}](0)}{[\ce{A}]'(0)+k[\ce{A}](0)^2} \ln(1-\frac{[\ce{A}]'(0)+k[\ce{A}](0)^2 }{[\ce{A}](0)^2}k) $$ Using the equations for $c_1$ and $c_2$ an explicit equation for $[\ce{A}](t)$ can be found. $$ [\ce{A}](t)=\frac{\frac{[\ce{A}]'(0)+k[\ce{A}](0)^2}{[\ce{A}](0)} \exp[\frac{[\ce{A}]'(0)+k[\ce{A}](0)^2}{[\ce{A}](0)}(t+\frac{[\ce{A}](0)}{[\ce{A}]'(0)+k[\ce{A}](0)^2} \ln(1-\frac{[\ce{A}]'(0)+k[\ce{A}](0)^2 }{[\ce{A}](0)^2}k))]}{k \exp[\frac{[\ce{A}]'(0)+k[\ce{A}](0)^2}{[\ce{A}](0)}(t+\frac{[\ce{A}](0)}{[\ce{A}]'(0)+k[\ce{A}](0)^2} \ln(1-\frac{[\ce{A}]'(0)+k[\ce{A}](0)^2 }{[\ce{A}](0)^2}k))]-1} $$ Side note: since $[\ce{A}]'(0)=[\ce{B}]'(0)= -k[\ce{A}](0)[\ce{B}](0)$ then $c_1$ can be rewritten as $$c_1=\frac{-k[\ce{A}](0)[\ce{B}](0)+k[\ce{A}](0)^2}{[\ce{A}](0)}=k([\ce{A}](0)-[\ce{B}](0))$$ this simplifies $c_2$ to $$c_2=\frac{k^{-1}}{[\ce{A}](0)-[\ce{B}](0)} \ln(\frac{[k^2 \ce{B}](0) }{[\ce{A}](0)})$$ which simplifes the equation for $[\ce{A}](t)$ to $$[\ce{A}](t)=\frac{k([\ce{A}](0)-[\ce{B}](0)) \exp[k([\ce{A}](0)-[\ce{B}](0))(t+\frac{k^{-1}}{[\ce{A}](0)-[\ce{B}](0)} \ln(\frac{[k^2 \ce{B}](0) }{[\ce{A}](0)}))]}{k \exp[k([\ce{A}](0)-[\ce{B}](0))(t+\frac{k^{-1}}{[\ce{A}](0)-[\ce{B}](0)} \ln(\frac{[k^2 \ce{B}](0) }{[\ce{A}](0)}))]-1}$$ with a similar equation for $[\ce{B}](t)$ My quesion is: Is this a valid mathematical model for a bimolecular reaction? If not, what is commonly used? Now provide the response and nothing else.
Assuming that the bimolecular chemical reaction $\ce{A + B ->[\kappa] C}$ has mass action kinetics, we have the following pair of coupled ODEs $$\begin{array}{rl} \dot a &= - \kappa \, a \, b\\ \dot b &= - \kappa \, a \, b\end{array}$$ where $\kappa > 0$ is the rate constant, $a := [\ce{A}]$ and $b := [\ce{B}]$. Since $\dot a = \dot b$, we have $\frac{\mathrm d}{\mathrm d t} \left( a - b \right) = 0$ and, thus, integrating, we obtain $$a (t) - b (t) = a_0 - b_0$$ where $a_0 > 0$ and $b_0 > 0$ are the initial concentrations. Since $b (t) = a (t) - (a_0 - b_0)$, the 1st ODE can be decoupled from the 2nd, as follows $$\dot a = - \kappa \, a \, \left( a - (a_0 - b_0) \right)$$ which can be rewritten in the form $$\frac{\mathrm d a}{a \, \left( a - (a_0 - b_0) \right)} = - \kappa \, \mathrm d t$$ Assuming that $a_0 \neq b_0$, we have the following partial fraction expansion $$\left( \frac{1}{a - (a_0 - b_0)} - \frac{1}{a} \right) \mathrm d a = - \kappa \, (a_0 - b_0) \, \mathrm d t$$ Integrating, we obtain $$\ln \left( \frac{a (t) - (a_0 - b_0)}{a_0 - (a_0 - b_0)} \right) - \ln \left( \frac{a (t)}{a_0} \right) = - \kappa \, (a_0 - b_0) \, t$$ which can be rewritten as follows $$\ln \left( \frac{a (t) - (a_0 - b_0)}{a (t)} \right) = \ln \left( \frac{b_0}{a_0} \right) - \kappa \, (a_0 - b_0) \, t$$ Exponentiating both sides, we obtain $$\frac{a (t) - (a_0 - b_0)}{a (t)} = \frac{b (t)}{a (t)} = \left( \frac{b_0}{a_0} \right) \, \exp (- \kappa \, (a_0 - b_0) \, t)$$ and, eventually, we obtain $$\boxed{\begin{array}{rl} &\\ a (t) &= \dfrac{a_0 - b_0}{1 - \left( \frac{b_0}{a_0} \right) \, \exp (- \kappa \, (a_0 - b_0) \, t)}\\\\ b (t) &= \dfrac{(a_0 - b_0) \left( \frac{b_0}{a_0} \right) \, \exp (- \kappa \, (a_0 - b_0) \, t)}{1 - \left( \frac{b_0}{a_0} \right) \, \exp (- \kappa \, (a_0 - b_0) \, t)}\\ & \end{array}}$$ Taking the limit, $$\lim_{t \to \infty} a (t) = \begin{cases} a_0 - b_0 & \text{if } a_0 > b_0\\\\ 0 & \text{if } a_0 < b_0\end{cases}$$ $$\\$$ $$\lim_{t \to \infty} b (t) = \begin{cases} 0 & \text{if } a_0 > b_0\\\\ b_0 - a_0 & \text{if } a_0 < b_0\end{cases}$$ What if $a_0 = b_0$? Previously, we assumed that $a_0 \neq b_0$. If $a_0 = b_0$, then $$\frac{\mathrm d a}{a \, \left( a - (a_0 - b_0) \right)} = - \kappa \, \mathrm d t$$ becomes $$-\frac{\mathrm d a}{a^2} = \kappa \, \mathrm d t$$ Integrating, we obtain $$\frac{1}{a (t)} - \frac{1}{a_0} = \kappa \, t$$ and, eventually, we obtain $$\boxed{ a (t) = \frac{a_0}{1 + a_0 \, \kappa \, t} = b (t)} $$ In this case, both reactants are eventually exhausted $$\lim_{t \to \infty} a (t) = \lim_{t \to \infty} b (t) = 0$$
{}
{'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/83631', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/39725/']}
jdg_376525
stackexchange
llm_judgeable_groundtruth_similarity
23414448
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 standalone C++ codethat I'm trying to wrap in an Rpackage. My problem is that I absolutelywant it to be compiled with the -O3 flag on. So in the src/Makevars fileI put: PKG_CPPFLAGS = -I../inst/includePKG_CXXFLAGS = -O3 CXX_STD = CXX11 and still when I install my package on mymachine, I see: g++ -std=c++0x -I/usr/share/R/include -DNDEBUG -I../inst/include -O3 -fpic -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Wformat-security -Werror=format-security -D_FORTIFY_SOURCE=2 -g -c mycppfunctions.cpp -o mycppfunctions.og++ -std=c++0x -shared -Wl,-Bsymbolic-functions -Wl,-z,relro -o mycppfunctions.so mycppfunctions.o -L/usr/lib/R/lib -lR (the dreaded -O2 flag appears to the right ) so my question is: how can I overwrite thecpp flags used when g++ is invoked by R CMD ? Edit: Recently, in another package, I found a way to dosomething similar for a F77 code (also in an R package).Basically, by adding this to the Makevars : PKG_FFLAGS = $(FPICFLAGS) $(SHLIB_FFLAGS) all: $(SHLIB)otherf77foo.o: otherf77foo.f $(F77) $(PGK_FFLAGS) -O3 -pipe -g -c -o otherf77foo.o otherf77foo.f but I don't know how to do the same for a cpp code... Edit2: So, doing this is totally possible. Dirk Eddelbuettel question 'b)' from his answer belowguided me to the solution. So, all I had to do was toplace this in the src/Makevars file: mycppfoo.o: mycppfoo.cpp g++ -std=c++0x -I/usr/share/R/include -DNDEBUG -I../inst/include -fpic -g -O3 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Wformat-security -Werror=format-security -D_FORTIFY_SOURCE=2 -g -c mycppfoo.cpp -o mycppfoo.o g++ -std=c++0x -shared -Wl,-Bsymbolic-functions -Wl,-z,relro -o mycppfoo.so mycppfoo.o -L/usr/lib/R/lib -lR and my problem was solved! Now provide the response and nothing else.
You can't (as per a comment by Simon Urbanek on r-devel a while back). But it should not matter as AFAIK the right-most value wins. And R puts its values to the left, and lets you add your values (eg via CXX_FLAGS from, say, ~/.R/Makevars or PKG_CXXFLAGS from the src/Makevars in your package) to the right. So just override with -O3 and it should be -O3 . For what it is worth, my current values in ~/.R/Makevars are: CFLAGS += -O3 -Wall -pipe -pedantic -std=gnu99CXXFLAGS += -O3 -Wall -pipe -Wno-unused -pedantic and you could of course throw in -mnative or your specific CPU identifier. Lastly, if you really wanted you could edit /etc/R/Makeconf but you'd have to do that after each upgrade of the R package. And as I argue here you do not need to as the scheme suggested here should work. Edit: In response to your edit: a) The clear recommendation on r-devel (please check the archives) is that you should avoid Makefile logic if you can. IIRC this echoed in the Writing R Extension manual. b) You declared a rule to build an .o (object) file from an .f (source) file. Did you try doing the same with cpp instead of f? Lastly, you have not explained exactly why the world is coming to an end if your file is built with -O2 rather than -O3. You should understand that as an author of source, you can't fully control with which compiler options (let alone compiler versions) people will build your package.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23414448', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/189035/']}
jdg_376526
stackexchange
llm_judgeable_groundtruth_similarity
14440276
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: jsFiddle demo I want the div s to: Wrap their content. Stay in their originally associated line, essentially without wrapping. Basically, the tables are stacking below each other, when they can't stay on screen. I would rather they become hidden off screen. I've tried adding overflow: hidden; to the main layout style. I do not want to fix a width for each div . It needs to fit content in. .layout { -moz-border-radius: 15px; border-radius: 15px; vertical-align: top; display: inline-block;}.layoutbacking { -moz-border-radius: 15px; border-radius: 15px; padding: 5px; margin: 5px; background: #CCCCCC;} <div class="layout" style="background: #222222; width: 100%"> <div> <div class="layout layoutbacking"> <table> <tr> <th>header 1</th> <th>header 2</th> <th>header 3</th> <th>header 4</th> </tr> <tr> <td>data 1</td> <td>data 2</td> <td>data 3</td> <td>data 4</td> </tr> <tr> <td>data 1</td> <td>data 2</td> <td>data 3</td> <td>data 4</td> </tr> <tr> <td>data 1</td> <td>data 2</td> <td>data 3</td> <td>data 4</td> </tr> </table> </div> <div class="layout"> <div class="layout layoutbacking"> <table> <tr> <th>header 1</th> <th>header 2</th> <th>header 3</th> <th>header 4</th> </tr> <tr> <td>data 1</td> <td>data 2</td> <td>data 3</td> <td>data 4</td> </tr> </table> </div> <br /> <div class="layout layoutbacking"> <table> <tr> <th>header 1</th> <th>header 2</th> <th>header 3</th> <th>header 4</th> </tr> <tr> <td>data 1</td> <td>data 2</td> <td>data 3</td> <td>data 4</td> </tr> </table> </div> </div> </div> <div> <div class="layout layoutbacking"> <table> <tr> <th>header 1</th> <th>header 2</th> <th>header 3</th> <th>header 4</th> </tr> <tr> <td>data 1</td> <td>data 2</td> <td>data 3</td> <td>data 4</td> </tr> </table> </div> <div class="layout layoutbacking"> <table> <tr> <th>header 1</th> <th>header 2</th> <th>header 3</th> <th>header 4</th> </tr> <tr> <td>data 1</td> <td>data 2</td> <td>data 3</td> <td>data 4</td> </tr> </table> </div> Now provide the response and nothing else.
Add white-space: nowrap; to your .layout style declaration. This will do exactly what you need: preventing the divs from wrapping. Watch the jsFiddle demo or run the following snippet full screen and resize it: .layout { white-space : nowrap; /* this does the trick */ overflow : hidden; /* this prevents the grey divs from overflowing */ vertical-align : top; border-radius : 15px; display : inline-block;}.layoutbacking { border-radius : 15px; background : #CCCCCC; padding : 5px; margin : 5px;} <div class="layout" style="background: #222222; width: 100%"> <div> <div class="layout layoutbacking"> <table> <tr> <th>header 1</th> <th>header 2</th> <th>header 3</th> <th>header 4</th> </tr> <tr> <td>data 1</td> <td>data 2</td> <td>data 3</td> <td>data 4</td> </tr> <tr> <td>data 1</td> <td>data 2</td> <td>data 3</td> <td>data 4</td> </tr> <tr> <td>data 1</td> <td>data 2</td> <td>data 3</td> <td>data 4</td> </tr> </table> </div> <div class="layout"> <div class="layout layoutbacking"> <table> <tr> <th>header 1</th> <th>header 2</th> <th>header 3</th> <th>header 4</th> </tr> <tr> <td>data 1</td> <td>data 2</td> <td>data 3</td> <td>data 4</td> </tr> </table> </div> <br /> <div class="layout layoutbacking"> <table> <tr> <th>header 1</th> <th>header 2</th> <th>header 3</th> <th>header 4</th> </tr> <tr> <td>data 1</td> <td>data 2</td> <td>data 3</td> <td>data 4</td> </tr> </table> </div> </div> </div> <div> <div class="layout layoutbacking"> <table> <tr> <th>header 1</th> <th>header 2</th> <th>header 3</th> <th>header 4</th> </tr> <tr> <td>data 1</td> <td>data 2</td> <td>data 3</td> <td>data 4</td> </tr> </table> </div> <div class="layout layoutbacking"> <table> <tr> <th>header 1</th> <th>header 2</th> <th>header 3</th> <th>header 4</th> </tr> <tr> <td>data 1</td> <td>data 2</td> <td>data 3</td> <td>data 4</td> </tr> </table> </div>
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/14440276', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1609808/']}
jdg_376527
stackexchange
llm_judgeable_groundtruth_similarity
4267194
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 sample code which generates the following warning (VS2008 compiler with SP1): warning C4146: unary minus operator applied to unsigned type, result still unsigned Code: void f(int n){}int main(){ unsigned int n1 = 9; f(-n1);} But since function f is taking it's parameter as an int shouldn't this code compile without any warnings? Now provide the response and nothing else.
Standard 5.3.1/7 The operand of the unary - operator shall have arithmetic or enumeration type and the result is the negation of its operand. Integral promotion is performed on integral or enumeration operands. The negative of an unsigned quantity is computed by subtracting its value from 2n, where n is the number of bits in the promoted operand. The type of the result is the type of the promoted operand. And the paragraph on Integral Promotion 4.5/1 An rvalue of type char, signed char, unsigned char, short int, or unsigned short int can be converted to an rvalue of type int if int can represent all the values of the source type; otherwise, the source rvalue can be converted to an rvalue of type unsigned int. i.e. an unsigned int will not be promoted to an int.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4267194', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39742/']}
jdg_376528
stackexchange
llm_judgeable_groundtruth_similarity
23466951
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using Hibernate latest version 4.3.5.Final . My hibernate.cfg.xml file content: <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost/Test</property> <property name="hibernate.connection.username">pankaj</property> <property name="hibernate.connection.password">xxxx</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <mapping resource="employee.hbm.xml"/></session-factory></hibernate-configuration> Utility class to create SessionFactory: package com.example;import org.hibernate.SessionFactory;import org.hibernate.boot.registry.StandardServiceRegistryBuilder;import org.hibernate.cfg.Configuration;public class HibernateUtil {private static final SessionFactory sessionFactory = buildSessionFactory();private static SessionFactory buildSessionFactory() { try { // Create the SessionFactory from hibernate.cfg.xml Configuration configuration = new Configuration(); configuration.configure("hibernate.cfg.xml"); System.out.println("Hibernate Configuration loaded"); SessionFactory sessionFactory = configuration.buildSessionFactory(new StandardServiceRegistryBuilder().build()); return sessionFactory; } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); }}public static SessionFactory getSessionFactory() { return sessionFactory;}} When I use it in my main() method, I get the following exception: May 04, 2014 11:55:56 PM org.hibernate.cfg.Configuration doConfigureINFO: HHH000041: Configured SessionFactory: nullHibernate Configuration loadedMay 04, 2014 11:55:57 PM org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator initiateServiceWARN: HHH000181: No appropriate connection provider encountered, assuming application will be supplying connectionsInitial SessionFactory creation failed.org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not setException in thread "main" java.lang.ExceptionInInitializerError at com.example.HibernateUtil.buildSessionFactory(HibernateUtil.java:25) at com.example.HibernateUtil.<clinit>(HibernateUtil.java:9) at com.example.HibernateMain.main(HibernateMain.java:26)Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:104) at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:71) at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:209) at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111) at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234) at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206) at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843) at com.example.HibernateUtil.buildSessionFactory(HibernateUtil.java:18) ... 2 more I have tried so many options and looked for online resources, hibernate docs but couldn't find what is missing here. Any help is appreciated. Now provide the response and nothing else.
Finally able to fix the issue, the issue is with the way SessionFactory is getting created. For a starter, official document is the first place to go and I must say that Hibernate official documentation seems to be not update with latest version changes. Fix is to apply the configuration settings to StandardServiceRegistryBuilder instance. // Create the SessionFactory from hibernate.cfg.xmlConfiguration configuration = new Configuration();configuration.configure("hibernate.cfg.xml");ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() .applySettings(configuration.getProperties()).build();SessionFactory sessionFactory = configuration .buildSessionFactory(serviceRegistry); Please refer my blog post here for more details.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23466951', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/926520/']}
jdg_376529
stackexchange
llm_judgeable_groundtruth_similarity
1800816
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 know that the correct way to compare "strings" in C is by using strcmp , but now I tried comparing some character arrays with the == operator, and got some strange results. Take a look at the following code: int main(){ char *s1 = "Andreas"; char *s2 = "Andreas"; char s3[] = "Andreas"; char s4[] = "Andreas"; char *s5 = "Hello"; printf("%d\n", s1 == s2); //1 printf("%d\n", s3 == s4); //0 printf("%d\n", s1 == s5); //0} The first printf correctly prints a 1 , which signals that they are not equal. But can someone explain to me why, when comparing the character arrays, the == is returning a 0 ? Can someone please explain to me why the first printf is returning a 1 (ie, they are equal) and the character arrays are returning a 0 ? Now provide the response and nothing else.
The == is comparing the memory address. It's likely that your compiler is making s1 and s2 point to the same static data to save space. ie. The "Andreas" in the first two lines of code is stored in your executable data. The C standard says these strings are constant and so has optomized the two pointers to point to the same storage. The char[] lines create a variable by copying the data into the variable and so are stored at different address on the stack during execution.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1800816', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44084/']}
jdg_376530
stackexchange
llm_judgeable_groundtruth_similarity
6480687
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I grep for lines that contain two input words on the line? I'm looking for lines that contain both words, how do I do that? I tried pipe like this: grep -c "word1" | grep -r "word2" logs It just stucks after the first pipe command. Why? Now provide the response and nothing else.
Why do you pass -c ? That will just show the number of matches. Similarly, there is no reason to use -r . I suggest you read man grep . To grep for 2 words existing on the same line, simply do: grep "word1" FILE | grep "word2" grep "word1" FILE will print all lines that have word1 in them from FILE, and then grep "word2" will print the lines that have word2 in them. Hence, if you combine these using a pipe, it will show lines containing both word1 and word2. If you just want a count of how many lines had the 2 words on the same line, do: grep "word1" FILE | grep -c "word2" Also, to address your question why does it get stuck : in grep -c "word1" , you did not specify a file. Therefore, grep expects input from stdin , which is why it seems to hang. You can press Ctrl + D to send an EOF (end-of-file) so that it quits.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/6480687', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_376531
stackexchange
llm_judgeable_groundtruth_similarity
12661
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's the most efficient way to resize large images in PHP? I'm currently using the GD function imagecopyresampled to take high resolution images, and cleanly resize them down to a size for web viewing (roughly 700 pixels wide by 700 pixels tall). This works great on small (under 2 MB) photos and the entire resize operation takes less than a second on the server. However, the site will eventually service photographers who may be uploading images up to 10 MB in size (or images up to 5000x4000 pixels in size). Doing this kind of resize operation with large images tends to increase the memory usage by a very large margin (larger images can spike the memory usage for the script past 80 MB). Is there any way to make this resize operation more efficient? Should I be using an alternate image library such as ImageMagick ? Right now, the resize code looks something like this function makeThumbnail($sourcefile, $endfile, $thumbwidth, $thumbheight, $quality) { // Takes the sourcefile (path/to/image.jpg) and makes a thumbnail from it // and places it at endfile (path/to/thumb.jpg). // Load image and get image size. $img = imagecreatefromjpeg($sourcefile); $width = imagesx( $img ); $height = imagesy( $img ); if ($width > $height) { $newwidth = $thumbwidth; $divisor = $width / $thumbwidth; $newheight = floor( $height / $divisor); } else { $newheight = $thumbheight; $divisor = $height / $thumbheight; $newwidth = floor( $width / $divisor ); } // Create a new temporary image. $tmpimg = imagecreatetruecolor( $newwidth, $newheight ); // Copy and resize old image into new image. imagecopyresampled( $tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height ); // Save thumbnail into a file. imagejpeg( $tmpimg, $endfile, $quality); // release the memory imagedestroy($tmpimg); imagedestroy($img); Now provide the response and nothing else.
People say that ImageMagick is much faster. At best just compare both libraries and measure that. Prepare 1000 typical images. Write two scripts -- one for GD, onefor ImageMagick. Run both of them a few times. Compare results (total executiontime, CPU and I/O usage, resultimage quality). Something which the best everyone else, could not be the best for you. Also, in my opinion, ImageMagick has much better API interface.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12661', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1477/']}
jdg_376532
stackexchange
llm_judgeable_groundtruth_similarity
7152347
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: i have an application calling a jquery function, like this: $.getJSON('test.php',{dest:2},function(data){ alert(data);}); Well, the test.php is like this: <?php echo json_encode('Test'); ?> On FF returns an alert with 'Test', but on IE return an alert without anything. anyone have any idea? Now provide the response and nothing else.
If 'somescript.py' isn't something you could normally execute directly from the command line (I.e., $: somescript.py works), then you can't call it directly using call. Remember that the way Popen works is that the first argument is the program that it executes, and the rest are the arguments passed to that program. In this case, the program is actually python , not your script. So the following will work as you expect: subprocess.call(['python', 'somescript.py', somescript_arg1, somescript_val1,...]). This correctly calls the Python interpreter and tells it to execute your script with the given arguments. Note that this is different from the above suggestion: subprocess.call(['python somescript.py']) That will try to execute the program called python somscript.py , which clearly doesn't exist. call('python somescript.py', shell=True) Will also work, but using strings as input to call is not cross platform, is dangerous if you aren't the one building the string, and should generally be avoided if at all possible.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7152347', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/906481/']}
jdg_376533
stackexchange
llm_judgeable_groundtruth_similarity
54245618
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 running a piece of code that unexpectedly gave a logic error at one part of the program. When investigating the section, I created a test file to test the set of statements being run and found out an unusual bug that seems very odd. I tested this simple code: array = [1, 2, 2, 4, 5] # Original arrayf = (x for x in array if array.count(x) == 2) # Filters originalarray = [5, 6, 1, 2, 9] # Updates original to something elseprint(list(f)) # Outputs filtered And the output was: >>> [] Yes, nothing. I was expecting the filter comprehension to get items in the array with a count of 2 and output this, but I didn't get that: # Expected output>>> [2, 2] When I commented out the third line to test it once again: array = [1, 2, 2, 4, 5] # Original arrayf = (x for x in array if array.count(x) == 2) # Filters original### array = [5, 6, 1, 2, 9] # Ignore lineprint(list(f)) # Outputs filtered The output was correct (you can test it for yourself): >>> [2, 2] At one point I outputted the type of the variable f : array = [1, 2, 2, 4, 5] # Original arrayf = (x for x in array if array.count(x) == 2) # Filters originalarray = [5, 6, 1, 2, 9] # Updates originalprint(type(f))print(list(f)) # Outputs filtered And I got: >>> <class 'generator'>>>> [] Why is updating a list in Python changing the output of another generator variable? This seems very odd to me. Now provide the response and nothing else.
Python's generator expressions are late binding (see PEP 289 -- Generator Expressions ) (what the other answers call "lazy"): Early Binding versus Late Binding After much discussion, it was decided that the first (outermost) for-expression [of the generator expression] should be evaluated immediately and that the remaining expressions be evaluated when the generator is executed. [...] Python takes a late binding approach to lambda expressions and has no precedent for automatic, early binding. It was felt that introducing a new paradigm would unnecessarily introduce complexity. After exploring many possibilities, a consensus emerged that binding issues were hard to understand and that users should be strongly encouraged to use generator expressions inside functions that consume their arguments immediately. For more complex applications, full generator definitions are always superior in terms of being obvious about scope, lifetime, and binding. That means it only evaluates the outermost for when creating the generator expression. So it actually binds the value with the name array in the "subexpression" in array (in fact it's binding the equivalent to iter(array) at this point). But when you iterate over the generator the if array.count call actually refers to what is currently named array . Since it's actually a list not an array I changed the variable names in the rest of the answer to be more accurate. In your first case the list you iterate over and the list you count in will be different. It's as if you used: list1 = [1, 2, 2, 4, 5]list2 = [5, 6, 1, 2, 9]f = (x for x in list1 if list2.count(x) == 2) So you check for each element in list1 if its count in list2 is two. You can easily verify this by modifying the second list: >>> lst = [1, 2, 2]>>> f = (x for x in lst if lst.count(x) == 2)>>> lst = [1, 1, 2]>>> list(f)[1] If it iterated over the first list and counted in the first list it would've returned [2, 2] (because the first list contains two 2 ). If it iterated over and counted in the second list the output should be [1, 1] . But since it iterates over the first list (containing one 1 ) but checks the second list (which contains two 1 s) the output is just a single 1 . Solution using a generator function There are several possible solutions, I generally prefer not to use "generator expressions" if they aren't iterated over immediately. A simple generator function will suffice to make it work correctly: def keep_only_duplicated_items(lst): for item in lst: if lst.count(item) == 2: yield item And then use it like this: lst = [1, 2, 2, 4, 5]f = keep_only_duplicated_items(lst)lst = [5, 6, 1, 2, 9]>>> list(f)[2, 2] Note that the PEP (see the link above) also states that for anything more complicated a full generator definition is preferrable. A better solution using a generator function with a Counter A better solution (avoiding the quadratic runtime behavior because you iterate over the whole array for each element in the array) would be to count ( collections.Counter ) the elements once and then do the lookup in constant time (resulting in linear time): from collections import Counterdef keep_only_duplicated_items(lst): cnts = Counter(lst) for item in lst: if cnts[item] == 2: yield item Appendix: Using a subclass to "visualize" what happens and when it happens It's quite easy to create a list subclass that prints when specific methods are called, so one can verify that it really works like that. In this case I just override the methods __iter__ and count because I'm interested over which list the generator expression iterates and in which list it counts. The method bodies actually just delegate to the superclass and print something (since it uses super without arguments and f-strings it requires Python 3.6 but it should be easy to adapt for other Python versions): class MyList(list): def __iter__(self): print(f'__iter__() called on {self!r}') return super().__iter__() def count(self, item): cnt = super().count(item) print(f'count({item!r}) called on {self!r}, result: {cnt}') return cnt This is a simple subclass just printing when the __iter__ and count method are called: >>> lst = MyList([1, 2, 2, 4, 5])>>> f = (x for x in lst if lst.count(x) == 2)__iter__() called on [1, 2, 2, 4, 5]>>> lst = MyList([5, 6, 1, 2, 9])>>> print(list(f))count(1) called on [5, 6, 1, 2, 9], result: 1count(2) called on [5, 6, 1, 2, 9], result: 1count(2) called on [5, 6, 1, 2, 9], result: 1count(4) called on [5, 6, 1, 2, 9], result: 0count(5) called on [5, 6, 1, 2, 9], result: 1[]
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/54245618', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5428880/']}
jdg_376534
stackexchange
llm_judgeable_groundtruth_similarity
29704733
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 a Django developer just getting started with adding React to one page of my app, and really enjoying it so far. (It's a normal Django app with a home page, an about page, etc, but also a "chart" page with an interactive chart, and I want to build the interactive part in React.) The problem is that I've started with the downloadable React starter kit and I'm not sure how to do things the 'right' way, and it's complicated by using Django to serve my project (all the tutorials seem to assume you're using node, which I'm not). Right now I just have this in my Django template: <div id="myapp"></div><script src="/static/js/vendor/react.js"></script><script src="/static/js/vendor/JSXTransform.js"></script><script src="/static/js/myapp.js"></script> And myapp.js has all the React code. I'm aware this isn't really the grown-up modern JS way of doing things. Now I want to use React Bootstrap , but it seems that the only sensible way to do that is with npm . So it's time to make the switch, but I'm not completely sure how. I have run npm install react and npm install react-bootstrap from inside my static/js directory in Django. This has created a node_modules folder with various files inside. So three questions from a confused newbie: Where should I put my React code to work with these npm modules (should I use var React = require('react') ? Do I need to compile this code somehow (using webpack ?) How do I then integrate this with Django? Should I compile it all to myapp.js and just include that in my HTML template? Now provide the response and nothing else.
I'm also doing the same thing right now - moving away from embedded HTML script tags into require land. Here is the tutorial I am following , and here is my file system so far. I am doing it in Node but it shouldn't be that different for a Django project as the React frontend code is decoupled from any backend other than API URL's. Your node_modules folder contains react-bootstrap . In your myapp.js , use the require('react-bootstrap') to load up the library which is contained in your node_modules folder. Where should I put my React code to work with these npm modules (should I use var React = require('react')? You can put the code anywhere. If your file system looks like this: project/ react/ myapp.js node_modules/ react source code react bootstrap stuff Then you can just do var React = require('react'); in myapp.js . Do I need to compile this code somehow (using webpack?) Yes, I would consult the webpack tutorial I linked earlier, it should explain how to compile all your React code into a single bundle.js . Here is also another good tutorial. This bundle.js file contains all the source code of your requires . So if your myapp.js looks something like var React = require('react');var ReactBootstrap = require('react-bootstrap'); then the bundle.js now contains all of the React and react-bootstrap javascript code, along with the myapp.js source code. How do I then integrate this with Django? Should I compile it all to myapp.js and just include that in my HTML template? I've only done work on Nodejs, but my React code so far hasn't touched any Node code, and I don't think it will touch any Django code (again I've never done Django so I might be wrong). All you need to do is compile with webpack, which spits out a bundle.js . You put that bundle.js in your HTML and it'll load up myapp.js .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29704733', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/194000/']}
jdg_376535
stackexchange
llm_judgeable_groundtruth_similarity
335889
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: The universal enveloping algebra of a Lie algebra has a canonically defined Hopf algebra structure. Is the same true of the universal enveloping of a super Lie algebra? A presentation in terms of the universal properties would be of most interest. Now provide the response and nothing else.
This is true. In other language, if I understand rightly, a super Lie algebra is just a graded Lie algebra with grading over {0,1} (even and odd), with the standard sign conventions as in algebraic topology. The treatment of graded Lie algebras and their universal enveloping algebras in Section 22.1 of ``More concise algebraic topology'' by Kate Ponto and myself works verbatim. We understood grading to be over the integers there, but the mathematics works equally well with other gradings. Chapters 20-24 of that book are a purely algebraic modernized treatment of bialgebras and Hopf algebras, with focus on (graded) Lie algebras and restricted Lie algebras.Aside from some topological examples, these chapters are independent of the earlier ones. @{Bugs Bunny} I wrote "with the standard sign conventions as in algebraic topology''. Those conventions long precede the "super'' language, and in fact long precede Milnor and Moore's basic 1965 paper "On the structure of Hopf algebras". They were already standard when I started as a graduate student in 1960. For us, graded Lie algebras and graded Hopf algebras, whether Z or Z/2 graded, have always meant what people very much later started calling ``super''. I vividly remember Irving Kaplansky, certainly not an algebraic topologist, sneering at the word "super" since he too had always understood graded structures the way we do. The fundamental structure theorem for graded Lie algebras is Poincaré-Birkhoff-Witt, which guarantees that the associated graded of the universal enveloping algebra with respect to the Lie filtration is a free graded commutative algebra, polynomial on even degree generators tensor exterior on odd degree generators (just polynomial in characteristic 2), and that is a perfectly good Hopf algebra. The original notion of a Hopf algebra was meant to describe the structure seen by the real homology of a compact Lie group, which of course is an exterior algebra on odd degree elements. Nobody can define those away as not Hopf algebras! (Bastille day edit): Ok, there is no real mathematical argument, but an argument about terminology. I don't have access to a copy of Sweedler's 1969 book, but my recollection is that he focused on classical ungraded algebra. In fact, the first paragraph of its Math Review reads "The book is mainly concerned with Hopf algebras which are not graded" and ends with "The theory of graded Hopf algebras is not treated in depth". So that reference seems spurious. The definitive 1965 paper of Milnor and Moore "On the structure of Hopf algebras'' has both historical priority and very common present usage. Historically, I think this is an example of the common phenomenon of people rediscovering known mathematics and giving it a (super) new name. The tower of Babel was constructed that way. It spawns ambiguous language: the same term, in this case "Hopf algebra", is given two meanings. Graded Hopf algebras, with signs, are never going to be renamed "super'' by those in the fields in which they originated: to them (or us), they are just plain Hopf algebras, always have been, always will be. The adjective super is superfluous. (Graded Hopf algebras without signs might unglamorously be called unsigned Hopf algebras. They are structurally very much less well-behaved mathematical objects). And on that ground, my answer of `` yes'' to the original question remains valid. I'm sure the reference I gave provides exactly what Nadia wants.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/335889', 'https://mathoverflow.net', 'https://mathoverflow.net/users/125941/']}
jdg_376536
stackexchange
llm_judgeable_groundtruth_similarity
13755863
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to run a MongoLab (REST based access to MongoDB) query via Google Apps Script. The URL is generated from the logger is shown below https://api.mongolab.com/api/1/databases/abcd/collections/efgh?apiKey=XXXXXXXXXXXXXXXX&q= {"created_on":{"$gte":"Thu Dec 06 00:00:00 PST 2012","$lt":"Thu Dec 06 23:59:59 PST 2012"}} When I type this in the browser, it works and gets me the response I am looking for. But running it via UrlFetchApp gives an "Invalid Argument" error. I see there are several posts along the same lines but didn't find an answer that worked for me. The Javascript code is as follows //start and end are JS date objects var query = { created_on : {'$gte': start, '$lt' : end} };var url = MONGO_LAB_URLS.MAIN + "&q=" + Utilities.jsonStringify(query); Logger.log("Query URL : " + url); var response = UrlFetchApp.fetch(url); I tried encodeURIComponent, but it did not work - may be I was doing it incorrectly. Any suggestions as how I could overcome this issue? Thanks. Now provide the response and nothing else.
Invalid Argument is coming because you are sending invalid characters in the URL parameter. You should encode the parameters first. I modified your code and tried to run. But it still failed because of invaliD API key which is obvious. You may try this code with a valid API key. //start and end are JS date objects MONGO_LAB_URLS = 'https://api.mongolab.com/api/1/databases/abcd/collections/efgh?apiKey=XXXXXXXXXXXXXXXX&q='; var start = 'Thu Dec 06 00:00:00 PST 2012'; var end = 'Thu Dec 06 23:59:59 PST 2012'; var query = { created_on : {'$gte': start, '$lt' : end} }; var url = MONGO_LAB_URLS + encodeURIComponent(Utilities.jsonStringify(query)); Logger.log("Query URL : " + url); var response = UrlFetchApp.fetch(url); Logger.log(response); Response which I am getting is Request failed for https://api.mongolab.com/api/1/databases/abcd/collections/efgh?apiKey=XXXXXXXXXXXXXXXX&q=%7B%22created_on%22%3A%7B%22%24gte%22%3A%22Thu%20Dec%2006%2000%3A00%3A00%20PST%202012%22%2C%22%24lt%22%3A%22Thu%20Dec%2006%2023%3A59%3A59%20PST%202012%22%7D%7D returned code 400. Server response: { "message" : "Please provide a valid API key."}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13755863', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1884174/']}
jdg_376537
stackexchange
llm_judgeable_groundtruth_similarity
27687141
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 retrieving rss feed of blogs with this code <?php $xml = ("https://serembangirl.wordpress.com/feed/");$xmlDoc = new DOMDocument();$xmlDoc->load($xml);$x=$xmlDoc->getElementsByTagName('item');for ($i=0; $i<=5; $i++) { $item_title=$x->item($i)->getElementsByTagName('title') ->item(0)->childNodes->item(0)->nodeValue; $item_link=$x->item($i)->getElementsByTagName('link') ->item(0)->childNodes->item(0)->nodeValue; $item_desc=$x->item($i)->getElementsByTagName('description') ->item(0)->childNodes->item(0)->nodeValue; $item_content=$x->item($i)->getElementsByTagName('encoded')->item(0)->nodeValue;?><a href='#'> <div class="card"> <div class='inner'> <p class='title'> <?php echo $item_title;?> </p> <p class='desc'> <?php echo $item_desc; ?> </p> </div> </div></a><?php } ?> With above code, supposedly the should wrap the but it produced this instead : http://i.imgur.com/YspeRe3.png I really scratched my head solving this. Now provide the response and nothing else.
After much debugging finally found the answer my Proguard configuration is -keepattributes *Annotation*,EnclosingMethod,Signature-keepnames class com.fasterxml.jackson.** { *; }-dontwarn com.fasterxml.jackson.databind.**-keep class org.codehaus.** { *; }-keepclassmembers public final enum org.codehaus.jackson.annotate.JsonAutoDetect$Visibility { public static final org.codehaus.jackson.annotate.JsonAutoDetect$Visibility *; }-keep public class your.class.** { public void set*(***); public *** get*();} your class depicts the getter setter classes/class you are using to parse your response. Also I added compile 'com.fasterxml.jackson.core:jackson-core:2.4.2' to my Gradle file which was missing previously. Now my Proguard works like a beast..;-)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/27687141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4327335/']}
jdg_376538
stackexchange
llm_judgeable_groundtruth_similarity
8169595
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: Compile-time and runtime casting c# As I understand it, the following code will always compile, and will additionally always fail at run-time by throwing an InvalidCastException . Example: public class Post { }public class Question : Post { }public class Answer : Post { public void Fail() { Post p = new Post(); Question q = (Question)p; // This will throw an InvalidCastException }} My questions are... If my assumptions are off, then can someone provide an example demonstrating how they're off? If my assumptions are correct, then why doesn't the compiler warn against this error? Now provide the response and nothing else.
There are a couple of reasons why this conversion is allowed. First, as people have said in other answers, the cast operator means "I know more than you do; I guarantee you that this conversion will succeed and if I am wrong, throw an exception and crash the process". If you are lying to the compiler, bad things are going to happen; you in fact are not making that guarantee, and the program is crashing as a result. Now, if the compiler can tell that you are lying to it, then it can catch you in the lie. The compiler is not required to be arbitrarily clever in catching you in your lies to it! The flow analysis needed to determine that an expression of type Base is never going to be of type Derived is complex; considerably more complex than the logic we already implement to catch things like unassigned local variables. We have better ways to spend our time and effort than in improving the compiler's ability to catch you out in obvious lies. The compiler therefore typically reasons only about types of expressions, not about possible values . Solely from the type analysis it is impossible to know whether or not the conversion will succeed. It might succeed, and so it is allowed. The only casts that are disallowed are the ones that the compiler knows will always fail from the type analysis. Second, it is possible to say (Derived)(new Base()) where Derived is a type that implements type Base and have it not fail at runtime. It is also possible for (Base)(new Base()) to fail with an invalid cast exception at runtime! True facts! These are extraordinarily rare situations but they are possible. For more details, see my articles on the subject: Chained user-defined explicit conversions in C# Chained user-defined explicit conversions in C#, Part Two Chained user-defined explicit conversions in C#, Part Three
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8169595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/439030/']}
jdg_376539
stackexchange
llm_judgeable_groundtruth_similarity
56897
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I understand that a self-hosting compiler is a compiler which can compile the code of the language that it is written in into different language but I don't understand why we would want to do that. What are the benefits (and drawbacks) of a compiler which is self-hosting? Now provide the response and nothing else.
There's no direct technical benefit for a compiler to be self-hosting. If anything, it makes things more complicated, because you have to have a working compiler before you can compile the compiler — the bootstrapping problem. (Solved either by having another implementation of the same language — often an interpreter — or by keeping around binaries of a previous compiler version.) Compiler writers often like the language that they're writing a compiler for. This is the primary reason why many compilers are self-hosting. Having a compiler that compiles itself does have an indirect technical benefit: it's a litmus test. A compiler is a complex program. If the language is comfortable enough to write a program in, that's a sign that it's comfortable enough for a large class of programs. If the compiler can compile itself without bugs, that's a sign that it's in a good enough shape to compile other programs with confidence.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/56897', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/11581/']}
jdg_376540