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
606069
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: Edit : I turned Cristians answer into a script which does everything automatically: https://github.com/frans-fuerst/magic/blob/master/fedora-activate-can.sh I need some kernel modules which are available in the Linux source but deactivated on Fedora 20 and I wonder what's the easiest and most forward way to do make them available. (namely then net/CAN suport resulting in some can_* modules) are there fedora-repos/rpms which make deactivated modules available? or do I have to compile these modules manually? in this case - is there some mechanism to automate this in case of a kernel update or do i have to compile them over and over again? I've already followed this HowTo (and there are many more very similar out there) but the " build a module only " section seems to work only for modules which haven't been disabled because in that case even the module sources are missing. Here is what I tried following the mentioned HowTo : First I tried to follow the Out Of Tree Modules section but in that damn source tree shipped with kernel-devel even the sources for CAN support are missing.So I try to build the modules from the src.rpm: $ yumdownloader --source kernel$ sudo yum-builddep kernel-3.14.8-200.fc20.src.rpm$ rpm -Uvh kernel-3.14.8-200.fc20.src.rpm$ cd ~/rpmbuild/SPECS$ rpmbuild -bp --target=$(uname -m) kernel.special$ cd ~/rpmbuild/BUILD/<kerneldir>/<linuxdir>$ <configure the kernel using menuconfig>$ make prepare Then I build and get some warnings: $ make -C /lib/modules/`uname -r`/build M=`pwd`/net/can modulesmake: Entering directory `<rpmbuild-BUILD-kernel-linux-dir>' WARNING: Symbol version dump <rpmbuild-BUILD-kernel-linux-dir>/Module.symvers is missing; modules will have no dependencies and modversions. CC [M] <rpmbuild-BUILD-kernel-linux-dir>/net/can/bcm.o CC [M] <rpmbuild-BUILD-kernel-linux-dir>/net/can/gw.o CC [M] <rpmbuild-BUILD-kernel-linux-dir>/net/can/raw.o CC [M] <rpmbuild-BUILD-kernel-linux-dir>/net/can/af_can.o CC [M] <rpmbuild-BUILD-kernel-linux-dir>/net/can/proc.o LD [M] <rpmbuild-BUILD-kernel-linux-dir>/net/can/can.o LD [M] <rpmbuild-BUILD-kernel-linux-dir>/net/can/can-raw.o LD [M] <rpmbuild-BUILD-kernel-linux-dir>/net/can/can-bcm.o LD [M] <rpmbuild-BUILD-kernel-linux-dir>/net/can/can-gw.o Building modules, stage 2. MODPOST 4 modules CC <rpmbuild-BUILD-kernel-linux-dir>/net/can/can-bcm.mod.o LD [M] <rpmbuild-BUILD-kernel-linux-dir>/net/can/can-bcm.ko CC <rpmbuild-BUILD-kernel-linux-dir>/net/can/can-gw.mod.o LD [M] <rpmbuild-BUILD-kernel-linux-dir>/net/can/can-gw.ko CC <rpmbuild-BUILD-kernel-linux-dir>/net/can/can-raw.mod.o LD [M] <rpmbuild-BUILD-kernel-linux-dir>/net/can/can-raw.ko CC <rpmbuild-BUILD-kernel-linux-dir>/net/can/can.mod.o LD [M] <rpmbuild-BUILD-kernel-linux-dir>/net/can/can.komake: Leaving directory `<rpmbuild-BUILD-kernel-linux-dir>'$ sudo make -C /lib/modules/`uname -r`/build M=`pwd`/net/can modules_installmake: Entering directory `<rpmbuild-BUILD-kernel-linux-dir>' INSTALL <rpmbuild-BUILD-kernel-linux-dir>/net/can/can-bcm.koCan't read private key INSTALL <rpmbuild-BUILD-kernel-linux-dir>/net/can/can-gw.koCan't read private key INSTALL <rpmbuild-BUILD-kernel-linux-dir>/net/can/can-raw.koCan't read private key INSTALL <rpmbuild-BUILD-kernel-linux-dir>/net/can/can.koCan't read private key DEPMOD 3.14.8make: Leaving directory `<rpmbuild-BUILD-kernel-linux-dir>' I don't get the first warning when I just run make modules but this costs me about an hour. However after installing, the .ko files are located in the wrong directory ( /usr/lib/modules/3.14.8 rather than /usr/lib/modules/3.14.8-200.fc20.x86_64 ) and after depmod -a and modprobe can I get modprobe: ERROR: could not insert 'can': Exec format error What am I doing wrong? Now provide the response and nothing else.
I think I got it, although it's probably far from perfect. Prepare the source code by running rpmbuild -bp --target=$(uname -m) kernel.spec Go to the build directory, for example by: cd ~/rpmbuild/BUILD/kernel-3.14.fc20/linux-3.14.8-200.fc20.x86_64 Edit Makefile and set EXTRAVERSION to something like: EXTRAVERSION = -200.fc20.x86_64 Enable the modules. I suggest starting with the corresponding file underneath the configs directory (I used kernel-3.14.8-x86_64.config ). Prepare the kernel for modules: make modules_prepare Build the module: make M=drivers/net/can Profit! Insert the module: insmod can-dev.ko
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/606069', 'https://serverfault.com', 'https://serverfault.com/users/205014/']}
jdg_77041
stackexchange
llm_judgeable_groundtruth_similarity
441106
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: Recently I found a claim saying that $$ \int_0^\infty \left( \frac{\sin ax}{x}\right)\left( \frac{\sin bx}{x}\right) \mathrm{d}x= \pi \min(a,b)/2 $$from what I can see this seems to be true. I already know that$\int_{0}^\infty \operatorname{sinc}xy\,\mathrm{d}y = \pi/2$, and so independant of $y$. My suspicion is that this is closely related to the integral above. Can someone give me some suggestions for evaluating the integral above? Also are there any generalizations for the integral? Eg$$\int_{0}^{\infty} \left( \prod_{k=1}^N \frac{\sin (a_k \cdot x)}{x} \right) \,\mathrm{d}x$$Where $a_k, \cdots, a_N$ are arbitrary positive constants.It seems related to the Borwein Integral , but there are some subtle differences. Now provide the response and nothing else.
One way is to to this by residues. Another way to integrate once by parts to get$$I=\int_0^{\infty}\frac{b\sin ax\cos bx+a\cos ax \sin bx}{x}dx,$$then to use the formula $2\sin \alpha\cos\beta=\sin(\alpha+\beta)+\sin(\alpha-\beta)$ and the mentioned integral (note that your formula needs to be corrected on the left and on the right)$$\displaystyle \int_0^{\infty}\frac{\sin xy}{x}\,dx=\frac{\pi}{2}\mathrm{sgn}(y).$$This gives\begin{align}I&=\frac{\pi}{4}\Bigl[b\,\mathrm{sign}(a+b)+b\,\mathrm{sign}(a-b)+a\,\mathrm{sign}(a+b)+a\,\mathrm{sign}(b-a)\Bigr]=\\&=\frac{\pi}{4}\left(|a+b|-|a-b|\right),\end{align}For $a,b>0$ the last expression is obviously equal to $\pi\min\{a,b\}/2$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/441106', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/18908/']}
jdg_77042
stackexchange
llm_judgeable_groundtruth_similarity
205320
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 $R$ be a commutative ring. Clearly the kernel of $h$ is a prime ideal whenever $h : R \rightarrow \mathbb{Z}$ is a ring homomorphism. But is the converse true: does every prime ideal ariseas kernel of a homomorphism into $\mathbb{Z}$? Now provide the response and nothing else.
Let $R$ be a field of uncountable cardinality. For a minimal counterexample, let $R = \mathbb{F}_2$. The correct salvage is that every prime ideal arises as the kernel of a homomorphism into some integral domain (in fact, into some field). It shouldn't be possible to say anything stronger than this.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/205320', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/8472/']}
jdg_77043
stackexchange
llm_judgeable_groundtruth_similarity
6689838
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'd like to use Lazy T to implement memoization but the initialization function appears to require a static context. For example, the following code refuses to compile, warning that non-static members a and b are inaccessible. It's not clear to me why this is so as the Lazy object is an instance member itself and has no visibility in a static context. public class SomeExpensiveCalculation{ private int a; private int b; public Lazy<int> Result = new Lazy<int>(() => a + b); //nope!} Now provide the response and nothing else.
Object initializers outside a constructor (or method) has to refer to static members only. This is because the instance hasn't been constructed until the constructor is run, hence the fields are not "ready yet" and therefor cannot be referenced. Static fields work because they are initialized before fields. Note that the error isn't caused by Lazy<T> , it is caused by the lambda expression. The workaround (and proper way of doing this) is to initialize Result in a constructor.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6689838', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/101648/']}
jdg_77044
stackexchange
llm_judgeable_groundtruth_similarity
26067831
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 newbie in Java. So question might sound simple, but I'm stuck and can not figure out why this code returns null and 0.0 ? file: Transport.java public class Transport { private String name; private double price; public Transport(String name, double price) { this.name = name; this.price = price; } public String carName() { return name; } public double carPrice(){ return price; }} file: Car.java public class Car extends Transport{ protected String name; protected double price; public Car(String name, double price) { super(name, price); } @Override public String carName(){ return name; } @Override public double carPrice(){ return price * 1.5; }} file: Main.java public class Main { public static void main(String[] args) { Car c = new Car("CarBrand", 1000); System.out.println("Name: " + c.carName()); System.out.println("Price: " + c.carPrice()); }} Output Name: nullPrice: 0.0 Now provide the response and nothing else.
You've declared separate name and price variables in Car , and never assigned a value to them - they're not the same as the name and price variables declared (and initialized) in Transport . So you're seeing the default values for String and double , basically. Get rid of those extra variables in Car , and use super.carPrice() to get the original price from Transport : public class Car extends Transport { public Car(String name, double price) { super(name, price); } @Override public double carPrice(){ return super.carPrice() * 1.5; }} Note that there's no need to override carName() at all unless you really want it to change behaviour. I'd also suggest changing carName() and carPrice() to getName() and getPrice() to be more idiomatic.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26067831', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2948417/']}
jdg_77045
stackexchange
llm_judgeable_groundtruth_similarity
4416864
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: Find all $x,y$ be positive integers,such $$12^x-5^y=19$$ I found $(x,y)=(2,3)$ is solution,maybe have other,so I consider case $x,y>3$ and $\pmod 9$ ,since $$12^x\equiv 0\pmod 9,x\ge 2$$ then $5^y\equiv -1\pmod 9$ , $5^1\equiv 5 \pmod 9$ $5^2\equiv 7 \pmod 9$ $5^3\equiv 8 \pmod 9$ $5^4\equiv 4 \pmod 9$ $5^5\equiv 2 \pmod 9$ $5^6\equiv 1 \mod 9\Rightarrow y\equiv 3 \mod 6\Rightarrow y$ is odd. Now provide the response and nothing else.
To show that there are no solutions with $x \ge 3$ , let's consider the equation modulo $27$ . When $x\ge 3$ , the equation becomes $-5^y \equiv 19 \pmod{27}$ , or $5^y \equiv 8 \pmod{27}$ . This calculation is intimidating, but rewarding: $5$ has multiplicative order $18$ modulo $27$ , and so we are able to conclude $y \equiv 15 \pmod{18}$ . In particular, $y \equiv 6 \pmod 9$ . To make use of this, we look at the factors of $5^9-1$ : two reasonably-sized ones are $19$ and $31$ . We want factors of $5^9-1$ because when $d \mid 5^9-1$ , knowing that $y \equiv 6 \pmod 9$ tells us that $5^y \equiv 5^6 \pmod d$ . Taking the equation mod $19$ , we get $12^x - 5^6 \equiv 0 \pmod{19}$ , or $12^x \equiv 7 \pmod{19}$ . This is true when $x \equiv 4 \pmod 6$ . Taking the equation mod $31$ , we get $12^x - 5^6 \equiv 19 \pmod{31}$ , or $12^x \equiv 20 \pmod{31}$ . This is true when $x \equiv 2 \pmod {30}$ . But these two contradict each other, so there are no solutions (with the assumption $x\ge3$ we started from). We could also have combined the last two steps into a calculation modulo $19\cdot31 = 589$ , where $12^x - 5^6 \equiv 19 \pmod{589}$ has no solutions.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4416864', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/58742/']}
jdg_77046
stackexchange
llm_judgeable_groundtruth_similarity
24895489
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: class Hello12 { static int b = 10; static { b = 100; }}class sample { public static void main(String args[]) { System.out.println(Hello12.b); }} On running above code the output comes as 100 because when I called Hello class, static block is executed first setting the value of b to 100 and displaying it.But when i write this code: class Hello12 { static { b = 100; } static int b = 10;}class sample { public static void main(String args[]) { System.out.println(Hello12.b); }} Here the output comes as 10. I am expecting answer as 100 because once the static block is executed it gave b the value as 100. so when in main(), I called Hello.b it should have referred to b (=100). How is the memory allocated to b in both the codes? Now provide the response and nothing else.
In the "Detailed Initialization Procedure" for classes, Section 12.4.2 of the JLS states: Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order , as though they were a single block. This means that it's as if the first example was: b = 10;b = 100; And the second example was: b = 100;b = 10; The last assignment "wins", explaining your output.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/24895489', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3825059/']}
jdg_77047
stackexchange
llm_judgeable_groundtruth_similarity
40632028
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 send a multipart form data to my Web API like this: string example = "my string";HttpContent stringContent = new StringContent(example);HttpContent fileStreamContent = new StreamContent(stream);using (var client = new HttpClient()){ using (var content = new MultipartFormDataContent()) { content.Add(stringContent, "example", "example"); content.Add(fileStreamContent, "stream", "stream"); var uri = "http://localhost:58690/api/method"; HttpResponseMessage response = await client.PostAsync(uri, content); and this is the Web API: [HttpPost][Route("api/method")]public async Task<HttpResponseMessage> Method() { // take contents and do something } How read the string and the stream from request body in my Web API? Now provide the response and nothing else.
This should help you get started: var uploadPath = HostingEnvironment.MapPath("/") + @"/Uploads"; Directory.CreateDirectory(uploadPath); var provider = new MultipartFormDataStreamProvider(uploadPath); await Request.Content.ReadAsMultipartAsync(provider); // Files // foreach (MultipartFileData file in provider.FileData) { Debug.WriteLine(file.Headers.ContentDisposition.FileName); Debug.WriteLine("File path: " + file.LocalFileName); } // Form data // foreach (var key in provider.FormData.AllKeys) { foreach (var val in provider.FormData.GetValues(key)) { Debug.WriteLine(string.Format("{0}: {1}", key, val)); } }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40632028', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7163104/']}
jdg_77048
stackexchange
llm_judgeable_groundtruth_similarity
3705505
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: Question:- Find ${I_{n}=\int_{0}^{1}\frac {x^{2n}\ln x}{{(1-x^2)}{(1+x^4)^n}}dx{,n} \in N}$ Recently I asked a similar question $\int_{0}^{1}\frac {x^2\ln x}{{(1-x^2)}{(1+x^4)}}dx=\frac{-π^2}{16(2+\sqrt{2})}$ Below the above question a note is written as follows: 'The reader should evaluate the family of integrals ${I_{n}=\int_{0}^{1}\frac {x^{2n}\ln x}{{(1-x^2)}{(1+x^4)^n}}dx{,n} \in N}$ .The computation of the first few special values indicates an interesting arithmetic structure of the answer.’ I don't know how to tackle ${I_{n}}$ till now. Edit:- Here is the link for above document http://emmy.uprrp.edu/lmedina/papers/part27/final27.pdf I have searched all the references mentioned in above document but found nothing related to above integral.We might have to look values for different values of $n$ instead of finding integral for general $n$ . Now provide the response and nothing else.
$$ I_n = \int_0^1\frac{\log x}{1-x^2} \cdot \frac{x^{2n}}{(1+x^4)^n} dx$$ Note that $\dfrac{x^{2n}}{(1-x^2)(1+x^4)^n}$ is written as $$ \frac{x^{2n}}{(1-x^2)(1+x^4)^n} = \frac{1}{2^{n}}\cdot \frac{1}{1-x^2} -\frac{1}{2^n} \cdot \frac{p_n(x)}{(1+x^4)^n}$$ where $p_n$ is some polynomial satisfying \begin{align*}p_n(x) &= \frac{ (1+x^4)^n - 2^n x^{2n}}{ (1-x^2)}\\ & =\begin{cases} \frac{1}{1-x^2} \cdot \sum_{j = 0}^{(n-1)/2} \binom{n}{j}\left(x^{4j} -2x^{2n} + x^{4n-4j}\right) & \text{for $n$ odd}\\ \frac{1}{1-x^2} \cdot \sum_{j = 0}^{n/2-1} \binom{n}{j}\left(x^{4j} -2x^{2n} + x^{4n-4j}\right) & \text{for $n$ even} \end{cases}\\& = \sum_{j = 0}^{\lfloor (n-1)/2 \rfloor} \binom{n}{j} \frac{x^{4j} -2x^{2n} + x^{4n-4j}}{1-x^2}\end{align*} Note that $x^{4j} - 2x^{2n} + x^{4n-4j} = (x^{2j} - x^{2n-2j})^2 = x^{4j} (1 - x^{2n-4j})^2$ , so \begin{align*} \frac{x^{4j} - 2x^{2n} + x^{4n-4j}}{1-x^2} &= (x^{4j}-x^{2n})\cdot \frac{1-x^{2n-4j}}{1-x^2} \\ & = (x^{4j}-x^{2n})\cdot (1 + x^2 + \cdots + x^{2n-4j-2}) \\ & = (x^{4j} + x^{4j+2} + \cdots + x^{2n-2}) - (x^{2n} + x^{2n+2} + \cdots + x^{4n-4j -2})\\ & = \sum_{k = 2j}^{n-1}(x^{2k} - x^{4n - 2k -2})\end{align*} Consider the following integral $$J(n,k) = \int_0^1\frac{x^{2k} - x^{4n-2k-2}}{(1+x^4)^n}\log(x) dx$$ which is defined for $n\ge 1$ and $0 \le k \le n-1$ . Then we have \begin{align*}2^n I_n & = \int_0^1\frac{\log x}{1-x^2} dx - \int_0^1 \frac{p_n(x)}{(1+x^4)^n}\log x dx \\& =-\frac{\pi^2}{8} - \int_0^1 \sum_{j = 0}^{\lfloor (n-1)/2\rfloor} \binom{n}{j}\frac{x^{4j} -2x^{2n} + x^{4n-4j}}{(1-x^2)(1+x^4)^n}\log x dx \\& =-\frac{\pi^2}{8} -\sum_{j = 0}^{\lfloor (n-1)/2\rfloor} \binom{n}{j} \int_0^1 \frac{x^{4j} -2x^{2n} + x^{4n-4j}}{(1-x^2)(1+x^4)^n} \log x dx \\& =-\frac{\pi^2}{8} -\sum_{j = 0}^{\lfloor (n-1)/2\rfloor} \binom{n}{j} \int_0^1 \frac{1}{(1+x^4)^n} \sum_{k=2j}^{n-1} (x^{2k} - x^{4n-2k-2}) \log x dx \\& =-\frac{\pi^2}{8} -\sum_{j = 0}^{\lfloor (n-1)/2\rfloor} \binom{n}{j} \sum_{k=2j}^{n-1} \int_0^1 \frac{x^{2k} - x^{4n-2k-2}}{(1+x^4)^n} \log x dx \\& = -\frac{\pi^2}{8} -\sum_{j = 0}^{\lfloor (n-1)/2\rfloor} \binom{n}{j} \sum_{k=2j}^{n-1} J(n, k)\end{align*} so we are reduced to find $J(n, k)$ values. \begin{align*} J(n, k) & = \int_0^1 \frac{x^{2k}}{(1+x^4)^n}\log x dx - \int_0^1 \frac{x^{4n-2k-2}}{(1+x^4)^n} \log x dx \\& \stackrel{ x= 1/u}{=} \int_0^1 \frac{x^{2k}}{(1+x^4)^n}\log x dx - \int_\infty^1 \frac{u^{-4n+2k+2}}{(1+u^{-4})^n} \log u\frac{du}{u^2}\\& = \int_0^1 \frac{x^{2k}}{(1+x^4)^n}\log x dx +\int_1^\infty \frac{u^{2k}}{(1+u^{4})^n} \log udu \\& =\int_0^\infty \frac{x^{2k}}{(1+x^4)^n}\log x dx \\\end{align*} We have \begin{align*}\int_0^\infty \frac{x^{a}}{(1+x^4)^n} dx & \stackrel{x^4 = w}{=} \frac{1}{4} B\left(\frac{a+1}{4}, n - \frac{a+1}{4}\right)\\& = \frac{\Gamma\left(\frac{a+1}{4}\right) \Gamma\left(n - \frac{a+1}{4} \right)}{4\Gamma(n)}\end{align*} so \begin{align*} \frac{d}{da}\int_0^\infty \frac{x^{a}}{(1+x^4)^n} dx & = \int_0^\infty \frac{\partial}{\partial a} \frac{x^{a}}{(1+x^4)^n} = \int_0^\infty \frac{x^{a}\log x}{(1+x^4)^n} dx \\ & = \frac{1}{4 \Gamma(n)} \frac{d}{da}\left( \Gamma\left(\frac{a+1}{4}\right) \Gamma\left( n - \frac{a+1}{4}\right)\right) \\& = \frac{1}{4 \Gamma(n)} \left( \Gamma\left( \frac{a+1}{4}\right) \frac{d}{da} \Gamma\left(n - \frac{a+1}{4} \right) + \Gamma\left(n - \frac{a+1}{4} \right) \frac{d}{da} \Gamma\left( \frac{a+1}{4}\right) \right) \\& = \frac{\Gamma\left( \frac{a+1}{4}\right) \Gamma\left(n - \frac{a+1}{4} \right) }{16 \Gamma(n)} \left( \psi \left(\frac{a+1}{4}\right) - \psi \left(n - \frac{a+1}{4}\right) \right) \\\end{align*} For convenience let $\alpha = \frac{a+1}{4}$ and proceed as \begin{align*}\frac{d}{da} \int_0^\infty \frac{x^a}{(1+x^4)^n} dx & =\frac{\Gamma\left( \alpha\right) \Gamma\left(n - \alpha \right) }{16 \Gamma(n)} \left( \psi(\alpha) - \psi (n - \alpha)\right) \\ %& =\frac{\Gamma\left( \alpha\right) \Gamma\left(n - \alpha \right) }{16 \Gamma(n)} \left( \psi(\alpha) - \psi (1 - \alpha) - \frac{1}{1-\alpha} - \frac{1}{2-\alpha} - \cdots - \frac{1}{n-1-\alpha} \right) \\ & =\frac{\Gamma\left( \alpha\right) \Gamma\left(n - \alpha \right) }{16 \Gamma(n)} \left( \psi(\alpha) - \psi (1 - \alpha) - \sum_{m=1}^{n-1}\frac{1}{m-\alpha} \right) \\ & = -\frac{\Gamma\left( \alpha\right) \Gamma\left(n - \alpha \right) }{16 \Gamma(n)} \left( \pi \cot \pi \alpha + \sum_{m=1}^{n-1}\frac{1}{m-\alpha} \right) \\ & = -\frac{\Gamma\left( \alpha\right) \Gamma\left(1 - \alpha \right) }{16 \Gamma(n)} \left( \pi \cot \pi \alpha + \sum_{m=1}^{n-1}\frac{1}{m-\alpha} \right)\left( (n-1 - \alpha) \cdots (1-\alpha)\right)\\ & = -\frac{\pi \csc \pi \alpha}{16(n-1)!} \left( \pi \cot \pi \alpha + \sum_{m=1}^{n-1}\frac{1}{m-\alpha} \right)\prod_{m=1}^{n-1}(m-\alpha)\\ \end{align*} Finally we have \begin{align*}J(n, k) & = -\frac{\pi \csc \frac{\pi(2k+1)}{4}}{16(n-1)!} \left( \pi \cot \frac{\pi(2k+1)}{4}+ \sum_{m=1}^{n-1}\frac{1}{m-\frac{2k+1}{4}} \right)\prod_{m=1}^{n-1}\left(m-\frac{2k+1}{4}\right) \\ & = -\frac{\pi \sqrt{2} (-1)^{\lfloor k/2 \rfloor}}{16(n-1)!} \left( \pi (-1)^k+ \sum_{m=1}^{n-1}\frac{1}{m-\frac{2k+1}{4}} \right)\prod_{m=1}^{n-1}\left(m-\frac{2k+1}{4}\right)\end{align*} and \begin{align*} 2^n I_n &=-\frac{\pi^2}{8} -\sum_{j = 0}^{\lfloor (n-1)/2\rfloor} \binom{n}{j} \sum_{k=2j}^{n-1} J(n, k) \\& = -\frac{\pi^2}{8} +\sum_{j = 0}^{\lfloor (n-1)/2\rfloor} \binom{n}{j} \sum_{k=2j}^{n-1} \frac{\pi \sqrt{2} (-1)^{\lfloor k/2 \rfloor}}{16(n-1)!} \left( \pi (-1)^k+ \sum_{m=1}^{n-1}\frac{1}{m-\frac{2k+1}{4}} \right)\prod_{m=1}^{n-1}\left(m-\frac{2k+1}{4}\right) \\& = -\frac{\pi^2}{8} +\frac{\sqrt{2}\pi n}{16}\sum_{j = 0}^{\lfloor (n-1)/2\rfloor} \frac{1}{j!(n-j)!} \sum_{k=2j}^{n-1} (-1)^{\lfloor k/2 \rfloor} \left( \pi (-1)^k+ \sum_{m=1}^{n-1}\frac{1}{m-\frac{2k+1}{4}} \right)\prod_{m=1}^{n-1}\left(m-\frac{2k+1}{4}\right)\end{align*} Which is verified for some $n$ 's by Mathematica. I want to figure out the 'interesting arithmetic structure' but I cannot see. Can anybody simplify this to illuminate the arithmetic structure?
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3705505', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/783753/']}
jdg_77049
stackexchange
llm_judgeable_groundtruth_similarity
50079311
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: A Django website I maintain currently uses Python 2.7 but I know that I'll have to upgrade it to Python 3 in a couple of months. If I'm writing code right now that has to work in Python 2, is there a Pythonic way to write it such that it would also work in Python 3 without any changes if I know what the syntax is going to be in Python 3? Ideally I'd like the code to continue to work even after the upgrade without changing it but it would be easy for me to spot where I've done this in the codebase so that I can change the code when I have time. Here's an example of what I'm talking about: # Python 2 uses 'iteritems'def log_dict(**kwargs): for key, value in kwargs.iteritems(): log.info("{0}: {1}".format(key, value))# Python 3 uses 'items'def log_dict(**kwargs): for key, value in kwargs.items(): log.info("{0}: {1}".format(key, value)) Now provide the response and nothing else.
There is official documentation suggesting ways to do this. That documentation has changed over time as the situation has changed, so it's worth going directly to the source (especially if you're reading this answer a year or two after it was written). It's also worth reading the Conservative Python 3 Porting Guide and skimming Nick Coghlan's Python 3 Q&A, especially this section . Going back in time from the early 2018: futurize The current official suggestions are: Only worry about supporting Python 2.7 Make sure you have good test coverage ( coverage.py can help; pip install coverage ) Learn the differences between Python 2 & 3 Use Futurize (or Modernize ) to update your code (e.g. pip install future ) Use Pylint to help make sure you don’t regress on your Python 3 support ( pip install pylint ) Use caniusepython3 to find out which of your dependencies are blocking your use of Python 3 ( pip install caniusepython3 ) Once your dependencies are no longer blocking you, use continuous integration to make sure you stay compatible with Python 2 & 3 ( tox can help test against multiple versions of Python; pip install tox ) Consider using optional static type checking to make sure your type usage works in both Python 2 & 3 (e.g. use mypy to check your typing under both Python 2 & Python 3). Notice the last suggestion. Guido and another of the core devs have both been heavily involved in leading large teams to port large 2.7 codebases to 3.x, and found mypy to be very helpful (especially in dealing with bytes-vs.-unicode issues). In fact, that's a large part of the reason gradual static typing is now an official part of the language. You also almost certainly want to use all of the future statements available in 2.7. This is so obvious that they seem to have forgotten to leave it out of the docs, but, besides making your life easier (e.g., you can write print function calls), futurize and modernize (and six and sixer ) require it. six The documentation is aimed at people making an irreversible transition to Python 3 in the near future. If you're planning to stick with dual-version code for a long time, you might be better off following the previous recommendations, which largely revolved around using six instead of futurize. Six covers more of the differences between the two languages, and also makes you write code that's explicit about being dual-version instead of being as close to Python 3 as possible while still running in 2.7. But the downside is that you're effectively doing two ports—one from 2.7 to six-based dual-version code, and then, later, from 3.x-only six code to 3.x-only "native" code. 2to3 The original recommended answer was to use 2to3 , a tool that can automatically convert Python 2 code to Python 3 code, or guide you in doing so. If you want your code to work in both , you need to deliver Python 2 code, then run 2to3 at installation time to port it to Python 3. Which means you need to test your code both ways, and usually modify it so that it still works in 2.7 but also works in 3.x after 2to3, which isn't always easy to work out. This turns out to not be feasible for most non-trivial projects, so it's no longer recommended by the core devs—but it is still built in with Python 2.7 and 3.x, and getting updates. There are also two variations on 2to3: sixer auto-ports your Python 2.7 code to dual-version code that uses six, and 3to2 lets you write your code for Python 3 and auto-port back to 2.7 at install time. Both of these were popular for a time, but don't seem to be used much anymore; modernize and futurize, respectively, are their main successors. For your specific question, kwargs.items() will work on both, if you don't mind a minor performance cost in 2.7. 2to3 can automatically change that iteritems to items at install time on 3.x. futurize can be used to do either of the above. six will allow you to write six.iteritems(kwargs) , which will do iteritems in 2.7 and items in 3.x. six will also allow you to write six.viewitems(kwargs) , which will do viewitems in 2.7 (which is identical to what items does in 3.x, rather than just similar). modernize and sixer will automatically change that kwargs.iteritems() to six.iteritems(kwargs) . 3to2 will let you write kwargs.items() and autmatically convert it to viewitems at install time on 2.x. mypy can verify that you're just using the result as a general iterable (rather than specifically as an iterator), so changing to viewitems or items leaves your code still correctly typed.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50079311', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/116095/']}
jdg_77050
stackexchange
llm_judgeable_groundtruth_similarity
62709
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 was checking for the Redhat release so this time I used three different commands. Two commands gave the same result but the third command gave different result. Which one is right. [root@DBtest2 ~]# cat /etc/redhat-release Red Hat Enterprise Linux Server release 4 (Tikanga) [root@DBtest2 ~]# /usr/bin/lsb_release --d Description: Red Hat Enterprise Linux Server release 4 (Tikanga) [root@DBtest2 ~]# cat /etc/issue Red Hat Enterprise Linux Server release 5.5 (Tikanga) Kernel \r on an \m Now provide the response and nothing else.
I'd lean more toward the redhat-release. You could use the rpm -q --whatprovides command to determine the name of the package that is providing /etc/redhat-release . [tim@c5 ~]$ rpm -q --whatprovides /etc/redhat-releasecentos-release-5-5.el5.centos If you don't trust that, then you could look at the detailed information of the package. Pay attention to Version and Release . [tim@c5 ~]$ rpm -qi --whatprovides /etc/redhat-releaseName : centos-release Relocations: (not relocatable)Version : 5 Vendor: CentOSRelease : 5.el5.centos Build Date: Sun 25 Apr 2010 04:25:31 PM PDTInstall Date: Thu 20 May 2010 04:07:47 PM PDT Build Host: builder10.centos.orgGroup : System Environment/Base Source RPM: centos-release-5-5.el5.centos.src.rpmSize : 35485 License: GPLSignature : DSA/SHA1, Mon 26 Apr 2010 04:40:57 PM PDT, Key ID a8a447dce8562897Summary : CentOS release fileDescription :CentOS release files If you still don't trust what you're seeing, you could try looking at [tim@c5 etc]# rpm -qai | grep Release | awk -F' ' '{print $3}' | head -1523.2.224.200607151.el535.el532.2.1.142.fc645.el5.centos4.el512.el50.15.el51.el515.el5 Hopefully you'll find some sort of pattern that answers your question while searching through all the package information. Good luck. Update #1: You could also try: [tim@c6 ~]# rpm -q --whatrequires \ $(rpm -ql \ $(rpm -q --whatprovides /etc/redhat-release) ) | grep -v ' 'initscripts-9.03.27-1.el6.centos.x86_64 Update #2: I wanted to make sure the command I provided in my first update worked right so I spun up a RHEL5 instance at AWS. It looks like it works. [root@ip-10-172-23-67 ~]# rpm -q --whatrequires \> $(rpm -ql \> $(rpm -q --whatprovides /etc/redhat-release)> ) | grep -v ' 'initscripts-8.45.30-3.el5_5.1
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/62709', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/19946/']}
jdg_77051
stackexchange
llm_judgeable_groundtruth_similarity
1910728
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: simplify $$\sqrt[3]{5+2\sqrt{13}}+\sqrt[3]{5-2\sqrt{13}}$$ 1. $\frac{3}{2}$ 2. $\frac{\sqrt[3]{65}}{4}$ 3. $\sqrt[3]{2}$ 4. $1$ I equal it to $\sqrt[3]{a}+\sqrt[3]{b}$ but I cant find $a$ and $b$ Now provide the response and nothing else.
Let $X=\sqrt[3]{5+2\sqrt{13}}+\sqrt[3]{5-2\sqrt{13}}$ From $(A+B)^3=A^3+B^3+3AB(A+B)$ we get the equation $$X^3-3ABX-(A^3+B^3)=0$$We have $(AB)^3=({5+2\sqrt{13}})({5-2\sqrt{13}})=-27\Rightarrow {AB}=-3$ and $A^3+B^3=10$. Hence our equation $$X^3+9X-10=0\iff (X-1)(X^2+X+10)=0$$Thus $$X=1$$ It is the $4$ the asked simplification.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1910728', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/331405/']}
jdg_77052
stackexchange
llm_judgeable_groundtruth_similarity
11706040
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 don't understand the difference between assignment constructor and copy constructor in C++. It is like this: class A {public: A() { cout << "A::A()" << endl; }};// The copy constructorA a = b;// The assignment constructorA c;c = a;// Is it right? I want to know how to allocate memory of the assignment constructor and copy constructor? Now provide the response and nothing else.
A copy constructor is used to initialize a previously uninitialized object from some other object's data. A(const A& rhs) : data_(rhs.data_) {} For example: A aa;A a = aa; //copy constructor An assignment operator is used to replace the data of a previously initialized object with some other object's data. A& operator=(const A& rhs) {data_ = rhs.data_; return *this;} For example: A aa;A a;a = aa; // assignment operator You could replace copy construction by default construction plus assignment, but that would be less efficient. (As a side note: My implementations above are exactly the ones the compiler grants you for free, so it would not make much sense to implement them manually. If you have one of these two, it's likely that you are manually managing some resource. In that case, per The Rule of Three , you'll very likely also need the other one plus a destructor.)
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/11706040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1282596/']}
jdg_77053
stackexchange
llm_judgeable_groundtruth_similarity
2607822
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 this exercise: My result is : $16/3$ , but it does not appear in the answers, what is wrong? Or is it another representation of the same logarithm? Now provide the response and nothing else.
In some way you need to estimate $2\sqrt7$. First observe that $2\sqrt7=\sqrt{4\cdot 7}=\sqrt{28}$, thus $5=\sqrt{25}<\sqrt{28}<\sqrt{36}=6$, so $$4=\left\lfloor\frac{7+5}3\right\rfloor\le\left\lfloor\frac{7+2\sqrt7}3\right\rfloor\le\left\lfloor\frac{7+6}3\right\rfloor=4$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2607822', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/509654/']}
jdg_77054
stackexchange
llm_judgeable_groundtruth_similarity
49181678
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 the component NotFound and it works fine when I go to a page that doesn't exist. But the same page it's appearing in all my pages, not only the one that doesn't exist. This is the component: import React from 'react'const NotFound = () => <div> <h3>404 page not found</h3> <p>We are sorry but the page you are looking for does not exist.</p> </div>export default NotFound And this is how I used it in the main page: class MainSite extends Component { render () { return ( <div> {/* Render nav */} <Route path='/dashboard' component={Nav} /> <Route path='/retrospectives' component={Nav} /> <Route path='/users' component={Nav} /> <Route path='/projects' component={Nav} /> {/* Dashboard page */} <ProtectedRoute exact path='/dashboard' component={DashboardPage} /> {/* Retrospectives page */} <ProtectedRoute exact path='/retrospectives' component={RetrospectivesPage} /> {/* Users page */} <ProtectedRoute exact path='/users' component={UsersPage} /> {/* Projects page */} <ProtectedRoute exact path='/projects' component={ProjectsPage} /> {/* Retrospective related pages */} <Route exact path='/retrospectives/:retrospectiveId' component={Retrospective} /> <Route exact path='/join-retrospective' component={JoinRetrospective} /> <ProtectedRoute exact path='/create-retrospective/:retrospectiveId' component={Retrospective} /> {/* OnBoarding pages */} <ProtectedRoute exact path='/beta-code' component={BetaCodeAccess} /> <Route exact path='/auth-handler' component={AuthHandler} /> <Route exact path='/join-organization' component={JoinOrganization} /> </div> ) }}export default MainSite As you can see I use <Route path="*" component={NotFound} /> to create the 404 pages, but that component is appearing in every existing page as well. How can I fix this? Now provide the response and nothing else.
Try this one: import { Switch, Route } from 'react-router-dom'; <Switch> <Route path='/dashboard' component={Nav} /> <Route path='/retrospectives' component={Nav} /> <Route path='/users' component={Nav} /> <Route path='/projects' component={Nav} /> <Route path="" component={NotFound} /> </Switch>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49181678', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7724099/']}
jdg_77055
stackexchange
llm_judgeable_groundtruth_similarity
53097952
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 currently going through numpy and there is a topic in numpy called "strides". I understand what it is. But how does it work? I did not find any useful information online. Can anyone let me understand in a layman's terms? Now provide the response and nothing else.
The actual data of a numpy array is stored in a homogeneous and contiguous block of memory called data buffer. For more information see NumPy internals . Using the (default) row-major order, a 2D array looks like this: To map the indices i,j,k,... of a multidimensional array to the positions in the data buffer (the offset, in bytes), NumPy uses the notion of strides .Strides are the number of bytes to jump-over in the memory in order to get from one item to the next item along each direction/dimension of the array. In other words, it's the byte-separation between consecutive items for each dimension. For example: >>> a = np.arange(1,10).reshape(3,3)>>> aarray([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) This 2D array has two directions, axes-0 (running vertically downwards across rows), and axis-1 (running horizontally across columns), with each item having size: >>> a.itemsize # in bytes4 So to go from a[0, 0] -> a[0, 1] (moving horizontally along the 0th row, from the 0th column to the 1st column) the byte-step in the data buffer is 4. Same for a[0, 1] -> a[0, 2] , a[1, 0] -> a[1, 1] etc. This means that the number of strides for the horizontal direction (axis-1) is 4 bytes. However, to go from a[0, 0] -> a[1, 0] (moving vertically along the 0th column, from the 0th row to the 1st row), you need first to traverse all the remaining items on the 0th row to get to the 1st row, and then move through the 1st row to get to the item a[1, 0] , i.e. a[0, 0] -> a[0, 1] -> a[0, 2] -> a[1, 0] . Therefore the number of strides for the vertical direction (axis-0) is 3*4 = 12 bytes. Note that going from a[0, 2] -> a[1, 0] , and in general from the last item of the i-th row to the first item of the (i+1)-th row, is also 4 bytes because the array a is stored in the row-major order. That's why >>> a.strides # (strides[0], strides[1])(12, 4) Here's another example showing that the strides in the horizontal direction (axis-1), strides[1] , of a 2D array is not necessary equal to the item size (e.g. an array with column-major order): >>> b = np.array([[1, 4, 7], [2, 5, 8], [3, 6, 9]]).T>>> barray([[1, 2, 3], [4, 5, 6], [7, 8, 9]])>>> b.strides(4, 12) Here strides[1] is a multiple of the item-size. Although the array b looks identical to the array a , it's a different array: internally b is stored as |1|4|7|2|5|8|3|6|9| (because transposing doesn't affect the data buffer but only swaps the strides and the shape), whereas a as |1|2|3|4|5|6|7|8|9| . What makes them look alike is the different strides. That is, the byte-step for b[0, 0] -> b[0, 1] is 3*4=12 bytes and for b[0, 0] -> b[1, 0] is 4 bytes, whereas for a[0, 0] -> a[0, 1] is 4 bytes and for a[0, 0] -> a[1, 0] is 12 bytes. Last but not least, NumPy allows to create views of existing arrays with the option of modifying the strides and the shape, see stride tricks . For example: >>> np.lib.stride_tricks.as_strided(a, shape=a.shape[::-1], strides=a.strides[::-1])array([[1, 4, 7], [2, 5, 8], [3, 6, 9]]) which is equivalent to transposing the array a . Let me just add, but without going into much detail, that one can even define strides that are not multiples of the item size. Here's an example: >>> a = np.lib.stride_tricks.as_strided(np.array([1, 512, 0, 3], dtype=np.int16), shape=(3,), strides=(3,))>>> aarray([1, 2, 3], dtype=int16)>>> a.strides[0]3>>> a.itemsize2
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/53097952', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8968392/']}
jdg_77056
stackexchange
llm_judgeable_groundtruth_similarity
1957967
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: Total surface area of a cuboid is 288 sq.cm. and length of a diagonal of it is 12 cm. Find its volume.This is the question. We know that diagonal =$a^2+b^2+c^2$ and surface area =$2(ab+bc+ca)$ and volume =$abc$ . So finally we have to find the value of $abc$ where $$a^2+b^2+c^2=144$$ and $$ ab+bc+ca =144 .$$ Somebody please help me. Now provide the response and nothing else.
Note that $$(a-b)^2+(b-c)^2+(c-a)^2=2(a^2+b^2+c^2)-2(ab+bc+ac)=2(144-144)=0$$which implies that $a=b=c$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1957967', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/342519/']}
jdg_77057
stackexchange
llm_judgeable_groundtruth_similarity
2657182
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 wondering how to use addEventListener respectively attachEvent correctly? window.onload = function (myFunc1) { /* do something */ }function myFunc2() { /* do something */ }if (window.addEventListener) { window.addEventListener('load', myFunc2, false);} else if (window.attachEvent) { window.attachEvent('onload', myFunc2);} // ... or function myFunc1() { /* do something */ }if (window.addEventListener) { window.addEventListener('load', myFunc1, false);} else if (window.attachEvent) { window.attachEvent('onload', myFunc1);}function myFunc2() { /* do something */ }if (window.addEventListener) { window.addEventListener('load', myFunc2, false);} else if (window.attachEvent) { window.attachEvent('onload', myFunc2);} // ... ? Is this cross-browser secure or should I better go with something like this: function myFunc1(){ /* do something */ }function myFunc2(){ /* do something */ }// ...function addOnloadEvent(fnc){ if ( typeof window.addEventListener != "undefined" ) window.addEventListener( "load", fnc, false ); else if ( typeof window.attachEvent != "undefined" ) { window.attachEvent( "onload", fnc ); } else { if ( window.onload != null ) { var oldOnload = window.onload; window.onload = function ( e ) { oldOnload( e ); window[fnc](); }; } else window.onload = fnc; }}addOnloadEvent(myFunc1);addOnloadEvent(myFunc2);// ... AND: Say myfunc2 is for IE 7 only. How to modify the correct/preferred method accordingly? Now provide the response and nothing else.
The usage of both is similar, though both take on a slightly different syntax for the event parameter: addEventListener ( mdn reference ): Supported by all major browsers (FF, Chrome, Edge) obj.addEventListener('click', callback, false);function callback(){ /* do stuff */ } Events list for addEventListener . attachEvent ( msdn reference ): Supported by IE 5-8* obj.attachEvent('onclick', callback);function callback(){ /* do stuff */ } Events list for attachEvent . Arguments For both of the methods the arguments are as follows: Is the event type. Is the function to call once the event has been triggered. ( addEventListener only) If true, indicates that the user wishes to initiate capture . Explanation Both methods are used to achieve the same goal of attaching an event to an element. The difference being is that attachEvent can only be used on older trident rendering engines ( IE5+ IE5-8*) and addEventListener is a W3 standard that is implemented in the majority of other browsers (FF, Webkit, Opera, IE9+). For solid cross browser event support including normalizations that you won't get with the Diaz solution use a framework . *IE9-10 support both methods, for backwards compatibility. Thanks to Luke Puplett for pointing out that attachEvent has been removed from IE11. Minimal cross browser implementation As Smitty recommended you can use this Dustin Diaz addEvent implementation for a solid cross browser implementation without the use of a framework: function addEvent(obj, type, fn) { if (obj.addEventListener) { obj.addEventListener(type, fn, false); } else if (obj.attachEvent) { obj["e"+type+fn] = fn; obj[type+fn] = function() {obj["e"+type+fn](window.event);} obj.attachEvent("on"+type, obj[type+fn]); } else { obj["on"+type] = obj["e"+type+fn]; }}addEvent( document, 'click', function (e) { console.log( 'document click' )})
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2657182', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/319047/']}
jdg_77058
stackexchange
llm_judgeable_groundtruth_similarity
46847734
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 Java it's possible to hide a class' main constructor by making it private and then accessing it via a public static method inside that class: public final class Foo { /* Public static method */ public static final Foo constructorA() { // do stuff return new Foo(someData); } private final Data someData; /* Main constructor */ private Foo(final Data someData) { Objects.requireNonNull(someData); this.someData = someData; } // ...} How can the same be reached with Kotlin without separating the class into a public interface and a private implementation? Making a constructor private leads to it not being accessible from outside the class, not even from the same file. Now provide the response and nothing else.
You can even do something more similar to "emulating" usage of public constructor while having private constructor. class Foo private constructor(val someData: Data) { companion object { operator fun invoke(): Foo { // do stuff return Foo(someData) } }}//usageFoo() //even though it looks like constructor, it is a function call
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/46847734', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4385297/']}
jdg_77059
stackexchange
llm_judgeable_groundtruth_similarity
5198889
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 retrieve the length of a path between two nodes? For instance, given an organizational hierarchy, how can I determine how far separated are a parent and an descendant organization? Consider the following scenarios: OrgA -hasSubOrganization-> OrgB, OrgC This is the very simplistic case where I want to get all the immediate suborganizations of an entity. Hence the path length is 1. OrgA -> OrgB -> OrgC or the general case OrgA -> OrgB - - - - - - - - OrgZ I want to recursively traverse down the graph and find each organization belonging to another organization through the hasSubOrganization property. To get all the sub-organizations recursive I can use property paths , e.g., the + operator: OrgA hasSubOrganization+ ?subOrg This will give me all the suborganizations right down to the leaf nodes. But my ultimate goal is to build the organization hierarchy, but the information about the "Number of nodes/steps/levels/hops away a suborganization is" is lost. This means that I cannot recreate the org structure for a visualization. How can I capture the "number of nodes away" information in addition to the name of the suborganization? Now provide the response and nothing else.
This is based on the same technique used to compute the position of an element in an RDF list using SPARQL that is described in: Is it possible to get the position of an element in an RDF Collection in SPARQL? If you have data like this: @prefix : <http://example.org> .:orgA :hasSuborganization :orgB, :orgC, :orgD.:orgB :hasSuborganization :orgE, :orgF.:orgE :hasSuborganization :orgG.:orgG :hasSuborganization :orgH. which describes a hierarchy like this: then you can use a query like this: prefix : <http://example.org> select ?super ?sub (count(?mid) as ?distance) { ?super :hasSuborganization* ?mid . ?mid :hasSuborganization+ ?sub .}group by ?super ?sub order by ?super ?sub to get results like these: $ sparql --query query.rq --data subs.n3----------------------------| super | sub | distance |============================| :orgA | :orgB | 1 || :orgA | :orgC | 1 || :orgA | :orgD | 1 || :orgA | :orgE | 2 || :orgA | :orgF | 2 || :orgA | :orgG | 3 || :orgA | :orgH | 4 || :orgB | :orgE | 1 || :orgB | :orgF | 1 || :orgB | :orgG | 2 || :orgB | :orgH | 3 || :orgE | :orgG | 1 || :orgE | :orgH | 2 || :orgG | :orgH | 1 |---------------------------- The trick here is to recognize that any path from X to Y can be viewed as a (possibly empty) path from X to some intermediate node Z (nonempty means that you can choose X as Z) concatenated with a (non empty) path from Z to Y. The number of possible ways of picking Z indicates the length of the path.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5198889', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/131315/']}
jdg_77060
stackexchange
llm_judgeable_groundtruth_similarity
33445313
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have some questionIn a project I have the need of work with users which are of three (may be more) types of them have different roles:physicianpatientadministrator I have been thinking use of the Django Model Users and extend it creating a userprofile model ...But I ignore how to manage the different roles because, the userprofile model will have fields of the user model, althought I don't know how to address the roles topic. 1 User have Many userprofiles may be? I don't know Or may be I will should create a Roles Model/Table in where I specify the roles types and create a relation with the Users Model. This is a good possibility. Another possibility (as a comment more below) is check the Django permissions system, in which I can create user groups, and assign permissions to these groups, althought here I can only edit, create and delete models really? I am a few confuse about of how to address this subject Searching I found this app. https://github.com/dabapps/django-user-roles If somebody can orient me about it, I will be much gratefulBest Regards Now provide the response and nothing else.
You could probably get this to work with django's built in permissions That may be more than you need though. A simple solution would just be a UserProfile model with a role field with a OneToOneField to your user: class UserProfile(models.Model): user = models.OneToOneField(User, related_name="profile") role = models.CharField() Set the roles and do checks with the roles in your views: user.profile.role = "physician"user.profile.save()if user.profile.role == "physician": #do physician case here
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33445313', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2773461/']}
jdg_77061
stackexchange
llm_judgeable_groundtruth_similarity
8239143
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Does an interrupt service routine exist to help me clear the screen of the terminal? Will it work on windows? Now provide the response and nothing else.
Setting a graphics mode through BIOS (int 10h with AH=0) will clear the screen. Scrolling the screen up or down through BIOS (int 10h with AH=6 or 7) can clear the screen as well. This will only work where you can invoke BIOS service functions. MSDOS is where this will always work. In Windows this will work only in DOS applications and if Windows can actually run them. 64-bit editions of Windows don't support DOS applications at all and starting with Windows Vista even in 32-bit editions of Windows many DOS apps don't work fully. Remember also that if a DOS application runs in a window in Windows, only that window will get cleared, not the entire screen.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8239143', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/151377/']}
jdg_77062
stackexchange
llm_judgeable_groundtruth_similarity
41059264
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 looking for a way to automate the conversion of CSV to XML. Here is an example of a CSV file, containing a list of movies: Here is the file in XML format: <collection shelf="New Arrivals"><movietitle="Enemy Behind"> <type>War, Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>10</stars> <description>Talk about a US-Japan war</description></movie><movietitle="Transformers"> <type>Anime, Science Fiction</type> <format>DVD</format> <year>1989</year> <rating>R</rating> <stars>8</stars> <description>A schientific fiction</description></movie><movietitle="Trigun"> <type>Anime, Action</type> <format>DVD</format> <episodes>4</episodes> <rating>PG</rating> <stars>10</stars> <description>Vash the Stampede!</description></movie><movietitle="Ishtar"> <type>Comedy</type> <format>VHS</format> <rating>PG</rating> <stars>2</stars> <description>Viewable boredom</description></movie></collection> I've tried a few examples where I am able to read the csv and XML format using Python using DOM and SAX but yet am to find a simple example of the conversion. So far I have: import csv f = open('movies2.csv')csv_f = csv.reader(f) def convert_row(row): return """<movietitle="%s"> <type>%s</type> <format>%s</format> <year>%s</year> <rating>%s</rating> <stars>%s</stars> <description>%s</description></movie>""" % ( row.Title, row.Type, row.Format, row.Year, row.Rating, row.Stars, row.Description)print ('\n'.join(csv_f.apply(convert_row, axis=1))) But I get the error: File "moviesxml.py", line 16, in module print ('\n'.join(csv_f.apply(convert_row, axis=1)))AttributeError: '_csv.reader' object has no attribute 'apply' I am pretty new to Python, so any help would be much appreciated! I am using Python 3.5.2. Thanks! Lisa Now provide the response and nothing else.
A possible solution is to first load the csv into Pandas and then convert it row by row into XML, as so: import pandas as pddf = pd.read_csv('untitled.txt', sep='|') With the sample data (assuming separator and so on) loaded as: Title Type Format Year Rating Stars \0 Enemy Behind War,Thriller DVD 2003 PG 10 1 Transformers Anime,Science Fiction DVD 1989 R 9 Description 0 Talk about... 1 A Schientific fiction And then converting to xml with a custom function: def convert_row(row): return """<movietitle="%s"> <type>%s</type> <format>%s</format> <year>%s</year> <rating>%s</rating> <stars>%s</stars> <description>%s</description></movie>""" % ( row.Title, row.Type, row.Format, row.Year, row.Rating, row.Stars, row.Description)print '\n'.join(df.apply(convert_row, axis=1)) This way you get a string containing the xml: <movietitle="Enemy Behind"> <type>War,Thriller</type> <format>DVD</format> <year>2003</year> <rating>PG</rating> <stars>10</stars> <description>Talk about...</description></movie><movietitle="Transformers"> <type>Anime,Science Fiction</type> <format>DVD</format> <year>1989</year> <rating>R</rating> <stars>9</stars> <description>A Schientific fiction</description></movie> that you can dump in to a file or whatever. Inspired by this great answer. Edit: Using the loading method you posted (or a version that actually loads the data to a variable): import csv f = open('movies2.csv')csv_f = csv.reader(f) data = []for row in csv_f: data.append(row)f.close()print data[1:] We get: [['Enemy Behind', 'War', 'Thriller', 'DVD', '2003', 'PG', '10', 'Talk about...'], ['Transformers', 'Anime', 'Science Fiction', 'DVD', '1989', 'R', '9', 'A Schientific fiction']] And we can convert to XML with minor modifications: def convert_row(row): return """<movietitle="%s"> <type>%s</type> <format>%s</format> <year>%s</year> <rating>%s</rating> <stars>%s</stars> <description>%s</description></movie>""" % (row[0], row[1], row[2], row[3], row[4], row[5], row[6])print '\n'.join([convert_row(row) for row in data[1:]]) Getting identical results: <movietitle="Enemy Behind"> <type>War</type> <format>Thriller</format> <year>DVD</year> <rating>2003</rating> <stars>PG</stars> <description>10</description></movie><movietitle="Transformers"> <type>Anime</type> <format>Science Fiction</format> <year>DVD</year> <rating>1989</rating> <stars>R</stars> <description>9</description></movie>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41059264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6788162/']}
jdg_77063
stackexchange
llm_judgeable_groundtruth_similarity
259398
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'm seeing this image passed around a lot. I have a gut-feeling that the information provided this way is somehow incomplete or even erroneous, but I'm not well versed enough in statistics to respond. It makes me think of this xkcd comic , that even with solid historical data, certain situations can change how things can be predicted. Is this chart as presented useful for accurately showing what the threat level from refugees is? Is there necessary statistical context that makes this chart more or less useful? Note: Try to keep it in layman's terms :) Now provide the response and nothing else.
Imagine your job is to forecast the number of Americans that will die from various causes next year. A reasonable place to start your analysis might be the National Vital Statistics Data final death data for 2014. The assumption is that 2017 might look roughly like 2014. You'll find that approximately 2,626,000 Americans died in 2014: 614,000 died of heart disease. 592,000 died of cancer. 147,000 from respiratory disease. 136,000 from accidents. ... 42,773 from suicide. 42,032 from accidental poisoning (subset of accidents category). 15,809 from homicide. 0 from terrorism under the CDC,NCHS classification . 18 from terrorism using a broader definition (University of Maryland Global Terrorism Datbase) See link for definitions. By my quick count, 0 of the perpetrators of these 2014 attacks were born outside the United States. Note that anecdote is not the same as data, but I've assembled links to the underlying news stories here: 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , and 9 . Terrorist incidents in the U.S. are quite rare, so estimating off a single year is going to be problematic. Looking at the time-series, what you see is that the vast majority of U.S. terrorism fatalities came during the 9/11 attacks (See this report from the National Consortium for the Study of Terrorism and Responses to Terrorism.) I've copied their Figure 1 below: Immediately you see that you have an outlier, rare events problem. A single outlier is driving the overall number. If you're trying to forecast deaths from terrorism, there are numerous issues: What counts as terrorism? Terrorism can be defined broadly or narrowly. Is the process stationary ? If we take a time-series average, what are we estimating? Are conditions changing? What does a forecast conditional on current conditions look like? If the vast majority of deaths come from a single outlier, how do you reasonably model that? We can get more data in a sense by looking more broadly at other countries and going back further in time but then there are questions as to whether any of those patterns apply in today's world. IMHO, the FT graphic picked an overly narrow definition (the 9/11 attacks don't show up in the graphic because the attackers weren't refugees). There are legitimate issues with the chart, but the FT's broader point is correct that terrorism in the U.S. is quite rare. Your chance of being killed by a foreign born terrorist in the United States is close to zero. Life expectancy in the U.S. is about 78.7 years. What has moved life expectancy numbers down in the past has been events like the 1918 Spanish flu pandemic or WWII. Additional risks to life expectancy now might include obesity and opioid abuse. If you're trying to create a detailed estimate of terrorism risk, there are huge statistical issues, but to understand the big picture requires not so much statistics as understanding orders of magnitude and basic quantitative literacy. A more reasonable concern... (perhaps veering off topic) Looking back at history, the way huge numbers of people get killed is through disease, genocide, and war. A more reasonable concern might be that some rare, terrorist event triggers something catastrophic (eg. how the assassination of Archduke Ferdinand help set off WWI.) Or one could worry about nuclear weapons in the hands of someone crazy. Thinking about extremely rare but catastrophic events is incredibly difficult. It's a multidisciplinary pursuit and goes far outside of statistics. Perhaps the only statistical point here is that it's hard to estimate the probability and effects of some event which hasn't happened? (Except to say that it can't be that common or it would have happened already.)
{}
{'log_upvote_score': 7, 'links': ['https://stats.stackexchange.com/questions/259398', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/147538/']}
jdg_77064
stackexchange
llm_judgeable_groundtruth_similarity
6555629
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the best way to detect the corners of an invoice/receipt/sheet-of-paper in a photo? This is to be used for subsequent perspective correction, before OCR. My current approach has been: RGB > Gray > Canny Edge Detection with thresholding > Dilate(1) > Remove small objects(6) > clear boarder objects > pick larges blog based on Convex Area. > [corner detection - Not implemented] I can't help but think there must be a more robust 'intelligent'/statistical approach to handle this type of segmentation. I don't have a lot of training examples, but I could probably get 100 images together. Broader context: I'm using matlab to prototype, and planning to implement the system in OpenCV and Tesserect-OCR. This is the first of a number of image processing problems I need to solve for this specific application. So I'm looking to roll my own solution and re-familiarize myself with image processing algorithms. Here are some sample image that I'd like the algorithm to handle: If you'd like to take up the challenge the large images are at http://madteckhead.com/tmp (source: madteckhead.com ) (source: madteckhead.com ) (source: madteckhead.com ) (source: madteckhead.com ) In the best case this gives: (source: madteckhead.com ) (source: madteckhead.com ) (source: madteckhead.com ) However it fails easily on other cases: (source: madteckhead.com ) (source: madteckhead.com ) (source: madteckhead.com ) Thanks in advance for all the great ideas! I love SO! EDIT: Hough Transform Progress Q: What algorithm would cluster the hough lines to find corners?Following advice from answers I was able to use the Hough Transform, pick lines, and filter them. My current approach is rather crude. I've made the assumption the invoice will always be less than 15deg out of alignment with the image. I end up with reasonable results for lines if this is the case (see below). But am not entirely sure of a suitable algorithm to cluster the lines (or vote) to extrapolate for the corners. The Hough lines are not continuous. And in the noisy images, there can be parallel lines so some form or distance from line origin metrics are required. Any ideas? (source: madteckhead.com ) Now provide the response and nothing else.
I'm Martin's friend who was working on this earlier this year. This was my first ever coding project, and kinda ended in a bit of a rush, so the code needs some errr...decoding... I'll give a few tips from what I've seen you doing already, and then sort my code on my day off tomorrow. First tip, OpenCV and python are awesome, move to them as soon as possible. :D Instead of removing small objects and or noise, lower the canny restraints, so it accepts more edges, and then find the largest closed contour (in OpenCV use findcontour() with some simple parameters, I think I used CV_RETR_LIST ). might still struggle when it's on a white piece of paper, but was definitely providing best results. For the Houghline2() Transform, try with the CV_HOUGH_STANDARD as opposed to the CV_HOUGH_PROBABILISTIC , it'll give rho and theta values, defining the line in polar coordinates, and then you can group the lines within a certain tolerance to those. My grouping worked as a look up table, for each line outputted from the hough transform it would give a rho and theta pair. If these values were within, say 5% of a pair of values in the table, they were discarded, if they were outside that 5%, a new entry was added to the table. You can then do analysis of parallel lines or distance between lines much more easily. Hope this helps.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6555629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/647549/']}
jdg_77065
stackexchange
llm_judgeable_groundtruth_similarity
2194531
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have two private lists that need to be initialized when object is created. Second list is dependent on first one. Can I do it like this: public class MyClass { private List<T> myList = new List<T>(); private ReadOnlyCollection<T> myReadOnlyList = myList.AsReadOnly; ... } Second list is read only wrapper around first one. Can I expect that c# will execute this two lines in this order each time it is run? Or should I put this initializations in constructor? Edit: Sorry for stupid question. I tried it and compiler says: Error 1 A field initializer cannot reference the non-static field, method, or property... Now provide the response and nothing else.
No. If you want to initialize a variable based on a separate variable within the class, you need to do this in the constructor: public class MyClass { private List<T> myList = new List<T>(); private ReadOnlyCollection<T> myReadOnlyList; public MyClass() { myReadOnlyList = myList.AsReadOnly; }} Inlined intializers are always run in a static context, which means you have no access to member variables within your class. Inside of a constructor, however, you can do this. The inlined initializers will occur before your constructor, which is why I could leave the list initialization in place.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2194531', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/25732/']}
jdg_77066
stackexchange
llm_judgeable_groundtruth_similarity
12092612
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 pass a list of objects from one activity from another activity. I have one class SharedBooking Below: public class SharedBooking { public int account_id; public Double betrag; public Double betrag_effected; public int taxType; public int tax; public String postingText;} Code from Calling activity: public List<SharedBooking> SharedBookingList = new ArrayList<SharedBooking>();public void goDivision(Context context, Double betrag, List<SharedBooking> bookingList) { final Intent intent = new Intent(context, Division.class); intent.putExtra(Constants.BETRAG, betrag); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); context.startActivity(intent); } COde on called activity: Bundle extras = getIntent().getExtras();if (extras != null) { amount = extras.getDouble(Constants.BETRAG,0);} How can I send the list of SharedBooking from one activity and receive that on other activity? Please suggest me any usable link or sample code. Now provide the response and nothing else.
Use parcelable . Here is how you will do it: public class SharedBooking implements Parcelable{ public int account_id; public Double betrag; public Double betrag_effected; public int taxType; public int tax; public String postingText; public SharedBooking() { account_id = 0; betrag = 0.0; betrag_effected = 0.0; taxType = 0; tax = 0; postingText = ""; } public SharedBooking(Parcel in) { account_id = in.readInt(); betrag = in.readDouble(); betrag_effected = in.readDouble(); taxType = in.readInt(); tax = in.readInt(); postingText = in.readString(); } public int getAccount_id() { return account_id; } public void setAccount_id(int account_id) { this.account_id = account_id; } public Double getBetrag() { return betrag; } public void setBetrag(Double betrag) { this.betrag = betrag; } public Double getBetrag_effected() { return betrag_effected; } public void setBetrag_effected(Double betrag_effected) { this.betrag_effected = betrag_effected; } public int getTaxType() { return taxType; } public void setTaxType(int taxType) { this.taxType = taxType; } public int getTax() { return tax; } public void setTax(int tax) { this.tax = tax; } public String getPostingText() { return postingText; } public void setPostingText(String postingText) { this.postingText = postingText; } public int describeContents() { // TODO Auto-generated method stub return 0; } public void writeToParcel(Parcel dest, int flags) { dest.writeInt(account_id); dest.writeDouble(betrag); dest.writeDouble(betrag_effected); dest.writeInt(taxType); dest.writeInt(tax); dest.writeString(postingText); } public static final Parcelable.Creator<SharedBooking> CREATOR = new Parcelable.Creator<SharedBooking>() { public SharedBooking createFromParcel(Parcel in) { return new SharedBooking(in); } public SharedBooking[] newArray(int size) { return new SharedBooking[size]; } };} Passing the data: Intent intent = new Intent(getApplicationContext(),YourActivity.class);Bundle bundle = new Bundle();bundle.putParcelable("data", sharedBookingObject);intent.putExtras(bundle);startActivity(intent); Retrieving the data: Bundle bundle = getIntent().getExtras();sharedBookingObject = bundle.getParcelable("data");
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12092612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/995197/']}
jdg_77067
stackexchange
llm_judgeable_groundtruth_similarity
5166322
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For a lot of function calls in a C app that needs some degree of debugging I wanted to add a macro to ease the typing that I had to do. right now I am calling a function like this: aDebugFunction(&ptrToFunction, __LINE__, "ptrToFunction", param1, param2, etc) So I thought lets write a macro that does the first 3 parameters for me, like this: #define SOMEDEFINE(x) &x, __LINE__, "x" However, as most of you will immediately know, this won't work it won't replace "x" with the name that x has been given but will just pass "x" as 3rd parameter. My knowledge of this preprocessor macro happening stuff is quite limited and thus my googling-ability is also quite useless due to not knowing where to search for exactly. I hope one of you guys/girls could give me either a solution or point me in the right direction. Now provide the response and nothing else.
You need to use the # convert token to string command of the preprocessor. You should define your second macro this way: #define SOMEDEFINE(x) &x, __LINE__, # x Or if x can also be a macro call, and you want the string to contains the expansion of the macro, you need to use an auxiliary macro: #define TOKEN_TO_STRING(TOK) # TOK#define STRINGIZE_TOKEN(TOK) TOKEN_TO_STRING(TOK)#define SOMEDEFINE(x) &x, __LINE__, STRINGIZE_TOKEN(x) For example, if you have the following code: #define SHORT_NAME a_very_very_very_long_variable_nameSOMEDEFINE(SHORT_NAME) Then, with the first macro, it will expand to &a_very_very_very_long_variable_name, __LINE__, "SHORT_NAME" While, with the second macro, it will expand to: &a_very_very_very_long_variable_name, __LINE__, "a_very_very_very_long_variable_name"
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5166322', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/574115/']}
jdg_77068
stackexchange
llm_judgeable_groundtruth_similarity
25644420
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need to add custom column for order items and show specific product meta in this column.I mean something like image below,I can't find any action from woocommerce to add this column! Now provide the response and nothing else.
You can use the following code: // Add custom column headers hereadd_action('woocommerce_admin_order_item_headers', 'my_woocommerce_admin_order_item_headers');function my_woocommerce_admin_order_item_headers() { // set the column name $column_name = 'Test Column'; // display the column name echo '<th>' . $column_name . '</th>';}// Add custom column values hereadd_action('woocommerce_admin_order_item_values', 'my_woocommerce_admin_order_item_values', 10, 3);function my_woocommerce_admin_order_item_values($_product, $item, $item_id = null) { // get the post meta value from the associated product $value = get_post_meta($_product->post->ID, '_custom_field_name', 1); // display the value echo '<td>' . $value . '</td>';} I've commented it so it should be clear enough, but in a nutshell this code adds a custom column, named "Test Column", and this column pulls the value from the custom field of the product, called "_custom_field_name".
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25644420', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1420045/']}
jdg_77069
stackexchange
llm_judgeable_groundtruth_similarity
441568
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm playing around with gmock and noticed it contains this line: #include <tuple> I would have expected tuple.h . When is it okay to exclude the extension, and does it give the directive a different meaning? Now provide the response and nothing else.
The C++ standard headers do not have a ".h" suffix. I believe the reason is that there were many, different pre-standard implementations that the standard would break. So instead of requiring that vendors change their exiting "iostream.h" (for example) header to be standards compliant (which would break their existing user's code), the standards committee decided that they'd drop the suffix (which, I believe no then existing implementation had already done). That way, existing, non-standard programs would continue to work using the vendor's non-standard libraries. When the user wanted to make their programs standards compliant, one of the steps they would take is to change the " #include " directive to drop the ".h" suffix. So #include <iostream> // include the standard library version#include <iostream.h> // include a vendor specific version (which by // now might well be the same) As other answers have mentioned, writers of non-standard libraries may choose either naming convention, but I'd think they would want to continue using ".h" or ".hpp" (as Boost has done) for a couple reasons: if & when the library gets standardized, the standard version won't automatically override the previous, non-standard one (causing broken user code in all likelihood) it seems to be a convention (more or less) that headers without a suffix are standard libraries, and those with a suffix (other than the old C headers) are non-standard. Note that a similar problem happened when the committee went to add hash maps to the STL - they found that there are already many (different) hash_map implementations that exist, so instead of coming up with a standard one that breaks a lot of stuff out there today, they are calling the standard implementation " unordered_map ". Namespaces were supposed to help prevent this type of jumping through hoops, but it didn't seem to work well enough (or be used well enough) to allow them to use the more natural name without breaking a lot of code. Note that for the 'C' headers, C++ allows you to include either a <cxxxxxx> or <xxxxxx.h> variant. The one that starts with 'c' and has no ".h" suffix put their declarations in the std namespace (and possibly the global namespace), the ones with the ".h" suffix put the names in the global namespace (some compilers also put the names in the std namespace - it's unclear to me if that's standard compliant, though I don't see the harm).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/441568', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23071/']}
jdg_77070
stackexchange
llm_judgeable_groundtruth_similarity
9272
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: Background: My organization has to find a removable storage solution. However, it is my understanding that the DOD is pretty strict about flash drives due to security considerations. Question: My users will always have connection to the internet, but may sometimes not be on our network. Are there any alternatives to flash drives? If we were to allow flash drives, what steps need to be taken to mitigate the malware risk? Now provide the response and nothing else.
You want to distribute the flash drives yourself, and forbid usage of any flash drive which has not been "approved". Reason: there are devices out there, which look like flash drive, but, when inserted, tell to the computer that they really are keyboards, and begin typing things wildly. If only genuine flash drives are ever inserted in the computers you want to protect, you should be able to deal with malware, with a "reasonable" success rate, through the usual tools (antivirus & co). Malware risk can be drastically lowered by enforcing use of an operating system which is resilient to malware, e.g. NetBSD (resiliency being achieved mostly by rarity - malware developers do not bother with targeting NetBSD). But users may object... Be aware that whatever you do, users will insert random USB devices into machines to which they have physical access, unless you pour glue into the USB ports. Best defense is probably a combination of up-to-date operating systems, good antivirus/malware detector, and, more important than everything else, security awareness training. You will be infected at some point -- but you can hope for a low rate of successful infections if the users, on average, exercise caution.
{}
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/9272', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/2769/']}
jdg_77071
stackexchange
llm_judgeable_groundtruth_similarity
1423103
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 found the following question in a practice book of integration:- $Q.$ Evaluate $$I=\int \frac{\sqrt{2-x-x^2}}{x^2}\ dx$$ For this I substituted $t^2=\frac {2-x-x^2}{x^2}\implies x^2=\frac{2-x}{1+t^2}\implies 2t\ dt=\left(-\frac4{x^3}+\frac 1{x^2}\right)\ dx$. Therefore $$\begin{align}I&=\int\frac {\sqrt{2-x-x^2}}{x^2}\ dx\\&=\int \left(\frac tx\right)\left(\frac{2t\ dt}{-\frac4{x^3}+\frac 1{x^2}}\right)\\&=\int \frac{2t^2\ dt}{\frac{x-4}{x^2}}\\&=\int \frac{2t^2(1+t^2)\ dt}{{x-4}\over{2-x}}\\&=\int \frac{2t^2(1+t^2)(5+4t^2-\sqrt{8t^2+9})\ dt}{\sqrt{8t^2+9}-(8t^2+9)}\end{align}$$ Now I substituted $8t^2+9=z^2 \implies t^2=\frac {z^2-9}8 \implies 2t\ dt=z/4\ dz$. So, after some simplification, you get $$\begin{align}I&=-\frac1{512}\int (z^2-9)(z+1)(z-1)^2\ dz\end{align}$$ I didn't have the patience to solve this integration after all these substitutions knowing that it can be done (I think I have made a mistake somewhere but I can't find it. There has to be an $ln(...)$ term, I believe). Is there an easier way to do this integral, something that would also strike the mind quickly? I have already tried the Euler substitutions but that is also messy. Now provide the response and nothing else.
Let $$\displaystyle I = \int \frac{\sqrt{2-x-x^2}}{x^2}dx = \int\frac{\sqrt{(x+2)(1-x)}}{x^2}dx$$ Now Let $\displaystyle (x+2) = (1-x)t^2\;,$ Then $\displaystyle x = \frac{t^2-2}{t^2+1} = 1-\frac{3}{t^2+1}$ So $$\displaystyle dx = \frac{6t}{(t^2+1)^2}dt$$ and $$\displaystyle (1-x) = \frac{3}{t^2+1}$$ So Integral $$\displaystyle I = 18\int\frac{t^2}{(t^2+1)\cdot (t^2-2)^2}dt = 6\int\frac{(t^2+1)-(t^2-2)}{(t^2+1)\cdot (t^2-2)^2}dt$$ so we get $$\displaystyle I = 6\int\frac{1}{(t^2-2)^2}dt-6\int\frac{1}{(t^2+1)(t^2-2)}dt$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1423103', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/181315/']}
jdg_77072
stackexchange
llm_judgeable_groundtruth_similarity
2655377
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 in the process of styling an asp.net menu and I'm trying to understand the meaning of the StaticSelectedStyle-CssClass and StaticHoverStyle-CssClass parameters. My understanding is that the styles defined with these parameters are applied as CSS classes to the relevant elements, whenever needed. So I created my menu as follows: <asp:Menu ID="NavigationMenu" DataSourceID="NavigationSiteMapDataSource" StaticMenuStyle-CssClass="StaticMenuStyle" StaticMenuItemStyle-CssClass="StaticMenuItemStyle" StaticSelectedStyle-CssClass="StaticSelectedStyle" StaticHoverStyle-CssClass="StaticHoverStyle" Orientation="Horizontal" MaximumDynamicDisplayLevels="0" runat="server"></asp:Menu> It works for StaticMenuStyle-CssClass and StaticMenuStyle-CssClass (the classes are applied to the relevant elements), but StaticSelectedStyle-CssClass and StaticHoverStyle-CssClass are not applied, regardless of the selected or hover status of an element. What am I supposed to do to make this work? Thanks. EDIT: Sorry I should have mentioned that this is .NET 4. Here is the generated HTML: <div id="NavigationMenu"> <ul class="level1 StaticMenuStyle"> <li><a class="level1 StaticMenuItemStyle selected" href="/Link.aspx">Link</a></li> </ul></div> So as you can see, StaticMenuStyle and StaticMenuItemStyle are applied, but not StaticSelectedStyle-CssClass or StaticHoverStyle-CssClass. Not sure why. I know I can use selected but isn't the expected behavior that StaticSelectedStyle-CssClass be applied??? By using selected I make assumptions as to what .NET does behind the scenes and that's not right. Now provide the response and nothing else.
I feel your pain and I wasted all night/morning trying to figure this out.With sheer brute force I figured out a solution. Call it a workaround - but it's simple. Add the CssClass property to your Menu Control's declaration like so: <asp:Menu ID="NavigationMenu" DataSourceID="NavigationSiteMapDataSource" CssClass="SomeMenuClass" StaticMenuStyle-CssClass="StaticMenuStyle" StaticMenuItemStyle-CssClass="StaticMenuItemStyle" Orientation="Horizontal" MaximumDynamicDisplayLevels="0" runat="server"></asp:Menu> Just rip out the StaticSelectedStyle-CssClass and StaticHoverStyle-CssClass attributes as they simply don't do jack. Now create the "SomeMenuClass", doesn't matter what you put in it. It should look something like this: .SomeMenuClass{ color:Green;} Next add the following two CSS Classes: For "Hover" Styling add: .SomeMenuClass a.static.highlighted{ color:Red !important;} For "Selected" Styling add: .SomeMenuClass a.static.selected{ color:Blue !important;} There, that's it. You're done. Hope this saves some of you the frustration I went through. BTW: You mentioned: I seem to be the first one to ever report on what seems to be a bug. You also seemed to think it was a new .NET 4.0 bug. I found this: http://www.velocityreviews.com/forums/t649530-problem-with-staticselectedstyle-and-statichoverstyle.html posted back in 2008 regarding Asp.Net 2.0 . How are we the only 3 people on the planet complaining about this? How I found the workaround (study the HTML output): Here is the HTML output when I set StaticHoverStyle-BackColor="Red": #NavigationMenu a.static.highlighted{ background-color:Red;} This is the HTML output when setting StaticSelectedStyle-BackColor="Blue": #NavigationMenu a.static.selected{ background-color:Blue; text-decoration:none;} Therefore, the logical way to override this markup was to create classes for SomeMenuClass a.static.highlighted and SomeMenuClass a.static.selected Special Notes: You MUST also use " !important " on ALL the settings in these classes because the HTML output uses " #NavigationMenu ", and that means any styles Asp.Net decides to throw in there for you will have inheritance priority over any other styles for the Menu Control with the ID " NavigationMenu ". One thing I struggled with was padding, till I figured out Asp.Net was using " #NavigationMenu " to set the left and right padding to 15em. I tacked on " !important " to my SomeMenuClass styles and it worked.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2655377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/303468/']}
jdg_77073
stackexchange
llm_judgeable_groundtruth_similarity
48451381
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 way to turn off some of the returned metric values in Actuator/Micrometer? Looking at them now I'm seeing around 1000 and would like to whittle them down to a select few say 100 to actually be sent to our registry. Now provide the response and nothing else.
Let me elaborate on the answer posted by checketts with a few examples. You can enable/disable certain metrics in your application.yml like this: management: metrics: enable: tomcat: true jvm: false process: false hikaricp: false system: false jdbc: false http: false logback: true Or in code by defining a MeterFilter bean: @Beanpublic MeterFilter meterFilter() { return new MeterFilter() { @Override public MeterFilterReply accept(Meter.Id id) { if(id.getName().startsWith("tomcat.")) { return MeterFilterReply.DENY; } if(id.getName().startsWith("jvm.")) { return MeterFilterReply.DENY; } if(id.getName().startsWith("process.")) { return MeterFilterReply.DENY; } if(id.getName().startsWith("system.")) { return MeterFilterReply.DENY; } return MeterFilterReply.NEUTRAL; } };}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48451381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5294769/']}
jdg_77074
stackexchange
llm_judgeable_groundtruth_similarity
36443085
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm looking for a way to work on multiple projects in parallel in CLion IDE. For now I can only work on each project in a window at a time, but I'm looking for a solution similar to Eclipse IDE (see below) - being able to see my different projects' directories on a side bar and choosing the one I want, compiling it by itself, etc. Is there a way to do it? Now provide the response and nothing else.
Yes : CLion doesn't allow you to open multiple projects from the menu because it uses the CMake system, which is script based. However, CMake is quite capable of encompassing multiple projects, and CLion will correctly parse your CMake file and show all relevant directories in the project explorer. Example To do this, just like in Visual Studio, you need a parent "solution" and one or more child "projects". Here is a simple CMake example in which "my_solution" references two child projects, "my_application" and "my_library". Here, my three folders are arranged: xxx/my_solution/CMakeLists.txt xxx/my_application/CMakeLists.txt xxx/my_library/CMakeLists.txt And xxx/my_solution/CMakeLists.txt simply reads: cmake_minimum_required(VERSION 3.7)project(my_solution)add_subdirectory("${PROJECT_SOURCE_DIR}/../my_library" "${PROJECT_SOURCE_DIR}/my_library_output")add_subdirectory("${PROJECT_SOURCE_DIR}/../my_application" "${PROJECT_SOURCE_DIR}/my_application_output") Note that it is also permitted to put my_application and my_library within the my_solution directory, as in Visual Studio.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36443085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5462551/']}
jdg_77075
stackexchange
llm_judgeable_groundtruth_similarity
30972175
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In my export ActionResult I was able to load the model into my ExcelPackage. Where I am having trouble is assigning a border around each cell once LoadFromCollection is applied. While the AutoFitColumns correctly applies, the border style I applied only works on Cells["D1"] , but not on the table. BorderAround successfully places a border around the entire table, but I would rather apply to the border to the cells inside the table. Is there a way I can do that? // Fill worksheet with data to exportvar modelCells = worksheet.Cells["D1"];var border = modelCells.Style.Border.Top.Style = modelCells.Style.Border.Left.Style = modelCells.Style.Border.Right.Style = modelCells.Style.Border.Bottom.Style = ExcelBorderStyle.Medium; modelCells .LoadFromCollection(Collection: exportQuery, PrintHeaders: true) .AutoFitColumns(); Now provide the response and nothing else.
If I know the amount of columns the model has, I can count the number of rows with a function and do this: var modelRows = exportQuery.Count()+1; string modelRange = "D1:F" + modelRows.ToString();var modelTable = worksheet.Cells[modelRange]; Or, with more context. I verified that EPPlus will accept a string variable in Cells[], which allows me to select the entire table and apply my border styling and AutoFitColumns{} correctly. All I have to do manually is enter the starting column and ending column in the modelRange variable. var modelCells = worksheet.Cells["D1"];var modelRows = exportQuery.Count()+1; string modelRange = "D1:F" + modelRows.ToString();var modelTable = worksheet.Cells[modelRange];// Assign bordersmodelTable.Style.Border.Top.Style = ExcelBorderStyle.Thin;modelTable.Style.Border.Left.Style = ExcelBorderStyle.Thin;modelTable.Style.Border.Right.Style = ExcelBorderStyle.Thin;modelTable.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;// Fill worksheet with data to exportmodelCells.LoadFromCollection(Collection: exportQuery, PrintHeaders: true);modelTable.AutoFitColumns();
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30972175', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_77076
stackexchange
llm_judgeable_groundtruth_similarity
653011
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: Like this: model EFUSE_MODEL ( input PG_MODE, ...); ... buf (pg_mode_buf, PG_MODE);// the body of this model uses pg_mode_buf only Now provide the response and nothing else.
Can I use a 220V to 220V transformer in 110V to 110V? What happenswith the power rating? Yes you can use it but the power rating will reduce proportionately. This is because the full-load current handling of the transformer cannot increase at a lower voltage i.e. it is what it is and you are stuck with that maximum current. There are two basic things that govern the VA rating of a transformer. The first thing is limiting the supply voltage to avoid excessive magnetic core saturation. The 2nd thing is limiting the current handling capacity of the wires to prevent excessive \$I^2R\$ heat. Clearly, lowering the voltage isn't going to make things worse regards core saturation but, you still cannot exceed the maximum current handling of the transformer winding wires.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/653011', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/258385/']}
jdg_77077
stackexchange
llm_judgeable_groundtruth_similarity
4254452
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I came up with this when trying to solve a problem of a markov chain with the transition matrix $$P=\begin{bmatrix} 0,0,0,\cdots,1\\ 0,0,\cdots,\frac{1}{2},\frac{1}{2}\\ 0,\cdots,\frac{1}{3},\frac{1}{3},\frac{1}{3}\\ \cdots\cdots\\ \frac{1}{n},\cdots,\frac{1}{n},\frac{1}{n} \end{bmatrix}$$ and it asked me to find $$\lim\limits_{k \rightarrow +\infty}{P^k}\alpha$$ where $\alpha=(0,1,\cdots,n-1)^\top$ . So, I tried to diagonalize $P$ and surprisedly found that it has eigenvalues $1,-\frac{1}{2},\cdots,(-1)^{n-1}\frac{1}{n}$ when $n\leq 7$ .So I wonder if this is true for all $n$ from $N^+$ and then how to calculate $$\lim\limits_{k \rightarrow +\infty}{P^k}\alpha$$ Thanks! Now provide the response and nothing else.
$P$ is an irreducible stochastic matrix. Therefore, by Perron-Frobenius theorem, $\lim_{k\to\infty}P^k=\frac{vu^T}{u^Tv}$ , where $u$ and $v$ are respectively a left eigenvector and a right eigenvector of $P$ corresponding to the eigenvalue $1$ . By inspection, we see that up to scaling, $v=(1,1,\ldots,1)^T$ and $u=(1,2,\ldots,n)^T$ . Thus $$\lim_{k\to\infty}P^k=\frac{2}{n(n+1)}\pmatrix{1&2&\cdots&n\\ 1&2&\cdots&n\\ \vdots&\vdots&&\vdots\\ 1&2&\cdots&n}\tag{1}$$ and $\lim_{k\to\infty}P^k\alpha=\frac{2(n-1)}{3}(1,1,\ldots,1)^T$ . Without using Perron-Frobenius theorem, one may consider the following matrix first: $$M(t,n)=\pmatrix{&&&&-(n-1)&t+n\\&&&-(n-2)&t+(n-1)\\&&\cdots&\cdots\\&-2&t+3\\-1&t+2\\t+1}\in\mathbb R^{n\times n}.$$ Let $V\in\mathbb R^{n\times n}$ be the upper triangular matrix of ones. Then $V^{-1}$ is the bidiagonal matrix whose main diagonal entries are ones and whose superdiagonal entries are minus ones. By direct calculation, we get \begin{aligned}M(t,n)V&=\pmatrix{&&&&-(n-1)&t+1\\&&&-(n-2)&t+1&t+1\\&&\cdots&\cdots&\cdots&\cdots\\&-2&t+1&\cdots&\cdots&t+1\\-1&t+1&\cdots&\cdots&\cdots&t+1\\t+1&\cdots&\cdots&\cdots&\cdots&t+1},\\V^{-1}M(t,n)V&=\left(\begin{array}{ccccc|c}&&&n-2&-(t+n)&0\\&&n-3&-(t+n-1)&0&0\\&\cdots&\cdots&\cdots&\cdots&\cdots\\1&-(t+3)&0&\cdots&\cdots&0\\-(t+2)&0&\cdots&\cdots&\cdots&0\\\hlinet+1&\cdots&\cdots&\cdots&\cdots&t+1\end{array}\right)\\&=\pmatrix{-M(t+1,n-1)&0\\ \ast&t+1}.\end{aligned} So, recursively, we have \begin{aligned}\operatorname{spectrum}\left(M(t,n)\right)&=\{t+1\}\cup\operatorname{spectrum}\left(-M(t+1,n-1)\right)\\&=\{t+1,-(t+2)\}\cup\operatorname{spectrum}\left(M(t+2,n-2)\right)\\&=\{t+1,-(t+2),t+3\}\cup\operatorname{spectrum}\left(-M(t+3,n-3)\right)\\&\vdots\\&=\{t+1,\,-(t+2),\,t+3,\,\ldots,\,(-1)^{n-1}(t+n)\}.\\\end{aligned} It follows that \begin{aligned}\operatorname{spectrum}(P)=\operatorname{spectrum}\left(M(0,n)^{-1}\right)=\left\{1,\,-\frac12,\,\frac13,\,\ldots,\,\frac{(-1)^{n-1}}{n}\right\}.\end{aligned} Since $1$ is a simple eigenvalue and the moduli of all other eigenvalues are strictly smaller than $1$ , we again conclude that $\lim_{k\to\infty}P^k=\frac{vu^T}{u^Tv}$ , where $u$ and $v$ are respectively any left and right eigenvectors of $P$ corresponding to the eigenvalue $1$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4254452', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/920329/']}
jdg_77078
stackexchange
llm_judgeable_groundtruth_similarity
16319463
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What is the best way to clean out a database before running a test suite (is there a npm library or recommended method of doing this). I know about the before() function. I'm using node/express, mocha and sequelize. Now provide the response and nothing else.
The before function is about as good as you will do for cleaning out your database. If you only need to clean out the database once i.e. before you run all your tests, you can have a global before function in a separate file globalBefore.js before(function(done) { // remove database data here done()}) single-test-1.js require('./globalBefore')// actual test 1 here single-test-2.js require('./globalBefore')// actual test 2 here Note that the globalBefore will only run once even though it has been required twice Testing Principles Try to limit the use of external dependecies such as databases in your tests. The less external dependencies the easier the testing. You want to be able to run all your unit tests in parallel and a shared resource such as a database makes this difficult. Take a look at this Google Tech talk about writing testable javascript http://www.youtube.com/watch?v=JjqKQ8ezwKQ Also take look at the rewire module. It works quite well for stubbing out functions.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16319463', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/541744/']}
jdg_77079
stackexchange
llm_judgeable_groundtruth_similarity
7169869
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 highcharts to generate graphical data pulled from a database. I am having trouble using the exporting module. I have included the exporting property: exporting{ enabled:true} but the buttons do not appear... I have also linked the exporting.js to the file too...no buttons appear.. Has anyone else had this issue? EDIT: Here is the code: $.ajax({ type:"POST", url: "retrievechartdata.php", data: {questionId:qId, questionIdTwo:qIdTwo, title:title, titleTwo:titleTwo, from:from, to:to}, dataType: "json", success: function(data) { //$("#response").html("<div class='successMessage'>"+ data.valuesTwo +"</div>"); var maxY = parseInt(data.max) + 1; var minY = parseInt(data.min); if(minY > 0){ minY = 0; }else{ minY -= 1; } var cdata = new Array(); cdata= data.values.split(','); for(var i=0;i<cdata.length;i++) { cdata[i]= parseInt(cdata[i]); } var leg = false; var title = data.questionTitle; if(data.valuesTwo != "FALSE"){ leg = true; title += " & "+data.questionTitleTwo; var cdataTwo = new Array(); cdataTwo = data.valuesTwo.split(','); for(var i=0;i<cdataTwo.length;i++) { cdataTwo[i]= parseInt(cdataTwo[i]); } } chart = new Highcharts.Chart({ chart: { renderTo: 'container', zoomType: 'x', spacingRight: 20 }, credits: { enabled: false }, title: { text: title }, subtitle: { text: document.ontouchstart === undefined ? 'Click and drag in the plot area to zoom in' : 'Drag your finger over the plot to zoom in' }, xAxis: { type: 'datetime', maxZoom: 14 * 24 * 3600000, // fourteen days lineWidth: 1, lineColor: '#999999', title: { text: 'Date' } }, yAxis: { title: { text: data.questionTitle }, labels: { y: 2 }, lineWidth: 1, lineColor: '#999999', gridLineWidth: 1, gridLineColor: '#eaeaea', min: minY, max: maxY, startOnTick: false, showFirstLabel: false }, tooltip: { shared: true }, legend: { enabled: leg }, plotOptions: { area: { Color: { linearGradient: [0, 0, 0, 600], stops: [ [0, 'rgb(69, 114, 167)'], [1, 'rgba(2,0,0,0)'] ] }, lineWidth: 1, marker: { enabled: false, states: { hover: { enabled: true, radius: 5 } } }, shadow: false, states: { hover: { lineWidth: 1 } } } }, series: [{ type: 'spline', name: data.questionTitle, pointInterval: 24 * 3600 * 1000, pointStart: Date.UTC(data.year, data.month, data.day), data: cdata, lineColor: '#f6a828', color: '#418ed6' }, { type: 'spline', name: data.questionTitleTwo, pointInterval: 24 * 3600 * 1000, pointStart: Date.UTC(data.year, data.month, data.day), data: cdataTwo, lineColor: '#808080', color: '#ff0000' }], exporting: { enabled: true } }) Now provide the response and nothing else.
Which version of Highcharts you are using? Which version of jQuery? Currently is the v2.1.6, I recommend you use the latest release because they are continuously fixing bugs, adding new functionality, etc. Prior to v2.0 there is no support to the exporting feature The only things you need to do in order to bring the exporting module working are: 1- First: Add the js script after the highcharts script, like this: ... <script type="text/javascript" src="../js/highcharts.js"></script> <!-- 1b) Optional: the exporting module --> <script type="text/javascript" src="../js/modules/exporting.js"></script> ... The exporting module is enabled by default, so there is no need to have the code you posted, so you can remove it: exporting{ enabled:true} 2- Second: Be sure to publish the exporting-server/index.php file correctly. Here you have what the official documentation reads about the exporting module installation: Exporting module From version 2.0 an exporting module is available for Highcharts, which allows users to download images or PDF's of your charts. This module consists of an extra JavaScript file, exporting.js, and a web service or server module written in PHP. Highslide Software offers the exporting web service free of charge. If you include the exporting module in your charts, two buttons will appear in the upper right. One button prints the chart, which is done on the client side only. The other button handles exporting. By default, an SVG representation of the chart is sent by POST to http://export.highcharts.com , where it is converted using Apache's Batik converter to PDF, PNG or JPEG. See the navigation and exporting reference items for a full documentation for the options available. Also see under "Methods and Properties" in the reference for members releated to exporting. Here you can see the configuration options regarding the exporting module: http://www.highcharts.com/ref/#exporting Hope it helps you.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7169869', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/906568/']}
jdg_77080
stackexchange
llm_judgeable_groundtruth_similarity
12985088
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Reading from here: ASP.NET MVC Action SelectCategory has been created inside controller - public ActionResult SelectCategory() { List<SelectListItem> items = new List<SelectListItem>(); items.Add(new SelectListItem { Text = "Action", Value = "0"}); items.Add(new SelectListItem { Text = "Drama", Value = "1" }); items.Add(new SelectListItem { Text = "Comedy", Value = "2", Selected = true }); ViewBag.MovieType = items; return View(); } I am not able to understand binding of Data in following line. @Html.DropDownList("MovieType") While binding data in similar way, @Html.DropDownList("IdList"); I obtain following error- There is no ViewData item of type 'IEnumerable' that has the key 'IdList'. Controller Action : public ActionResult SelectId() { List<SelectListItem> items = new List<SelectListItem>(); items.Add(new SelectListItem { Text = "MyId1", Value = "MyId1", Selected=true }); items.Add(new SelectListItem { Text = "MyId2", Value = "MyId2" }); ViewBag.IdList = items; return View(); } What am I missing ? Thank you for your help ! Now provide the response and nothing else.
You have set ViewBag.MovieType => when you use @Html.DropDownList("MovieType") the dropdown will use this value. When you write @Html.DropDownList("IdList") , the helper doesn't find a corresponding IdList property in ViewBag and throws an error because it doesn't know from where to bind the data. Alternatively if you want to change the name of the dropdown you could use the following: @Html.DropDownList("SelectedMovieType", (IEnumerable<SelectListItem>)ViewBag.MovieType) and your POST action will have a SelectedMovieType parameter to retrieve the selected value. But I would avoid ViewBag. Defining a view model is better: public class MyViewModel{ public string SelectedMovieType { get; set; } public IEnumerable<SelectListItem> MovieTypes { get; set; }} and then have your controller action populate this view model and pass it to the view: public ActionResult SelectId(){ List<SelectListItem> items = new List<SelectListItem>(); items.Add(new SelectListItem { Text = "MyId1", Value = "MyId1", Selected=true }); items.Add(new SelectListItem { Text = "MyId2", Value = "MyId2" }); var model = new MyViewModel { MovieTypes = items }; return View(model);} and in your strongly typed view: @model [email protected](x => x.SelectedMovieType, Model.MovieTypes)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12985088', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1431250/']}
jdg_77081
stackexchange
llm_judgeable_groundtruth_similarity
54303384
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hello I'm working on Xamarin.Forms, I'm facing a problem of data binding in ListView . There's a string value in model and a list in model, the list is the ItemsSource of ListView and string value should be shown in every cell row. XMAL View <ListView ItemsSource="{Binding StudentList, Mode=TwoWay}"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <StackLayout> <Label Text={Binding Name} /> <Label Text={Binding ConstantName} /> //// Not present in Itemsource. Should bind from Model. It does not render. </Stacklayout> </ViewCell> </DataTemplate> </ListView.ItemTemplate></ListView> C# public ObservableCollection<PagingButtons> _lstPagingButtons { get; set; }public ObservableCollection<PagingButtons> lstPagingButtons{ get { return _lstPagingButtons; } set { _lstPagingButtons = value; OnPropertyChanged(); }}string _ConstantName {get; set;} = "Xamarin";public string ConstantName { get { return _ConstantName; } set { __ConstantName = value; OnPropertyChange(); } I know that I can add ConstantName to PagingButtons class but I do have this scenario for 30-40 class and it will be tedious to do that and wont be effective way to do that. Now provide the response and nothing else.
I'm going to assume that there is a ContentPage around your ListView , but this can be any page (or even element). Give that page a name, if it doesn't already have one, like this: <ContentPage x:Name="MyAwesomePage" ...> Now, change your Label to this: <Label Text={Binding BindingContext.ConstantName, Source={x:Reference Name=MyAwesomePage}} /> This way, you refer the binding to your page's BindingContext , effectively changing the scope.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54303384', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4549371/']}
jdg_77082
stackexchange
llm_judgeable_groundtruth_similarity
1965026
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 developing a site using pinax. In one of my templates I am trying to open a simple jquery dialog box. However I keep getting the "Dialog not a function" javascript error. I am using jquery 1.2.6 and jquery-ui 1.6. My javascript and HTML are as follows: <html><head><link type="text/css" href="/site_media/smoothness/ui.all.css" rel="stylesheet" /><script src="/site_media/jquery.js" type="text/javascript"></script><script src="/site_media/ui/ui.core.js" type="text/javascript"></script><script src="/site_media/ui/ui.draggable.js" type="text/javascript"></script><script src="/site_media/ui/ui.resizeable.js" type="text/javascript"></script><script src="/site_media/ui/ui.dialog.js" type="text/javascript"></script><script type="text/javascript">$(document).ready(function(){ $('#dialogbox').dialog(); }); </script> </head> <body> <div id="dialogbox" title="dialog title"> <p>Test dialog</p> </div> </body> </html> Can someone please explain why this is happening? Now provide the response and nothing else.
I tried to duplicate your error both by using the public google versions and by downloading the legacy (1.6) version from the jQuery UI site and manually including the files. Neither caused a problem ( http://jsbin.com/uloqi to see it working). So, that means one of the following might solve your problem: Use a tool like Firebug for Firefox to verify each JS file is being included. Make sure there is no other JS on the page that could cause an error. Verify you have the correct versions of the files downloaded. I don't know what else to tell you since the code you pasted, when paired with the right files, works perfectly.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1965026', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/123871/']}
jdg_77083
stackexchange
llm_judgeable_groundtruth_similarity
9282967
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 at how to do file input and output in Python. I've written the following code to read a list of names (one per line) from a file into another file while checking a name against the names in the file and appending text to the occurrences in the file. The code works. Could it be done better? I'd wanted to use the with open(... statement for both input and output files but can't see how they could be in the same block meaning I'd need to store the names in a temporary location. def filter(txt, oldfile, newfile): '''\ Read a list of names from a file line by line into an output file. If a line begins with a particular name, insert a string of text after the name before appending the line to the output file. ''' outfile = open(newfile, 'w') with open(oldfile, 'r', encoding='utf-8') as infile: for line in infile: if line.startswith(txt): line = line[0:len(txt)] + ' - Truly a great person!\n' outfile.write(line) outfile.close() return # Do I gain anything by including this?# input the name you want to check againsttext = input('Please enter the name of a great person: ') letsgo = filter(text,'Spanish', 'Spanish2') Now provide the response and nothing else.
Python allows putting multiple open() statements in a single with . You comma-separate them. Your code would then be: def filter(txt, oldfile, newfile): '''\ Read a list of names from a file line by line into an output file. If a line begins with a particular name, insert a string of text after the name before appending the line to the output file. ''' with open(newfile, 'w') as outfile, open(oldfile, 'r', encoding='utf-8') as infile: for line in infile: if line.startswith(txt): line = line[0:len(txt)] + ' - Truly a great person!\n' outfile.write(line)# input the name you want to check againsttext = input('Please enter the name of a great person: ') letsgo = filter(text,'Spanish', 'Spanish2') And no, you don't gain anything by putting an explicit return at the end of your function. You can use return to exit early, but you had it at the end, and the function will exit without it. (Of course with functions that return a value, you use the return to specify the value to return.) Using multiple open() items with with was not supported in Python 2.5 when the with statement was introduced, or in Python 2.6, but it is supported in Python 2.7 and Python 3.1 or newer. http://docs.python.org/reference/compound_stmts.html#the-with-statement http://docs.python.org/release/3.1/reference/compound_stmts.html#the-with-statement If you are writing code that must run in Python 2.5, 2.6 or 3.0, nest the with statements as the other answers suggested or use contextlib.nested .
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/9282967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1204115/']}
jdg_77084
stackexchange
llm_judgeable_groundtruth_similarity
60688
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $(X,\mathcal{E})$ be a measure space. Let $\mu : \mathcal{E} \to \mathbb{R}^+$ be a positive measure. If $f: X \to \mathbb{R}^m$ is measurable and $z \in \mathbb{R}^m$, is it true that: $\int_B \langle f, z \rangle d\mu = \langle \int_B f d\mu, z \rangle$? I could prove this for simple functions $f$ but not for general functions. Any help is much appreciated. Thanks,Phanindra Now provide the response and nothing else.
Writing $f=(f_1,\ldots,f_m)$ and $z=(z_1,\ldots,z_m)$, both sides are $\displaystyle\sum\limits_{k=1}^mz_k\int_Bf_k\text{d}\mu$, so, yes, they are equal as soon as everything written makes sense, that is, as soon as every $f_k$ is integrable on $B$. On the LHS, this follows from the definition of the scalar product $\langle\ ,\ \rangle$ and the linearity of the integral. On the RHS, this follows from the definition of the integral of a vector-valued function and the definition of the scalar product $\langle\ ,\ \rangle$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/60688', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/13199/']}
jdg_77085
stackexchange
llm_judgeable_groundtruth_similarity
4943962
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 defined the following two types in my XSD-file: <complexType name="primitive"> <attribute name="seq_num" type="int"/> <element name="prim_to" type="int"/></complexType><complexType name="configdata"> <sequence> <element name="enable" type="boolean"/> <element name="type" default="int"/> </sequence></complexType> Both types are used in a number of definitions, i.e. I would rather not change these them. I would like to define a new element set which extends primitive and contains all sub-elements of configdata . The XML-file for this element would look like this (please note, that enable and type are at the same level as prim_to ): <set seq_num="1234"> <prim_to>22</prim_to> <enable>true<enable> <type>42</type></set> I could declare set the following way: <element name="set"> <complexType> <complexContent> <extension base="primitive"> <sequence> <element name="config" type="configdata"/> </sequence> </extension> </complexContent> </complexType></element> In this case the XML-file would look like this: <set seq_num="1234"> <prim_to>22</prim_to> <config> <enable>true<enable> <type>42</type> </config></set> My challenge is to define set in such a way that it extends primitive and contains all sub-elements of configdata - but does not contain an element of the type configdata . Basically for the XML-file above it is a question of not having the two 'config'-tags. Is this possible in XSD? I would highly appreciate any hints. Thanks in Advance, Witek Now provide the response and nothing else.
In the following, "auto-generated" means "implicitly declared as defaulted, but not defined as deleted". There are situations where the special member functions are declared, but defined as deleted. The default constructor is auto-generated if there is no user-declared constructor (§12.1/5). The copy constructor is auto-generated if there is no user-declared move constructor or move assignment operator (because there are no move constructors or move assignment operators in C++03, this simplifies to "always" in C++03) (§12.8/8). The copy assignment operator is auto-generated if there is no user-declared move constructor or move assignment operator (§12.8/19). The destructor is auto-generated if there is no user-declared destructor (§12.4/4). C++11 and later only: The move constructor is auto-generated if there is no user-declared copy constructor, copy assignment operator or destructor, and if the generated move constructor is valid (§12.8/10). The move assignment operator is auto-generated if there is no user-declared copy constructor, copy assignment operator or destructor, and if the generated move assignment operator is valid (e.g. if it wouldn't need to assign constant members) (§12.8/21).
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/4943962', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/389471/']}
jdg_77086
stackexchange
llm_judgeable_groundtruth_similarity
22312
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In python, if you wish to reverse a list, here is the trick: range(10)[::-1] => [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] Note: list[start:end:steps] is the slice method in python. The above code omitted the first two arguments. It rings a bell in Mathematica : Part[list, Span[start, end, step]] <=> list[[start;; end;; step]] However this isn't gonna work in MMA (or not yet? since mine is still MMA 7) Range[10][[;; ;; -1]] Part::take: Cannot take positions 1 through -1 in {1,2,3,4,5,6,7,8,9,10}. >> Part[{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, 1 ;; All ;; -1] This error message gave clues to what happened.When step length is negative, the start index should be greater than the end one - no matter in python or MMA syntax. The problem why this didn't work lies in the omitted arguments. MMA filled them with 1 and All and then got stuck. By contrast python smartly exchanged the two. My actual question in this is: How can I can look into the default values /optional arguments of a built-in function like Span ? I can't find it in the documentations. Give another look at the fun code: range(10)[::-1] My implementation of this it to modify the definitions Unprotect[Span, Part];Part[x_List, Span[1, All, k_]] /; k < 0 := Part[x, Span[All, 1, k]];Protect[Span, Part](*behold lol*)Range[10][[;; ;; -1]](* {10, 9, 8, 7, 6, 5, 4, 3, 2, 1} *) To clear the modifications: Unprotect[Span, Part]; Clear[Span, Part]; Protect[Span, Part] or CompoundExpression@@ Through[{Unprotect, Clear, Protect}[Span, Part]] Now provide the response and nothing else.
To answer your question: In this case you could just type a fake Span call and keep it unevaluated. When you then look at the fullForm you see: Hold[list[[ ;; ;;-1]]]//FullForm(* Hold[Part[list,Span[1,All,-1]]] *) what you actually called: Span[1,All,-1] . Since you now know what happens, you can catch, when someone calls Part[list_, Span[1, All, -1] and use Reverse to give the reversed list Unprotect[Span];Span /: Part[list_, Span[1, All, -1]] := Reverse[list];Protect[Span] and now your simple example works as expected Range[10][[;;;;-1]](* {10,9,8,7,6,5,4,3,2,1} *)
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/22312', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/5136/']}
jdg_77087
stackexchange
llm_judgeable_groundtruth_similarity
42032668
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 a user inputs a url that is wrong, my Django app returns an HTML error. How can I get DRF to return a json formatted error? Currently my urls is from django.conf.urls import urlfrom snippets import viewsurlpatterns = [ url(r'^snippets/$', views.snippet_list), url(r'^snippets/(?P<pk>[0-9]+)/$', views.snippet_detail),] but if a user goes to 127.0.0.1:8000/snip They get the html formatted error rather than a json formatted error. Now provide the response and nothing else.
Simply way to do it, you can use raise Http404 , here is your views.py from django.http import Http404from rest_framework import statusfrom rest_framework.response import Responsefrom rest_framework.views import APIViewfrom yourapp.models import Snippetfrom yourapp.serializer import SnippetSerializerclass SnippetDetailView(APIView): def get_object(self, pk): try: return Snippet.objects.get(pk=pk) except Snippet.DoesNotExist: raise Http404 def get(self, request, pk, format=None): snippet = self.get_object(pk) serializer = SnippetSerializer(snippet) return Response(serializer.data, status=status.HTTP_200_OK) You also can handle it with Response(status=status.HTTP_404_NOT_FOUND) , this answer is how to do with it: https://stackoverflow.com/a/24420524/6396981 But previously, inside your serializer.py from rest_framework import serializersfrom yourapp.models import Snippetclass SnippetSerializer(serializers.ModelSerializer): user = serializers.CharField( source='user.pk', read_only=True ) photo = serializers.ImageField( max_length=None, use_url=True ) .... class Meta: model = Snippet fields = ('user', 'title', 'photo', 'description') def create(self, validated_data): return Snippet.objects.create(**validated_data) To test it, an example using curl command; $ curl -X GET http://localhost:8000/snippets/<pk>/# example;$ curl -X GET http://localhost:8000/snippets/99999/ Hope it can help.. Update If you want to handle for all error 404 urls with DRF, DRF also provide about it with APIException , this answer may help you; https://stackoverflow.com/a/30628065/6396981 I'll give an example how do with it; 1. views.py from rest_framework.exceptions import NotFounddef error404(request): raise NotFound(detail="Error 404, page not found", code=404) 2. urls.py from django.conf.urls import ( handler400, handler403, handler404, handler500)from yourapp.views import error404handler404 = error404 Makesure your DEBUG = False
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/42032668', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1364586/']}
jdg_77088
stackexchange
llm_judgeable_groundtruth_similarity
264924
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: In quantum mechanics if two quantities $A$ and $B$ are said to be coupled what does this actually mean? I would guess that it means we have a term like $A\cdot B$ in the Hamiltonian but this is only a guess. Now provide the response and nothing else.
Let me preface by saying that "coupling" is a favorite physicist word that is perhaps best described linguistically than rigorously; it's deployed in a few different situations. In general, we say that a coupling exists in quantum mechanics if the evolution of one part of the system depends on another quantity, which could be either classical or quantum. I'll give one example for each. Suppose the Hamiltonian of a two-level system is an internal Hamiltonian $H_\mathrm{int}$ and an additional part that depends on some external parameter, maybe $\theta$:\begin{equation}H = H_\mathrm{int} + \theta \sigma_z\end{equation}Here the $\sigma_z$ was arbitrary. The point is that this system's evolution depends directly on the parameter $\theta$--maybe it's an external magnetic field, or some other feature of the environment. In this case, we would generally say that the system is "coupled to $\theta$." (You'd often see this in a metrological context, where we might be interested in using a quantum system coupled to an external parameter to measure the parameter.) In this case, there is only one quantum object, evolving under $H$. Another common system--maybe a little more general--would be the evolution of two different variables both treated quantum mechanically. The idea here is that there would be some operator $A$ characterizing one observable of interest, and another $B$ characterizing a second. Then the Hamiltonian might be:\begin{equation}H = H_A + H_B + H_{AB}\end{equation}Where $H_A$ doesn't contain any term depending on $B$, $H_B$ doesn't contain any term depending on $A$, and $H_{AB}$ might have terms like $A \cdot B$, $A^2 B$, etc. The reason why this couples the system is that if we now evaluate Heisenberg equations of motion $\dot{A} = \frac{i}{\hbar} \left[ H, A \right]$ we'll find that the $H_{AB}$ term will put terms depending on $B$ into $\dot{A}$ and vice versa. Therefore, solving the equations of motion will require describing both $A$ and $B$. On the other hand, if the equations "decouple" or we do something to decouple them ourselves, we can usually find a solution for $A(t)$ that doesn't depend on $B$ and vice versa. This is all paralleled in classical mechanics, by the way, where we would call two variables coupled if they appeared in each others' equations of motion. EDIT: Peter Shor points out that objects can be "indirectly coupled," which is correct but would usually require me to introduce another variable $C$. I think the most general statement of being coupled/uncoupled is asking whether the equations of motion can be solved independently of each other.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/264924', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/70392/']}
jdg_77089
stackexchange
llm_judgeable_groundtruth_similarity
637791
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How to show that the set of irrational numbers is a Baire space ? Now provide the response and nothing else.
Let's see. The definition of a Baire space is that a countable intersection of dense open sets is dense. So let $I$ be the space of irrational numbers, and let $U_1,U_2,U_3,\dots$ be a sequence of dense open subsets of $I$; I have to show that $\bigcap_{n=1}^\infty U_n$ is dense. Now, "$U$ is open in $I$" means that $U=V\cap I$ for some $V$ which is open in $\mathbb R$; moreover, if $V\cap I$ is dense in $I$, then (since $I$ is dense in $\mathbb R$) it's dense in $\mathbb R$, and so is $V$. So it's enough to show is that, if $V_1,V_2,\dots$ is a sequence of dense open sets in $\mathbb R$, then $\bigcap_{n=1}^\infty(V_n\cap I)=(\bigcap_{n=1}^\infty V_n)\cap I$ is dense. But $I$ itself is a countable intersection of dense open subsets of $\mathbb R$, namely, $I=\bigcap_{q\in\mathbb Q}(\mathbb R\setminus\{q\})$. So now I have to show that $(\bigcap_{n=1}^\infty V_n)\cap\bigcap_{q\in\mathbb Q}(\mathbb R\setminus\{q\})$ is dense, but that's a countable intersection of dense open subsets of $\mathbb R$, so by the Baire category theorem . . .
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/637791', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/107723/']}
jdg_77090
stackexchange
llm_judgeable_groundtruth_similarity
9439210
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 PowerShell script that will parse some very large file for ETL purposes. For starters my test file is ~ 30 MB. Larger files around 200 MB are expected. So I have a few questions. The script below works, but it takes a very long time to process even a 30 MB file. PowerShell Script: $path = "E:\Documents\Projects\ESPS\Dev\DataFiles\DimProductionOrderOperation"$infile = "14SEP11_ProdOrderOperations.txt"$outfile = "PROCESSED_14SEP11_ProdOrderOperations.txt"$array = @()$content = gc $path\$infile | select -skip 4 | where {$_ -match "[|].*[|].*"} | foreach {$_ -replace "^[|]","" -replace "[|]$",""}$header = $content[0]$array = $content[0]for ($i = 1; $i -le $content.length; $i+=1) { if ($array[$i] -ne $content[0]) {$array += $content[$i]}}$array | out-file $path\$outfile -encoding ASCII DataFile Excerpt: ---------------------------|Data statistics|Number of||-------------------------||Records passed | 93,118|---------------------------02/14/2012 Production Operations and Confirmations 2-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------Production Operations and Confirmations-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|ProductionOrderNumber|MaterialNumber |ModifiedDate|Plant|OperationRoutingNumber|WorkCenter|OperationStatus|IsActive| WbsElement|SequenceNumber|OperationNumber|OperationDescription |OperationQty|ConfirmedYieldQty|StandardValueLabor|ActualDirectLaborHrs|ActualContractorLaborHrs|ActualOvertimeLaborHrs|ConfirmationNumber||---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------||180849518 |011255486L1 |02/08/2012 |2101 | 9901123118|56B30 |I9902 | |SOC10MA2302SOCJ31| |0140 |Operation 1 | 1 | 0 | 0.0 | | 499.990 | | 9908651250||180849518 |011255486L1 |02/08/2012 |2101 | 9901123118|56B30 |I9902 | |SOC10MA2302SOCJ31|14 |9916 |Operation 2 | 1 | 0 | 499.0 | | | | 9908532289||181993564 |011255486L1 |02/09/2012 |2101 | 9901288820|56B30 |I9902 | |SOC10MD2302SOCJ31|14 |9916 |Operation 1 | 1 | 0 | 499.0 | | 399.599 | | 9908498544||180885825 |011255486L1 |02/08/2012 |2101 | 9901162239|56B30 |I9902 | |SOC10MG2302SOCJ31| |0150 |Operation 3 | 1 | 0 | 0.0 | | 882.499 | | 9908099659||180885825 |011255486L1 |02/08/2012 |2101 | 9901162239|56B30 |I9902 | |SOC10MG2302SOCJ31|14 |9916 |Operation 4 | 1 | 0 | 544.0 | | | | 9908858514||181638583 |990104460I0 |02/10/2012 |2101 | 9902123289|56G99 |I9902 | |SOC11MAR105SOCJ31| |0160 |Operation 5 | 1 | 0 | 1,160.0 | | | | 9914295010||181681218 |990104460B0 |02/08/2012 |2101 | 9902180981|56G99 |I9902 | |SOC11MAR328SOCJ31|0 |9910 |Operation 6 | 1 | 0 | 916.0 | | | | 9914621885||181681036 |990104460I0 |02/09/2012 |2101 | 9902180289|56G99 |I9902 | |SOC11MAR108SOCJ31| |0180 |Operation 8 | 1 | 0 | 1.0 | | | | 9914619196||189938054 |011255486A2 |02/10/2012 |2101 | 9999206805|5AD99 |I9902 | |RS08MJ2305SOCJ31 | |0599 |Operation 8 | 1 | 0 | 0.0 | | | | 9901316289||181919894 |012984532A3 |02/10/2012 |2101 | 9902511433|A199399Z |I9902 | |SOC12MCB101SOCJ31|0 |9935 |Operation 9 | 1 | 0 | 0.5 | | | | 9916914233||181919894 |012984532A3 |02/10/2012 |2101 | 9902511433|A199399Z |I9902 | |SOC12MCB101SOCJ31|22 |9951 |Operation 10 | 1 | 0 | 68.080 | | | | 9916914224| Now provide the response and nothing else.
Your script reads one line at a time (slow!) and stores almost the entire file in memory (big!). Try this (not tested extensively): $path = "E:\Documents\Projects\ESPS\Dev\DataFiles\DimProductionOrderOperation"$infile = "14SEP11_ProdOrderOperations.txt"$outfile = "PROCESSED_14SEP11_ProdOrderOperations.txt"$batch = 1000[regex]$match_regex = '^\|.+\|.+\|.+'[regex]$replace_regex = '^\|(.+)\|$'$header_line = (Select-String -Path $path\$infile -Pattern $match_regex -list).line[regex]$header_regex = [regex]::escape($header_line)$header_line.trim('|') | Set-Content $path\$outfileGet-Content $path\$infile -ReadCount $batch | ForEach { $_ -match $match_regex -NotMatch $header_regex -Replace $replace_regex ,'$1' | Out-File $path\$outfile -Append } That's a compromise between memory usage and speed. The -match and -replace operators will work on an array, so you can filter and replace an entire array at once without having to foreach through every record. The -readcount will cause the file to be read in chunks of $batch records, so you're basically reading in 1000 records at a time, doing the match and replace on that batch then appending the result to your output file. Then it goes back for the next 1000 records. Increasing the size of $batch should speed it up, but it will make it use more memory. Adjust that to suit your resources.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9439210', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/652261/']}
jdg_77091
stackexchange
llm_judgeable_groundtruth_similarity
10643489
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 scrolling div with a visible width that's half of the content. (The actual content is double the width.) I just want a simple javascript utilizing jquery (serialscroll plugin is really too much) to trigger the scroll to slide into view the next half of the content, then click again the slide it back. (the amount of the sliding is a static #) I've got a jsfiddle with what I have so far. The initial slide left works, but the slide back does not and then it stops working altogether after that. http://jsfiddle.net/w7Uvj/1/ Now provide the response and nothing else.
From a very basic standpoint, throwing aside the specific example that you've provided, here is how I would approach the problem and solution. A Generic Problem / Solution Here's a generic version of the problem: You need to fetch a model by its id. You need a view to render after the model has been fetched. This is fairly simple. Attach the model to the view before fetching the data, then use the "sync" event of the model to render the view: MyView = Backbone.View.extend({ initialize: function(){ this.model.on("sync", this.render, this); }, render: function(){ ... }});myModel = new MyModel({id: someId});new MyView({ model: myModel});myModel.fetch(); Things to note: I'm setting up the model with its id, and the view with the model before calling fetch on the model. This is needed in order to prevent a race condition between loading the data and rendering the view. I've specified generic Backbone stuff here. Marionette will generally work the same, but do the rendering for you. Your Specific Needs Blocking Fetch Bad idea, all around. Don't try it. A blocking fetch will make your application completely unresponsive until the data has returned from the server. This will manifest itself as an application that performs poorly and freezes any time the user tries to do anything. The key to not doing this is taking advantage of events and ensuring that your events are configured before you actually make the asynchronous call, as shown in my generic example. And don't call the fetch from within the model's initializer. That's asking for trouble as you won't be able to set up any views or events before the fetch happens. I'm pretty sure this will solve the majority of the problems you're having with the asynchronous call. Events Between View And Model First, I would avoid using MyApp.vent to communicate between the model and the view instance. The view already has a reference to the model, so they should communicate directly with each other. In other words, the model should directly trigger the event and the view should listen to the event on the model. This works in the same way as my simple example, but you can have your model trigger any event you want at any time. I would also be sure to the use bindTo feature of Marionette's views, to assist in cleaning up the events when the view is closed. MyView = Backbone.Marionette.ItemView.extend({ initialize: function(){ this.bindTo(this.model, "do:something", this.render, this); }});MyModel = Backbone.Model.extend({ doSomething: function(){ this.trigger('do:something'); }});myModel = new MyModel();new MyView({ model: myModel});myModel.doSomething(); Other Items There are some other items that I think are causing some problems, or leading toward odd situations that will cause problems. For example, you have too much happening in the DOMReady event: $ -> It's not that you have too much code being executed from this event, but you have too much code defined within this event. You should not have to do anything more than this: $ -> App.MyApp.start(data) Don't define your Marionette.Application object in this event callback, either. This should be defined on its own, so that you can set up your initializers outside of the DOMReady callback, and then trigger them with the app.start() call. Take a look at the BBCloneMail sample application for an example on rendering a layout and then populating its regions after loading data and external templates: source: https://github.com/derickbailey/bbclonemail live app: http://bbclonemail.heroku.com/ I don't think I'm directly answering your questions the way you might want, but the ideas that I'm presenting should lead you to the answer that you need. I hope it helps at least. :)
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10643489', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/774773/']}
jdg_77092
stackexchange
llm_judgeable_groundtruth_similarity
1639645
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I don't understand why Gauss's lemma is invoked in the proof in Dummit and Foote that $\Phi_n(x)$ (the $n$th cyclotomic polynomial) belongs to $\mathbb{Z}[x]$. I'm an analyst and I wanted to remind myself about cyclotomic polynomials. The following is the proof as I've written it, and because it's been a while since I've done algebra I want to know if there is something I'm taking for granted. It is a fact that if $R$ is a unital commutative ring, $f \in R[x]$ is a monic polynomial and$g \in R[x]$ is a polynomial, then there are $q,r \in R[x]$ with$g = qf+r$, $r=0$ or $\deg r < \deg f$. First, $\Phi_1(x)=x-1 \in \mathbb{Z}[x]$. For $n>1$, assume that$\Phi_d(x) \in \mathbb{Z}[x]$ for $1 \leq d < n$. Then let$f = \prod_{d \mid n, d<n} \Phi_d$,which by hypothesis belongs to $\mathbb{Z}[x]$; and since each $\Phi_d$ is monic, so is $f$. On the one hand,since $g(x)=x^n-1 \in \mathbb{Z}[x]$, there are $q,r \in \mathbb{Z}[x]$ with$g = q f + r$ and$r=0$ or $\deg r < \deg f$.On the other hand, using $x^n-1= \prod_{d \mid n} \Phi_d(x)$ we have$g = \Phi_n f \in \mathbb{C}[x]$. Thus $\Phi_n f = qf+r \in \mathbb{C}[x]$, so $r = f \cdot (\Phi_n - q) \in \mathbb{C}[x]$. If $\Phi_n \neq q$ then $\deg r = \deg f + \deg (\Phi_n-q) \geq \deg f$, contradicting that$r=0$ or $\deg r < \deg f$. Therefore $\Phi_n = q \in \mathbb{C}[x]$, and because $q \in \mathbb{Z}[x]$ this means that$\Phi_n \in \mathbb{Z}[x]$. I don't see any tacit assumptions, like for example degree meaning two different things in $\mathbb{C}[x]$ and $\mathbb{Z}[x]$, but if I'm not assuming anything then I don't see why Gauss's lemma is being used in the proofs I've come across. Now provide the response and nothing else.
Here are some remarks : For those who haven't Dummit and Foote (lemma 40, Sec. 13.6 in the third edition), let me recall that they define $\Phi_n(X)$ as the product of the $X-\zeta$ with $\zeta \in \mu_n$ going through the primitive $n$-th roots of unity. In their proof, they say : $f$ divides $X^n-1$ in $\Bbb Q(\zeta_n)[X]$ and also in $\Bbb Q[X]$ by the division algorithm. Then, $X^n-1=f(X)\Phi_n(X)$ in $\Bbb Q[X]$ and thanks to Gauss' lemma ($f$ being monic in $\Bbb Z[X]$), one has $f \in \Bbb Z[X]$ and $\Phi_n \in \Bbb Z[X]$. In this version, they need to use Gauss' lemma. But I think your version is also right. Actually, since $f$ is assumed to be a monic polynomial in $\Bbb Z[X]$, the division algorithm allows us to write $X^n-1 = q(X)f(X)+r(X)$ in $\Bbb Z[X]$ as you did. In particular, you don't need to use Gauss' lemma here. Then the conclusion follows by your argument, which seems correct to me. Sometimes, the $n$-th cyclotomic polynomial is defined as the minimal polynomial of $\zeta_n$ over $\mathbb Q$. Then $\Phi_n$ divides $X^n-1$ in $\mathbb Q[X]$, since it is a minimal polynomial. By Gauss' lemma, we get : $\Phi_n$ divides $X^n-1$ in $\mathbb Z[X]$, in particular $\Phi_n \in \Bbb Z[X]$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1639645', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/114417/']}
jdg_77093
stackexchange
llm_judgeable_groundtruth_similarity
16565943
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 limit the text to two lines inside a <div> If the text is coming in more than two lines, then it should hide rest of the text after displaying two lines For example: Long text continues down the road into a lane. * * *this should come as: Long text continues down the road I have to do it using css only.. Please suggest? Now provide the response and nothing else.
How about fixing the height of your div to be exactly two lines high, and using overflow:hidden; ? For example: <style type="text/css"> .twolines { font-size: 20px; height: 48px; overflow: hidden; }</style> You could also use em values and line-height : <style type="text/css"> .twolines { font-size: 1em; line-height: 1em; height: 2em; overflow: hidden; }</style> Here's a complete, working example: <!DOCTYPE html><html><head> <style type="text/css"> .twolines { font-size: 1em; background-color: silver; line-height: 1em; height: 2em; overflow: hidden; } .twolines p { margin: 0; } </style></head><body> <div class="twolines"> <p>Long text continues</p> <p>down the road</p> <p>into a lane.</p> </div></body></html>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16565943', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2385986/']}
jdg_77094
stackexchange
llm_judgeable_groundtruth_similarity
12532064
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: PHP 5 introduced DirectoryIterator , and PHP 5.3 introduced FileSystemIterator . FileSystemIterator extends DirectoryIterator , but the documentation fails to say what extra features it brings. Can you tell the difference between DirectoryIterator and FileSystemIterator ? Now provide the response and nothing else.
This goes out of the top of my head, where I sort of got caught in the changes prior to PHP 5.3 that were going to change in 5.3 and later, concerning the SPL (StandardPHPLibrary) and stuff that were going to be moved to the (horrible) PECL extensions. The major thing that changed since 5.3, was that the SPL became an extension that could not be disabled anymore, see the changelog of 5.3 noting that Added SPL to list of standard extensions that cannot be disabled.(Marcus) so all the fancy classes like DirectoryIterator or SPLDoublyLinkedList were now a fix suite of classes that came with PHP 5.3. There were a lot of discussions going on that the DirectoryIterator was still very clumsy in iterating over files/directories and from behaviour not anonymous enough to the filesystem being used. Because depending on the filesystem (Windows NTFS / *nix EXTx) the results the iterator would return were different from another, where *nix environments per default always resulted the dot and double dot directories ( . and .. ) as valid directories. These dot directories could then be filtered in the loop by using the isDot() method. $it = new DirectoryIterator(__DIR__);foreach ($it as $fileinfo) { if (!$fileinfo->isDot()) var_dump($fileinfo->getFilename());} So FilesystemIterator became the new parent class in PHP 5.3, which prior to its release was the DirectoryIterator (where FilesystemIterator extends DirectoryIterator to implement this interchangeable behaviour by default ). The behaviour, or result the FilesystemIterator produced, would then be equal to all different filesystems and interchangeable without the need of any overhead in the loop $it = new FilesystemIterator(__DIR__);foreach ($it as $fileinfo) { echo $fileinfo->getFilename() . "\n";} It's a good question why they didn't update the documentation for noticing the user on the fact that actually the FilesystemIterator preceded the DirectoryIterator .
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12532064', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/759866/']}
jdg_77095
stackexchange
llm_judgeable_groundtruth_similarity
10029089
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Using JavaScript I am pulling names out of webpage and stringing them together somehow (probably going with an array). Once I gather all the names together I need to make another string that gives all the email addresses of the names. The email addresses are not on the webpage so I will have to list every possible thisName=thisEmail in my script somehow. I was about to approach this with making a bazillion if statements but I thought there has to be a more efficient way. Any suggestions? var x = getElementById("names");var name = x.InnerHTML;var email;if (name == 'Steve'){ email == '[email protected]'; }if (name == 'Bob'){ email == '[email protected]'; }.... Now provide the response and nothing else.
A switch statement, as your code is only if-elses :-) No, honestly. The best thing would be if you'd find a simple algorithm to create an email address from any given name, like function mail(name) { return name.toLowerCase() + "@gmail.com";}var email = mail("Bob") // example usage If they differ to much, you might use an object as a key-value-map: var mails = { "Steve": "[email protected]", "Bob": "[email protected]", ...}var email = mails[name]; You could also combine those, if you have to determine which algorithm you need to use: var map = [{ algorithm: function(name) { return name+"@something"; }, names: ["Steve", "Bob", ...]},{ algorithm: function(name) { return "info@"+name+".org"; }, names: ["Mark", ...]}];for (var i=0; i<map.length; i++) if (map[i].names.indexOf(name) > -1) { var email = map[i].algorithm(name); break; } or when it is a bit simpler: var domains = { "gmail.com": ["Steve", "Bob", ...], "free.xxx": ["Mark", ...], ...};for (var domain in domains) if (domains[domain].indexOf(name) > -1) var email = name.toLowerCase()+"@"+domain; break; } Just try to reduce the amount of data to deliver to the client as much as you can.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10029089', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/985851/']}
jdg_77096
stackexchange
llm_judgeable_groundtruth_similarity
6854586
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 create a BASH script what would extract the data from HTML table. Below is the example of table from where I need to extract data: <table border=1><tr><td><b>Component</b></td><td><b>Status</b></td><td><b>Time / Error</b></td></tr><tr><td>SAVE_DOCUMENT</td><td>OK</td><td>0.406 s</td></tr><tr><td>GET_DOCUMENT</td><td>OK</td><td>0.332 s</td></tr><tr><td>DVK_SEND</td><td>OK</td><td>0.001 s</td></tr><tr><td>DVK_RECEIVE</td><td>OK</td><td>0.001 s</td></tr><tr><td>GET_USER_INFO</td><td>OK</td><td>0.143 s</td></tr><tr><td>NOTIFICATIONS</td><td>OK</td><td>0.001 s</td></tr><tr><td>ERROR_LOG</td><td>OK</td><td>0.001 s</td></tr><tr><td>SUMMARY_STATUS</td><td>OK</td><td>0.888 s</td></tr></table> And I want the BASH script to output it like so: SAVE_DOCUMENT OK 0.475 sGET_DOCUMENT OK 0.345 sDVK_SEND OK 0.002 sDVK_RECEIVE OK 0.001 sGET_USER_INFO OK 4.465 sNOTIFICATIONS OK 0.001 sERROR_LOG OK 0.002 sSUMMARY_STATUS OK 5.294 s How to do it? So far I have tried using the sed, but I don't know how to use it quite well. The header of the table(Component, Status, Time/Error) I excluded with grep using grep "<tr><td> , so only lines starting with <tr><td> will be selected for next parsing (sed).This is what I used: sed 's@<\([^<>][^<>]*\)>\([^<>]*\)</\1>@\2@g' But then <tr> tags still remain and also it wont separate the strings. In other words the result of this script is: <tr>SAVE_DOCUMENTOK0.406 s</tr> The full command of the script I'm working on is: cat $FILENAME | grep "<tr><td>" | sed 's@<\([^<>][^<>]*\)>\([^<>]*\)</\1>@\2@g' Now provide the response and nothing else.
Go with (g)awk , it's capable :-), here is a solution, but please note : it's only working with the exact html table format you had posted. awk -F "</*td>|</*tr>" '/<\/*t[rd]>.*[A-Z][A-Z]/ {print $3, $5, $7 }' FILE Here you can see it in action: https://ideone.com/zGfLe Some explanation: -F sets the input field separator to a regexp (any of tr 's or td 's opening or closing tag then works only on lines that matches those tags AND at least two upercasse fields then prints the needed fields. HTH
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6854586', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/689642/']}
jdg_77097
stackexchange
llm_judgeable_groundtruth_similarity
16891397
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have 2 * array and I want to merge them, but each of theme have some NULL rows . $a = array( 'a' => NULL, 'b' => 1, 'c' => 1);$b = array( 'a' => 1, 'b' => NULL, 'c' => 1 ); So, code: $c = array_merge($a,$b); Will give $c: array { 'a'=> 1 'b'=> NULL 'c'=>1} Is there build in or simple way to do margin ($a,$b) like following, but now $a is overwritten for every same index from $b . I want $b to be overwritten by $a index if $b index is null - in example $b['b'] should be overwritten from $a All NULL rows should be filled if possible. Now provide the response and nothing else.
I think you can use array_filter function to remove null values in both array and then merge them $a = array( 'a' => NULL, 'b' => 1, 'c' => 1);$b = array( 'a' => 1, 'b' => NULL, 'c' => 1 );$b = array_filter($b);$a = array_filter($a);$c = array_merge($a, $b);var_dump($c); This will output array(3) { ["b"]=> int(1) ["c"]=> int(1) ["a"]=> int(1)} LIVE SAMPLE As side note i would add that using array_filter without second parameter will end up in deleting all NULL values as well as EMPTY array etc. If you want to only remove NULL values so you will need to use array_filter($yourarray, 'strlen'); EDITED If you want to preserve NULL if both arrays have it with the same key and supposing that both arrays have same number of keys/values, then you will need to loop inside your array and build a new array preserving NULL where you need $a = array( 'a' => NULL, 'b' => 1, 'c' => 1, 'd' => NULL);$b = array( 'a' => 1, 'b' => NULL, 'c' => 1, 'd' => NULL,);$c = array();foreach($a as $key => $val){ if($key == NULL && $b[$key] == NULL) { $c[$key] = $val; } else if($key != NULL && $b[$key] == NULL) { $c[$key]= $val; } else if($key != NULL && $b[$key] != NULL) { $c[$key]= $b[$key]; } else { $c[$key]= $b[$key]; }}var_dump($c); This will output array (size=4) 'a' => int 1 'b' => int 1 'c' => int 1 'd' => NULL LIVE SAMPLE
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16891397', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2446799/']}
jdg_77098
stackexchange
llm_judgeable_groundtruth_similarity
2701
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Why does the butterfly have a cocoon stage in its life cycle? It could have simply grown up within the egg/cocoon, and emerged as a butterfly. Instead it is first an egg, then a worm, then a chrysalis, and finally after some time a butterfly. Now provide the response and nothing else.
Holometaboly is believed to have evolved only once ( Labandeira, 2011 ), but is arguably the most successful mode of development we know of in terms of species richness ( Kristensen, 1999 - PDF link). Insects which have adopted this method are far more diverse than their hemimetabolous counterparts. A conservative estimate by Hammond (1992) is that holometabolous insects comprise more than 60% of all living organisms. The subclass Pterygota (winged insects) is divided into (super orders) endopterygota (wings develop interiorly) which are holometabolous, and the exopterygota (external wing development) which are hemimetabolous. Hemimetabolous insects (usually) develop from an egg to an adult through a series of immature forms (known as nymphs or instars) which are slightly modified (and usually slightly larger) forms of the preceding form. There are exceptions to this mode within the exopterygota including asexual parthenogenesis which is common in aphids. The general life cycle is well illustrated in the Dermaptera (earwigs). All stages inhabit the same ecological niche and so maintain the same general body plan. Image file from Wikimedia Commons here Although hemimetaboly is a more gradual process than holometaboly, it happens in a small number (often four or five nymphal instars) of discrete steps rather than the more continuous development of other animals such as mammals. Although all insects fall into either the exopterygote or endopterygote categories (i.e. wings either develop externally or internally), there are examples of intermediate processes which lie somewhere between hemi- and holometaboly. A notable example are the Cicadas. Cicadas are Hemiperans (true bugs) which lie in the exopterygota and so are, by default hemimetabolous. However there is a considerable difference between their immature and mature stages: Illustration by Debbie Hadley, using drawings from Insects - Their Ways and Means of Living by Robert Evans Snodgrass, U.S. Bureau of Entomology. These drawings are in the public domain. From here . During the immature stages, the larva (or nymph) will burrow underground, sometimes for many years. This requires strong front appendages, which they also use when they surface to grip onto a surface whilst they shed their final skin to become an adult. This differential niche exploitation is likely to have given rise to the morphological differences between immature and mature life stages. Exploiting different niches during different developmental stages not only reduces intra-specific competition between young and adult, it also enables the insect to be more specialised to fulfill their specific role, which changes as they develop. The role of the immature is to grow, they do not yet need to be able to reproduce or disperse; whereas the role of the adult is to find a mate and reproduce. Young often develop below ground where there are fewer predators, adults often fly to enhance dispersal (further reducing competition and also decreasing inbreeding). These two activities call for vastly different body designs. Some other common holometabolous insect orders are Coleoptera (beetles), Hymenoptera (bees, wasps, and ants), and Diptera (true flies), whereas hemimetabolous groups include Orthoptera (grasshoppers, crickets etc.), Mantodea (praying mantids), and Blattaria (cockroaches). As for the chrysalis which Lepidoptera (butterflies and moths) have evolved to surround their pupal stage, the main role is likely to be protection. Larvae (caterpillars) are a highly nutritious and energetic food source and thus have adapted defensive mechanisms such as mimicry, warning colours, and dropping to the ground when disturbed. This drop would damage the metamorphosing pupa (the most vulnerable stage as it is usually relatively immobile), as the cuticle softens to allow for cell-rearrangement. The process of insect development is regulated by juvenile hormone (JH), see Konopova et al , (2011) for more on this. References Hammond, P. (1992) Species Inventory. Global Biodiversity (ed B. Groombridge), pp. 17–39. Chapman and Hall, London. Konopova, B., Smykal, V. & Jindra, M. (2011) Common and Distinct Roles of Juvenile Hormone Signaling Genes in Metamorphosis of Holometabolous and Hemimetabolous Insects. PLoS ONE, 6, e28728. Kristensen, N.P. (1999) Phylogeny of endopterygote insects, the most successful lineage of living organisms. European Journal of Entomology, 96, 237–253. Labandeira, C.C. (2011) Evidence for an Earliest Late Carboniferous Divergence Time and the Early Larval Ecology and Diversification of Major Holometabola Lineages. Entomologica Americana, 117, 9–21.
{}
{'log_upvote_score': 5, 'links': ['https://biology.stackexchange.com/questions/2701', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/1005/']}
jdg_77099
stackexchange
llm_judgeable_groundtruth_similarity
4264623
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Just created a blank "ASP.NET Web Application". Where's the entry point? I see "Default.aspx" which seems to be the default template that calls. "Site.Master" which I guess acts as a layout file. "Global.asax" that seems to provide some method stubs for event handling. And then "Web.config" which seems to have some site-specific settings such as a DB connection string, and some authentication stuff. But no where do I see any "routes" or anything to indicate that "Default.aspx" should be called by default, or "Global.asax" should be used to handle events. Where's this stuff specified? Is it baked into the core of ASP? Can't I filter all the requests through one C# method and then delegate how I please? And return some sort of Http response? Now provide the response and nothing else.
I think I wanted to know the first line of code that gets hit when a new request comes in. The HttpApplication class contains the first line of code of your application. Its constructor is very much the entry point for your application. From the docs : After all core application objects have been initialized, the application is started by creating an instance of the HttpApplication class. There are two canonical ways to write the first line of code that gets hit for a new request. Both involve creating a Global.asax file and handling its events. To handle application events or methods, you can create a file named Global.asax in the root directory of your application. You will want to handle Application_Start and/or Application_BeginRequest . Application_Start is for code that gets hit on the very first request to the application. Each time we restart the application, the next request will enter here. This is per application startup. Application_BeginRequest is for code that gets hit on each request to the application. This is per request. Of course, this all changes with ASP.NET Core.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4264623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/65387/']}
jdg_77100
stackexchange
llm_judgeable_groundtruth_similarity
46216966
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 test case: it("should pass the test", async function (done) { await asyncFunction(); true.should.eq(true); done(); }); Running it asserts: Error: Resolution method is overspecified. Specify a callback or return a Promise; not both. And if I remove the done(); statement, it asserts: Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. How to solve this paradox? Now provide the response and nothing else.
You need to remove the done parameter as well, not just the call to it. Testing frameworks like Mocha look at the function's parameter list (or at least its arity) to know whether you're using done or similar. Using Mocha 3.5.3, this works for me (had to change true.should.be(true) to assert.ok(true) as the former threw an error): const assert = require('assert');function asyncFunction() { return new Promise(resolve => { setTimeout(resolve, 10); });}describe('Container', function() { describe('Foo', function() { it("should pass the test", async function () { await asyncFunction(); assert.ok(true); }); });}); But if I add done : describe('Container', function() { describe('Foo', function() { it("should pass the test", async function (done) { // <==== Here await asyncFunction(); assert.ok(true); }); });}); ...then I get Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46216966', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1026271/']}
jdg_77101
stackexchange
llm_judgeable_groundtruth_similarity
2005304
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The sum of two even integers is also even. I assume P is the sum of two integers, Q is an even number. So $P \rightarrow Q$. Am I correct? Now provide the response and nothing else.
Note that $\displaystyle\left(\prod_{d \mid n} d\right)^2=\prod_{d \mid n} d \prod_{d \mid n} \frac{n}{d}=n^{\tau(n)}$. Therefore, we seek $n$ such that $n^{\tau(n)}=n^6$, that is, $n=1$ or $\tau(n)=6$. Write $n=\prod_p p^{e_p}$. Then $\tau(n)=\prod_p (1+e_p)$. There aren't many possibilities if this is to be $6$ because each possibility corresponds to a factorisation of $6$: $6=6$ gives $n=p^5$. $6=2\cdot 3$ gives $n=pq^2$.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2005304', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/379974/']}
jdg_77102
stackexchange
llm_judgeable_groundtruth_similarity
23644193
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 docs for NSURL state that: An NSURL object represents a URL that can potentially contain the location of a resource on a remote server, the path of a local file on disk, or even an arbitrary piece of encoded data . I have a blob of in-memory data that I'd like to hand to a library that wants to load a resource via an NSURL . Sure, I can first write this NSData to a temp file and then create a file:// NSURL from that, but I'd prefer to have the URL point directly to the buffer that I already have present in memory. The docs quoted above seem to suggest this is possible, but I can't find any hint of how to accomplish it. Am I missing something? Now provide the response and nothing else.
NSURL supports the data:// URL-Scheme ( RFC 2397 ). This scheme allows you to build URLs in the form of data://data:MIME-Type;base64,<data> A working Cocoa example would be: NSImage* img = [NSImage imageNamed:@"img"];NSData* imgData = [img TIFFRepresentation];NSString* dataFormatString = @"data:image/png;base64,%@";NSString* dataString = [NSString stringWithFormat:dataFormatString, [imgData base64EncodedStringWithOptions:0]];NSURL* dataURL = [NSURL URLWithString:dataString]; Passing around large binary blobs with data URLs might be a bit inefficient due to the nature of base64 encoding. You could also implement a custom NSURLProtocol that specifically deals with your data.Apple has some sample code that uses a custom protocol to pass around image objects: https://developer.apple.com/library/mac/samplecode/SpecialPictureProtocol/Introduction/Intro.html#//apple_ref/doc/uid/DTS10003816
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23644193', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/73297/']}
jdg_77103
stackexchange
llm_judgeable_groundtruth_similarity
16041790
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have been switching between branches in a project and each of them have different migrations... This is the scenario: $ rake db:migrate:status Status Migration ID Migration Name-------------------------------------------------- ... up 20130307154128 Change columns in traffic capture up 20130311155109 Remove log settings up 20130311160901 Remove log alarm table up 20130320144219 ********** NO FILE ********** up 20130320161939 ********** NO FILE ********** up 20130320184628 ********** NO FILE ********** up 20130322004817 Add replicate to root settings up 20130403190042 ********** NO FILE ********** up 20130403195300 ********** NO FILE ********** up 20130403214000 ********** NO FILE ********** up 20130405164752 Fix ap hostnames up 20130410194222 ********** NO FILE ********** The problem is rake db:rollback don't work at all because of the missing files... What should I do to be able to rollback again and get rid of the NO FILE messages? Btw, rake db:reset or rake db:drop are not an option, I cannot lose data from other tables... Now provide the response and nothing else.
I ended up solving the problem like this: (1) Go to the branches that has the migration files and roll them back. This is not trivial when you have many branches which are will result in many conflicts if you try to merge them. So I use this commands to find out the branches of each orphan migration belongs to. So, I need to find commit of the last time the migration was modified. git log --all --reverse --stat | grep <LASTEST_ORPHAN_MIGRATION_ID> -C 10 I take the commit hash and determine which branch it belongs like this: git branch --contains <COMMIT_HASH> Then I can go back to that branch, do a rollback and repeat this process for all the missing files. (2) Run migrations: checkout the branch you finally want to work on and run the migrations and you should be good to go. Troubleshooting I also ran in some cases where orphaned migrations where on deleted branches. To solve this I created dummy migration files with the same migration_id of the missing files and roll them back. After that, I was able to delete they dummy migrations and have a clean migration status :) Another alternative is deleting the missing files from the database directly ( rails dbconsole ): delete from schema_migrations where version='<MIGRATION_ID>';
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/16041790', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/684957/']}
jdg_77104
stackexchange
llm_judgeable_groundtruth_similarity
9777731
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In an effort to make a progress reporting process a little more reliable and decouple it from the request/response, I am performing the processing in a Windows Service and persisting the intended response to a file. When the client starts polling for updates, the intention is that the controller returns the contents of the file, whatever they are, as a JSON string. The contents of the file are pre-serialized to JSON. This is to ensure that there is nothing standing in the way of the response. No processing needs to happen (short of reading the file contents into a string and returning it) to get the response. I initially though this would be fairly simple, but it is not turning out to be the case. Currently my controller method looks thusly: Controller Updated [HttpPost]public JsonResult UpdateBatchSearchMembers(){ string path = Properties.Settings.Default.ResponsePath; string returntext; if (!System.IO.File.Exists(path)) returntext = Properties.Settings.Default.EmptyBatchSearchUpdate; else returntext = System.IO.File.ReadAllText(path); return this.Json(returntext);} And Fiddler is returning this as the raw response HTTP/1.1 200 OKServer: ASP.NET Development Server/10.0.0.0Date: Mon, 19 Mar 2012 20:30:05 GMTX-AspNet-Version: 4.0.30319X-AspNetMvc-Version: 3.0Cache-Control: privateContent-Type: application/json; charset=utf-8Content-Length: 81Connection: Close"{\"StopPolling\":false,\"BatchSearchProgressReports\":[],\"MemberStatuses\":[]}" AJAX Updated The following will likely be changed later, but for now this was working when I was generating the response class and returning it as JSON like a normal person. this.CheckForUpdate = function () {var parent = this;if (this.BatchSearchId != null && WorkflowState.SelectedSearchList != "") { showAjaxLoader = false; if (progressPending != true) { progressPending = true; $.ajax({ url: WorkflowState.UpdateBatchLink + "?SearchListID=" + WorkflowState.SelectedSearchList, type: 'POST', contentType: 'application/json; charset=utf-8', cache: false, success: function (data) { for (var i = 0; i < data.MemberStatuses.length; i++) { var response = data.MemberStatuses[i]; parent.UpdateCellStatus(response); } if (data.StopPolling = true) { parent.StopPullingForUpdates(); } showAjaxLoader = true; } }); progressPending = false; }} Now provide the response and nothing else.
The issue, I believe, is that the Json action result is intended to take an object (your model) and create an HTTP response with content as the JSON-formatted data from your model object. What you are passing to the controller's Json method, though, is a JSON-formatted string object , so it is "serializing" the string object to JSON, which is why the content of the HTTP response is surrounded by double-quotes (I'm assuming that is the problem). I think you can look into using the Content action result as an alternative to the Json action result, since you essentially already have the raw content for the HTTP response available. return this.Content(returntext, "application/json");// not sure off-hand if you should also specify "charset=utf-8" here, // or if that is done automatically Another alternative would be to deserialize the JSON result from the service into an object and then pass that object to the controller's Json method, but the disadvantage there is that you would be de-serializing and then re-serializing the data, which may be unnecessary for your purposes.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9777731', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/281348/']}
jdg_77105
stackexchange
llm_judgeable_groundtruth_similarity
594442
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 recently read the questions that recommend against using switch-case statements in languages that do support it. As far as Python goes, I've seen a number of switch case replacements, such as: Using a dictionary (Many variants) Using a Tuple Using a function decorator ( http://code.activestate.com/recipes/440499/ ) Using Polymorphism (Recommended method instead of type checking objects) Using an if-elif-else ladder Someone even recommended the Visitor pattern (Possibly Extrinsic) Given the wide variety of options, I am having a bit of difficulty deciding what to do for a particular piece of code. I would like to learn the criteria for selecting one of these methods over the other in general. In addition, I would appreciate advice on what to do in the specific cases where I am having trouble deciding (with an explanation of the choice). Here is the specific problem: (1) def _setCurrentCurve(self, curve): if curve == "sine": self.currentCurve = SineCurve(startAngle = 0, endAngle = 14, lineColor = (0.0, 0.0, 0.0), expansionFactor = 1, centerPos = (0.0, 0.0)) elif curve == "quadratic": self.currentCurve = QuadraticCurve(lineColor = (0.0, 0.0, 0.0)) This method is called by a qt-slot in response to choosing to draw a curve from a menu. The above method will contain a total of 4-7 curves once the application is complete. Is it justified to use a throw away dictionary in this case? Since the most obvious way to do this is if-elif-else, should I stick with that? I have also consider using **kargs here (with a friends help) since all the curve classes use **kargs... (2) This second piece of code is a qt-slot that is called when the user changes a property of a curve. Basically the slot takes the data from the gui (spinBox) and puts it in an instance variable of the appropriate curve class. In this case, I again have the same question - should I use a dict? Here is the aforementioned slot- def propertyChanged(self, name, value): """A Qt slot, to react to changes of SineCurve's properties.""" if name == "amplitude": self.amplitude = value elif name == "expansionFactor": self.expansionFactor = value elif name == "startAngle": self.startAngle = value elif name == "endAngle": self.endAngle = value For reference, here is the code for connecting to the above slot - def _connectToPage(self, page): for connectionData in page.getConnectibles(): self.connect(connectionData["object"], SIGNAL(connectionData["signal"]), lambda value, name = connectionData["property"]:\ self.currentCurve.propertyChanged(name, value)) self.connect(connectionData["object"], SIGNAL(connectionData["signal"]), self.hackedDisplayArea.update) Note - The self.endAngle etc. are initialized in the constructor. As far as I know, the reasons for choosing a dict is for fast lookup. When is that warranted? when I have 100 cases or more? Is it a good idea to keep building and throwing away a dictionary each time the function is called? If I build a dict for this purpose outside a function, should I check If it is needed elswhere? What happens if it is not needed elsewhere? My question is what is the best-practice if there is one? What is the best/most elegant way to go about things? Put in yet another way, when to use if-elif-else , when to use each of the other options? Now provide the response and nothing else.
Sigh. Too much hand-wringing over the wrong part of the problem. The switch statement is not the issue. There are many ways of expressing "alternative" that don't add meaning . The issue is meaning -- not technical statement choices. There are three common patterns. Mapping a key to an object . Use a dictionary if it is almost totally static and you have a mapping between a simple key and another more complex thing. Building a dictionary on the fly each time you need it is silly. You can use this if it's what you mean : your "conditions" are simple, static key values that map to objects. Variant behavior among subclasses . Use Polymorphism instead of type checking objects. Correct. If you have similar objects in multiple classes with variant behavior, they should be polymorphic. Use this as often as possible. Other variant behavior . Use an if-elif-else ladder. Use this when you don't have largely static key-to-value mapping. Use this when the conditions are complex, or you mean procedures, not objects. Everything else is just tricky code that can achieve similar results. Using a Tuple. This is just dictionary without the mapping. This requires search, and search should be avoided whenever possible. Don't do this, it's inefficient. Use a dictionary. Using a function decorator ( http://code.activestate.com/recipes/440499/ ). Icky. This conceals the if-elif-elif nature of the problem you're solving. Don't do this, it isn't obvious that the choices are exclusive . Use anything else. Someone even recommended the Visitor pattern. Use this when you have an object which follows the Composite design pattern. This depends on polymorphism to work, so it's not really a different solution.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/594442', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/59024/']}
jdg_77106
stackexchange
llm_judgeable_groundtruth_similarity
12868143
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am having a problem with the program I am trying to code. It's just a Windows console program and I am very new to C++. It's only my 4th program. The problem I am having is that when I run my program I have no errors but a lot of warnings that say "comparison with string literal results in unspecified behaviour" in the lines that I will highlight below. When the program runs instead of adding the numbers I want it to it just gives me a random huge number no matter what I put in for my inputs. Here is the code: #include <iostream>using namespace std;int main(){ int hold; int i; int n; i = 6; int result; int * price; char items[100][100]; if (items == 0) cout << "No items can be stored"; else { for (n=0; n<i; n++) { cout << "Item#" << n << ": "; cin >> items[n]; } cout << "\nYou Entered: \n"; for (n=0; n<i; n++) cout << items[n] << ", "; } for (n=0; n<i; n++) { if (items[n] == "ab"){ price[n] = 2650; } else if (items[n] == "ae"){ price[n] = 1925; } else if (items[n] == "ie"){ price[n] = 3850; } else if (items[n] == "bt"){ price[n] = 3000; } else if (items[n] == "pd"){ price[n] = 2850; } else if (items[n] == "ga"){ price[n] = 2600; } } for (n=0; n<i; n++) { result = result + price[n]; } cout << "\nTotal gold for this build: " << result; cin >> hold; return 0;} Any help is appreciated. There is probably something big that I've done wrong. The names in the if statements are all currently placeholders and I'll be adding a lot more if statements when I can get it to work with the bare 6 which is what it needs to work. Now provide the response and nothing else.
In C++ == only implemented internally for primitive types and array is not a primitive type, so comparing char[100] and string literal will only compare them as 2 char* or better to say as 2 pointers and since this 2 pointers can't be equal then items[n] == "ae" can never be true, instead of this you should either use std::string to hold string as: std::string items[100];// initialize itemsif( items[n] == "ae" ) ... or you should use strcmp to compare strings, but remeber strcmp return 0 for equal strings, so your code will be as: char items[100][100];// initialize itemsif( strcmp(items[n], "ae") == 0 ) ... And one extra note is if (items == 0) is useless, since items allocated on stack and not in the heap!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12868143', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1742497/']}
jdg_77107
stackexchange
llm_judgeable_groundtruth_similarity
571783
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: hope you can assist me in this case. I am administrating an Postfix server which is used for newsletters. Recently one of the major recipient domains changed their policies to only accept one email per smtp session/connection. To adhere to their policy I found the following settings in main.cf to be kind of useful as they refer to concurrency of email delivery, though it doesn't seem to help. (I've tested with values as low as 1) initial_destination_concurrency default_destination_concurrency_limit smtp_destination_concurrency_limit The error I am facing is: dsn=4.4.2, status=deferred, along with a link telling me to send a single email per SMTP connection. Postfix version: 2.9.6 Any suggestions will be appreciated! Now provide the response and nothing else.
If you're faced with a specific domain asking for slower delivery, the easiest way is to set up a custom transport: In /etc/postfix/main.cf place these two lines (name it what you want, just use it consistently): smtp-slowdelivery unix - - n - - smtp-o syslog_name=smtp-slowdelivery In /etc/postfix/main.cf add these lines: smtp-slowdelivery_destination_rate_delay = 12s smtp-slowdelivery_destination_concurrency_limit = 1 smtp-slowdelivery_destination_recipient_limit = 1 smtp-slowdelivery_initial_destination_concurrency=1 Add this to /etc/postfix/transport (which you may need to create) /\@thatdomain.com$/ smtp-slowdelivery: (replace thatdomain with the domain you need to slow deliveries to) Postmap the file postmap /etc/postfix/transport then tell postfix the file is a regex: in /etc/postfix/main.cf add: transport_maps = regexp:/etc/postfix/transport and then run postfix reload You should then see mail sent though your new transport in your maillog.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/571783', 'https://serverfault.com', 'https://serverfault.com/users/167428/']}
jdg_77108
stackexchange
llm_judgeable_groundtruth_similarity
56228092
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 multiple buttons on my page: <div> <h1>Home</h1> <button>Action 1</button> <button>Action 2</button></div> How can I select the "Action 2" button by its text , so that I can click on it? I know that there may be other ways to select that button, but I am specifically looking for the best way to select an element by its text . One way I have found is shown below. Is there a better way? const action2Button = wrapper.find('button[children="Action 2"]');expect(action2Button).toHaveLength(1);action2Button.simulate('click'); Now provide the response and nothing else.
The best way I can find to do this, so far, is the following: const button = wrapper.findWhere(node => { return ( node.type() && node.name() && node.text() === "Action 2" );}); There must be a name, and a type, to prevent finding a text node. I'm sure that there must be a better way to do this. Updated: I'm not sure if Enzyme has changed since I answered this. I see that you can now avoid a text node by checking that node.type() is not undefined. I'm not sure how you would avoid a parent node with the same text though.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56228092', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/293680/']}
jdg_77109
stackexchange
llm_judgeable_groundtruth_similarity
102621
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Let $P$ be a poset and denote by $\operatorname{Hom}(P, \mathbb N)$ the set of all monotone functions from $P$ to natural numbers $\mathbb N$ . Under what conditions on $P$ Is it possible to recover the order on $P$ from the knowledge of $\operatorname{Hom}(P, \mathbb N)$ ? I should mention here that the only example I am interested in is the poset of prime ideals in a commutative Noetherian ring. It would be great if you could include references. Now provide the response and nothing else.
Sitting inside $Hom(P,{\bf N})$ is the set $P^*$ of monotone functions from $P$ into $\{0,1\}$ . This set carries the structure of a "Stone lattice", and the normal lattice homomorphisms from any Stone lattice into $\{0,1\}$ will be a poset, in the case of $P^*$ it recovers $P$ . In fact I have just described a dual equivalence between the category of posets with order preserving maps and the category of Stone lattices with normal lattice homomorphisms. See Theorem 6.33 of my book Lipschitz Algebras (second edition).
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/102621', 'https://mathoverflow.net', 'https://mathoverflow.net/users/7041/']}
jdg_77110
stackexchange
llm_judgeable_groundtruth_similarity
23742274
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 Bootstrap ( docs ) say to "always try to place a modal's HTML code in a top-level position in your document to avoid other components affecting the modal's appearance and/or functionality." Does this mean to place modals at the very top of my <body> tags? If so, why? Now provide the response and nothing else.
A ' top-level position ' does not necessarily mean first, it means that it needs to be near the top of the DOM tree. Examples: <body> <div id="content"> <div id="modal"></div> </div></body> This is not at the top of the DOM, because div#modal is inside div#content . So we have this DOM tree: body +-> div#content +-> div#modal Another Example: <body> <div id="content"> <!-- Content goes here --> </div> <div id="modal"></div></body> Although div#modal is not at the top of the page, it's at the top of the DOM tree: body +-> div#content +-> div#modal
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23742274', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2144912/']}
jdg_77111
stackexchange
llm_judgeable_groundtruth_similarity
4426581
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 Python docs on file.read() state that An empty string is returned when EOF is encountered immediately. The documentation further states: Note that this method may call the underlying C function fread() more than once in an effort to acquire as close to size bytes as possible. Also note that when in non-blocking mode, less data than was requested may be returned, even if no size parameter was given. I believe Guido has made his view on not adding f.eof() PERFECTLY CLEAR so need to use the Python way! What is not clear to ME, however, is if it is a definitive test that you have reached EOF if you receive less than the requested bytes from a read, but you did receive some. ie: with open(filename,'rb') as f: while True: s=f.read(size) l=len(s) if l==0: break # it is clear that this is EOF... if l<size: break # ? Is receiving less than the request EOF??? Is it a potential error to break if you have received less than the bytes requested in a call to file.read(size) ? Now provide the response and nothing else.
You are not thinking with your snake skin on... Python is not C. First, a review: st=f.read() reads to EOF, or if opened as a binary, to the last byte; st=f.read(n) attempts to reads n bytes and in no case more than n bytes; st=f.readline() reads a line at a time, the line ends with '\n' or EOF; st=f.readlines() uses readline() to read all the lines in a file and returns a list of the lines. If a file read method is at EOF, it returns '' . The same type of EOF test is used in the other 'file like" methods like StringIO, socket.makefile, etc. A return of less than n bytes from f.read(n) is most assuredly NOT a dispositive test for EOF! While that code may work 99.99% of the time, it is the times it does not work that would be very frustrating to find. Plus, it is bad Python form. The only use for n in this case is to put an upper limit on the size of the return. What are some of the reasons the Python file-like methods returns less than n bytes? EOF is certainly a common reason; A network socket may timeout on read yet remain open; Exactly n bytes may cause a break between logical multi-byte characters (such as \r\n in text mode and, I think, a multi-byte character in Unicode) or some underlying data structure not known to you; The file is in non-blocking mode and another process begins to access the file; Temporary non-access to the file; An underlying error condition, potentially temporary, on the file, disc, network, etc. The program received a signal, but the signal handler ignored it. I would rewrite your code in this manner: with open(filename,'rb') as f: while True: s=f.read(max_size) if not s: break # process the data in s... Or, write a generator : def blocks(infile, bufsize=1024): while True: try: data=infile.read(bufsize) if data: yield data else: break except IOError as (errno, strerror): print "I/O error({0}): {1}".format(errno, strerror) breakf=open('somefile','rb')for block in blocks(f,2**16): # process a block that COULD be up to 65,536 bytes long
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4426581', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/298607/']}
jdg_77112
stackexchange
llm_judgeable_groundtruth_similarity
61098
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: Given a list of vertices associated with its degree, says: $$7, 7, 3, 3, 3, 3, 3, 1$$ Determine whether it is possible to draw a graph $G$, where $G$ is connected and un-directed. Solution : The above graph is impossible to draw because the first two vertices will make every other vertices have degree 2. But I realize this approach is too specific, and it's not feasible if the given list is large, let's say $n > 100$, where $n$ is the number of vertices. So my question is, if a general list of $n$ vertices is given with a degree from $1 \rightarrow n - 1$, then is there a general formula to determine whether it is possible to draw its graph? Thank you. Now provide the response and nothing else.
It is not enough for the sums of the degrees of the vertices to be even. A simple counterexample is 2,2,2,4. I know of 2 common algorithms that can be used to determine whether or not a list of integers represents a valid degree sequence. They are the Erdos-Gallai Theorem and the Havel-Hakimi Theorem. I believe that generally Havel-Hakimi is a little easier to implement and a quick google search turns up several different existing programs.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/61098', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/5711/']}
jdg_77113
stackexchange
llm_judgeable_groundtruth_similarity
9644044
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a question concerning how the "this" pointer is treated in a nested function scenario. Say I insert this following sample code into a web page. I get an error when I call the nested function "doSomeEffects()". I checked in Firebug and it indicates that when I am in that nested function, the "this" pointer is actually pointing to the global "window" object - which I did not expect. I must not be understanding something correctly because I thought since I declared the nested function within a function of the object, it should have "local" scope in relation to the function (i.e. the "this" pointer would be referring to the object itself like how it is in my first "if" statement). Any pointers (no pun intended) would be appreciated. var std_obj = { options : { rows: 0, cols: 0 }, activeEffect : "none", displayMe : function() { // the 'this' pointer is referring to the std_obj if (this.activeEffect=="fade") { } var doSomeEffects = function() { // the 'this' pointer is referring to the window obj, why? if (this.activeEffect=="fade") { } } doSomeEffects(); }};std_obj.displayMe(); Now provide the response and nothing else.
In JavaScript the this object is really based on how you make your function calls. In general there are three ways to setup the this object: someThing.someFunction(arg1, arg2, argN) someFunction.call(someThing, arg1, arg2, argN) someFunction.apply(someThing, [arg1, arg2, argN]) In all of the above examples the this object will be someThing .Calling a function without a leading parent object will generally get you the global object which in most browsers means the window object.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9644044', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/251843/']}
jdg_77114
stackexchange
llm_judgeable_groundtruth_similarity
556911
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How can we prove $\displaystyle \int_{0}^{1}x^{k}\cdot \left(1-x\right)^{n-k}dx = \frac{1}{\binom{n}{k}\cdot (n+1)}$ $\bf{My\; Try}::$ Let $\displaystyle I_{k,n-k} = \int_{0}^{1}\left(1-x\right)^{n-k}\cdot x^kdx = \left[(1-x)^{n-k}\cdot \frac{x^{k+1}}{k+1}\right]_{0}^{1}-\frac{\left(n-k\right)}{k+1}\int_{0}^{1}(1-x)^{n-k-1}\cdot x^{k+1}dx$ $\displaystyle I_{k,n-k}= -\frac{\left(n-k\right)}{\left(k+1\right)}\cdot I_{k+1,n-k-1}$ Using Recursively we get $\displaystyle I_{k,n-k} = -\frac{\left(n-k\right)}{\left(k+1\right)}\cdot I_{k+2,n-k-2} = +\frac{(n-k)(n-k-1)}{(k+1)(k+2)}\cdot I_{k+3,n-k-3} = $ Now I did not understand how can i solve after that help required. Thanks Now provide the response and nothing else.
The basic idea of identifying the recursion via integration by parts is fine. You seem to have mixed up your indices a bit, however. Nevertheless, in particular since you know where you want to arrive, I would suggest doing it in the form $$\begin{align}\frac{n!}{k!(n-k)!} \int_0^1 x^k(1-x)^{n-k}\,dx &= \frac{n!}{(k+1)!(n-k)!} \left[x^{k+1}(1-x)^{n-k}\right]_0^1\\&\quad + \frac{n!}{(k+1)!(n-k-1)!}\int_0^1 x^{k+1}(1-x)^{n-k-1}\,dx\\&= \frac{n!}{(k+1)!(n-k-1)!}\int_0^1 x^{k+1}(1-x)^{n-k-1}\,dx\\&= \quad \dotsb\\&= \frac{n!}{n!(n-n)!} \int_0^1 x^n(1-x)^{n-n}\,dx\\&= \int_0^1 x^n\,dx\\&= \frac{1}{n+1}.\end{align}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/556911', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/14311/']}
jdg_77115
stackexchange
llm_judgeable_groundtruth_similarity
1236190
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a question about combinatorics.I have the following set:$$M = \{ 1,2,...,n \}$$ How many disjoint subsets$$A\subseteq M, \quad |A| = 2$$ are there? For the future, how do I approach questions like these?Thanks in advance for your help EDIT:$n$ is even. I want to know how many ways there are to split $M$ into disjoint subsets of size $2$. If this is any help, I am trying to figure out how many permutations in $S_n$ exist, that are involutions as well as derangements. For $n$ odd there are none, that's what I've shown so far. For $n$ even, I can write the permutation in brackets of size two (I don't know how you call this way of writing a permutation down).The order of the sets do not matter. Now provide the response and nothing else.
Let $A_n$ be the number of ways of partitioning an $n$-element set $M$ into $2$-element subsets. Pick $x \in M$. There are $n - 1$ choices for the element that is going to belong to the same partition as $x$, and then the remaining $n - 2$ elements can be partitioned into $2$-element subsets in $A_{n - 2}$ ways. Clearly $A_1 = 0$ and $A_2 = 1$, so we have: \begin{align}A_n &= (n - 1)A_{n-2}\\A_2 &= 1\\A_1 &= 0\end{align} Hence $A_n = 0$ for odd $n$ and for even $n$ we have: $$A_{n} = 1 \cdot 3 \cdot \ldots \cdot n -1.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1236190', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/220920/']}
jdg_77116
stackexchange
llm_judgeable_groundtruth_similarity
414115
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to bridge a dot1q trunk and cannot seem to figure it out. I am able to connect to hosts on the trunk with my eth0.2 interface but when I bridge the interface with br0 and try to connect I get nothing. Am I missing something simple here? auto loiface lo inet loopbackauto br0iface br0 inet manualbridge_ports eth0bridge_stp offbridge_fd 9bridge_hello 2bridge_maxwait 0auto br0.100iface br0.100 inet staticaddress 192.168.100.99netmask 255.255.255.0auto eth0.2iface eth0.2 inet static address 10.1.2.225 netmask 255.255.255.0 network 10.1.2.1 broadcast 10.2.1.255 gateway 10.1.2.1 mtu 1500 Now provide the response and nothing else.
If an interface ( eth0 in your case) is added to a bridge, by default its VLAN subinterfaces ( eth0.2 ) will no longer get the incoming traffic — all packets will be passed to the bridge. Before Linux 2.6.37 VLAN subinterfaces could sometimes work depending on your hardware (if the hardware and driver supported RX VLAN acceleration ( NETIF_F_HW_VLAN_RX ), VLANs were handled before bridging, and VLAN subinterfaces worked); since 2.6.37 the behavior is the same for all cards and drivers. There are several solutions with different drawbacks: Add VLAN subinterfaces to the bridge instead of the physical interface. But in this case all ports of the bridge will have access to all VLANs, which is probably not desired. Use ebtables to pass 802.1Q tagged traffic to VLAN subinterfaces: ebtables -t broute -A BROUTING -i eth0 -p 802_1Q -j DROP (In the BROUTING chain ACCEPT means “bridge”, and DROP means “route”, or actually “process according to ethertype”, which for the 802_1Q type means “pass to the appropriate VLAN subinterface”.) In this case the bridge will not get any tagged traffic, but there will be slightly more overhead due to ebtables processing. Reconfigure the network to make all traffic on the interface tagged and avoid the need to bridge the untagged traffic at all.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/414115', 'https://serverfault.com', 'https://serverfault.com/users/130901/']}
jdg_77117
stackexchange
llm_judgeable_groundtruth_similarity
37533431
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: ApplicationInsights has recently started mailing me a Weekly Telemetry Report. My problem is that it tells me that I have a bunch of Failed Requests, Failed Dependencies, and Exceptions, but when I click through to analyze the failures I see that they are all associated with attempts by bots or Bad Guys to access nonexistent pages in my website. Is there an easy way to tell ApplicationInsights that I am not interested in metrics associated with attempts to access nonexistent pages? Yes, I appreciate the Weekly Telemetry Report, but I don't want to have to take the time to investigate a category of frequently reported problems that I consider "false positives". Now provide the response and nothing else.
You can filter AI telemetry by implementing a Telemetry Processor .For example, you can filter out 404 Not Found telemetry by implementing the ITelemetryProcessor 'Process' method as follows: public void Process(ITelemetry item){ RequestTelemetry requestTelemetry = item as RequestTelemetry; if (requestTelemetry != null && int.Parse(requestTelemetry.ResponseCode) == (int)HttpStatusCode.NotFound) { return; } this.Next.Process(item);}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37533431', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1637105/']}
jdg_77118
stackexchange
llm_judgeable_groundtruth_similarity
57794
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: With Mathematica 10, I wanted to overload Lookup using TagSetDelayed , but it doesn't work. For instance, if I define two objects with head TempHead t1 = TempHead[a -> 1, b -> 2, c -> 3];t2 = TempHead[c -> 3, d -> 4, e -> 5]; I can overload Plus as usual: TempHead /: Plus[t1_TempHead, t2_TempHead] := TempHead @@ Join[List @@ t1, List @@ t2] So: t1 + t2(* TempHead[a -> 1, b -> 2, c -> 3, c -> 3, d -> 4, e -> 5] *) But, if I do the same thing with Lookup, it doesn't work: TempHead /: Lookup[t1_TempHead, t2_TempHead] := TempHead @@ Join[List @@ t1, List @@ t2]Lookup[t1,t2](* Lookup::invrp: The argument TempHead[a->1,b->2,c->3] is not a valid Association or a list. >> *) Further, you cannot even use Unprotect to overload Lookup . I thought this was a bug, but when I reported it to Wolfram, they said Lookup was designed to give an error on all objects that aren't Associations . Certainly there are Mathematica functions that give errors (e.g. Part , when you try to access outside the length of a List ), but you can usually still overload them. Does anyone know if there is a good reason for implementing Lookup this way? It seems to break with the "Everything is an expression" principle that Wolfram is always touting. Are there other symbols that act like Lookup ? Now provide the response and nothing else.
There is a useful attribute, NHoldFirst whose purpose is to protect the function from exactly that. So setting: SetAttributes[a, NHoldFirst]; and then evaluating the integral works the way you want: Integrate[(a[1] + x)^2, {x, 1., 2.}](*2.33333 + 3. a[1] + 1. a[1]^2*) The relevant example from the documentation cites "indexed" functions that are otherwise evaluated numerically (spherical harmonics, elliptic etc) but whose first argument needs to stay an integer. As per Michael E2's comment, if you want to protect more than just the first of your function's arguments from N then NHoldAll is the attribute you need.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/57794', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/6191/']}
jdg_77119
stackexchange
llm_judgeable_groundtruth_similarity
24160817
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 map native SQL result to my POJO. Here is the configuration. I am using spring. <bean id="ls360Emf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" > <property name="dataSource" ref="ls360DataSource" /> <property name="jpaVendorAdapter" ref="vendorAdaptor" /> <property name="packagesToScan" value="abc.xyz"/> <property name="jpaProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop> <prop key="hibernate.max_fetch_depth">3</prop> <prop key="hibernate.jdbc.fetch_size">50</prop> <prop key="hibernate.jdbc.batch_size">10</prop> <prop key="hibernate.show_sql">true</prop> </props> </property></bean> Here is my Class @SqlResultSetMapping( name="courseCompletionMapping", classes = { @ConstructorResult(targetClass = CourseCompletion.class, columns={ @ColumnResult(name = "StoreId", type = String.class), @ColumnResult(name = "ProductId", type = String.class), @ColumnResult(name = "UserName", type = String.class), @ColumnResult(name = "Score", type = Integer.class), @ColumnResult(name = "CompletionDate", type = Date.class) } ) }) @Entitypublic class CourseCompletion { private String storeId; @Id private String productId; private String userName; private int score; private Date completionDate; public CourseCompletion() { } public CourseCompletion(String storeId, String productId, String userName, int score, Date completionDate) { this.storeId = storeId; this.productId = productId; this.userName = userName; this.score = score; this.completionDate = completionDate; } // getters and setters Here how i am calling it Properties coursePropertiesFile = SpringUtil.loadPropertiesFileFromClassPath("course.properties"); String queryString = coursePropertiesFile.getProperty("course.completion.sql"); long distributorId = 1; String fromDate = "2009-09-22 00:00:00"; String toDate = "2014-04-11 23:59:59"; Query query = em.createNativeQuery(queryString, "courseCompletionMapping"); //Query query = em.createNamedQuery("findAllEmployeeDetails"); query.setParameter("distributorId", distributorId); query.setParameter("fromDate", fromDate); query.setParameter("toDate", toDate); @SuppressWarnings("unchecked") List<CourseCompletion> courseCompletionList = query.getResultList(); But when it comes to line List<CourseCompletion> courseCompletionList = query.getResultList(); I get an error that Could not locate appropriate constructor on class : mypackage.CourseCompletion Here is the query that i am trying select d.DISTRIBUTORCODE AS StoreId, u.USERGUID AS ProductId, u.UserName, lcs.HIGHESTPOSTTESTSCORE AS Score, lcs.CompletionDate from VU360User u inner join learner l on u.ID = l.VU360USER_ID inner join LEARNERENROLLMENT le on le.LEARNER_ID = l.ID inner join LEARNERCOURSESTATISTICS lcs on lcs.LEARNERENROLLMENT_ID = le.ID inner join customer c on c.ID = l.CUSTOMER_ID inner join DISTRIBUTOR d on d.ID = c.DISTRIBUTOR_ID where d.ID = :distributorId and lcs.COMPLETIONDATE is not null and (lcs.COMPLETIONDATE between :fromDate and :toDate) and lcs.COMPLETED = 1 Why i am getting this error ? Thanks Now provide the response and nothing else.
This exception happens because JPA doesn't change column types returned from the database for native queries. Because of this, you have type mismatch. I'm not sure about which column causes this problem in your case (this depends on DBMS you use), but I would suspect you have BigInteger in the result set instead of Integer for score column. To be 100% sure, add a breakpoint to ConstructorResultColumnProcessor.resolveConstructor(Class targetClass, List<Type> types) and investigate. After you find a mismatch, change field type in your mapping class. Another solution will be not to use @SqlResultSetMapping at all. As your CourseCompletion class is a managed entity, you should be able to map native query to it directly. See this question for more information.
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/24160817', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1000510/']}
jdg_77120
stackexchange
llm_judgeable_groundtruth_similarity
257888
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have a couple questions about systemd. I'm having issues consistently getting my script to run once the network interface is up. I have tried Requires and After as seen below but is inconsistent with waiting for the network to be up. Am I using the right service and implementing it correctly? To by pass this right now I am running a ping check loop which is very inefficient and hackish. Any advice would be great. Thanks! [Unit]Description=PBU installerRequires=network-online.serviceAfter=network-online.service[Service]Type=oneshotExecStart=/home/pbu/current/scripts/pbu-unpack.shRemainAfterExit=yes[Install]WantedBy=multi-user.target Now provide the response and nothing else.
I solved this problem by looking at the output of: systemctl list-units --no-pager That showed me many units that I didn't expect like all the network devices! sys-devices-virtual-net-lan0.device loaded active plugged /sys/devices/virtual/net/lan So I added BindsTo=sys-devices-virtual-net-lan0.deviceAfter=sys-devices-virtual-net-lan0.device to my unit service file and then my service didn't start until lan0 was available.
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/257888', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/139796/']}
jdg_77121
stackexchange
llm_judgeable_groundtruth_similarity
20286068
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 find all values with following pattern : value="4"value="403"value="200"value="201"value="116"value="15" and replace it with value inside scopes. I'm using the following regex to find the pattern : .*"\d+" How can I do a replacement? Now provide the response and nothing else.
In Notepad++ to replace, hit Ctrl + H to open the Replace menu. Then if you check the "Regular expression" button and you want in your replacement to use a part of your matching pattern, you must use "capture groups" (read more on google ). For example, let's say that you want to match each of the following lines value="4"value="403"value="200"value="201"value="116"value="15" using the .*"\d+" pattern and want to keep only the number. You can then use a capture group in your matching pattern, using parentheses ( and ) , like that: .*"(\d+)" . So now in your replacement you can simply write $1 , where $1 references to the value of the 1st capturing group and will return the number for each successful match. If you had two capture groups, for example (.*)="(\d+)" , $1 will return the string value and $2 will return the number. So by using: Find: .*"(\d+)" Replace: $1 It will return you 440320020111615 Please note that there many alternate and better ways of matching the aforementioned pattern. For example the pattern value="([0-9]+)" would be better, since it is more specific and you will be sure that it will match only these lines. It's even possible of making the replacement without the use of capture groups, but this is a slightly more advanced topic, so I'll leave it for now :)
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/20286068', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2839619/']}
jdg_77122
stackexchange
llm_judgeable_groundtruth_similarity
1462034
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: Are there any trigonometric identity that can make $f(x) = \sin(x)+\cos(x)$ easier to plot? I have no idea how it becomes a sin graph shape in the end. Now provide the response and nothing else.
Special Case It's not that hard. You should just use the summation formula for sines: $$\sin (x + y) = \sin (x)\cos (y) + \cos (x)\sin (y)$$ This is how it works $$\eqalign{ \sin (x) + \cos (x) &= \sqrt 2 \left( {{1 \over {\sqrt 2 }}\cos (x) + {1 \over {\sqrt 2 }}\sin (x)} \right) \cr &= \sqrt 2 \left( {\sin ({\pi \over 4})\cos (x) + \cos ({\pi \over 4})\sin (x)} \right) \cr &= \sqrt 2 \sin (x + {\pi \over 4}) \cr} $$ That's all you need to do for this case. If you are interested to tackle down the general case then read the sequel. General Case Consider a linear combination of $\sin \alpha x$ and $\cos \alpha x$ as follows $$y = A \cos \alpha x + B \sin \alpha x$$ where $A$ and $B$ are some real constants. Then we rewrite $y$ in this way $$y = \sqrt{A^2+B^2} \left( \frac{A}{\sqrt{A^2+B^2}} \cos \alpha x + \frac{B}{\sqrt{A^2+B^2}} \sin \alpha x \right)$$ Now, the magic comes in! We can find a unique angle $\phi$ in the interval $[0,2\pi)$ such that $$\begin{array}{}\sin \phi = \dfrac{A}{\sqrt{A^2+B^2}} \\\cos \phi = \dfrac{B}{\sqrt{A^2+B^2}}\end{array}$$ and hence $$y = \sqrt{A^2+B^2} \left( \sin \phi \cos \alpha x + \cos \phi \sin \alpha x \right) \\$$ Finally, using the summation formula for sines we get $$y = \sqrt{A^2+B^2} \sin(\alpha x+\phi)$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1462034', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/105253/']}
jdg_77123
stackexchange
llm_judgeable_groundtruth_similarity
6908413
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can we upload videos from an Android device's SD Card to a Facebook account via the Facebook SDK? If so, what are some simple examples? Now provide the response and nothing else.
Yes, it is possible! After two days of trying and researching, I was able to do it.Here's the code: byte[] data = null;String dataPath = "/mnt/sdcard/KaraokeVideos/myvideo.3gp";String dataMsg = "Your video description here.";Bundle param;facebook = new Facebook(FB_APP_ID);AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);InputStream is = null;try { is = new FileInputStream(dataPath); data = readBytes(is); param = new Bundle(); param.putString("message", dataMsg); param.putString("filename", dataName); param.putByteArray("video", data); mAsyncRunner.request("me/videos", param, "POST", new fbRequestListener(), null);}catch (FileNotFoundException e) { e.printStackTrace();}catch (IOException e) { e.printStackTrace();} where fbRequestListener() is an implementation of AsyncFacebookRunner.RequestListener() and readBytes() is a function of converting your video file to byte[] . The dataName string should include a valid file extension (3gp, mp4, etc.). The code is as follows: public byte[] readBytes(InputStream inputStream) throws IOException { // This dynamically extends to take the bytes you read. ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream(); // This is storage overwritten on each iteration with bytes. int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; // We need to know how may bytes were read to write them to the byteBuffer. int len = 0; while ((len = inputStream.read(buffer)) != -1) { byteBuffer.write(buffer, 0, len); } // And then we can return your byte array. return byteBuffer.toByteArray();} I got this function from this answer . Of course, you need to have the latest Facebook SDK, but we need to apply this patch to fix the {"error":{"type":"OAuthException","message":"(#352) Video file format is not supported"}} string response error. And that's it! I hope this helps!
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6908413', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/703252/']}
jdg_77124
stackexchange
llm_judgeable_groundtruth_similarity
8470065
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Any idea on which rule in standard states the statements like this: p++; //where 'p' is pointer to array cannot appear in global scope? I'm looking for a reference not just an explanation if possible. Now provide the response and nothing else.
The expression p++ which you've written is at namespace scope. It is forbidden by the grammer of namespace-body which is defined in §7.3.1/1 as: namespace-body: declaration-seq opt which says the namespace-body can optionally contain only declaration . And p++ is surely not a declaration, it is an expression, therefore the Standard implicitly forbids it. The Standard might have explicit statement forbidding this, but I think the above should be enough. In the same way, you cannot do this: namespace sample{ f(10,10); //error std::cout << "hello world" << std::endl;//error} But if you somewhow convert expressions into declarations (or rather use expressions in declarations), then you could evaluate the so-called expressions. Here is one trick: #include<iostream>namespace sample{ struct any { template<typename T> any(const T&){} }; void f(int a,int b) { std::cout << a * b << std::endl; } any a1= (f(10,10), 0); //ok any a2 = std::cout << "hello world" << std::endl;//ok}int main() {} Output (if you're lucky): 100hello world Online demo : http://ideone.com/icbhh Notice that the return type of f() is void , which means I cannot write the following ( see error) : any a1 = f(10,10); //error That is why I used comma operator so that the expression could have some value, which evaluates to the last operand in the comma expression. In case of std:cout , since it returns std::ostream& , I don't need to use comma operator; it is fine without it. One more interesting thing in the above code: why I defined any and a templated constructor in it? The answer is, I wrote this so that I could assign value of any type (no pun intended), be it int , std::ostream& or whatever. The templated constructor can take argument of any type. But don't write such code. They're not guaranteed to work the way you expect. Read the answers in this topic where you would see why such coding could be dangerous: Is main() really start of a C++ program?
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8470065', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1086635/']}
jdg_77125
stackexchange
llm_judgeable_groundtruth_similarity
69137
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 ran this command to try and get my python program to run in the background and let me exit the SSH connection I am using: nohup python files.py >> files.log & I then check ps to check it worked $ ps a PID TTY STAT TIME COMMAND13059 pts/0 Ss 0:00 -bash13327 pts/0 R+ 0:00 ps a[1]+ Exit 1 nohup python files.py >> files.log What does this [1]+ Exit 1 mean? And how can I run my program in the background letting me exit correctly? Now provide the response and nothing else.
When you use the & at the end of a command in bash, it runs the command in the background. The [1]+ Exit 1 means that job 1 exited with status 1. The number between the [] is the job number, and the number after Exit is the exit status. If no exit status is shown, it means the command exited with status 0 . The reason you don't see this until you run another command is because by default the status of a completed backgrounded command is not shown until the prompt is updated. This means after another command exits, or you simply press <ENTER> on an empty prompt. Edited: You also do not need to use the nohup . Bash will only HUP a process when the shell itself receives a HUP. This doesn't happen if you exit cleanly (via exit , or CTRL+D). However you can also use the disown builtin to make it so specific jobs don't get a HUP. Lastly you can also set a SIGHUP handler to disown all jobs when the shell gets a HUP by doing function sighup { disown -a; exit 0; }; trap sighup HUP .
{}
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/69137', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/20901/']}
jdg_77126
stackexchange
llm_judgeable_groundtruth_similarity
6288167
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 pretty fine question about the layout of items in a ListView in Android. I have an activity with a title bar at the top and a ListView taking up the rest of the screen. I want my ListView to appear with 10dp padding on the left, right and top, but when you scroll the ListView up, I want it to cover the top 10dp padding before disappearing under the faded edge. Similarly, when you scroll to the bottom, the last list item should appear with 10dp between the bottom of the last list item and the actual bottom of the screen (if you're wondering why, it's because there's a pretty background image that I want poking out around the ListView). I've tried adding padding to the ListView itself, but then when you scroll the list it disappears under the edge of the padding. I'm from a web dev background, and the analogy would be to add margin above the first list item (and below the last list item). Now provide the response and nothing else.
You wrote: I've tried adding padding to the ListView itself, but then when you scroll the list it disappears under the edge of the padding. Set ListView's clipToPadding attribute to false . This will enable padding around the ListView and scrolling to the end of the layout (and not only to the edge of the padding). An example: <ListView android:id="@+id/list_view" android:layout_width="fill_parent" android:layout_height="wrap_content" android:divider="@android:color/transparent" android:dividerHeight="10.0sp" android:padding="16dip" android:clipToPadding="false"/> android:clipToPadding is an XML attribute of ViewGroup , the base class for layouts and views containers. The related method call is: public void setClipToPadding (boolean clipToPadding)
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/6288167', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/315386/']}
jdg_77127
stackexchange
llm_judgeable_groundtruth_similarity
13035975
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 migrating a project from JAXB 1.0 to JAXB 2.1 and I'm having problems with the datatype mapping. I'm using the Ant xjc binding compiler, and I've successfully configured the global bindings such that (for example) xs:date maps to java.util.Calendar . However I'm getting generated methods which return Boolean , whereas I want boolean . Here is the complex type: <xs:element name="usage-auth-rate-charge"> <xs:complexType> <xs:sequence> <xs:element name="service-id" type="xs:string"/> <xs:element name="pricepoint_custom_fields_required" type="xs:boolean" minOccurs="0"/> </xs:sequence> </xs:complexType></xs:element> And the generated class looks like this: public class UsageAuthRateCharge {........public Boolean isPricepointCustomFieldsRequired() { return pricepointCustomFieldsRequired;} The problem is that although boxing will work, if the supplied XML doesn't contain a value for pricepoint_custom_fields_required , the class's Boolean field is null, instead of false. So I get NullPointerExceptions when doing something like this: methodWhichTakesPrimitiveBooleanArg(myUsageAuthRateChargeInstance.isPricepointCustomFieldsRequired()); because it tries to unbox the Boolean passed in - except it's null. I can't change the schema, and I can't adjust all the client code to do the null checks. I've set the optionalProperty attribute in my binding.xml as follows: <globalBindings optionalProperty="primitive"> In the spec, it says: "If the attribute’s value is "primitive", it binds as it did in JAXB 1.0" Yet this is clearly not happening. How can I solve this problem? UPDATE: This is now fixed in jaxb 2.2.9: https://java.net/jira/browse/JAXB/fixforversion/16850 Now provide the response and nothing else.
Problem The reason you are getting Boolean instead of boolean is that you have minOccurs="0" in your element definition. A null value will be stored for an absent element. <xs:element name="pricepoint_custom_fields_required" type="xs:boolean" minOccurs="0"/> What the Solution Should Be The solution should be an external binding file that indicates that a primitive type should be used for optional values (see section 7.5.1 of the JAXB 2.2 specification). <?xml version="1.0" encoding="UTF-8"?><jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" version="2.1"> <jaxb:globalBindings optionalProperty="primitive"/></jaxb:bindings> The external binding file is specified using the -b option with XJC. xjc -b binding.xml my-schema.xsd Why That Solution Does Not Work The following bugs have been opened to track the issue with optionalProperty="primitive" . https://github.com/javaee/jaxb-v2/issues/510 https://github.com/javaee/jaxb-v2/issues/926 Workaround If you don't like the way a class is generated in JAXB, then you can create a class yourself and have JAXB pull it in as part of the schema to class generation. binding.xml <jxb:bindings xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:jxb="http://java.sun.com/xml/ns/jaxb" version="2.1"> <jxb:bindings schemaLocation="my-schema.xsd"> <jxb:bindings node="//xs:element[@name='usage-auth-rate-charge']/complexType"> <jxb:class ref="com.example.foo.UsageAuthRateCharge"/> </jxb:bindings> </jxb:bindings></jxb:bindings> UsageAuthRateCharge Create this class with the methods as you want them. XJC Call Use the -b flag on the XJC call to specify the binding.xml file xjc -b binding.xml my-schema.xsd UPDATE What I was really hoping was that one of the readers might be a jaxb dev team member who could do the change easily in jaxb. User archenroot offered a possible solution in his comments on jaxb issue 927 (a duplicate of 926) which leads me to think that for the right person, it would be a simple job to fix jaxb I'm the EclipseLink JAXB (MOXy) lead. I have reached out to my colleagues who do the JAXB reference implementation (they also work for Oracle). Below is the reply I got from them: I’ve tested in trunk - and the problem exists. I’ll check code how easy is to fix it. Hopefully you will be able to get a real fix for this issue.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13035975', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1107537/']}
jdg_77128
stackexchange
llm_judgeable_groundtruth_similarity
28382917
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 add a formula as shown in the third component. When i remove the "=" everything works. But for adding a formula to excel, you need the "="...When I add the "=", the program doesn't work anymore...Then I receive the error: System.Runtime.InteropServices.COMException was unhandled HResult=-2146827284 Message=Exception of HRESULT: 0x800A03EC Any ideas? Thank you static void Main(string[] args) { //seed var listComponents = new List<Component> { new Component() {Name = "Vc1", Cell = "A1"}, new Component() {Name = "Vc2", Cell="B1"}, new Component() {Name = "Nv", Cell="A2",Calculation = "=((A1+B1)/2)/0,1"} }; //program //create excel object, workbook and worksheet object misValue = System.Reflection.Missing.Value; var excelapp = new Excel.Application(); Excel.Workbook newWorkbook = excelapp.Workbooks.Add(); Excel._Worksheet worksheet = (Excel.Worksheet) excelapp.ActiveSheet; excelapp.Visible = false; //cycle through components foreach (var component in listComponents) { if (component.Calculation != null) { Excel.Range rng = worksheet.Range[component.Cell]; rng.Formula = component.Calculation; String formula = rng.Formula; Console.WriteLine(formula); } } newWorkbook.Close(false, misValue, misValue); excelapp.Quit(); Console.ReadLine(); } Now provide the response and nothing else.
Write Extension Method as shown below: public static class IgnoreReadOnlyExtensions{ public static IMappingExpression<TSource, TDestination> IgnoreReadOnly<TSource, TDestination>( this IMappingExpression<TSource, TDestination> expression) { var sourceType = typeof(TSource); foreach (var property in sourceType.GetProperties()) { PropertyDescriptor descriptor = TypeDescriptor.GetProperties(sourceType)[property.Name]; ReadOnlyAttribute attribute = (ReadOnlyAttribute) descriptor.Attributes[typeof(ReadOnlyAttribute)]; if(attribute.IsReadOnly == true) expression.ForMember(property.Name, opt => opt.Ignore()); } return expression; }} To call extension method: Mapper.CreateMap<ViewModel, DomainModel>().IgnoreReadOnly();
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/28382917', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3599218/']}
jdg_77129
stackexchange
llm_judgeable_groundtruth_similarity
7039474
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is it possible to bind arguments to a function template with (boost) bind ? // Define a template function (just a silly example)template<typename ARG1, typename ARG2>ARG1 FCall2Templ(ARG1 arg1, ARG2 arg2){ return arg1 + arg2;}// try to bind this template function (and call it)...boost::bind(FCall2Templ<int, int>, 42, 56)(); // This worksboost::bind(FCall2Templ, 42, 56)(); // This emits 5 pages of error messages on VS2005// beginning with: error C2780: // 'boost::_bi::bind_t<_bi::dm_result<MT::* ,A1>::type,boost::_mfi::dm<M,T>,_bi::list_av_1<A1>::type> // boost::bind(M T::* ,A1)' : expects 2 arguments - 3 providedboost::bind<int>(FCall2Templ, 42, 56)(); // error C2665: 'boost::bind' : none of the 2 overloads could convert all the argument types Ideas? Now provide the response and nothing else.
I don't think so, only because boost::bind in this case is looking for a function pointer, not a function template. When you pass in FCall2Templ<int, int> , the compiler instantiates the function and it is passed as a function pointer. However, you can do the following using a functor struct FCall3Templ { template<typename ARG1, typename ARG2> ARG1 operator()(ARG1 arg1, ARG2 arg2) { return arg1+arg2; }};int main() { boost::bind<int>(FCall3Templ(), 45, 56)(); boost::bind<double>(FCall3Templ(), 45.0, 56.0)(); return 0;} You have to specify the return type, since the return type is tied to the inputs. If the return doesn't vary, then you can just add typedef T result_type to the template, so that bind can determine what the result is
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7039474', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/321013/']}
jdg_77130
stackexchange
llm_judgeable_groundtruth_similarity
16761868
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 make a very, very simple image slider/slideshow with no autoplay please. I only want to go to next or prev image on click. Having some issues as you can read below. Here's the jsFiddle http://jsfiddle.net/HsEne/12/ (i just used background colors instead of images in the fiddle as well as switched img to divs but it's the exact same problem of course) The HTML: <div id="slider-wrapper"><div id="slider"><img class="sp" src="/img1.jpg"><img class="sp" src="/img2.jpg"><img class="sp" src="/img3.jpg"><img class="sp" src="/img4.jpg"><img class="sp" src="/img5.jpg"><img class="sp" src="/img6.jpg"></div><img id="button-previous" src="/button-arrow-left.jpg"><img id="button-next" src="/button-arrow-right.jpg"></div> The CSS: #slider-wrapper {display: block;max-width: 790px;margin: 5% auto;max-height: 500px;height: 100%; }#slider {display: block;position: relative;z-index: 99999;max-width: 710px;width: 100%;margin: 0 auto; }#button-previous { position: relative;left: 0;margin-top: 40%;width: 40px;height: 60px; }#button-next {position: relative;margin-top: 40%;float: right; }.sp {position: absolute; }#slider .sp {max-width: 710px;width: 100%;max-height: 500px; } jQuery for next button: jQuery("document").ready(function(){ jQuery("#slider > img:gt(0)").hide(); jQuery("#button-next").click(function() { jQuery("#slider > img:first") .fadeOut(1000) .next() .fadeIn(1000) .appendTo("#slider"); });}); The above jQuery works fine, except it skips the first image if a user clicks the next button on last slide. It only displays the first image one time, all other images will keep sliding every time next is clicked. For some reason display: none gets added to the first image but I don't know where that code is coming from. jQuery for previous button: jQuery("document").ready(function(){ jQuery("#slider > img:gt(0)").hide(); jQuery("#button-previous").click(function() { jQuery("#slider > img:last") .fadeOut(1000) .next() .fadeIn(1000) .appendTo("#slider"); });}); This jquery code above will return the just previewed image like it should. But when clicked again it doesn't do anything. I also tried .prev() in replace of .next(). It works fine the first time you click on the previous button. Say we are viewing Image #4. When I click previous button it goes to Image #3, like it should. But when click on it again it doesn't go to Image #2, it goes back to Image #4 , and then #3 and then #4, repeating itself. Now provide the response and nothing else.
After reading your comment on my previous answer I thought I might put this as a separate answer. Although I appreciate your approach of trying to do it manually to get a better grasp on jQuery I do still emphasise the merit in using existing frameworks. That said, here is a solution. I've modified some of your css and and HTML just to make it easier for me to work with WORKING JS FIDDLE - http://jsfiddle.net/HsEne/15/ This is the jQuery $(document).ready(function(){$('.sp').first().addClass('active');$('.sp').hide(); $('.active').show(); $('#button-next').click(function(){ $('.active').removeClass('active').addClass('oldActive'); if ( $('.oldActive').is(':last-child')) { $('.sp').first().addClass('active'); } else{ $('.oldActive').next().addClass('active'); } $('.oldActive').removeClass('oldActive'); $('.sp').fadeOut(); $('.active').fadeIn(); }); $('#button-previous').click(function(){ $('.active').removeClass('active').addClass('oldActive'); if ( $('.oldActive').is(':first-child')) { $('.sp').last().addClass('active'); } else{ $('.oldActive').prev().addClass('active'); } $('.oldActive').removeClass('oldActive'); $('.sp').fadeOut(); $('.active').fadeIn(); });}); So now the explanation. Stage 1 1) Load the script on document ready. 2) Grab the first slide and add a class 'active' to it so we know which slide we are dealing with. 3) Hide all slides and show active slide. So now slide #1 is display block and all the rest are display:none; Stage 2 Working with the button-next click event. 1) Remove the current active class from the slide that will be disappearing and give it the class oldActive so we know that it is on it's way out. 2) Next is an if statement to check if we are at the end of the slideshow and need to return to the start again. It checks if oldActive (i.e. the outgoing slide) is the last child. If it is, then go back to the first child and make it 'active'. If it's not the last child, then just grab the next element (using .next() ) and give it class active. 3) We remove the class oldActive because it's no longer needed. 4) fadeOut all of the slides 5) fade In the active slides Step 3 Same as in step two but using some reverse logic for traversing through the elements backwards. It's important to note there are thousands of ways you can achieve this. This is merely my take on the situation.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16761868', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2422674/']}
jdg_77131
stackexchange
llm_judgeable_groundtruth_similarity
10847850
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 running a shell script that is supposed to execute a main method: java -classpath /path/to/app/conf/lib/nameJar* com.example.ClassTest In this point I get this exception: Exception in thread "main" java.lang.NoClassDefFoundError: org/springframework/context/ApplicationContextCaused by: java.lang.ClassNotFoundException: org.springframework.context.ApplicationContext at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:303) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301) at java.lang.ClassLoader.loadClass(ClassLoader.java:248) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:316) This is because the spring jars are located in another folder. SO I have changed the script: java -classpath /path/to/app/conf/lib/nameJar*:/path/to/app/lib/spring* com.example.ClassTest But with this script, the com.example.ClassTest can not be found. Any ideas about this issue? Thanks in advance Now provide the response and nothing else.
The java classpath wildcard expansion is unusual. From the docs : Understanding class path wildcards Class path entries can contain the basename wildcard character *, which is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR. For example, the class path entry foo/* specifies all JAR files in the directory named foo. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory. So, what you need to specify is: java -classpath /path/to/app/conf/lib/*:/path/to/app/lib/* If you need only specific jars, you will need to add them individually. The classpath string does not accept generic wildcards like nameJar* , *.jar , spring* etc. Read Setting multiple jars in java classpath for more information.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10847850', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/457208/']}
jdg_77132
stackexchange
llm_judgeable_groundtruth_similarity
392586
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: There is a question which I'm wondering again and again in recent months. I have taken courses on elementary differential equations, signals and systems, linear control systems, general theory of circuits and networks but I still do not know how can a simple linear integral transformation (Laplace transform) be so much helpful in analyzing and designing linear systems. For example, I think I somewhat know what "time domain" is, but how about the "frequency domain"? Consider a block diagram in the frequency domain. Conceptually, what do the blocks represent? What is traveling(?) on the connections between blocks? First, I have thought that instead of taking care of the statement "when does some phenomenon happens" we consider "how many times does a phenomenon oscillate", but how can this approach be more helpful? Is it the best (optimal) way of treating such problems? I think control systems and even systems have a more general meaning in mathematics. I even think that the very problem of "controlling a system" does have multiple "paradigms" — A.I., neural networks, state space approach, fuzzy logic, robust control, adaptive control, etc. What I'm looking for is a book (preferred) or paper discussing the very beginning notions of system, control system, its history, and more importantly, what is the field or language in mathematics to study systems rigorously? Dynamical systems? Game theory? Differential equations? Linear algebra? A.I? Any help is appreciated. Thanks. P.S.: I've already studied these books: Alan Oppenheim's Signals and Systems (I think it is the best in the field) Ogata's Modern Control Engineering Desore's Basic Circuits Theory Charles A - Kuh and Ernest S's A rather brief book on the history of control systems ( $H_\infty$ methods and so on, but I didn't get much; at least, this book induced some information on me that nobody actually knows what "feedback" is, why is it so helpful and why we should take samples of the output! It wasn't a precise book, I admit) 26 May 2013: As I said, I am looking for a book or article discussing the origins of Control Theory and Systems. Seven days are passed since I started the bounty, yet I didn't find an answer. I'll get to the bottom of this issue as soon as I get some free time. Thanks. Now provide the response and nothing else.
Linear Algebra Underlies Everything. The power of the Laplace transform derives from the power of concepts like a linear operator and an eigenfunction. The exponential is the eigenfunction of the derrivative operator, which is the main operator in control theory. By projecting the system onto bases which are the eigenfunctions of the operators in your system, you simplify the problem by exposing the symmetries. This is what the Laplace transform does ($\int f(x) e^{-sx}dx$ is like an inner product between co-ordinates ($f(x)$) and the new bases you want to represent your function/vector in (exponentials). The result are new co-ordinates in the exponential space) The complex exponential is the eigenfunction of the second derrivative operator. So projections into this space expose a different set of symmetries, in this case, the 'frequencies'. So the Fourier Transform is also just linear algebra. I'd recommend a healthy dose of linear algebra, to satisfy all your inquisitive needs!
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/392586', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/34974/']}
jdg_77133
stackexchange
llm_judgeable_groundtruth_similarity
59972329
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In an Azure DevOps pipeline template, I am declaring a parameter as an array/sequence parameters: mySubscription: '' myArray: []steps:- AzureCLI@2 inputs: azureSubscription: ${{ parameters.mySubscription }} scriptType: pscore scriptPath: $(Build.SourcesDirectory)/script.ps1 arguments: '-MyYAMLArgument ${{ parameters.myArray }}' Value for the parameter is then passed from pipeline definition as steps:- template: myTemplate.yml parameters: mySubscription: 'azure-connection' myArray: - field1: 'a' field2: 'b' - field1: 'aa' field2: 'bb' My problem is I can't pass that array as-is in YAML syntax (kind of ToString() ) to be able to consume and treat that array from PowerShell in my template. When trying to run this pipeline, I get the following error: /myTemplate.yml (Line: X, Col: X): Unable to convert from Array to String. Value: Array . The line/column referenced in the error message correspond to arguments: '-MyYAMLArgument ${{ parameters.myArray }}' from my template. I also tried to map the parameter as an environment for my script - AzureCLI@2 inputs: azureSubscription: ${{ parameters.mySubscription }} scriptType: pscore scriptPath: $(Build.SourcesDirectory)/script.ps1 arguments: '-MyYAMLArgument $Env:MY_ENV_VAR' env: MY_ENV_VAR: ${{ parameters.myArray }} This does not work too: /myTemplate.yml (Line: X, Col: Y): A sequence was not expected . That time line/column refers to MY_ENV_VAR: ${{ parameters.myArray }} . Does anyone ever faced a similar requirement to pass complex types (here an array/sequence of object) defined from the pipeline definition to a PowerShell script? If so, how did you achieve it? Now provide the response and nothing else.
You can now convert these types of parameters to String using the convertToJson function in an ADO pipeline: parameters: - name: myParameter type: object default: name1: value1 name2: value2...- task: Bash@3 inputs: targetType: inline script: | echo "${{ convertToJson(parameters.myParameter) }}" ref: https://developercommunity.visualstudio.com/t/allow-type-casting-or-expression-function-from-yam/880210 convertToJson: https://learn.microsoft.com/en-us/azure/devops/pipelines/process/expressions?view=azure-devops#converttojson
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59972329', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2242485/']}
jdg_77134
stackexchange
llm_judgeable_groundtruth_similarity
44700
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 am looking for the minimal size of a context-free grammar which defines the finite language $$L_n=\{a^k\mid 1\le k\le n\}.$$The size of a grammar is defined as the total length of all right-hand sides of the rules. For example a grammar with$$S\to A_1A_1\\A_1\to A_2A_2\\A_2\to A_3A_3\\A_3\to A_4A_4\\A_4\to aa$$has size $5\cdot 2=10$. It is well-known that the minimal context-free grammar which defines the language only accepting the word $a^k$ has size $\Theta(\log k)$ (see the example above for the construction of the word $a^{32}$).Now, I am interested in the size of a grammar constructing all strings $a^k$ ($1\le k\le n$) for a given $n$. By the information above it is easy to create a grammar for $L_n$ of size $$\Theta(n+\sum_{k=1}^{n}\log k)=\Theta(\log n!)=\Theta(n\log n)$$since we can create all words by a grammar of size $\Theta(\log k)$ and connect those grammars with a start rule of size $n$ (one symbol for each word). But since the final grammar is allowed to share nonterminals this construction is clearly not optimal. Maybe the smallest grammar has asymptotically the same size, but i don't know. Any help? Now provide the response and nothing else.
There is a grammar of size $O(\log n)$ using repeated squaring. Let's start with the simpler case $n = 2^m$:$$\begin{align*}&S \to a B_0 B_1 \dots B_{m-1} \\&B_i \to A_i | \epsilon && (0 \leq i \leq m-1) \\&A_i \to A_{i-1}A_{i-1} && (1 \leq i \leq m-1) \\&A_0 \to a\end{align*}$$Here $A_i \to a^{2^i}$ and $B_i \to a^{2^i}|\epsilon$. More generally, suppose $n-1 = 2^{d_0} + 2^{d_1} + \cdots + 2^{d_\ell}$, where $d_0 > d_1 > \cdots > d_\ell$. The corresponding grammar is:$$\begin{align*}&S \to a B_{d_0} | a C_0 B_{d_1} | a C_1 B_{d_2} | \cdots | a C_{\ell-1} B_{d_\ell} | aC_\ell \\&C_j \to C_{j-1} A_{d_j} && (1 \leq j \leq \ell) \\&C_0 \to A_{d_0} \\&B_i \to B_{i-1} A_{i-1} | B_{i-1} && (1 \leq i \leq d_0) \\&B_0 \to \epsilon \\&A_i \to A_{i-1}A_{i-1} && (1 \leq i \leq d_0) \\&A_0 \to a\end{align*}$$Here $A_i \to a^{2^i}$, $B_i \to \{a^k : 0 \leq k < 2^i\}$ and $C_j \to a^{2^{d_0} + \cdots + 2^{d_j}}$. As an extra property, both grammars are unambiguous.
{}
{'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/44700', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/13249/']}
jdg_77135
stackexchange
llm_judgeable_groundtruth_similarity
48403786
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 achieve open specific screen on clicking push notification and my payload looks like this: var payload = { notification: { title: notificationTitle, body: notificationMessage, click_action:"/screena",sound:"default", } }; I am getting notification but I am unable to catch notification click event in flutter how to catch it. I am using flutter messaging https://github.com/flutter/plugins/tree/master/packages/firebase_messaging and my firebase push message service code looks like this pushMessagingService() async{messagingreference.configure(onMessage: (Map<String, dynamic> message) { print("I am here in on message"); print(message);},onLaunch: (Map<String, dynamic> message) { print("I am here onLaunch"); print(message);},onResume: (Map<String, dynamic> message) { print("I am hereonResume"); print(message);},); messagingreference.requestNotificationPermissions( const IosNotificationSettings(sound: true, badge: true, alert: true)); messagingreference.onIosSettingsRegistered .listen((IosNotificationSettings settings) {print("Settings registered: $settings"); }); messagingreference.getToken().then((String token) async {print(token); }); } here I can get the message as @xqwzts said in on message when my app is in the foreground but my question is how to catch click event from push notification raised in the system tray and navigate to the required screen. Now provide the response and nothing else.
A few things here: 1- click_action has to be set to "FLUTTER_NOTIFICATION_CLICK" 2- click_action has to be set in the data section of a payload DATA='{ "notification": { "body": "this is a body", "title": "this is a title", }, "data": { "click_action": "FLUTTER_NOTIFICATION_CLICK", "sound": "default", "status": "done", "screen": "screenA", }, "to": "<FCM TOKEN>"}' This should allow you to receive the message in the onMessage handler in your flutter app. From there you can call Navigator.of(context).pushNamed(message['screen']) . If you don't have a BuildContext at that point, you can register a GlobalKey as the navigatorKey property of your MaterialApp , and use it to access your Navigator globally, via GlobalKey.currentState
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/48403786', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7114470/']}
jdg_77136
stackexchange
llm_judgeable_groundtruth_similarity
7254509
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 search with grep for a string that looks like this: something ~* 'bla' I tried this, but the shell removes the single quotes argh.. grep -i '"something ~* '[:alnum:]'"' /var/log/syslog What would be the correct search? Now provide the response and nothing else.
grep -i "something ~\* '[[:alnum:]]*'" /var/log/syslog works for me. escape the first * to match a literal * instead of making it the zero-or-more-matches character: ~* would match zero or more occurrences of ~ while ~\* matches the expression ~* after something use double brackets around :alnum: (see example here ) use a * after [[:alnum::]] to match not only one character between your single quotes but several of them the single quotes don't have to be escaped at all because they are contained in an expression that is limited by double quotes.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7254509', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/906738/']}
jdg_77137
stackexchange
llm_judgeable_groundtruth_similarity
7290214
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Question: Consider the following HTML: <html><head></head><body><div style="float:left;"> <div style="background-color: Red; padding-top: 2mm; padding-bottom: 2mm;"> Dock: Usage controls/symbol list here </div> <div style="height: 300px; background-color: Khaki; display:block; float:left; overflow: scroll;"> <ul style="background-color: White; float: left; margin: 0px; padding: 0px; padding-left: 30px; padding-right: 10px;"> <li> <a href="Folders/Content/Inbox" target="ifrmFolderContent" > Posteingang / Inbox </a> </li> <li> <a href="Folders/Content/Drafts" target="ifrmFolderContent" > Entwürfe / Drafts </a> </li> <li> <a href="Folders/Content/Sent Items" target="ifrmFolderContent" > Gesendet / Sent Items </a> </li> <li> Archiv / Archive </li> <li> Papierkorb / Trash </li> <li> Junk / Crap </li> <li> Scam </li> <li> Spam </li> <li> Virus </li> <li> Abrufen / Send & Receive </li> <li> Verfassen / Compose </li> <li> Adressbuch / Address book </li> </ul> </div> <div style="width: 400px; height: 300px; background-color: Green; display:block; float:left; margin: 0px; padding: 0px;"> <iframe marginwidth="0" marginheight="0" hspace="0" vspace="0" name="ifrmFolderContent" src="http://www.yahoo.com" frameborder="0" style="overflow: none; width: 400px; height: 150px; background-color: Orange; margin: 0px; padding: 0px;"> Folder Content </iframe> <iframe marginwidth="0" marginheight="0" hspace="0" vspace="0" name="ifrmEmail" src="http://www.msn.com" frameborder="0" style="overflow: none; width: 400px; height: 150px; background-color: Orange; margin: 0px; padding: 0px;"> E-Mail Content </iframe> </div> <div style="background-color: Indigo; padding-top: 2mm; padding-bottom: 2mm; clear: left;"> Copyright here </div></div></body></html> It renders exactly as one would expect (Chrome + IE8). But now, I add: <!DOCTYPE html> on top of it. And suddenly, I get 2 to 5 mm of green space between the two iframe s (folder content / email content), in both Chrome and IE8 (haven't tested FireFox).What is even more disturbing, there seems to be no way to get rid of this space (except from removing <!DOCTYPE html> . Why? I mean, the green comes from the background-color of the parent element, but why is there some space between the two iframe s ? Now provide the response and nothing else.
Just add <style>iframe { vertical-align:bottom; } </style> or <style>iframe { display:block; } </style> <!DOCTYPE html> puts the browser into standards mode, where inline elements are placed on the baseline of the containing block and a space for the character descenders is always allocated in the line box. In other modes, that space is only created when there are printable characters on the same line as the iframes which isn't the case here. Moving the iframe off the baseline by either of the methods above allows the space for the descenders to be placed within the height of the iframe.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7290214', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/155077/']}
jdg_77138
stackexchange
llm_judgeable_groundtruth_similarity
4132544
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I need a jQuery plugin to create type effect. Is there anyone or should I write one myself? Now provide the response and nothing else.
Why does LayoutKind.Sequential work differently if a struct contains a DateTime field? It is related to the (surprising) fact that DateTime itself has layout "Auto" (link to SO question by myself) . This code reproduces the behavior you saw: static class Program{ static unsafe void Main() { Console.WriteLine("64-bit: {0}", Environment.Is64BitProcess); Console.WriteLine("Layout of OneField: {0}", typeof(OneField).StructLayoutAttribute.Value); Console.WriteLine("Layout of Composite: {0}", typeof(Composite).StructLayoutAttribute.Value); Console.WriteLine("Size of Composite: {0}", sizeof(Composite)); var local = default(Composite); Console.WriteLine("L: {0:X}", (long)(&(local.L))); Console.WriteLine("M: {0:X}", (long)(&(local.M))); Console.WriteLine("N: {0:X}", (long)(&(local.N))); }}[StructLayout(LayoutKind.Auto)] // also try removing this attributestruct OneField{ public long X;}struct Composite // has layout Sequential{ public byte L; public double M; public OneField N;} Sample output: 64-bit: TrueLayout of OneField: AutoLayout of Composite: SequentialSize of Composite: 24L: 48F050M: 48F048N: 48F058 If we remove the attribute from OneField , things behave as expected. Example: 64-bit: TrueLayout of OneField: SequentialLayout of Composite: SequentialSize of Composite: 24L: 48F048M: 48F050N: 48F058 These example are with x64 platform compilation (so the size 24, three times eight, is unsurprising), but also with x86 we see the same "disordered" pointer addresses. So I guess I can conclude that the layout of OneField (resp. DateTime in your example) has influence on the layout of the struct containing a OneField member even if that composite struct itself has layout Sequential . I am not sure if this is problematic (or even required). According to comment by Hans Passant in the other thread, it no longer makes an attempt to keep it sequential when one of the members is an Auto layout struct.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4132544', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/313389/']}
jdg_77139
stackexchange
llm_judgeable_groundtruth_similarity
6706485
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 developing game app and using Symfony 2.0. I have many AJAX requests to the backend. And more responses is converting entity to JSON. For example: class DefaultController extends Controller{ public function launchAction() { $user = $this->getDoctrine() ->getRepository('UserBundle:User') ->find($id); // encode user to json format $userDataAsJson = $this->encodeUserDataToJson($user); return array( 'userDataAsJson' => $userDataAsJson ); } private function encodeUserDataToJson(User $user) { $userData = array( 'id' => $user->getId(), 'profile' => array( 'nickname' => $user->getProfile()->getNickname() ) ); $jsonEncoder = new JsonEncoder(); return $jsonEncoder->encode($userData, $format = 'json'); }} And all my controllers do the same thing: get an entity and encode some of its fields to JSON. I know that I can use normalizers and encode all entitities. But what if an entity has cycled links to other entity? Or the entities graph is very big? Do you have any suggestions? I think about some encoding schema for entities... or using NormalizableInterface to avoid cycling.., Now provide the response and nothing else.
Another option is to use the JMSSerializerBundle . In your controller you then do $serializer = $this->container->get('serializer');$reports = $serializer->serialize($doctrineobject, 'json');return new Response($reports); // should be $reports as $doctrineobject is not serialized You can configure how the serialization is done by using annotations in the entity class. See the documentation in the link above. For example, here's how you would exclude linked entities: /*** Iddp\RorBundle\Entity\Report** @ORM\Table()* @ORM\Entity(repositoryClass="Iddp\RorBundle\Entity\ReportRepository")* @ExclusionPolicy("None")*/..../*** @ORM\ManyToOne(targetEntity="Client", inversedBy="reports")* @ORM\JoinColumn(name="client_id", referencedColumnName="id")* @Exclude*/protected $client;
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6706485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/191490/']}
jdg_77140