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
41595
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: So I used to be able to SSH to Raspbian but now I can't even though we are on the same network. Any idea why is that? Monas-MacBook-Pro:~ mona$ ssh pi@192.168.1.105ssh: connect to host 192.168.1.105 port 22: Operation timed out P.S.: I should be able to SSH to Raspbian shell using any network, right? Here's the ping result as requested in the comments: Monas-MacBook-Pro:~ mona$ ping 192.168.1.105PING 192.168.1.105 (192.168.1.105): 56 data bytesRequest timeout for icmp_seq 0Request timeout for icmp_seq 1Request timeout for icmp_seq 2Request timeout for icmp_seq 3ping: sendto: No route to hostRequest timeout for icmp_seq 4ping: sendto: Host is downRequest timeout for icmp_seq 5ping: sendto: Host is downRequest timeout for icmp_seq 6ping: sendto: Host is downRequest timeout for icmp_seq 7ping: sendto: Host is downRequest timeout for icmp_seq 8ping: sendto: Host is downRequest timeout for icmp_seq 9ping: sendto: Host is downRequest timeout for icmp_seq 10ping: sendto: Host is downRequest timeout for icmp_seq 11 Right now both Pi and my laptop are on the WiFi. Now provide the response and nothing else.
You may want to try these instructions: The local IP address of your Raspberry Pi is not fixed, unless you are using a wireless adapter to connect, which will keep its IP address. You must be on the same Wi-Fi network for this to work. If you want to use SSH for the RPI, you can use these steps: This is for remote desktop connection: Start up your Pi to the terminal prompt. Type the following command "sudo apt-get install xrdp" If promoted enter your password (the default is "raspberry") Type "Y" and press enter. This is now installing xrdp onto your Pi which is the software we are going to use for the remote desktop connection. Wait for it to complete. Restart your Pi. We are going to check that xrdp is going to start up automatically. When your Pi has booted to the command prompt look for [ ok ] Starting Remote Desktop Protocol server : xrdp sesman. This shows you that xrdp is installed and automatically starting up on start up of your Pi The last step is to make a note of the IP address of your Pi which should also be displayed on the start up screen. In my case below it is 192.168.1.9. This is the address of your Pi on your network and what we will use to connect to your Pi from the second machine. Second Machine Setup Launch Remote Desktop Connection which can be found at Start->All Programs->Accessories->Remote Desktop Connection Type in the IP Address for your Pi which you noted above. Click Connect (you may get a security warning at this stage just click OK if you do. After all it is your Pi on your network so nothing to worry about security wise). Leave the Module on the default of sesman-Xvnc and enter your username and password for your Pi. (The default is pi and raspberry if you haven't changed them). Click OK and after a few moments you should be greeted my your Raspberry Pi's desktop! When you are finished simply log-out from the Pi's desktop. I found these step from here and they worked for me Here is another way to use SSH: SSH into Raspberry Pi I generally log into my Raspberry Pi via SSH, or Secure Shell to give it its full name. This allows command line access, to your Raspberry Pi, from another computer. Although it is possible to SSH into the Raspberry Pi from anywhere in the world, and I do, this post only covers SSH access over the local network. I will cover remote connection in a future blog post. Although this does not give access to a GUI (Graphical User Interface), having access to the command line generally allows me to do 95% of what I need to do. The other 5% I could probably do through SSH, but sometimes you can't beat the comfort of a GUI. :-) First of all you need to know the IP address of the Raspberry Pi you are wanting to log into. If you are unsure how to find this, then read my blog post explaining how you can do this remotely using an excellent tool called nmap. To SSH into your Raspberry Pi from a Linux or Apple Mac computer this is very easy. You can just type your username and IP address into the command line using the following format: ssh username@IPaddress Ensure you substitute username with the username you are wanting to log into the remote computer with. The IP address should take the format 192.168.1.66 You may get a message explaining that the authenticity of the host cannot be established, and if you are sure you want to continue connecting. You will only see this message the first time you SSH into your Raspberry Pi. Simply type yes. You will then be asked for your password, enter the password for the username you are trying to connect with. For windows this is a little more tricky to set up as it requires an additional piece of software called PuTTY. However once installed this is really simple to use. First go to the PuTTY website, www.putty.org, download and install the software. Once installed load PuTTY Under Host Name (or IP address) type in the IP address you would like to connect to. Select the SSH radio button. In the box under Saved Sessions type in a name to identify this computer, such as Raspberry Pi, and then click Save. Clicking on Open should now start your SSH session. Next time you want to SSH into your Raspberry Pi you just need to load PuTTY, click on the saved session to highlight it and then click Open. Once you have typed in your password, when asked, you have remote access to your Raspberry Pi. I found these instructions from here The original link is here: https://raspberrypi.stackexchange.com/a/34870/32923
{}
{'log_upvote_score': 4, 'links': ['https://raspberrypi.stackexchange.com/questions/41595', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/40226/']}
jdg_370041
stackexchange
llm_judgeable_groundtruth_similarity
114779
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: I'm in need of a condition that is analogous to the "finality" condition in the following lemma: Lemma: A functor $F\colon A\to B$ is final if and only if for any functor $x\colon B\to Set$, the natural map $colim (xF)\to colim(x)$ is an isomorphism. This lemma could be taken instead as a definition of final functor , but finality is more easily recognized by whether all slice categories of a certain kind are non-empty and connected. I want a recognition principle for a more general kind of finality, which I'm calling local finality. The more general context requires a bit of notation. If $A$ is a category, write $A-Set$ for the category of functors $A\to Set$. If $F\colon A\to B$ is a functor, write $\Delta_F\colon B-Set\to A-Set$ for the ``composition with $F$" functor, and write $\Sigma_F$ for its left adjoint and $\Pi_F$ for its right adjoint (these three are also sometimes denoted by $F^*, F_!$, and $F_*$ respectively). The following lemma (obviously) holds for some appropriate definition of locally final . Lemma: Suppose that we have a commutative diagram $A\xrightarrow{F}B\xrightarrow{x}C$ and let $G:=xF$. Then $F$ is locally final if and only if the natural map $\Sigma_G\Delta_F\to\Sigma_x$ is an isomorphism. Is there a nice recognition principle for this kind of ``local finality"? I have a big messy condition obtained by following my nose, but it's of no use. Any help would be greatly appreciated. Thanks! Now provide the response and nothing else.
Since nobody has said so, I will mention that the notion you describe is a particular case of the known --- but perhaps obscure --- concept of Guitart exact square. One can read about it in the nlab page and in an article by Maltsiniotis . Even though the latter article aims to generalize exact squares to a homotopical context, it still gives a good, if somewhat skewed, overview of the concept. To justify the relative usefulness of exact squares, let me state that instances of that notion characterize: fully faithful functors, (co)final functors, initial functors, absolute Kan extensions, among other concepts (including my personal favourite, absolutely dense functors ). For completeness, I will summarize some characterizations of the notion of exact square. A square of small categories, functors, and natural transformations:$$ \begin{matrix} A & \overset{U}{\longrightarrow} & B \\\llap{\scriptstyle L}\Big\downarrow & \big\Downarrow\rlap{\scriptstyle\alpha} & \Big\downarrow\rlap{\scriptstyle R} \\A' & \underset{D}{\longrightarrow} & B'\end{matrix} $$(i.e. a natural transformation $\alpha:R\circ U\to D\circ L$) is called exact if any of the following equivalent conditions hold: The natural 2-cell induced by $\alpha$ in$$ \begin{matrix} \textrm{Set}^A & \overset{\Delta_U}{\longleftarrow} & \textrm{Set}^B \\\llap{\scriptstyle \Sigma_L}\Big\downarrow & \big\Downarrow & \Big\downarrow\rlap{\scriptstyle \Sigma_R} \\\textrm{Set}^{\smash{A'}} & \underset{\Delta_D}{\longleftarrow} & \textrm{Set}^{\smash{B'}}\end{matrix} $$is an isomorphism. That is, the induced natural transformation $\Sigma_L\circ\Delta_U \to \Delta_D\circ\Sigma_R$ is an isomorphism. For every $x\in A'$, the naturally induced functor on over-categories$$ A/x=L/x \longrightarrow R/(D(x))=B/(D(x)) $$is (co)final. For every $x\in B$, the naturally induced functor on under-categories$$ x/A=x/U \longrightarrow (R(x))/D=(R(x))/A' $$is initial. For each object $x\in B$ and $y\in A'$, and each arrow $f:R(x) \to D(y)$ in $B'$, the category of factorizations $C_{x,y,f}$ is connected (which I, Karol, and a surprisingly large/vocal set of mathematicians take to mean non-empty). Here, the category $C_{x,y,f}$ is defined by: the objects of $C_{x,y,f}$ are triples $(z,g,h)$ where $z$ is an object of $A$, $g:x\to U(z)$ is a morphism in $B$, and $h:L(z)\to y$ is a morphism of $A'$, such that $D(h)\circ\alpha_z \circ R(g)=f$; a morphism $(z,g,h)\to (z',g',h')$ in $C_{x,y,f}$ is an arrow $k:z\to z'$ such that $g'= U(k)\circ g$ and $h=h'\circ L(k)$. For all objects $x\in B$ and $y\in A'$, the natural map from the coend$$ \int^{a\in A} B(x,U(a))\times A'(L(a),y) \longrightarrow B'(R(x),D(y)) $$ is an isomorphism of sets. Before proceeding, observe that condition 4 is simply a restatement of conditions 2 and 3. In fact, the categories of factorizations $C_{x,y,f}$ defined in 4 are exactly the categories whose connectedness must be checked to ensure that the functor in condition 2 is cofinal (respectively, that the functor in condition 3 is initial). More precisely, the categories $C_{x,y,f}$ are the under-categories $a/F$ of the functor $F$ in condition 2 (respectively, the over-categories of the functor in condition 3) for objects $a$ in the codomain of $F$. I feel this both motivates and gives a nice way to remember the definition of $C_{x,y,f}$. Then $A\overset{F}{\rightarrow}B\overset{x}{\rightarrow}C$ is locally final (in the sense David Spivak states) if and only if the the square$$ \begin{matrix} A & \overset{F}{\longrightarrow} & B \\\llap{\scriptstyle G}\Big\downarrow & \big\Downarrow\rlap{\scriptstyle\textrm{id}_G}\ & \Big\downarrow\rlap{\scriptstyle x} \\C & \underset{\textrm{id}_C}{\longrightarrow} & C\end{matrix} $$(filled by the the identity 2-cell on $G=x\circ F$) is exact. Under this interpretation, condition 4 above is exactly the condition given in Karol Szumiło's answer. Addendum: To finish off, here are a few further equivalent characterizations of the exactness of the original square ($\alpha:R\circ U\to D\circ L$) drawn at the top of this answer: For any cocomplete category X, the natural 2-cell induced by $\alpha$ in$$ \begin{matrix} X^A & \overset{\Delta_U}{\longleftarrow} & X^B \\\llap{\scriptstyle \Sigma_L}\Big\downarrow & \big\Downarrow & \Big\downarrow\rlap{\scriptstyle \Sigma_R} \\X^{\smash{A'}} & \underset{\Delta_D}{\longleftarrow} & X^{\smash{B'}}\end{matrix} $$is an isomorphism. Note that for $X=\textrm{Set}$, we recover condition 1 above. The natural 2-cell induced by $\alpha$ in$$ \begin{matrix} \textrm{Set}^A & \overset{\Pi_U}{\longrightarrow} & \textrm{Set}^B \\\llap{\scriptstyle \Delta_L}\Big\uparrow & \big\Uparrow & \Big\uparrow\rlap{\scriptstyle \Delta_R} \\\textrm{Set}^{\smash{A'}} & \underset{\Pi_D}{\longrightarrow} & \textrm{Set}^{\smash{B'}}\end{matrix} $$is an isomorphism. For any complete category X, the natural 2-cell induced by $\alpha$ in$$ \begin{matrix} X^A & \overset{\Pi_U}{\longrightarrow} & X^B \\\llap{\scriptstyle \Delta_L}\Big\uparrow & \big\Uparrow & \Big\uparrow\rlap{\scriptstyle \Delta_R} \\X^{\smash{A'}} & \underset{\Pi_D}{\longrightarrow} & X^{\smash{B'}}\end{matrix} $$is an isomorphism. Note that for $X=\textrm{Set}$, we recover the preceding condition. The opposite square$$ \begin{matrix} A^{\textrm{op}} & \overset{L^{\textrm{op}}}{\longrightarrow} & {A'}^{\textrm{op}} \\\llap{\scriptstyle U^{\textrm{op}}}\Big\downarrow & \big\Downarrow\rlap{\scriptstyle\alpha^{\textrm{op}}} & \Big\downarrow\rlap{\scriptstyle D^{\textrm{op}}} \\B^{\smash{\textrm{op}}} & \underset{R^{\textrm{op}}}{\longrightarrow} & {B'}^{\smash{\textrm{op}}}\end{matrix} $$is exact. Note that the preceding 3 conditions and condition 1 applied to this opposite square give diagrams with categories of presheaves (contravariant functors) on $A$, $B$, $A'$, and $B'$, instead of categories of covariant functors on those categories. In fact, a common (equivalent) definition of exactness is the analog of condition 1 for presheaves: the 2-cell in the square$$ \begin{matrix} \widehat{A} & \overset{\Sigma_{U^{\textrm{op}}}}{\longrightarrow} & \widehat{B} \\\llap{\scriptstyle \Delta_{L^{\textrm{op}}}}\Big\uparrow & \big\Downarrow\rlap{\scriptstyle} & \Big\uparrow\rlap{\scriptstyle \Delta_{R^{\textrm{op}}}} \\\widehat{A'} & \underset{\Sigma_{D^{\textrm{op}}}}{\longrightarrow} & \widehat{B'}\end{matrix} $$is an isomorphism.
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/114779', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2811/']}
jdg_370042
stackexchange
llm_judgeable_groundtruth_similarity
56356142
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So this a question about the same big project my others are. I am now just tidying up some formatting and essentially want a sub (that I can call from another) which will automatically add the borders I need around the new data being posted to the sheet. I recorded the macro of adding the borders (and changed the range to one that is variable - RowToPasteTo) and all was working well. I tried to call it from another piece of code and it went haywire, now giving me an error of: Run-Time error '1004': Unable to set the LineStyle Property of the Borders class As the error mentions, it seems to be an error with the .LineStyle but I am using the same style as what their recorder gave me. How can I get this working again so that is completes all borders? EDIT: Forgot to add the code - sorry! Sub Borders()Dim RowToPasteTo As LongWith Sheets(4) RowToPasteTo = .Cells(.Rows.Count, "B").End(xlUp).Row + 1 Range("B" & RowToPasteTo & ":" & "Z" & RowToPasteTo).Select With Selection.Borders .LineStyle = xlContinuous .ThemeColor = 3 .TintAndShade = -9.99786370433668E-02 .Weight = xlThin End WithEnd WithEnd Sub EDIT 2: This piece of code is to insert the borders when each new row of data is moved to this sheet (grid marks are off, as the borders are only to be shown on the lines with data. I have tried all amendments so far suggested and am still receiving errors when running the above code alone. I have now also created a blank sheet (and adjusted the sheets number accordingly) and I receive a different error there. The (minimised) code that will later call this piece if as follows: Sub ToTank()Dim RowToPasteTo As Long RowToPasteTo = .Cells(.Rows.Count, "B").End(xlUp).Row + 1 Sheets(4).Unprotect .Range("A" & RowToPasteTo & ":" & "Z" & RowToPasteTo).Locked = FalseCall Borders()End Sub Now provide the response and nothing else.
By default, importing an HTML file with react will not work. Given your use case and the route which you want to go, the best bet will be to convert the HTML page to a js file and then export for example: html.js file module.exports = `<!DOCTYPE html><html> <head> <title>Ably WebRTC Video call Demo</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" /> </head> <body> <script src="https://cdn.temasys.io/adapterjs/0.15.x/adapter.min.js"></script> <script src="https://cdn.temasys.io/adapterjs/0.15.x/adapter.screenshare.js"></script> <script src="https://cdn.ably.io/lib/ably.min-1.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/simple-peer/9.1.2/simplepeer.min.js"></script> <script src="ably-screenshare.js"></script> <script src="connection-helper.js"></script> <div class="container-fluid" style="margin-top: 5em;"> <div class="container" id="join"> <h4 id="online">Users online (0)</h4> <ul id="memberList"></ul> </div> <div class="container" id="call" style="display:none;"> <video width="320" height="240" id="local" controls></video> <video width="320" height="240" id="remote" controls></video> <button class="btn btn-xs btn-danger" onclick="handleEndCall()"> End call </button> </div> </div> </body> <style> small { border-bottom: 2px solid black; } li { list-style: none; } </style></html>`; Here, note the module.exports, as well as the template string used, so you can call it in your react page this way: import React, { Component } from "react";var __html = require('./index.html.js');var template = { __html: __html };class ScreenShare extends Component { render() { return ( <div className="screen-share"> <span dangerouslySetInnerHTML={template} /> </div> ); }}export default ScreenShare;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56356142', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10218602/']}
jdg_370043
stackexchange
llm_judgeable_groundtruth_similarity
33276
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Electrons annihilate with positrons produced through fusion processes in stars. Which particle interaction produces new electrons so that the sun isn't deplete of electrons? Or is something else happening altogether? Regular fusion cycles in stars produce neutrinos and positrons as by products. Those positrons annihilate with electrons that are already there in the plasma of the star to produce the light that we eventually see. How are those electrons replaced? Now provide the response and nothing else.
The proton-proton chain ultimately converts four protons into one helium nucleus. The charge of the 4 protons was balanced by 4 electrons, but helium contains 2 protons (and 2 neutrons), so it only needs 2 electrons to be balanced. As you point out, the process of converting a proton to a neutron releases a positron (and an electron neutrino), and that positron quickly annihilates with an electron. Here's the diagram from that Wikipedia page of the main p-p chain. So the process actually consumes 6 protons, and emits 2 protons, a helium nucleus, and 2 positrons (plus a couple of neutrinos), and a couple of gamma photons. The positrons annihilate with 2 electrons, releasing more gamma photons (usually 2 or 3 apiece, depending on the spin alignments of the positron & electron). If you add everything up, you'll see that the electromagnetic charge balance is unchanged. We started with 4 protons, which are balanced by 4 electrons nearby in the stellar core plasma. (We can ignore the intermediate pair of hydrogens that are eventually re-emitted). We end up with a helium nucleus that only needs 2 electrons to be electrically balanced, so if those other 2 electrons weren't annihilated then the star would build up an excess of negative charge.
{}
{'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/33276', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/29272/']}
jdg_370044
stackexchange
llm_judgeable_groundtruth_similarity
288739
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 generate random numbers within a specified interval, [max;min]. Also, the random numbers should be uniformly distributed over the interval, not located to a particular point. Currenly I am generating as: for(int i=0; i<6; i++){ DWORD random = rand()%(max-min+1) + min;} From my tests, random numbers are generated around one point only. Examplemin = 3604607;max = 7654607; Random numbers generated: 363159436092933630000362844136363763621404 From answers below: OK, RAND_MAX is 32767. I am on C++ Windows platform. Is there any other method to generate random numbers with a uniform distribution? Now provide the response and nothing else.
Why rand is a bad idea Most of the answers you got here make use of the rand function and the modulus operator. That method may not generate numbers uniformly (it depends on the range and the value of RAND_MAX ), and is therefore discouraged. C++11 and generation over a range With C++11 multiple other options have risen. One of which fits your requirements, for generating a random number in a range, pretty nicely: std::uniform_int_distribution . Here's an example: #include <iostream>#include <random>int main(){ const int range_from = 0; const int range_to = 1000; std::random_device rand_dev; std::mt19937 generator(rand_dev()); std::uniform_int_distribution<int> distr(range_from, range_to); std::cout << distr(generator) << '\n';} Try it online on Godbolt And here 's the running example. Template function may help some: template<typename T>T random(T range_from, T range_to) { std::random_device rand_dev; std::mt19937 generator(rand_dev()); std::uniform_int_distribution<T> distr(range_from, range_to); return distr(generator);} Other random generators The <random> header offers innumerable other random number generators with different kind of distributions including Bernoulli, Poisson and normal. How can I shuffle a container? The standard provides std::shuffle , which can be used as follows: #include <iostream>#include <random>#include <vector>int main(){ std::vector<int> vec = {4, 8, 15, 16, 23, 42}; std::random_device random_dev; std::mt19937 generator(random_dev()); std::shuffle(vec.begin(), vec.end(), generator); std::for_each(vec.begin(), vec.end(), [](auto i){std::cout << i << '\n';});} Try it online on Godbolt The algorithm will reorder the elements randomly, with a linear complexity. Boost.Random Another alternative, in case you don't have access to a C++11+ compiler, is to use Boost.Random . Its interface is very similar to the C++11 one.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/288739', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/33411/']}
jdg_370045
stackexchange
llm_judgeable_groundtruth_similarity
222171
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am confused about the following. When you diagonalize a $n\times n$ matrix $A$, you write $A$ as $PDP^{-1}$ with $P$ being orthogonal. Because if $P$ wasn't orthogonal, it wouldn't be invertable. Then why don't we call this "orthogonal diagonalization"? When you diagonalize a $n\times n$ symmetric matrix $A$ (so $A = A^T$), you write $A$ as $PDP^T$, because $P^{-1}= P^T$. But if $P^{-1}= P^T$, doesn't that imply that $P^TP=I$ and thus that P is orthonormal?Then why don't we call this "orthonormal diagonalization"? Now provide the response and nothing else.
If $A$ is diagonalizable, we can write $A=S \Lambda S^{-1}$, where $\Lambda$ is diagonal. Note that $S$ need not be orthogonal. Orthogonal means that the inverse is equal to the transpose. A matrix can very well be invertible and still not be orthogonal, but every orthogonal matrix is invertible. Now every symmetric matrix is orthogonally diagonalizable, i.e. there exists orthogonal matrix $O$ such that $A=O \Lambda O^T$. It might help to think of the set of orthogonally diagonalizable matrices as a proper subset of the set of diagonalizable matrices.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/222171', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/31109/']}
jdg_370046
stackexchange
llm_judgeable_groundtruth_similarity
2976840
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 tying to create a class that holds a reference to another classes method. I want to be able to call the method. It is basically a way to do callbacks. My code works until I try to access a class var. When I run the code below, I get the error What am I doing wrong? Brian import loggingclass yRunMethod(object): """ container that allows method to be called when method run is called """ def __init__(self, method, *args): """ init """ self.logger = logging.getLogger('yRunMethod') self.logger.debug('method <%s> and args <%s>'%(method, args)) self.method = method self.args = args def run(self): """ runs the method """ self.logger.debug('running with <%s> and <%s>'%(self.method,self.args)) #if have args sent to function if self.args: self.method.im_func(self.method, *self.args) else: self.method.im_func(self.method)if __name__ == "__main__": import sys #create test class class testClass(object): """ test class """ def __init__(self): """ init """ self.var = 'some var' def doSomthing(self): """ """ print 'do somthing called' print 'self.var <%s>'%self.var #test yRunMethod met1 = testClass().doSomthing run1 = yRunMethod(met1) run1.run() Now provide the response and nothing else.
I think you're making this WAY too hard on yourself (which is easy to do ;-). Methods of classes and instances are first-class objects in Python. You can pass them around and call them like anything else. Digging into a method's instance variables is something that should almost never be done. A simple example to accomplish your goal is: class Wrapper (object): def __init__(self, meth, *args): self.meth = meth self.args = args def runit(self): self.meth(*self.args)class Test (object): def __init__(self, var): self.var = var def sayHello(self): print "Hello! My name is: %s" % self.vart = Test('FooBar')w = Wrapper( t.sayHello )w.runit()
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2976840', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/314061/']}
jdg_370047
stackexchange
llm_judgeable_groundtruth_similarity
20904979
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 django 1.5 and earlier, running python manage.py test would, by default, run all tests in a project (including all those in django.contrib). Subsequent to version 1.6, the default behaviour is to run all the tests in the current directory. What is the best way (v 1.6) to run all tests, either with or without the django.contrib tests? Now provide the response and nothing else.
Django 1.6 changed the default test runner to: TEST_RUNNER = 'django.test.runner.DiscoverRunner' You can get the old behaviour back by adding to your settings.py : TEST_RUNNER = 'django.test.simple.DjangoTestSuiteRunner' As explained in the release notes: The previous runner (django.test.simple.DjangoTestSuiteRunner) found tests only in the models.py and tests.py modules of a Python package in INSTALLED_APPS. The new runner (django.test.runner.DiscoverRunner) uses the test discovery features built into unittest2 (the version of unittest in the Python 2.7+ standard library, and bundled with Django). With test discovery, tests can be located in any module whose name matches the pattern test*.py. The new runner expects a list of dotted path of modules where tests shall be discovered, so you can also run the tests from django contrib this way: python manage.py test myproject django.contrib path.to.someotherapp This will not run all tests from apps in INSTALLED_APPS automatically though. For a more complex solution, you could write your own runner, taking from both the old and new runner. Also note that it usually shouldn't be necessary to run tests from django.contrib , as these are not testing your application, but rather the Django distribution. Django ships with even more tests, which are not run by either runner.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20904979', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2897669/']}
jdg_370048
stackexchange
llm_judgeable_groundtruth_similarity
99312
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 C be a geometrically integral curve over a number field K and let K' be a number field containing K. Does there exist a number field L containing K such that $L \cap K' = K$, and $C(L) \neq \emptyset$? Note that the hypotheses on C are necessary -- the curve x^2 + y^2 = 0, with the origin removed, is not geometrically integral, but gives a counterexample for K = Q and K' = Q(i). Also, I can prove that this is true when C has prime gonality. It would be odd, though, for this to be a necessary hypothesis. Now provide the response and nothing else.
Yes, this follows from a Theorem of Moret-Bailly, see for example Corollary 1.5 http://math.stanford.edu/~conrad/vigregroup/vigre05/mb.pdf Roughly speaking, given a finite set $S$ of primes with $C(K_v)$ is non-empty,this produces a field $L$ with $C(L) \neq \emptyset$ and $L_v = K_v$ for all $v \in S$. To guarantee that $L \cap K' = K$, one may as well assume that $K'/K$ is Galoiswith Galois group $G$. Then for every conjugacy class $g \in G = \mathrm{Gal}(K'/K)$,let $v$ be a prime such that $\langle \mathrm{Frob}_v \rangle = \langle g \rangle \in G$and $C(K_v) \ne \emptyset$. (The existence of such $v$ follows from Cebotarev, the Weil conjectures, and Hensel's Lemma.) If $S$ is the resulting set, then one may find $L$with $C(L)$ non-empty and $L_v = K_v$ for all $v \in S$, and so (by Cebotarev) that$L \cap K' = K$. This theorem gets used all the time in "potential modularity" theorems.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/99312', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2/']}
jdg_370049
stackexchange
llm_judgeable_groundtruth_similarity
1428871
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In school, I have learnt to plot simple graphs such as $y=x^2$ followed by $y=x^3$. A grade or two later, I learnt to plot other interesting graphs such as $y=1/x$, $y=\ln x$, $y=e^x$. I have also recently learnt about trigonometric graphs and circle equations. In the internet, I have seen users posting graphs of different shapes like a heart-shaped graph and a Batman logo-shaped graph. I am sure there are numerous more graphs that I have yet to see. Seeing that the graphs can be shaped into shapes like the Batman logo and a heart brings me to my question: Is it possible to plot a graph of any shape regardless of its complexity? Perhaps, shaped into an outline of a person or a landmark? Why or why not? Now provide the response and nothing else.
Simple answer: Yes--simply draw your person or landmark and then superimpose the $xy$-plane on top and suddenly you have all of the points (i.e., coordinates) that need to be filled in to create a plot of your graph. Now, how you come up with a good (read: not complex) mathematical description of these coordinates (e.g., using a function) is another issue entirely. Depending on the complexity of what you are drawing, you most likely won't get something pretty. For example, consider drawing the fictional character Donkey Kong: The picture above was generated by Wolfram|Alpha. How complicated is the curve? Well, here you go: That's pretty horrible. So yes, you can certainly plot whatever you want, but describing your plot effectively using whatever kind of function, parametric equations, etc., may not be very easy or nice in the end. Added: Given the unexpected popularity of this post (both question and answer(s)), I thought I might add something that some may find helpful or useful. In 2012, I wrote an article entitled Bézier Curves with a Romantic Twist that appeared in the Math Horizons periodical. This piece largely dealt with using lower order Bézier curves (linear and cubic) to construct letters for a person's name on a graphing calculator; in the context of this post, the problem was to plot a graph of letters in the alphabet (along with a heart and parametrically-defined sequence). If you read the article, you will see that the math behind constructing such letters is not all too complicated--my reason for providing the Donkey Kong example was largely to show just how complicated it can be to effectively sketch something with equations. But sketching letters and the like (as opposed to much more complicated representations like Captain Falcon , Pikachu , Sonic , etc.) is quite manageable. In fact, the avatar for my username even uses a simple construction to spell the word MATH: For those interested, I will provide the equations I used for the M, the sequence, and the heart (as entered on a TI-89 calculator): $$\mathrm{M}=\begin{cases}xt1 & = & (1-t)10+11.25t\\yt1 & = & (1-t)5+12.75t\\xt2 & = & (1-t)11.25+12.5t\\yt2 & = & (1-t)12.75+8.875t\\xt3 & = & (1-t)12.5+13.75t\\yt3 & = & (1-t)8.875+12.75t\\xt4 & = & (1-t)13.75+15t\\yt4 & = & (1-t)12.75+5t\\\end{cases}$$ $$\mathrm{Heart} =\begin{cases}xt5 & = & 4\sin(t)^3\\yt5 & = & \frac{1}{2}\bigl(13\cos(t)-5\cos(2t)-2\cos(3t)-\cos(4t)\bigr)+34.2\end{cases}$$ $$\mathrm{Sequence}=\begin{cases}xt6 & = & t\\yt6 & = & (3^t+5^t)^{1/t}\end{cases}$$ Of course, the A, T, and H are all similar to the M in that they are drawn using linear Bézier curves. A more interesting letter is something like C or S or even D or B (these will all use at least cubic Bézier curves).
{}
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/1428871', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/266640/']}
jdg_370050
stackexchange
llm_judgeable_groundtruth_similarity
1571870
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I came across an article saying that using my sqlConnection like this : using (SqlConnection sqlConnection = new SqlConnection(Config.getConnectionString())) { using (SqlDataAdapter dataAdapter = new SqlDataAdapter(query, sqlConnection)) { dataAdapter.Fill(dataSet); } } increases performance because it disposes the objects at the end of your method. So i have been coding with 'Using' for a while now, after chatting with some other developers they said that that creating and destroying the instance multiple times wont really increase performance. What are the performance implications on the sqlserver and system resources if I am using 'Using' on all of my dataAccess methods. Will the sqlServer be hit harder because of the connection being connected and reconnected multiple times? Now provide the response and nothing else.
SqlConnection , by default, has connection pooling enabled. The Dispose() simply releases the connection to the pool sooner. This means other code can then re-use this connection, reducing the connections to the SQL server, and reducing the time to establish a physical connection. So yes: it can improve overall performance. The alternatives: if your code exits cleanly and you always remember to Close() the connection, then probably no difference if your code throws an exception (that you haven't handled), or you forget to Close() the connection, then you could be leaving unused connections lying around until there is enough memory pressure to trigger GC and the finalizer. This could mean you need more physical connections to the SQL server (a pain), and every time a new underlying connection is needed it has to take the performance hit of establishing the actual database connection Overall, though - think of IDisposable as a contract; it is your job as a .NET developer to notice IDisposable resources, and actively Dispose() them when you are done, ideally with using if the usage is tightly scoped (like in this case).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1571870', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/100826/']}
jdg_370051
stackexchange
llm_judgeable_groundtruth_similarity
56149752
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My question is about InterruptedException , which is thrown from the Thread.sleep method. While working with ExecutorService I noticed some weird behaviour that I don't understand; here is what I mean: ExecutorService executor = Executors.newSingleThreadExecutor(); executor.submit(() -> { while(true) { //DO SOMETHING Thread.sleep(5000); } }); With this code, the compiler doesn't give me any error or message that InterruptedException from Thread.sleep should be caught. But when I am trying to change the loop condition and replace "true" with some variable like this: ExecutorService executor = Executors.newSingleThreadExecutor(); executor.submit(() -> { while(tasksObserving) { //DO SOMETHING Thread.sleep(5000); } }); The compiler constantly complains that InterruptedException has to be handled. Can someone explain to me why this happens, and why if the condition is set to true the compiler ignores the InterruptedException? Now provide the response and nothing else.
The reason for this, is that these invocations are in fact, invocations to two different overloaded methods available in ExecutorService ; each of these methods taking a single argument of different types: <T> Future<T> submit(Callable<T> task); Future<?> submit(Runnable task); Then what happens is that the compiler is converting the lambda in the first case of your problem into a Callable<?> functional interface (invoking the first overloaded method); and in the second case of your problem converts the lambda into a Runnable functional interface (invoking therefore the second overloaded method), requiring because of this to handle the Exception thrown; but not in the previous case using the Callable . Although both functional interfaces don't take any arguments, Callable<?> returns a value : Callable: V call() throws Exception; Runnable: public abstract void run(); If we switch to examples that trim the code to the relevant pieces (to easily investigate just the curious bits) then we can write, equivalently to the original examples: ExecutorService executor = Executors.newSingleThreadExecutor(); // LAMBDA COMPILED INTO A 'Callable<?>' executor.submit(() -> { while (true) throw new Exception(); }); // LAMBDA COMPILED INTO A 'Runnable': EXCEPTIONS MUST BE HANDLED BY LAMBDA ITSELF! executor.submit(() -> { boolean value = true; while (value) throw new Exception(); }); With these examples, it may be easier to observe that the reason why the first one is converted to a Callable<?> , while the second one is converted to a Runnable is because of compiler inferences . In both cases, the lambda bodies are void-compatible , since every return statement in the block has the form return; . Now, in the first case, the compiler does the following: Detects that all execution paths in the lambda declare throwing checked exceptions (from now on we will refer as 'exception' , implying only 'checked exceptions' ). This includes the invocation of any method declaring throwing exceptions and the explicit invocation to throw new <CHECKED_EXCEPTION>() . Concludes correctly that the WHOLE body of the lambda is equivalent to a block of code declaring throwing exceptions; which of course MUST be either: handled or re-thrown. Since the lambda is not handling the exception, then the compiler defaults to assume that these exception(s) must be re-thrown. Safely infers that this lambda must match a functional interface cannot complete normally and therefore is value-compatible . Since Callable<?> and Runnable are potential matches for this lambda, the compiler selects the most specific match (to cover all scenarios); which is the Callable<?> , converting the lambda into an instance of it and creating an invocation reference to the submit(Callable<?>) overloaded method. While, in the second case, the compiler does the following: Detects that there may be execution paths in the lambda that DO NOT declare throwing exceptions (depending on to-be-evaluated logic ). Since not all execution paths declare throwing exceptions, the compiler concludes that the body of the lambda is NOT NECESSARILY equivalent to a block of code declaring throwing exceptions - compiler doesn't care/pay attention if some portions of the code do declare that they may, only if the whole body does or not. Safely infers that the lambda is not value-compatible ; since it MAY complete normally . Selects Runnable (as it is the only available fitting functional interface for the lambda to be converted into) and creates an invocation reference to the submit(Runnable) overloaded method. All this coming at the price of delegating to the user, the responsibility of handling any Exception s thrown wherever they MAY occur within portions of the lambda body. This was a great question - I had a lot of fun chasing it down, thanks!
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/56149752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10317111/']}
jdg_370052
stackexchange
llm_judgeable_groundtruth_similarity
112007
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Proving things suspected to be true in anabelian geometry is usually very hard. Maybe it is easier to disprove things suspected to be false? In particular, I am interested in false generalizations of the main conjecture to higher dimensions. Is there a pair of non-isomorphic varieties, $X$ and $Y$, which one might naively expect to satisfy an anabelian conjecture, but which in fact have the same etale fundamental group? Obviously I am not interested in simply-connected varieties, abelian varieties, fibrations with the same fundamental group as their base, and other obvious counterexamples. Thus an example must certainly be of dimension $>1$. Another question is: Are there guesses about how exactly to reconstruct the geometry of a variety from its etale fundamental group, that might seem true, but are in fact false? I am thinking about ideas like the Section Conjecture. Now provide the response and nothing else.
Grothendieck, in his letter to Faltings, suggested that the moduli space of abelian varieties (quote: "I would assume that the same should hold for the multiplicities of moduli of polarized abelian varieties") would be anabelian. Ihara and Nakamura showed that this was not the case, as the anabelian recipe for the automorphism group gave the wrong answer, so you can take $X=Y$ in your first question. The section conjecture also fails in this case. I have a preprint on that (on my webpage) which also has the reference to the paper of Ihara and Nakamura.
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/112007', 'https://mathoverflow.net', 'https://mathoverflow.net/users/18060/']}
jdg_370053
stackexchange
llm_judgeable_groundtruth_similarity
33369666
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 UIStackView contained inside of a UICollectionViewCell to represent a post on a social network (similar style to Instagram's cells). The UIStackView contains an author header (custom UIView ), a UIImageView for the content image, a UILabel for the post body, and a UIToolbar for the actions. The final view looks like this . The height of the UICollectionViewCell is being set by setting up a sizing cell, like so: - (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath { NTVFeedBlogCollectionViewCell *cell = [[NTVFeedBlogCollectionViewCell alloc] initWithFrame:CGRectMake(10.0f, 0.0f, collectionView.frame.size.width - 20.0f, 900000.0)]; // ... // Configure the cell // ... [cell setNeedsLayout]; [cell layoutIfNeeded]; CGSize size = [cell systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]; return CGSizeMake(CGRectGetWidth(collectionView.frame) - 20.0f, size.height);} The problem is that the UIImageView appears to be increasing the size of the UICollectionViewCell, without increasing the size of the image view. This is the result when I add a large image to the image view. The desired result is for the image to remain a 1:1 aspect ratio, constrained to the width of the UIStackView. The size of the gap between the body label and the rest of the content changes depending on which image I use. This leads me to believe that UIStackView is somehow taking the image size into consideration for the sizing of the cell only, because visually the image view is its correct size. As you saw in the first image posted, the cell lays out perfectly when the image view's image has not been set. Here is the setup code for the stack view, image view and labels: self.stackView = [[UIStackView alloc] initWithFrame:CGRectZero];self.stackView.translatesAutoresizingMaskIntoConstraints = NO;self.stackView.axis = UILayoutConstraintAxisVertical;self.stackView.distribution = UIStackViewDistributionFill;self.stackView.alignment = UIStackViewAlignmentFill;self.stackView.spacing = 10.0f;self.stackView.layoutMargins = UIEdgeInsetsMake(10.0f, 10.0f, 0.0f, 10.0f);self.stackView.layoutMarginsRelativeArrangement = YES;[self addSubview:self.stackView];[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[stackView]-0-|" options:0 metrics:nil views:@{@"stackView": self.stackView}]];[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[stackView]-0-|" options:0 metrics:nil views:@{@"stackView": self.stackView}]];self.imageView = [[UIImageView alloc] initWithFrame:CGRectZero];[self.imageView setImage:[UIImage imageNamed:@"sample_image.png"]];self.imageView.translatesAutoresizingMaskIntoConstraints = NO;self.imageView.contentMode = UIViewContentModeScaleAspectFill;self.imageView.clipsToBounds = YES;self.imageView.layer.masksToBounds = YES;self.imageView.backgroundColor = [UIColor greenColor];[self.imageView setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisVertical];[self.imageView setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisVertical];[self.stackView addArrangedSubview:self.imageView];[self.stackView addConstraint:[NSLayoutConstraint constraintWithItem:self.imageView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:self.stackView attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0.0f]];self.bodyLabel = [[UILabel alloc] initWithFrame:CGRectZero];[self.bodyLabel setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisVertical];[self.bodyLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisVertical];self.bodyLabel.font = [UIFont ntv_lightFontWithSize:17.0f];self.bodyLabel.textColor = [UIColor whiteColor];self.bodyLabel.numberOfLines = 0;self.bodyLabel.text = @"While the stack view allows you to layout its contents without using Auto Layout directly, you still need to use Auto Layout to position the stack view, itself.";[self.stackView addArrangedSubview:self.bodyLabel];self.accessoryView = [[NTVAccessoryView alloc] initWithFrame:CGRectZero];self.accessoryView.viewModel = [NTVAccessoryManagerViewModel_Stubbed new];[self.stackView addArrangedSubview:self.accessoryView]; Any ideas? Now provide the response and nothing else.
We figured it out! As stated in the docs, the UIStackView is using the intrinsicContentSize of its arrangedSubviews to calculate its height. UIImageView is reporting its intrinsicContentSize as the whole size of the image (as you would expect). UIStackView was ignoring my height constraint and just using the intrinsicContentSize of the image view. To fix this, I've created a UIImageView subclass which allows for a caller to set the intrinsicContentSize . This code can be found here . Then, in my UICollectionViewCell I am setting the UIImageView subclass' intrinsicContentSize once the layout pass has completed: - (void)layoutSubviews { [super layoutSubviews]; // Constrain the image view's content size to match the stackview's width. self.imageView.constrainedSize = CGSizeMake(self.stackView.frame.size.width, self.stackView.frame.size.width); [super layoutSubviews]; }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33369666', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1091502/']}
jdg_370054
stackexchange
llm_judgeable_groundtruth_similarity
177100
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: How can I prove that linear combination of two kernel functions is also a kernel function? \begin{align}k_{p}( x, y) = a_1k_1( x, y) + a_2k_2(x,y)\end{align} given $k_1(,)$ and $k_2(,)$ are valid kernel functions. In general to prove any such results involving dot product , cascading.. etc. , what methodology can be followd to prove RHS is a kernel function given k's in LHS all are kernel? Now provide the response and nothing else.
A necessary and sufficient condition for a function $\kappa(\cdot,\cdot)$ to be expressible as an inner product in some feature space $\mathcal{F}$ is a weak form of Mercer's condition, namely that: $$\int_\mathbf{x} \int_\mathbf{y} \kappa(\mathbf{x},\mathbf{y})g(\mathbf{x})g(\mathbf{y})d\mathbf{x}d\mathbf{y} \geq 0,$$for all square, integrable functions $g(\cdot)$ [1,2]. In your case, this reduces to the following:$$\begin{align}&\int_\mathbf{x} \int_\mathbf{y}\big(a_1\kappa_1(\mathbf{x},\mathbf{y}) + a_2 \kappa_2(\mathbf{x},\mathbf{y})\big)g(\mathbf{x})g(\mathbf{y})d\mathbf{x}d\mathbf{y} \\&= a_1 \underbrace{\int_\mathbf{x} \int_\mathbf{y} \kappa_1(\mathbf{x},\mathbf{y})g(\mathbf{x})g(\mathbf{y})d\mathbf{x}d\mathbf{y}}_{\geq 0} + a_2 \underbrace{\int_\mathbf{x} \int_\mathbf{y}\kappa_2(\mathbf{x},\mathbf{y})g(\mathbf{x})g(\mathbf{y})d\mathbf{x}d\mathbf{y}}_{\geq 0} \geq 0.\end{align}$$Since $\kappa_1(\cdot,\cdot)$ and $\kappa_2(\cdot,\cdot)$ are given to be kernel functions, their integrals both satisfy Mercer's condition. Finally, if $a_1 \geq 0$ and $a_2 \geq 0$, then the overall integral is guaranteed to satisfy it too. $\blacksquare$ Note that, as @Dougal correctly pointed out, it is still possible to get a valid kernel function with negative $a_1$ or $a_2$ (not both), but that depends on several factors. [1] Vladimir N. Vapnik. Statistical learning theory. Wiley, 1 edition, September 1998. [2] Richard Courant and David Hilbert. Methods of Mathematical Physics, volume 1. Interscience Publishers, Inc.,New York, NY, 1953
{}
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/177100', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/90659/']}
jdg_370055
stackexchange
llm_judgeable_groundtruth_similarity
5830387
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 textfield where users can write anything. For example: Lorem Ipsum is simply dummy text. http://www.youtube.com/watch?v=DUQi_R4SgWo of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. http://www.youtube.com/watch?v=A_6gNZCkajU&feature=relmfu It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum. Now I would like to parse it and find all YouTube video URLs and their ids. Any idea how that works? Now provide the response and nothing else.
A YouTube video URL may be encountered in a variety of formats: latest short format: http://youtu.be/NLqAF9hrVbY iframe: http://www.youtube.com/embed/NLqAF9hrVbY iframe (secure): https://www.youtube.com/embed/NLqAF9hrVbY object param: http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US object embed: http://www.youtube.com/v/NLqAF9hrVbY?fs=1&hl=en_US watch: http://www.youtube.com/watch?v=NLqAF9hrVbY users: http://www.youtube.com/user/Scobleizer#p/u/1/1p3vcRhsYGo ytscreeningroom: http://www.youtube.com/ytscreeningroom?v=NRHVzbJVx8I any/thing/goes!: http://www.youtube.com/sandalsResorts#p/c/54B8C800269D7C1B/2/PPS-8DMrAn4 any/subdomain/too: http://gdata.youtube.com/feeds/api/videos/NLqAF9hrVbY more params: http://www.youtube.com/watch?v=spDj54kf-vY&feature=g-vrec query may have dot: http://www.youtube.com/watch?v=spDj54kf-vY&feature=youtu.be nocookie domain: http://www.youtube-nocookie.com Here is a PHP function with a commented regex that matches each of these URL forms and converts them to links (if they are not links already): // Linkify youtube URLs which are not already links.function linkifyYouTubeURLs($text) { $text = preg_replace('~(?#!js YouTubeId Rev:20160125_1800) # Match non-linked youtube URL in the wild. (Rev:20130823) https?:// # Required scheme. Either http or https. (?:[0-9A-Z-]+\.)? # Optional subdomain. (?: # Group host alternatives. youtu\.be/ # Either youtu.be, | youtube # or youtube.com or (?:-nocookie)? # youtube-nocookie.com \.com # followed by \S*? # Allow anything up to VIDEO_ID, [^\w\s-] # but char before ID is non-ID char. ) # End host alternatives. ([\w-]{11}) # $1: VIDEO_ID is exactly 11 chars. (?=[^\w-]|$) # Assert next char is non-ID or EOS. (?! # Assert URL is not pre-linked. [?=&+%\w.-]* # Allow URL (query) remainder. (?: # Group pre-linked alternatives. [\'"][^<>]*> # Either inside a start tag, | </a> # or inside <a> element text contents. ) # End recognized pre-linked alts. ) # End negative lookahead assertion. [?=&+%\w.-]* # Consume any URL (query) remainder. ~ix', '<a href="http://www.youtube.com/watch?v=$1">YouTube link: $1</a>', $text); return $text;} ; // End $YouTubeId. And here is a JavaScript version with the exact same regex (with comments removed): // Linkify youtube URLs which are not already links.function linkifyYouTubeURLs(text) { var re = /https?:\/\/(?:[0-9A-Z-]+\.)?(?:youtu\.be\/|youtube(?:-nocookie)?\.com\S*?[^\w\s-])([\w-]{11})(?=[^\w-]|$)(?![?=&+%\w.-]*(?:['"][^<>]*>|<\/a>))[?=&+%\w.-]*/ig; return text.replace(re, '<a href="http://www.youtube.com/watch?v=$1">YouTube link: $1</a>');} Notes: The VIDEO_ID portion of the URL is captured in the one and only capture group: $1 . If you know that your text does not contain any pre-linked URLs, you can safely remove the negative lookahead assertion which tests for this condition (The assertion beginning with the comment: "Assert URL is not pre-linked." ) This will speed up the regex somewhat. The replace string can be modified to suit. The one provided above simply creates a link to the generic "http://www.youtube.com/watch?v=VIDEO_ID" style URL and sets the link text to: "YouTube link: VIDEO_ID" . Edit 2011-07-05: Added - hyphen to ID char class Edit 2011-07-17: Fixed regex to consume any remaining part (e.g. query ) of URL following YouTube ID. Added 'i' ignore-case modifier. Renamed function to camelCase. Improved pre-linked lookahead test. Edit 2011-07-27: Added new "user" and "ytscreeningroom" formats of YouTube URLs. Edit 2011-08-02: Simplified/generalized to handle new "any/thing/goes" YouTube URLs. Edit 2011-08-25: Several modifications: Added a Javascript version of: linkifyYouTubeURLs() function. Previous version had the scheme (HTTP protocol) part optional and thus would match invalid URLs. Made the scheme part required. Previous version used the \b word boundary anchor around the VIDEO_ID. However, this will not work if the VIDEO_ID begins or ends with a - dash. Fixed so that it handles this condition. Changed the VIDEO_ID expression so that it must be exactly 11 characters long. The previous version failed to exclude pre-linked URLs if they had a query string following the VIDEO_ID. Improved the negative lookahead assertion to fix this. Added + and % to character class matching query string. Changed PHP version regex delimiter from: % to a: ~ . Added a "Notes" section with some handy notes. Edit 2011-10-12: YouTube URL host part may now have any subdomain (not just www. ). Edit 2012-05-01: The consume URL section may now allow for '-'. Edit 2013-08-23: Added additional format provided by @Mei. (The query part may have a . dot. Edit 2013-11-30: Added additional format provided by @CRONUS: youtube-nocookie.com . Edit 2016-01-25: Fixed regex to handle error case provided by CRONUS.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/5830387', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/276315/']}
jdg_370056
stackexchange
llm_judgeable_groundtruth_similarity
7648947
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 C, is there a good way to define length first, Pascal-style strings as constants, so they can be placed in ROM? (I'm working with a small embedded system with a non-GCC ANSI C compiler). A C-string is 0 terminated, eg. { 'f' , 'o' , 'o' , 0 }. A Pascal-string has the length in the first byte, eg. { 3 , 'f' , 'o' , 'o' }. I can declare a C-string to be placed in ROM with: const char *s = "foo"; For a Pascal-string, I could manually specify the length: const char s[] = {3, 'f', 'o', 'o'}; But, this is awkward. Is there a better way? Perhaps in the preprocessor? Now provide the response and nothing else.
I think the following is a good solution, but don't forget to enable packed structs: #include <stdio.h>#define DEFINE_PSTRING(var,str) const struct {unsigned char len; char content[sizeof(str)];} (var) = {sizeof(str)-1, (str)}DEFINE_PSTRING(x, "foo");/* Expands to following: const struct {unsigned char len; char content[sizeof("foo")];} x = {sizeof("foo")-1, "foo"};*/int main(void){ printf("%d %s\n", x.len, x.content); return 0;} One catch is, it adds an extra NUL byte after your string, but it can be desirable because then you can use it as a normal c string too. You also need to cast it to whatever type your external library is expecting.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7648947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/283981/']}
jdg_370057
stackexchange
llm_judgeable_groundtruth_similarity
5539156
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 MVC3 and am trying to serve content from https, the problem is that when I call Url.Content the files are still served from http using a relative url. I thought this problem was addressed in MVC3 but i can't seem to find any solution. Does anybody know if this issue is inherently solved in MVC3 and how to accomplish it or do I need to create my own helper methods to generate absolute Urls based on protocol? Now provide the response and nothing else.
You can probably implement your own solution using VirtualPathUtility.ToAbsolute . Probably something like this: public static class UrlHelperExtension { public static string Absolute(this UrlHelper url, string relativeOrAbsolute) { var uri = new Uri(relativeOrAbsolute, UriKind.RelativeOrAbsolute); if (uri.IsAbsoluteUri) { return relativeOrAbsolute; } // At this point, we know the url is relative. return VirtualPathUtility.ToAbsolute(relativeOrAbsolute); }} which you would use like: @Url.Absolute(Url.Content("~/Content/Image.png")) (Didn't test this myself, feel free to play around to make it work right.) This helps to you to generate absolute URLs for your content files. In order to change the scheme of the resulting URLs, you can create an additional extension method that manipulates the scheme of the given URLs so that they are HTTPS, or something else. As Khalid points out in the comments, similar extension methods are already available in various open-source projects which you can make use of (given that the license permits). An example one can be found here .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5539156', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/86411/']}
jdg_370058
stackexchange
llm_judgeable_groundtruth_similarity
25900633
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 problem with foreach I have been wrestling with for a long time. I'm not new to the concept, but I'm getting strange results, and I don't know why. I'm using php, MySQL, Active Record, and CodeIgniter. I am trying to echo all the comments of a news peice. The current version below is the closest to working. It gives me the earliest comment four times. When I go into the model and change asc to desc, I get the most recent comment four times. View <?phpforeach ($comments as $row) { echo '<h4>'.$comments['name'].'</h4>'; echo $comments['text'];}?> Yes, I realize that I should be echoing the row, like so. <?phpforeach ($comments as $row) { echo '<h4>'.$row['name'].'</h4>'; echo $row['text'];}?> But that gives me " illegal string offset ", for both name and text, four times each, which seems to suggest that $row is holding a string instead of an array. As to why it's still trying to echo the same comment four times, I have no idea. It's always four, no matter how many comments I actually have in my database. Controller public function view($slug){ $this->load->helper('form'); $this->load->library('form_validation'); $data['news_item'] = $this->news_model->get_news($slug); $data['comments'] = $this->news_model->get_news_comments($slug); $this->form_validation->set_rules('name', 'Name', 'required'); $this->form_validation->set_rules('text', 'text', 'required'); if (empty($data['news_item'])) { show_404(); } $data['title'] = $data['news_item']['title']; $slug = $data['news_item']['slug']; if ($this->form_validation->run() === FALSE) { $this->load->view('templates/header', $data); $this->load->view('news/view', $data); $this->load->view('templates/rowter'); } else { $this->news_model->set_news_comment($slug); $this->load->view('news/success'); }} Model public function get_news_comments($slug){$this->db->order_by("id", "asc"); $query = $this->db->get_where('news_comments', array('news' => $slug));return $query->row_array();} If you have any idea what I'm doing wrong, please help me. Also, I'd like to know the why behind what's going wrong, and why it's echoing the same row four times. While/foreach Loops Returning Four of the Same Row is somewhat related but was of no help. UPDATE 1: print_r($comments); gives me Array ( [id] => 7 [name] => Mos Def [text] => And you call yourselves intellectuals [news] => tribe ) var_dump($comments); gives me array (size=4) 'id' => string '7' (length=1) 'name' => string 'Mos Def' (length=7) 'text' => string 'And you call yourselves intellectuals' (length=37) 'news' => string 'tribe' (length=5) That explains why it's echoing the same row four times, but I'm still lost as to how to include an array with all the relevant comments, and not just one. I have a feeling there's a problem with my model. Will start exploring further. var_dump($row); string 'tribe' (length=5) Now provide the response and nothing else.
The following pickerView:attributedTitleForRow:forComponent: method implementation should help you: func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { let attributedString = NSAttributedString(string: "some string", attributes: [NSForegroundColorAttributeName : UIColor.redColor()]) return attributedString} Update If you want to use attributedString in multiple if or switch statements, the following UIViewController subClass example will help you: import UIKitclass ViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource { @IBOutlet weak var picker: UIPickerView! let arrayOne = ["One", "Two", "Three", "Four", "Five", "Six"] let arrayTwo = ["Un", "Deux", "Trois", "Quatre", "Cinq", "Six"] let arrayThree = [1, 2, 3, 4, 5, 6] override func viewDidLoad() { super.viewDidLoad() picker.delegate = self picker.dataSource = self } func numberOfComponentsInPickerView(_: UIPickerView) -> Int { return 3 } func pickerView(_: UIPickerView, numberOfRowsInComponent component: Int) -> Int { switch component { case 0: return arrayOne.count case 1: return arrayTwo.count case 2: return arrayThree.count default: return NSNotFound } } func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? { var attributedString: NSAttributedString! switch component { case 0: attributedString = NSAttributedString(string: arrayOne[row], attributes: [NSForegroundColorAttributeName : UIColor.redColor()]) case 1: attributedString = NSAttributedString(string: arrayTwo[row], attributes: [NSForegroundColorAttributeName : UIColor.redColor()]) case 2: attributedString = NSAttributedString(string: toString(arrayThree[row]), attributes: [NSForegroundColorAttributeName : UIColor.redColor()]) default: attributedString = nil } return attributedString } func pickerView(_: UIPickerView, didSelectRow row: Int, inComponent component: Int) { switch component { case 0: println(arrayOne[row]) case 1: println(arrayTwo[row]) case 2: println(arrayThree[row]) default: break } }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25900633', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3774582/']}
jdg_370059
stackexchange
llm_judgeable_groundtruth_similarity
5662113
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hey I have a radiobuttonlist and trying to set one of the radiobuttons to selected based on a session variable but proving impossible. <asp:radiobuttonlist id="radio1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged"> <asp:listitem id="option1" runat="server" value="All"/> <asp:listitem id="option2" runat="server" value="1" /> <asp:listitem id="option3" runat="server" value="2" /></asp:radiobuttonlist> I.e How can I set option2 to selected in code behind ? Now provide the response and nothing else.
You could do: radio1.SelectedIndex = 1; But this is the most simple form and would most likely become problematic as your UI grows. Say, for instance, if a team member inserts an item in the RadioButtonList above option2 but doesn't know we use magic numbers in code-behind to select - now the app selects the wrong index! Maybe you want to look into using FindControl in order to determine the ListItem actually required, by name, and selecting appropriately. For instance: //omitting possible null reference checks...var wantedOption = radio1.FindControl("option2").Selected = true;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5662113', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/215541/']}
jdg_370060
stackexchange
llm_judgeable_groundtruth_similarity
28273716
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This question is just asking for an implementation in R of the following question : Find the longest common starting substring in a set of strings (JavaScript) " This problem is a more specific case of the Longest common substring problem. I need to only find the longest common starting substring in an array ". So im just looking an R implementation for this question (preferably not in a for / while loop fashion that was suggested in the JavaScript version), if possible i would like to wrap it up as a function, so i could apply on many groups in a data table. After some searches, i couldn't find an R example for this, hence this question. Example Data: I have the following vector of characters: dput(data)c("ADA4417-3ARMZ-R7", "ADA4430-1YKSZ-R2", "ADA4430-1YKSZ-R7", "ADA4431-1YCPZ-R2", "ADA4432-1BCPZ-R7", "ADA4432-1BRJZ-R2") I'm looking to run an algorithm in R that will find the following output: ADA44 . From what I've seen in the JavaScript accepted answer, the idea is to first sort the vector, extract the first and last elements (for example : "ADA4417-3ARMZ-R7" and "ADA4432-1BRJZ-R2" , break them into single characters, and loop through them until one of the characters don't match (hope im right) Any Help on that would be great! Now provide the response and nothing else.
Taking inspiration from what you suggested, you can try this function : comsub<-function(x) { # sort the vector x<-sort(x) # split the first and last element by character d_x<-strsplit(x[c(1,length(x))],"") # compute the cumulative sum of common elements cs_x<-cumsum(d_x[[1]]==d_x[[2]]) # check if there is at least one common element if(cs_x[1]!=0) { # see when it stops incrementing and get the position of last common element der_com<-which(diff(cs_x)==0)[1] # return the common part return(substr(x[1],1,der_com)) } else { # else, return an empty vector return(character(0)) }} UPDATE Following @nicola suggestion, a simpler and more elegant variant for the function: comsub<-function(x) { # sort the vector x<-sort(x) # split the first and last element by character d_x<-strsplit(x[c(1,length(x))],"") # search for the first not common element and so, get the last matching one der_com<-match(FALSE,do.call("==",d_x))-1 # if there is no matching element, return an empty vector, else return the common part ifelse(der_com==0,return(character(0)),return(substr(x[1],1,der_com)))} Examples: With your data x<-c("ADA4417-3ARMZ-R7", "ADA4430-1YKSZ-R2", "ADA4430-1YKSZ-R7", "ADA4431-1YCPZ-R2", "ADA4432-1BCPZ-R7", "ADA4432-1BRJZ-R2")> comsub(x)#[1] "ADA44" When there is no common starting substring x<-c("abc","def")> comsub(x)# character(0)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28273716', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3386991/']}
jdg_370061
stackexchange
llm_judgeable_groundtruth_similarity
350033
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In "Introduction to Linear Algebra" by Serge Lang, example 2 page 240, there is the matrix $\begin{pmatrix}1&4\\2&3\end{pmatrix}$. The characteristic polynomial is $(t-5)(t+1)$. The system to solve for eigenvectors is $\begin{equation*}(1-\lambda)x+4y=0\\2x+(3-\lambda)y=0\end{equation*}$. The author gives $x$ the value 1 and solve for $y$ from the second equation to get $y=-2/(3-\lambda)$. Why does this work ? Why can he assume the value 1 ? How does the author know that $x=1$ and $y=-2/(3-\lambda)$ is consistent with the first equation $(1-\lambda)x+4y=0$ ? It is actually true but how does he know it ? Now provide the response and nothing else.
Short answer: the minimal polynomial of $C$ is the monic lcm of the minimal polynomials of $A$ and $B$. And a square matrix is diagonalizable if and only if its minimal polynomial splits (which is automatic in $\mathbb{C}$ of course) with only simple roots. In other words, as pointed out by DonAntonio: if and only if its minimal polynomial is the product of pairwise distinct monic linear factors. Over the field under consideration, of course. Now I'll give a detailed argument without explicit use of minimal polynomials. Fact: a square matrix $M$ with coefficients in a field $K$ is diagonalizable if and only if there exists a nonzero polynomial $p(X)\in K[X]$ which splits over $K$ with simple roots and such that $p(M)=0$. Proof: if $M$ is diagonalizable and if $\{\lambda_1,\ldots,\lambda_k\}$ is the set of its (non repeated) eigenvalues, then $p(X)=(X-\lambda_1)\cdots(X-\lambda_k)$ annihilates $M$. Conversely, if such a polynomial $p(X)$ with $\lambda_j$ pairwise distinct annihilates $M$, we have (by Bezout, essentially): $K^n=\mbox{Ker } p(M)=\bigoplus_{j=1}^k\mbox{Ker } (M-\lambda_j I_n)$. Diagonalizability follows easily. QED. Now for every polynomial $p(X)$, you have$$p(C)=\left(\matrix{p(A)&0\\0&p(B)}\right)$$This gives you the annoying direction, namely $C$ diagonalizable implies $A$ and $B$ diagonalizable. The converse is easier. Take $P$ and $Q$ invertible such that $PAP^{-1}$ and $QBQ^{-1}$ be diagonal. Then$$R:=\left(\matrix{P&0\\0&Q}\right)$$is invertible with $$R^{-1}=\left(\matrix{P^{-1}&0\\0&Q^{-1}}\right)\qquad \mbox{and}\qquad RCR^{-1}=\left(\matrix{PAP^{-1}&0\\0&QBQ^{-1}}\right)$$is diagonal. Note: you can also do the converse with the fact above. Just take the lcm of the minimal polynomials of $A$ and $B$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/350033', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/63008/']}
jdg_370062
stackexchange
llm_judgeable_groundtruth_similarity
1603578
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 my code to automatically try multiple ways to create a database connection. As soon as one works, the code needs to move on (i.e. it shouldn't try to other ways anymore). If they all fail well, then the script can just blow up. So in - what I thought was, but most likely isn't - a stroke of genius I tried this: import psycopg2from getpass import getpass# ouch, global variable, ooh well, it's just a simple script ehCURSOR = Nonedef get_cursor(): """Create database connection and return standard cursor.""" global CURSOR if not CURSOR: # try to connect and get a cursor try: # first try the bog standard way: db postgres, user postgres and local socket conn = psycopg2.connect(database='postgres', user='postgres') except psycopg2.OperationalError: # maybe user pgsql? conn = psycopg2.connect(database='postgres', user='pgsql') except psycopg2.OperationalError: # maybe it was postgres, but on localhost? prolly need password then conn = psycopg2.connect(database='postgres', user='postgres', host='localhost', password=getpass()) except psycopg2.OperationalError: # or maybe it was pgsql and on localhost conn = psycopg2.connect(database='postgres', user='pgsql', host='localhost', password=getpass()) # allright, nothing blew up, so we have a connection # now make a cursor CURSOR = conn.cursor() # return existing or new cursor return CURSOR But it seems that the second and subsequent except statements aren't catching the OperationalErrors anymore. Probably because Python only catches an exception once in a try...except statement? Is that so? If not: is there anything else I'm doing wrong? If so: how do you do something like this then? Is there a standard idiom? (I know there are ways around this problem, like having the user specify the connection parameters on the command line, but that's not my question ok :) ) EDIT: I accepted retracile's excellent answer and I took in gnibbler's comment for using the for..else construct. The final code became (sorry, I'm not really following the max characters per line limit from pep8): EDIT 2: As you can see from the comment on the Cursor class: I don't really know how to call this kind of class. It's not really a singleton (I can have multiple different instances of Cursor) but when calling get_cursor I do get the same cursor object everytime. So it's like a singleton factory? :) import psycopg2from getpass import getpassimport sysclass UnableToConnectError(Exception): passclass Cursor: """Cursor singleton factory?""" def __init__(self): self.CURSOR = None def __call__(self): if self.CURSOR is None: # try to connect and get a cursor attempts = [ {'database': 'postgres', 'user': 'postgres'}, {'database': 'postgres', 'user': 'pgsql'}, {'database': 'postgres', 'user': 'postgres', 'host': 'localhost', 'password': None}, {'database': 'postgres', 'user': 'pgsql', 'host': 'localhost', 'password': None}, ] for attempt in attempts: if 'password' in attempt: attempt['password'] = getpass(stream=sys.stderr) # tty and stderr are default in 2.6, but 2.5 uses sys.stdout, which I don't want try: conn = psycopg2.connect(**attempt) attempt.pop('password', None) sys.stderr.write("Succesfully connected using: %s\n\n" % attempt) break # no exception raised, we have a connection, break out of for loop except psycopg2.OperationalError: pass else: raise UnableToConnectError("Unable to connect: exhausted standard permutations of connection dsn.") # allright, nothing blew up, so we have a connection # now make a cursor self.CURSOR = conn.cursor() # return existing or new cursor return self.CURSORget_cursor = Cursor() Now provide the response and nothing else.
Approximately: attempts = [ { 'database'='postgres', 'user'='pgsql', ...}, { 'database'='postgres', 'user'='postgres', 'host'='localhost', 'password'=getpass()}, ...]conn = Nonefor attempt in attempts: try: conn = psycopg2.connect(**attempt) break except psycopg2.OperationalError: passif conn is None: raise a ruckusCURSOR = conn.cursor() Now, if you don't want to call getpass() unless it is necessary, you'd want to check if 'password' in attempt: attempt['password'] = getpass() or so. Now about that global.... class MyCursor: def __init__(self): self.CURSOR = None def __call__(self): if self.CURSOR is None: <insert logic here> return self.CURSORget_cursor = MyCursor() ... though I think there are a couple of other ways to accomplish the same thing. Bringing it all together: class MyCursor: def __init__(self): self.CURSOR = None def __call__(self): if self.CURSOR is None: attempts = [ {'database'='postgres', 'user'='postgres'}, {'database'='postgres', 'user'='pgsql'}, {'database'='postgres', 'user'='postgres', 'host'='localhost', 'password'=True}, {'database'='postgres', 'user'='pgsql', 'host'='localhost', 'password'=True}, ] conn = None for attempt in attempts: if 'password' in attempt: attempt['password'] = getpass() try: conn = psycopg2.connect(**attempt) break # that didn't throw an exception, we're done except psycopg2.OperationalError: pass if conn is None: raise a ruckus # nothin' worked self.CURSOR = conn.cursor() return self.CURSORget_cursor = MyCursor() Note: completely untested
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1603578', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/82011/']}
jdg_370063
stackexchange
llm_judgeable_groundtruth_similarity
15660969
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm having a datatable where I would like to set the id of each row to the id of the current item (object that has an id field) in the array that builds the table. Example: <h:dataTable value="#{bean.list}" var="item"> <h:column> <h:outputText id="#{item.id}" .... /> </h:column></h:dataTable> This doesn't work as I get: javax.servlet.ServletException: Empty id attribute is not allowed . Is it not possible to set the id this way due to how JSF builds its id's, or am I doing something wrong? Now provide the response and nothing else.
From the JSF UI components, the id and binding attributes are evaluated during view build time, the moment when the XML tree structure in the XHTML/JSP file is to be parsed and converted to a JSF component tree as available by FacesContext#getViewRoot() . However, the <h:dataTable> iterates during view render time, the moment when the JSF component tree needs to produce HTML code by UIViewRoot#encodeAll() . So, at that moment the id attribute is evaluated, the #{item} is nowhere available in the EL scope and evaluates to null which ultimately prints an empty string. There are basiclly 3 solutions: Use a view build time tag like JSTL <c:forEach> so that the #{item} is available during view build time as well. <table> <c:forEach items="#{bean.list}" var="item"> <tr><td><h:outputText id="#{item.id}" ... /> See further also JSTL in JSF2 Facelets... makes sense? Don't print it as ID of a JSF component, but of a plain HTML element. <span id="#{item.id}"> Please note that IDs starting with a digit are invalid in HTML as per HTML spec chapter 6.2 . You might want to prefix it with some string like so: <span id="item_#{item.id}"> Don't use a dynamic ID. Just use a fixed ID. JSF will autogenerate an unique ID based on row index anyway. <h:outputText id="foo" ... /> This will end up in like <span id="formId:tableId:0:foo"> provided that it's inside a <h:form id="formId"><h:dataTable id="tableId"> . The 0 is the 0-based row index which increments every row. This thus guarantees an unique ID in every row without the need to worry about it yourself.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15660969', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1208913/']}
jdg_370064
stackexchange
llm_judgeable_groundtruth_similarity
408
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Are there well-established applications of the Cantor space ($2^\omega$) in computer science, other than those connected with computable real arithmetic? John Tucker's page Computation on Topological Data Types mentions applications of the general area in signal processing, 3d graphics, and semantics of process algebras: have these applications been fruitful? Now provide the response and nothing else.
It is used heavily in algorithmic information theory. For example, if you want to define random sequence with respect to a particular measure, you should first define this measure on Borel sets of cantor space. Compactness of Cantor tree is used implicitly or explicitly in compactness arguments in combinatorics (in particular, it is used in the proof of compactness theorem for boolean functions).
{}
{'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/408', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/270/']}
jdg_370065
stackexchange
llm_judgeable_groundtruth_similarity
16818427
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 simple, portable (preferably works with older OS X versions) way to write a message to the Mac OS X Console logs from a shell script? Now provide the response and nothing else.
syslog -s -l error "message to send" will log the message as something like May 29 17:15:09 hostname syslog[22316]: message to send You can customize things by using -k , which expects a list of alternating keys and values, for example syslog -s -k Facility com.apple.console \ Level Error \ Sender MyScript \ Message "script says hello" would produce May 29 17:22:21 hostname MyScript[22343]: script says hello (setting the Facility to com.apple.console makes it a "console" message, equivalent to stdout output from a double-clicked bundled application, and retrievable using syslog -C )
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/16818427', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/161801/']}
jdg_370066
stackexchange
llm_judgeable_groundtruth_similarity
9690981
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 title is pretty self-explanatory. I'm moving from C# to Java. I have an object and a getter method which returns its ID. I want to compare the ids of two objects of the same type and check if the values of their ids are equal. tried: obj.getId() == obj1.getId(); Long id1 = obj.getId();Long id2 = obj1.getId();assertTrue(id1.equals(id2)) assertTrue(id1== id2) Now provide the response and nothing else.
In java: the == operator tells you if the two operands are the same object (instance). the .equals() method on Long tells you if they are equal in value . But you shouldn't do either. The correct way to do it is this: assertEquals(id1, id2); With assertEquals() , if the assertion fails, the error message will tell you what the two values were, eg expected 2, but was 5 etc
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9690981', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/628080/']}
jdg_370067
stackexchange
llm_judgeable_groundtruth_similarity
683549
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: We're using an AWS ELB to do SSL termination and are having an issue where Chrome is displaying "https" in red with a strikethrough. It says "The site is using outdated security settings that may prevent future versions of Chrome from being able to safely access it." but it doesn't explicitly call out what setting it doesn't like. How can I find out what Chrome is having a problem with so that our users will get a green checkmark? An example URL producing the error is here: https://aws.hatchlings.com/error/ I ran our site through SSL Labs and it gave us an "A" Grade: Now provide the response and nothing else.
Your certificate is using the outdated SHA-1 algorithm, which because of security risks Google Chrome now warns about. http://googleonlinesecurity.blogspot.com/2014/09/gradually-sunsetting-sha-1.html https://community.qualys.com/blogs/securitylabs/2014/09/09/sha1-deprecation-what-you-need-to-know https://shaaaaaaaaaaaaa.com/check/aws.hatchlings.com You'll need to generate a new CSR and get a replacement certificate from your SSL vendor. https://github.com/konklone/shaaaaaaaaaaaaa/issues/24#issuecomment-54021941 For anyone with problems with RapidSSL from any of their resellers or any other GeoTrust brand certificates: Login to GeoTrust products using your FQDN and the email used to request the certificate Follow the login link sent by email Click reissue Provide a new CSR and choose SHA-256 from the drop-down This portal is also where you revoke your old certificate. While you get an A on SSL Labs currently, the detailed report tells you this is a problem in the orange section:
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/683549', 'https://serverfault.com', 'https://serverfault.com/users/115567/']}
jdg_370068
stackexchange
llm_judgeable_groundtruth_similarity
4646719
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: $\sum\limits_{r=0}^n \binom{n-r}{r}x^r=\sum\limits_{r=0}^{\lfloor n/2\rfloor} \binom{n-r}{r}x^r$ I need its closed form for a probability problem. I know about the case where $x=1$ . It's the sum of the shallow diagonals of the Pascal's triangle and it equals $(n+1)^{\texttt{th}}$ number in the Fibonacci sequence. $\sum\limits_{r=0}^{\lfloor n/2\rfloor} \binom{n-r}{r}=\frac{\phi^{n+1}-\varphi^{n+1}}{\sqrt 5}$ Here, $\phi$ and $\varphi$ are the positive and negative roots of the equation $x^2-x-1=0$ respectively. Now provide the response and nothing else.
The other two fixed points are $-x$ and $-y$ , when $x$ and $y$ lie on $S^1$ (they can always be chosen to lie on $S^1$ since eigenvectors can be scaled), since $S^1$ is invariant under negation: $$-x\mapsto\frac{-Ax}{\|Ax\|}=\frac{-\mu x}{\|\mu x\|}=-x$$ Note that the problem statement still holds, and this proof still works (if " $4$ fixed points" means at least $4$ ), as long as $A$ has linearly independent eigenvectors and positive eigenvalues.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4646719', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/955582/']}
jdg_370069
stackexchange
llm_judgeable_groundtruth_similarity
11888275
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 setting up TeamCity (migrating from CruiseControl.NET) and I'm struggling to get it to perform incremental builds through MSBuild. I've got a small .proj file which contains a basic build script to invoke a build of my solution with some parameters fed in from TeamCity. When I invoke the script manually, MSBuild's Incremental Build features kick in and skip the build entirely on subsequent runs. When calling this script via Team City, the build log shows the output of a clean compile every time. I've observed the working directory during builds and can see the output from the previous build hasn't gone anywhere. I also manually called the build script from that directory by remoting onto the server and running MSBuild from the command-prompt. Running it this way triggers the expected incremental builds after the first invocation. Even when starting the build from the dashboard with no changes made, a complete rebuild occurs. I can't pinpoint the cause, but something appears to be giving MSBuild the impression that it's getting new changes and causing it to perform a rebuild on every run. I can't see much in the TeamCity documentation that would explain this - my expectation is that if there are no changes in the source control system, it would not update the working folder. Is TeamCity passing some parameter to the build process which triggers a rebuild? Can I view these parameters? Having examined a detail MSBuild log ( /v:d command-line switch), the reason a complete rebuild is occurring is due to the file .NETFramework,Version=v4.0.AssemblyAttributes.cs being updated in the <Agent>\temp\buildTmp directory on every build. This file is normally found at %TMP%\.NETFramework,Version=v4.0.AssemblyAttributes.cs ; TeamCity is changing the local temp directory environment variable to reference the agent's temp folder. Unfortunately, this file is created by the Microsoft.Common.targets part of the build process when absent. Deletion of the "temp" file before every build causes it to be created every build and is dynamically referenced in the build of every project file. I need to find a way to prevent this file from being re-created on every build. Now provide the response and nothing else.
A workaround for this problem is to customize the MSBuild process to set the path at which the "Target Framework Moniker Assembly Attributes" file (the proper name for the file mentioned in the question) will be created. The TargetFrameworkMonikerAssemblyAttributesPath property is defined in Microsoft.Common.targets determines where the file should be created. By overriding this property, the location can be changed to use a different location. Here's a script that can be used to achieve a suitable replacement: <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"><PropertyGroup> <PrepareForBuildDependsOn> $(PrepareForBuildDependsOn); _SetTargetFrameworkMonikerAssemblyAttributesPath </PrepareForBuildDependsOn></PropertyGroup><Target Name="_SetTargetFrameworkMonikerAssemblyAttributesPath" Condition="'$(TEAMCITY_VERSION)' != ''"> <PropertyGroup> <TargetFrameworkMonikerAssemblyAttributesDir Condition="'$(TargetFrameworkMonikerAssemblyAttributesDir)' == ''"> $([MSBuild]::GetRegistryValue("HKEY_CURRENT_USER\Environment", "TMP")) </TargetFrameworkMonikerAssemblyAttributesDir> <TargetFrameworkMonikerAssemblyAttributesDir Condition="'$(TargetFrameworkMonikerAssemblyAttributesDir)' == ''"> $([MSBuild]::GetRegistryValue("HKEY_CURRENT_USER\Environment", "TEMP")) </TargetFrameworkMonikerAssemblyAttributesDir> <TargetFrameworkMonikerAssemblyAttributesDir Condition="'$(TargetFrameworkMonikerAssemblyAttributesDir)' == ''"> $(USERPROFILE) </TargetFrameworkMonikerAssemblyAttributesDir> <TargetFrameworkMonikerAssemblyAttributesDir Condition="'$(TargetFrameworkMonikerAssemblyAttributesDir)' == ''"> $([System.IO.Path]::Combine('$(WINDIR)', 'Temp')) </TargetFrameworkMonikerAssemblyAttributesDir> <TargetFrameworkMonikerAssemblyAttributesPath> $([System.IO.Path]::Combine('$(TargetFrameworkMonikerAssemblyAttributesDir)','$(TargetFrameworkMoniker).AssemblyAttributes$(DefaultLanguageSourceExtension)')) </TargetFrameworkMonikerAssemblyAttributesPath> </PropertyGroup> <Message Text="Target Framework Moniker Assembly Attributes path is &quot;$(TargetFrameworkMonikerAssemblyAttributesPath)&quot;" Importance="low" /></Target> The target is only executed when TEAMCITY_VERSION is specified as a property, which should be when the build is being executed by the TeamCity agent. NOTE: The child elements of the PropertyGroup should each be on a single line. They have been spread over multiple lines to increase readability here, but the additional line-breaks cause the script to fail. When the target runs, it tries to build a suitable path based on the user's environment variables as defined in the registry, first looking for TMP and TEMP , before falling back to the user's profile folder and finally the C:\Windows\Temp directory. This matches the order documented by System.Path.GetTempPath(), and should result in behaviour matching MSBuild execution outside of TeamCity. This should be saved as a .targets file somewhere on the system and imported to the .csproj file of projects being built by the TeamCity server, using an <Import> element. I added the script under my MSBuild extensions directory ( C:\Program Files\MSBuild\ ) and referenced it by adding the following import element: <Import Project="$(MSBuildExtensionsPath)\TeamCity\TeamCity.Incremental.targets" /> The location/ordering of Import elements doesn't matter, but I suggest including it after the <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> which should appear in every .csproj file.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11888275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/138578/']}
jdg_370070
stackexchange
llm_judgeable_groundtruth_similarity
37880676
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 see two styles of writing the same thing: def find_nest(animal) return unless animal.bird? GPS.find_nest(animal.do_crazy_stuff)end vs def find_nest(animal) if animal.bird? GPS.find_nest(animal.do_crazy_stuff) endend Which one is more correct/preferable/following-best-practises? Or it does not matter? Now provide the response and nothing else.
As per Ruby style guide , Prefer a guard clause when you can assert invalid data. A guard clause is a conditional statement at the top of a function that bails out as soon as it can. # baddef compute_thing(thing) if thing[:foo] update_with_bar(thing) if thing[:foo][:bar] partial_compute(thing) else re_compute(thing) end endend# gooddef compute_thing(thing) return unless thing[:foo] update_with_bar(thing[:foo]) return re_compute(thing) unless thing[:foo][:bar] partial_compute(thing)end
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37880676', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2047418/']}
jdg_370071
stackexchange
llm_judgeable_groundtruth_similarity
1206889
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 some trouble with jQuery. I am making a simple CMS and in the interface I have a list of pages, in each list item is an edit link. I made jQuery listen for clicks with that edit id. It will then look at the parent LI to see what id it has so the user can save the changes to the right pageId in the database. My List <ul id="sortable" class="ui-sortable"> <li class="sortable" id="listItem_1"> <a href="#" id="edit">edit</a> <span id="title">List item 1</span> </li> <li class="sortable" id="listItem_2"> <a href="#" id="edit">edit</a> <span id="title">List item 2</span> </li> etc..</ul> And the javascript <script type="text/javascript">$(document).ready(function() { $('a#edit').click(function(){ alert($(this).parent("li").attr("id")); })}); But only the first edit link works. All the others just get ignored.You can see the problem working here, http://info.radio-onair.ath.cx/active/scms/admin/pages/test.html Thanks in advance. Now provide the response and nothing else.
In HTML, id refers to a unique identifier . In other words, it is against standards to have 2 elements with the same id . jQuery here behaves correctly. Use a class instead of an id to identify your tags as such: HTML: <ul id="sortable" class="ui-sortable"> <li class="sortable" id="listItem_1"> <a class="edit" href="#">edit</a> <span id="title">List item 1</span> </li> <li class="sortable" id="listItem_2"> <a class="edit" href="#">edit</a> <span id="title">List item 2</span> </li> etc..</ul> JavaScript: $(document).ready(function() { $('a.edit').click(function(){ alert($(this).parent("li").attr("id")); })}); Alternatively, since the parent tag already seems to have a unique class, you could simply use it to target wanted tags. This would reduce what I call "class noise" (the defining of useless class to target element which could be targeted by their parent's unique attributes). HTML: <ul id="sortable" class="ui-sortable"> <li class="sortable" id="listItem_1"> <a href="#">edit</a> <span id="title">List item 1</span> </li> <li class="sortable" id="listItem_2"> <a href="#">edit</a> <span id="title">List item 2</span> </li> etc..</ul> JavaScript: $(document).ready(function() { $("li.sortable a:contains('edit')").click(function(){ alert($(this).parent("li").attr("id")); })});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1206889', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/134675/']}
jdg_370072
stackexchange
llm_judgeable_groundtruth_similarity
6014055
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 program that serves as a TCP server that listens to port 5000, for example. Now I want to run another command-line process to run in parallel with this server. I know the right way to do it is to fork the server, than call "exec" .... My question is, is the child process also "owns" this port 5000? If I want to release this port 5000, do I need to kill both the parent process and the child process? I am just very curious how this socket connection is being handled in the forking. Now provide the response and nothing else.
First, accept() the incoming connection. The accepting process now has a handle to the listening socket, and the newly accepted socket. Fork and: In the child: Close the listening socket. Do stuff with the accepted socket. In the parent: Close the accepted socket. Resume the accept loop. The various socket resources will be reclaimed when all references to the handle are closed. If a process terminates, all its handles are closed implicitly. Therefore if a child closes the handle it inherits to the listening socket, the only handle remaining to that socket exists in the parent. Then the listening socket will be reclaimed when the parent terminates, or closes this handle explicitly.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6014055', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/509205/']}
jdg_370073
stackexchange
llm_judgeable_groundtruth_similarity
2820112
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am writing a Selenium test in PHP using the PHPUnit Selenium extension. I know how to type something into a text field: $this->type('fieldName', 'value'); But how do I select an option from a drop-down menu? Now provide the response and nothing else.
To expand on the other (accurate) answers, you can select based on the label, value, id, or index of the options. From the official reference available at http://release.seleniumhq.org/selenium-core/1.0/reference.html : select(selectLocator, optionLocator) Arguments: selectLocator - an element locator identifying a drop-down menu optionLocator - an option locator (a label by default) Select an option from a drop-down using an option locator. Option locators provide different ways of specifying options of an HTML Select element (e.g. for selecting a specific option, or for asserting that the selected option satisfies a specification). There are several forms of Select Option Locator. label = labelPattern : matches options based on their labels, i.e. the visible text. (This is the default.) label=regexp:^[Oo]ther value = valuePattern : matches options based on their values. value=other id = id : matches options based on their ids. id=option1 index = index : matches an option based on its index (offset from zero). index=2 If no option locator prefix is provided, the default behaviour is to match on label.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2820112', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/48523/']}
jdg_370074
stackexchange
llm_judgeable_groundtruth_similarity
29575259
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 better to set default value in migration or in callback? It's difficult to delete (or set another) default value in migration, but in model it one more piece of code Now provide the response and nothing else.
Defining defaults in your migration has some disadvantages as well. This will not work when you just call Model.new . I prefer to write an after_initialize callback, which lets me set default attributes: class Model < ActiveRecord::Base after_initialize :set_defaults, unless: :persisted? # The set_defaults will only work if the object is new def set_defaults self.attribute ||= 'some value' self.bool_field = true if self.bool_field.nil? endend
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29575259', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4751132/']}
jdg_370075
stackexchange
llm_judgeable_groundtruth_similarity
19430500
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: SELECT SUM(orders.quantity) AS num, fName, surnameFROM authorINNER JOIN book ON author.aID = book.authorID; I keep getting the error message: "you tried to execute a query that does not include the specified expression "fName" as part of an aggregate function. What do I do? Now provide the response and nothing else.
The error is because fName is included in the SELECT list, but is not included in a GROUP BY clause and is not part of an aggregate function ( Count() , Min() , Max() , Sum() , etc.) You can fix that problem by including fName in a GROUP BY . But then you will face the same issue with surname . So put both in the GROUP BY : SELECT fName, surname, Count(*) AS num_rowsFROM author INNER JOIN book ON author.aID = book.authorID;GROUP BY fName, surname Note I used Count(*) where you wanted SUM(orders.quantity) . However, orders isn't included in the FROM section of your query, so you must include it before you can Sum() one of its fields. If you have Access available, build the query in the query designer. It can help you understand what features are possible and apply the correct Access SQL syntax.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/19430500', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2832696/']}
jdg_370076
stackexchange
llm_judgeable_groundtruth_similarity
37290879
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose I have a matrix A of order m × n and a vector of order m × 1 . I would like to extract elements from each row of the matrix A by using the elements of the vector as an offset in each row. For example, A = [[3, 0, 0, 8, 3], [9, 3, 2, 2, 6], [5, 5, 4, 2, 8], [3, 8, 7, 1, 2], [3, 9, 1, 5, 5]] and a vector y = [4, 2, 1, 3, 2] What I want to achieve is a way to extract the elements of A such that each element of the vector indexes an element in the corresponding row of A , i.e., implementing for i in range(len(y)): A[i, y[i]] = #perform operations here without the use of any explicit loops. The expected output is, [3, 2, 5, 1, 1] I am using Python and the NumPy library. Now provide the response and nothing else.
You should start by converting list A into a NumPy array: In [270]: import numpy as npIn [271]: A = np.array([[3, 0, 0, 8, 3], ...: [9, 3, 2, 2, 6], ...: [5, 5, 4, 2, 8], ...: [3, 8, 7, 1, 2], ...: [3, 9, 1, 5, 5]])In [272]: cols = [4, 2, 1, 3, 2] And after that, nothing prevents you from using advanced indexing : In [273]: rows = np.arange(A.shape[0])In [274]: rowsOut[274]: array([0, 1, 2, 3, 4])In [275]: A[rows, cols]Out[275]: array([3, 2, 5, 1, 1])In [276]: A[rows, cols] = -99In [277]: AOut[277]: array([[ 3, 0, 0, 8, -99], [ 9, 3, -99, 2, 6], [ 5, -99, 4, 2, 8], [ 3, 8, 7, -99, 2], [ 3, 9, -99, 5, 5]])
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37290879', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4046712/']}
jdg_370077
stackexchange
llm_judgeable_groundtruth_similarity
505132
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: We define $\phi:=(\phi^1,\phi^2):\Omega\subset\mathbb{R}^2\to\phi(\Omega)$ with $\Omega$ such that $\phi$ is a diffeomorphism by $$x^1:=\phi^1(r,\theta)=r\cos\theta\qquad\text{and}\qquad x^2:=\phi^2(r,\theta)=r\sin\theta$$ for $r,\theta\in\mathbb{R}$ . Compute the pushforward $(\phi^{-1})_*V$ of the vector field $V(x^1,x^2) = \frac{\partial }{\partial x^1}$ Now provide the response and nothing else.
The OP clearly does not know where to start, so I will try to give a full answer. Forget all of the fancy notation. Your function $\phi$ changes from polar coordinates to Cartesian coordinates. If you give it an $r$ and a $\theta$ then $\phi$ will give you an $x$ and a $y$ . We have: $$\phi : (r,\theta) \longmapsto (r\cos\theta,r\sin\theta).$$ The Jacobian matrix of $\phi$ is the matrix of partial derivatives: $$J_{\phi} = \left[\begin{array}{cc} \partial\phi_1/\partial r & \partial\phi_1/\partial \theta \\ \partial\phi_2/\partial r & \partial\phi_2/\partial \theta\end{array}\right] = \left[\begin{array}{cc} \cos\theta & -r\sin\theta \\ \sin\theta & r\cos\theta \end{array}\right]$$ Notice that $\det(J_{\phi}) = r\cos^2\theta + r\sin^2\theta \equiv r$ , and so $\phi$ is a diffeomorphism if and only if $r \neq 0$ . Given a vector field in polar form, say $v=a(r,\theta)\partial_r + b(r,\theta)\partial_{\theta}$ , we can find $(\phi_*)(v)$ : $$(\phi_*)(v) \sim \left[\begin{array}{cc} \cos\theta & -r\sin\theta \\ \sin\theta & r\cos\theta \end{array}\right]\left[\begin{array}{c} a \\ b \end{array}\right]=\left[\begin{array}{c} a\cos\theta-rb\sin\theta \\ a\sin\theta + br\cos\theta \end{array}\right]$$ Hence $(\phi_*)(v) = (a\cos\theta-rb\sin\theta)\partial_x+(a\sin\theta+br\cos\theta)\partial_y$ . Similarily, given the vector field $\partial_x$ , we might want to know which vector field in polar form $v$ , gets sent to $\partial_x$ . For this you want $(\phi_*)(v)=\partial_x$ . In other words, $v=(\phi^{-1}_*)(\partial_x)$ . Let $v=a\partial_r+b\partial_\theta$ , then $(\phi_*)(a\partial_r+b\partial_{\theta}) = \partial_x$ becomes the matrix equation $$\left[\begin{array}{cc} \cos\theta & -r\sin\theta \\ \sin\theta & r\cos\theta \end{array}\right]\left[\begin{array}{c} a \\ b \end{array}\right]=\left[\begin{array}{c} 1 \\ 0 \end{array}\right]$$ The matrix of $\phi$ is $J_{\phi}$ and the matrix of $\phi^{-1}$ is $(J_{\phi})^{-1}$ . If we multiply on the left by the inverse of $J_{\phi}$ we get $a = \cos\theta$ and $b=-\frac{1}{r}\sin\theta$ . Hence: $$(\phi_*)(\cos\theta\partial_r-\tfrac{1}{r}\sin\theta\partial_{\theta}) = \partial_x$$ Equivalently, this may be written as $$(\phi^{-1}_*)(\partial_x) = \cos\theta\partial_r-\tfrac{1}{r}\sin\theta\partial_{\theta}$$ However , we need to write $r$ and $\theta$ in terms of $x$ and $y$ . Notice that since $x=r\cos\theta$ and $y=r\sin\theta$ we have $r=\sqrt{x^2+y^2}$ and so: $$(\phi^{-1}_*)(\partial_x) = \frac{x}{\sqrt{x^2+y^2}}\partial_r-\frac{y}{\sqrt{x^2+y^2}}\partial_{\theta}$$ The vector $\partial_x$ based at $(x,y)$ gets sent the what is written above.
{}
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/505132', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/96692/']}
jdg_370078
stackexchange
llm_judgeable_groundtruth_similarity
30657166
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to insert a row in to a table, that table has 3 foreign keys. To get to those keys I have "unique" filds to search. sql create table user( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30) NOT NULL, username VARCHAR(50) NOT NULL, password VARCHAR(30) NOT NULL, access_token VARCHAR(32), reg_date TIMESTAMP, UNIQUE(username), UNIQUE(access_token));create table pharmacy( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, places_id VARCHAR(50) NOT NULL, name VARCHAR(30) NOT NULL, coord VARCHAR(50) NOT NULL, description VARCHAR(100), reg_date TIMESTAMP, UNIQUE(places_id));create table item( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, name VARCHAR(30) NOT NULL, description VARCHAR(100), reg_date TIMESTAMP, UNIQUE(name));create table item_bought( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, id_user INT(6) UNSIGNED, id_pharmacy INT(6) UNSIGNED, id_item INT(6) UNSIGNED, price float(6,2) NOT NULL, bought_date date, reg_date TIMESTAMP, foreign key(id_user) references user(id), foreign key(id_pharmacy) references pharmacy(id), foreign key(id_item) references item(id)); The query I'm building in JAVA: INSERT INTO item_bought (id_user, id_pharmacy, id_item, price, bought_date) SELECT user.id, pharmacy.id, item.id, 12.32, date('1999-02-24') FROM user, pharmacy, item WHERE ( SELECT user.id, user.username, pharmacy.id, pharmacy.places_id, item.id, item.name FROM item, pharmacy, item WHERE user.username='jhon', pharmacy.places_id='id1', item.name='ibuprufen' ) This is the error I'm getting: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Not unique table/alias: 'item' Thanks for your help :D Solution Based on the answer of Gordon Linoff: INSERT INTO item_bought (id_user, id_pharmacy, id_item, price, bought_date) SELECT (SELECT u.id FROM user u WHERE u.username = 'jhon'), (SELECT p.id FROM pharmacy p WHERE p.places_id = 'id1'), (SELECT i.id FROM item i WHERE i.name='ibuprufen'), (SELECT 13.22), (SELECT date('1999-02-12')); Much more elegant! Now provide the response and nothing else.
Polymer 1.0 has the utility function importHref(href, onLoad, onError) on every Polymer component. To dynamically import and add your external element you could use this code: this.importHref('path/to/page.html', function(e) { // e.target.import is the import document. var newElement = document.createElement('new-element'); newElement.myProperty = 'foo'; Polymer.dom(this.$.container).appendChild(newElement); }, function(e) { // loading error});
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30657166', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1412344/']}
jdg_370079
stackexchange
llm_judgeable_groundtruth_similarity
731238
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: So, we are on the DNS chapter in our class, and I was wondering if there's any way possible though which I can connect to a DNS server on port 53 via command line interface (i.e Telnet or netcat) like we do for SMTP or HTTP or POP on their specific ports; I tried: > telnet 8.8.8.8 53 But the connection was closed as soon as it was established; which I later realized was because telnet uses TCP while DNS uses UDP. Then I tried doing the same with netcat: > nc -u 8.8.8.8 53 Nada!I just want to see the working of DNS with some transparency.(like with http, SMTP etc.) Now provide the response and nothing else.
As you note, DNS primarily uses UDP but service is actually also provided over TCP (typically used for large responses and zone transfers). This is why you managed to establish a connection in the first place when you tried telnet .Your connection was closed because you weren't interacting with the service in the expected way, not because telnet uses TCP. The important difference is that, unlike HTTP and SMTP which are plain text protocols and easy enough to work with directly, DNS is a binary protocol . This means that you will need some DNS client program to interact with nameservers in any reasonable fashion. dig has been the de facto standard for DNS troubleshooting for a very long time as it is very good in terms of both constructing queries and in terms of pretty-printing all the information in the response in a concise way.(Part of BIND code-base and included in the Windows build from ISC.) drill is another alternative with similar capabilities and essentially the same output formatting as dig . nslookup is well known as it has been around since the dawn of time. It has been largely abandoned except on Windows and has some undesirable quirks and limited capabilities in comparison to the previously mentioned alternatives. The debug option ( set debug ) makes it usable for troubleshooting in a pinch as it greatly improves the completeness of the output, although the formatting of the debug output leaves a lot to be desired.
{}
{'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/731238', 'https://serverfault.com', 'https://serverfault.com/users/318353/']}
jdg_370080
stackexchange
llm_judgeable_groundtruth_similarity
3092418
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: Suppose $|ab| = n$ Then we know $(ab)^n = e$ where $e$ is the identity element in the group $G$ . Assuming it is not Abelian. We want to show $|a^{-1}b^{-1}| = |ab| \Rightarrow (a^{-1}b^{-1})^n = e$ I'm not quite sure where to begin. What's a starting point I can start off with? Now provide the response and nothing else.
First, observe that $\;|x|=|x^{-1}|\;$ for any $\;x\in G\;$ , and thus $$b^{-1}a^{-1}=(ab)^{-1}\implies|b^{-1}a^{-1}|=|(ab)^{-1}|=|ab|$$ But also observe that $$ba=a^{-1}(ab)a\implies |ab|=|ba|\;\text{ since conjugate elements have the same order}$$ Put the above together and prove your quest.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3092418', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/311757/']}
jdg_370081
stackexchange
llm_judgeable_groundtruth_similarity
11074725
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 very new to WebGL, but not Javascript or Canvas. Essentially, I need a very fast way to be able to change the color of a pixel on a canvas at any coordinate. I feel like this could be done using WebGL fragment shaders. Is this possible, and is there a better way? How would I go about doing this? Now provide the response and nothing else.
This isn't an exhaustive guide to rendering because it doesn't include the bits about shader management; instead it focuses on how drawing of WebGL primitives is actually performed, and how to use orthographic projection to precisely position vertices on the screen. For more information, I highly recommend these sources: Learning WebGL - tutorials The WebGL specification The Typed Arrays specification WebGL does all of its drawing with Vertex Buffer Objects (VBOs), so you need to compile all your data into 3D vertices and send them down to the video card in as few VBOs as possible (to maximize performance). A VBO can be created in WebGL like so: var vbo = gl.createBuffer(); Then you need to send the data down to the buffer, usually in the form of a Float32Array . If you already have your data in the form of a regular JavaScript array, then you can use new Float32Array(jsArray) to initialize the Float32Array from the jsArray 's contents. Try to do this rarely though. Typed arrays are very fast, but initialize very slowly. It's best to create them once and reuse them whenever possible. Once you have a Float32Array , you can pass the data down to the buffer like so: gl.bindBuffer(gl.ARRAY_BUFFER, vbo);gl.bufferData(gl.ARRAY_BUFFER, float32Data, gl.DYNAMIC_DRAW); You'll need to perform a bufferData or bufferSubData call every time the data changes. By this time the data is on the graphics card, so you only need to actually draw it: // bind the VBO to be drawn if you haven't alreadygl.bindBuffer(gl.ARRAY_BUFFER, vbo);// send the vertex data to the shader programgl.vertexAttribPointer(vertexAttributeLocation, 3, gl.FLOAT, false, 0, 0);// draw the buffergl.drawArrays(gl.POINTS, 0, float32Data.length / 3); Note that although the graphics card can hold quite a few VBOs, you should use as few of them as possible, because the more drawArrays calls you have to perform, the slower things are going to get. Indeed, if you render only a single pixel at a time in a given VBO, it's going to be too slow to run. The reason the length of the Float32Array is divided by 3 is because each single data element is a 3D (X, Y, Z) coordinate, so each data element consists of 3 float components. Note that the first argument to gl.drawArrays was gl.POINTS . This instructs the graphics card to draw a single point (by default, a single pixel in size) for each item in the array. There are other ways to draw, and if you need to fill a group of pixels, one of the other draw modes (e.g. gl.TRIANGLES ) may be more to your liking. As for lighting up specific pixels, it depends on how the shader is written, but most likely you're making use of a modelview matrix and a projection matrix. The modelview matrix represents the orientation of the camera relative to the points being drawn, and the projection matrix represents the camera dimensions (width and height, field of view, nearest and furthest visible ranges, etc). So if you want to light specific pixels, your best bet is to apply an orthographic projection matrix with a width and height equal to the width and height of the canvas; and a modelview matrix set to the identity (no transformation). In an orthographic projection, objects don't shrink as they get further away from the camera, so they're very helpful for specifying exact positions relative to the screen. Also, if you give them the proper dimensions, you can position vertices very precisely -- at specific pixels , if you wish. Different matrix libraries work in different ways, but for example, to set up an orthographic matrix in gl-matrix , you can do so like this: var ortho = mat4.ortho(left, right, bottom, top, near, far); The exact numbers depend on your preference; if you'd like to place the origin (0, 0) at the bottom-left of the canvas, you'd do so like this: var ortho = mat4.ortho(0, canvas.width, 0, canvas.height, 0.01, 200); Note that the Z value of each point still has to lie between near and far in order to be rendered, however, and the near value cannot be set to 0 . Let me know if any of this needs clarifying.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11074725', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1175802/']}
jdg_370082
stackexchange
llm_judgeable_groundtruth_similarity
845561
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Many journals require submission of a blinded version of your paper. The blinded version usually removes: the list of authors any citations to the authors' work How can I create a blinded version of my manuscript without doing this manually? Now provide the response and nothing else.
You could use the extract package to generate a separate LaTeX source file for the paper with the author list and acknowledgements automatically removed. I believe the versions package could be used to do this as well. As for blinding the citations, I think the point is to refer to your own work in a neutral and unrevealing way. Here are some examples of correct and incorrect ways to cite your own work in a blinded manuscript: Incorrect: "As I have argued elsewhere..."Corrected: "As Jones (2001) has argued..."Incorrect: "As I argue in (Jones 2001)."Corrected: "As Jones (2001) argues."Incorrect: "This argument is fleshed out in my (2001)." Corrected: "Jones (2001) makes this argument in more detail."
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/845561', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16632/']}
jdg_370083
stackexchange
llm_judgeable_groundtruth_similarity
38664
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I = imread('us-currency.png');mean = 0.5;variance = 0.5;J = imnoise(I,'gaussian', mean, variance);imshow(J); What are the effects of mean and variance on that image? Does mean increases the brightness? Does variance increases the amount of noise? Input Output Now provide the response and nothing else.
Does mean increases the brightness? As you add a constant mean to each pixels of the image you will get an image that has an overall higher average image pixel value. Since images are generally encoded with the maximum pixel value being white, you would get an image which is closer to white, and hence perceptually appears brighter. Does variance increases the amount of noise? That one deserve a little bit more background. Indeed, quoting from Wikipedia : In experimental sciences, noise can refer to any random fluctuations of data that hinders perception of an expected signal. So in that context, even adding or subtracting a constant value to the entire image could be coined as noise (especially if this makes the image too bright or too dark so as to make it harder to discern objects in the image). If on the other hand we focus our attention to what is commonly described as a "noise" effect then this typically refer to some kind of perceived "dots" that occurs due to somewhat large variations in pixel values in close proximity. Since the variance is directly linked to the variation in pixel values, it is clear that an increase of the variance would increase the amount of noise (in the sense of perceived quantity of "dots").
{}
{'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/38664', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/-1/']}
jdg_370084
stackexchange
llm_judgeable_groundtruth_similarity
43253453
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 deployed Azure function using Arm template. I need the Function Key & host Key of deployed Azure Function in Powershell.Currently I am trying to get the keys From Output Section of ARM template "outputs": {"FunctionAppName": { "type": "string", "value": "[variables('functionAppName')]"},"Key": { "type": "string", "value": "[listKeys(resourceId('Microsoft.Web/sites', '[variables('functionAppName')]'),'2015-08-01').keys]"} } I tried different combinations But it failing. Is there any way to retrieve keys in Powershell? Now provide the response and nothing else.
I got it working by using the following: "outputs": { "FunctionAppName": { "type": "string", "value": "[parameters('functionName')]" }, "Key": { "type": "string", "value": "[listsecrets(resourceId('Microsoft.Web/sites/functions', parameters('existingFunctionAppName'), parameters('functionName')),'2015-08-01').key]" }, "Url": { "type": "string", "value": "[listsecrets(resourceId('Microsoft.Web/sites/functions', parameters('existingFunctionAppName'), parameters('functionName')),'2015-08-01').trigger_url]" } } I couldn't find any examples either.But by using the above, a quickstart sample at GitHub and the documentation of resource functions along with a some trial and error, I got it to out. Please note the variables/parameters and names have been changed.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43253453', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6902938/']}
jdg_370085
stackexchange
llm_judgeable_groundtruth_similarity
49072800
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 performing the following Oracle select on sqldeveloper: select (2299) / (((2299) * 20 )/ (100 * 360)) from dual; and it is giving me 1800.000000000000000000000000000000000003 as a result instead of 1800 , why is that? and how can i fix it? Now provide the response and nothing else.
You shouldn't modify the object being passed in as a prop. Instead, you should create a new data property in the child component and initialize it with a copy of the prop object. Then, I would just use a v-model for each of the inputs in the child component and add a deep watcher to the internal value which would emit an update whenever the internal value changes. Vue.component('child', { template: '#child', props: ['value'], data() { return { val: {...this.value} }; }, watch: { val: { deep: true, handler(value) { this.$emit('input', value); } } }});new Vue({ el: '#app', data: { parentObject: {value1: "1st Value", value2: "2nd value"} }}); <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script><div id="app"> <p>Parent value: {{parentObject}}</p> <child v-model="parentObject"></child></div><template id="child"> <div> <input type="text" v-model="val.value1"> <input type="text" v-model="val.value2"> </div></template> I made a shallow copy of the prop in my example ( {...this.value} ), because the object doesn't have any nested properties. If that wasn't the case, you might need to do a deep copy ( JSON.parse(JSON.stringify(this.value)) ).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49072800', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4899050/']}
jdg_370086
stackexchange
llm_judgeable_groundtruth_similarity
418354
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: My server LAN IP is 192.168.1.1 and there is an intranet web server on 192.168.1.2The OpenVPN daemon is configured to give clients 192.168.2.* addresses. There is push "route 192.168.1.0 255.255.255.0" line in the config which I expect to enable the VPN clients to access the entire 192.168.1.0 net, but they can only access 192.168.1.1 - the VPN server itself. I've tried enabling net.ipv4.ip_forward = 1 in /etc/sysctl.conf but this doesn't help. Any ideas? PS: The server runs Ubuntu 12.04. PPS: OpenVPN runs in tun mode over UDP. Now provide the response and nothing else.
Make sure that the ip forwarding is acutally enabled echo 1 > /proc/sys/net/ipv4/ip_forward Also, in order for route push to work, the servers on the inside also needs to know the route to your OpenVPN client IP address. So they will need to know the route to 192.168.2.0/24 You can most likely make iptables do the routing via masquerade using /sbin/iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE/sbin/iptables -A FORWARD -i eth0 -o tun0 -m state --state RELATED,ESTABLISHED -j ACCEPT/sbin/iptables -A FORWARD -i tun0 -o eth0 -j ACCEPT
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/418354', 'https://serverfault.com', 'https://serverfault.com/users/42777/']}
jdg_370087
stackexchange
llm_judgeable_groundtruth_similarity
60451458
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: In the summer of last year I started refactoring my Android application with Android's architecture components (Room, ViewModel, LiveData). I have two Room repositories, one of them is accessed by multiple views (fragments) of the application. Because of that I used an AndroidViewModel , which has access to this repository and which is initialized in my MainActivity . new ViewModelProvider(this).get(CanteensViewModel.class); In my two fragments I accessed this ViewModel by new ViewModelProvider(getActivity()).get(CanteensViewModel.class); Until yesterday that worked perfectly. But then I updated my dependencies and since androidx.lifecycle version 2.2.0 this does not work anymore. I always get an exception (siehe EDIT 2): Caused by: java.lang.InstantiationException: java.lang.Class<com.(...).CanteensViewModel> has no zero argument constructor So I checked the docs and as I understood right I should/could now use ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication()).create(CanteensViewModel.class); to get my ViewModel. But with this approach I can't add the owner (parameter of ViewModelProvider s constructor), which results in the problem, that I can't really access the ViewModel I created in the Activity from inside my fragments. Is there a way I can access the Activity's ViewModel from inside the fragments? Or would it be better to recreate the ViewModel in each fragment by ViewModelProvider.AndroidViewModelFactory.getInstance(getActivity().getApplication()).create(CanteensViewModel.class); instead of creating it inside the Activity? EDIT: It seems to work, when I use the other constructor of ViewModelProvider , where a AndroidViewModelFactory is the second parameter. new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(CanteensViewModel.class); Doing this in my MainActivity I can access the CanteensViewModel in my Fragment via new ViewModelProvider(requireActivity()).get(CanteensViewModel.class); EDIT 2 Stacktrace for above mentioned exception: 2020-02-28 14:30:16.098 25279-25279/com.pasta.mensadd E/AndroidRuntime: FATAL EXCEPTION: main Process: com.pasta.mensadd, PID: 25279 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pasta.mensadd/com.pasta.mensadd.ui.MainActivity}: java.lang.RuntimeException: Cannot create an instance of class com.pasta.mensadd.ui.viewmodel.CanteensViewModel at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2795) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2873) at android.app.ActivityThread.-wrap11(Unknown Source:0) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1602) at android.os.Handler.dispatchMessage(Handler.java:106) at android.os.Looper.loop(Looper.java:164) at android.app.ActivityThread.main(ActivityThread.java:6543) at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807) Caused by: java.lang.RuntimeException: Cannot create an instance of class com.pasta.mensadd.ui.viewmodel.CanteensViewModel at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:221) at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187) at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150) at com.pasta.mensadd.ui.MainActivity.onCreate(MainActivity.java:70) at android.app.Activity.performCreate(Activity.java:7023) at android.app.Activity.performCreate(Activity.java:7014) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1215) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2748) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2873)  at android.app.ActivityThread.-wrap11(Unknown Source:0)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1602)  at android.os.Handler.dispatchMessage(Handler.java:106)  at android.os.Looper.loop(Looper.java:164)  at android.app.ActivityThread.main(ActivityThread.java:6543)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)  Caused by: java.lang.InstantiationException: java.lang.Class<com.pasta.mensadd.ui.viewmodel.CanteensViewModel> has no zero argument constructor at java.lang.Class.newInstance(Native Method) at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:219) at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:187)  at androidx.lifecycle.ViewModelProvider.get(ViewModelProvider.java:150)  at com.pasta.mensadd.ui.MainActivity.onCreate(MainActivity.java:70)  at android.app.Activity.performCreate(Activity.java:7023)  at android.app.Activity.performCreate(Activity.java:7014)  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1215)  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2748)  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2873)  at android.app.ActivityThread.-wrap11(Unknown Source:0)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1602)  at android.os.Handler.dispatchMessage(Handler.java:106)  at android.os.Looper.loop(Looper.java:164)  at android.app.ActivityThread.main(ActivityThread.java:6543)  at java.lang.reflect.Method.invoke(Native Method)  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)  ``` Now provide the response and nothing else.
So I checked the docs and as I understood right I should now use ViewModelProvider.AndroidViewModelFactory.getInstance( this.getApplication()).create(CanteensViewModel.class); Please share a link to this "docs" you mentioned, because this is NOT the first time I see this code, and yet it was equally wrong in both cases. The code you actually should be using is new ViewModelProvider(this).get(CanteensViewModel.class); Is there a way I can access the Activity's ViewModel from inside the fragments? Or would it be better to recreate the ViewModel in each fragment by new ViewModelProvider(requireActivity()).get(CanteensViewModel.class); Consider also receiving a SavedStateHandle as an argument in your AndroidViewModel , and not only Application . If you ask me, apparently the removal of ViewModelProviders.of() was an API mistake, but this is what we have now. EDIT: With the help of the provided stack trace, I can finally somewhat figure out what's going on. at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.java:219) We are using NewInstanceFactory as the default. What does default NewInstanceFactory do? It just calls no-arg constructor if available. Wait, what? Isn't it supposed to fill in the Application for an AndroidViewModel ? Theoretically yes, as long as you got the original default ViewModelProvider.Factory , but this is not the one! Why is it not the one that can fill in AndroidViewModel? See this commit Add default ViewModel Factory interfaceUse a marker interface to allow instances ofViewModelStoreOwner, such as ComponentActivityand Fragment, to provide a defaultViewModelProvider.Factory that can be used witha new, concise ViewModelProvider constructor.This updates ComponentActivity and Fragment touse that new API to provide anAndroidViewModelFactory by default. It updatesthe 'by viewModels' Kotlin extensions to usethis default Factory if one isn't explicitlyprovided. Also ComponentActivity:+ @NonNull+ @Override+ public ViewModelProvider.Factory getDefaultViewModelProviderFactory() {+ if (getApplication() == null) {+ throw new IllegalStateException("Your activity is not yet attached to the "+ + "Application instance. You can't request ViewModel before onCreate call.");+ }+ return ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication());+ }+ And most importantly public ViewModelProvider(@NonNull ViewModelStoreOwner owner) { this(owner.getViewModelStore(), owner instanceof HasDefaultViewModelProviderFactory ? ((HasDefaultViewModelProviderFactory) owner).getDefaultViewModelProviderFactory() : NewInstanceFactory.getInstance());} This means that you get the default view model provider factory that can properly set up AndroidViewModel if the ViewModelStoreOwner implements HasDefaultViewModelProviderFactory . Theoretically, ComponentActivity is indeed a HasDefaultViewModelProviderFactory ; and AppCompatActivity extends from ComponentActivity . In your case however, that doesn't seem to be the case. For some reason, your AppCompatActivity is not HasDefaultViewModelProviderFactory . I think the solution to your problem is to update Lifecycle to 2.2.0, and ALSO update implementation 'androidx.core:core-ktx to at least 1.2.0. (specifically at least AndroidX-Activity 1.1.0, and AndroidX-Fragment 1.2.0).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60451458', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12979097/']}
jdg_370088
stackexchange
llm_judgeable_groundtruth_similarity
16775379
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given the list a = [6, 3, 0, 0, 1, 0] What is the best way in Python to return the list b = [1, 1, 0, 0, 1, 0] where the 1's in b correspond to the non-zero elements in a. I can think of running a for loop and simply appending onto b, but I'm sure there must be a better way. Now provide the response and nothing else.
List comprehension method: a = [6, 3, 0, 0, 1, 0]b = [1 if i else 0 for i in a]print b>>> [1, 1, 0, 0, 1, 0] Timing mine, Dave's method and Lattyware's slight alteration : $ python3 -m timeit -s "a = [6, 3, 0, 0, 1, 0]" "[1 if i else 0 for i in a]"1000000 loops, best of 3: 0.838 usec per loop$ python3 -m timeit -s "a = [6, 3, 0, 0, 1, 0]" "[int(i != 0) for i in a]"100000 loops, best of 3: 2.15 usec per loop$ python3 -m timeit -s "a = [6, 3, 0, 0, 1, 0]" "[i != 0 for i in a]"1000000 loops, best of 3: 0.794 usec per loop Looks like my method is twice as fast ... I am actually surprised it is that much faster. Taking out the int() call, however, makes the two essentially the same - but leaves the resulting list full of Booleans instead of Integers (True/False instead of 1/0)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16775379', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2186160/']}
jdg_370089
stackexchange
llm_judgeable_groundtruth_similarity
22523
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: If we have function $y=L(x_1,x_2,x_3,...,x_n)$, and function $z=R(x_1,x_2,x_3,...,x_n)$. How to compute the derivative $\frac{dy}{dz}$? Shall I do $\frac{dy}{dz} = \sup_{g\in \Re^n}\frac{\bigtriangledown_x L \cdot g}{\bigtriangledown_x R \cdot g}$? Is there any mathematical term associated with this kind of derivatives? Now provide the response and nothing else.
There is no reason to expect that such a thing as $dy/dz$ exists. If you rephrase everything in terms of differentials, you have $$dy=\sum_{i=1}^n\frac{\partial L}{\partial x_i}dx_i,\quad dz=\sum_{i=1}^n\frac{\partial R}{\partial x_i}dx_i$$ where $dx_1,\ldots,dx_n$ are linearly independent, and so you find $dy=a\, dz$ if and only if $\nabla L=a\nabla R$. But normally, the two gradient won't be parallel, so you cannot define $dy/dz$. You can do so in any given direction, though: Your fraction $(\nabla L\cdot g)/(\nabla R\cdot g)$ is a perfectly good expression for $dy/dz$ as measured in the direction given by $g$ .
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/22523', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2013/']}
jdg_370090
stackexchange
llm_judgeable_groundtruth_similarity
9551230
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 going to get a element from a html-string with jQuery, but I always get an undefined in my console.My String is: <td class="test">asd</td><td class="second">fgh</td><td class="last">jkl</td> and I want to get the td.test. I've tested: console.log($('.test', '<td class="test">asd</td><td class="second">fgh</td><td class="last">jkl</td>').innerHTML);console.log($('.test', '<td class="test">asd</td><td class="second">fgh</td><td class="last">jkl</td>').html());console.log($('.test', '<td class="test">asd</td><td class="second">fgh</td><td class="last">jkl</td>').first().innerHTML); and some more, but nothing works :/ Does anyone know a solution for my problem? Now provide the response and nothing else.
First, use jQuery.parseHTML to parse the HTML into an array of elements; then you’ll be able to convert it to a jQuery collection and use filter to restrict the collection to elements matching a selector. var html = '<td class="test">asd</td>' + '<td class="second">fgh</td>' + '<td class="last">jkl</td>';var text = $($.parseHTML(html)).filter('.test').text();console.log(text); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9551230', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1126207/']}
jdg_370091
stackexchange
llm_judgeable_groundtruth_similarity
47024826
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 found many questions and tutorials before finally putting this all together. Wanted to document it so somebody else can save many hours of frustration. I am trying to get a private git repository on BitBucket to work with Spring Boot Config Server using deploy keys and have it run in Docker. I am running into many issues. How to actually configure using the application.yml files. I cant seem to figure out where I should put the SSH info. All tutorials seem to be for https. How to provide the private key to the configuration. For Dev the syntax for inline in YML is a pain. For production, you have to provide it via an environment variable, which is another syntax chore. I keep getting an error that the private key is invalid. How to get the Docker container to trust the host key without that pesky "do you trust this guy" prompt. There seems to be several ways to make this work, but only one that worked for me. Now provide the response and nothing else.
First piece is the configuration. You want to ignore the standard private key and use one provided as an environment variable. (SSH_KEY). Also, the git repo is an EV (GIT_URL) but you can hardcode if you want. spring: cloud: config: server: git: uri: ${GIT_URL} ignore-local-ssh-settings: true private-key: ${SSH_KEY} Part 2 is tricky. For Dev, you want the key inline, so you need to use a pipe to prefix the block in YAML. (Note this key is throw away as in I just generated it and have now thrown it away) private-key: | -----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAszmCR06LVHk/kNYV6LoYgEfHlK4rp75sCsRJ7rdAbWNED+yB bneOm5gue0LGIhT7iTP9D7aN6bKVHv1SBconCA7Pa2NMA9epcMT5ecJc8ndpZOFn iqM77jmMMPvj8EIC06w5oK5zoYwpGotYQFHllf8M+20HtW2fZdPYAYwLcVdmc5tI vLoS+10qw5D3X9zrwk2Cbt37Iqnz1cHOQq+g7sxgVgt18aIKKeg0JslaGqSlWMoT ICUMHj89E4BMHj8ND8otSXHL+VhN+ghd7w1MpckxLWBsNs1+G1FuiJEVAtRq/j+8 SOilxgifvI1LqpZ5kO01XFlmkcuN4NMT03qpcwIDAQABAoIBAB5oQGk2sz7mv1kk aV0tzaBeDUd1cWSpUw1UljKRFrY4ZEDLYH5MfH57iE9TWehIZRC3KFU1JMikitZS JktjK9IbKSfQFgKE4XOHh8gXqMteZRw/feCwpydYzic1ZUvK903QZ4qSbn3XGNYv FA79lhUny50Qt4EZkzSkh35js0FMSR9VmyXENxN6IgXUZyoaNAATr44Vkd488BY2 7PvdOniemo8/8p4Ij0Aq9Q7rOtm77ZXjyFRX5mDTi2ndSllMEhVcWXHSii+ukbvF 117Ns+8M7VWroNfRzI+Ilm/Xz/ePOLlNoYcY0h5+QM9vMPTX9Cpl5WofgOMK1sKd mSdI4ukCgYEA12kcu0aDyIrEPHcyaT9izSFply0Uon2QKS9EQn6cr83vaEGViamh f5q1coYouGnsLfbgKolEMKsYtbmJvInPFDCdc2x0Fmc207Wp1OECsN+HwElEXkrs uPDpGQgs5odjN5Grue9837920oG3UBBdVDAKly2dTOcvoWW+88seFSUCgYEA1P7f p78HDMQ8zTy5+3Rd4+lmJjPsY618XxSQ80j8Elrhi/DyTMA0XGc5c3cKRPmSj+JD GN34WQbw7JO2mKM7YJs+tkSBeTKce8F3cZQy1jy3LNHCtfXylOxmxOFKynV5h2b/ jno+pGdmAPK5yvnGASd2eujtzt+AL07XiD2LnLcCgYEAsFRz131WfP/SuShdlLf1 WbODKuQVIxojuwLdHo1kF6k805v0G/dGoxzycOgPRz41vj57q3Yn4qr8FC3n6PTq FT3idUyPDpO41r67Ye469KxWBHo1Q/aTJqTWOs5tatvixOcyqoa3MrUZQCI8+4YZ z8Nvt+b3/66zV6vhDtHzMx0CgYAvWW2M0+mUS/ecRHivzqGkrdkYewh87C8uz9qd SsdGqU9kla63oy7Ar+3Unkz5ImYTeGAkIgw4dlOOtBOugPMNOdXKHRaPQ9IHrO2J oUFf4OVzoDnhy4ge1SLPd6nxsgXPNPVwzfopABdr9Ima9sWusgAjuK5NA+ByI9vE HLJxpwKBgQCTM938cdx457ag1hS6EaEKyqljS1/B8ozptB4cy3h0hzw0crNmW84/ 1Lt9MJmeR4FrWitQkkVLZL3SrYzrP2i+uDd4wVVD5epvnGP/Bk6g05/eB9LgDRx/ EeBgS282jUBkXZ6WpzqHCcku3Avs3ajzsC1WaEYx0tCiBxSkiJlaLQ== -----END RSA PRIVATE KEY----- On the production front, you need to use a bash variable at the command prompt to store your key before you pass it to the Docker command that runs your container. Example: $ pem=$( cat path_to_key )$ docker run -e "SSH_KEY=$pem" configserver At this point you should have the application taken care of. Now all you need is to get past the ssh host not trusted problem. For this, add these lines in your Dockerfile. Replace "bitbucket.org" with whatever host you want. These commands create the ssh config directory, fix the permissions, and then create and populate the knownhosts file. RUN mkdir -p /root/.sshRUN chmod 700 /root/.sshRUN ssh-keyscan bitbucket.org > /root/.ssh/known_hosts
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47024826', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/794274/']}
jdg_370092
stackexchange
llm_judgeable_groundtruth_similarity
1833696
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 $UV$ be a subgroup of $G$ and $P$ is a Sylow $p$-subgroup of $G$. Suppose that $P \cap U \in \operatorname{Syl}_p(U)$ and $P \cap V \in \operatorname{Syl}_p(V)$. I need to show that $P\cap UV \in \operatorname{Syl}_p(UV)$ $P \cap UV$ is clearly a $p$-subgroup of $UV$. Also $(P \cap U)(P \cap V) \subseteq P \cap UV$. We need to show that it is a maximal $p$-subgroup of $UV$ but I'm not sure how to proceed Now provide the response and nothing else.
We use a counting argument to show that indeed $(P \cap U)(P \cap V)=P \cap UV$. Observe that $|(P\cap U)(P\cap V)|=\frac{|P\cap U| \cdot|P\cap V|}{|P\cap U\cap V|}=\frac{|U|_p \cdot |V|_p}{|P \cap U \cap V|}$, where the index $p$ denotes the largest power of $p$, dividing the order of the group between its $|\cdot|$. Now, $|P \cap U \cap V| \leq |U \cap V|_p$, since $P \cap U \cap V$ is a $p$-subgroup of $U \cap V$. Hence, $$|(P\cap U)(P\cap V)| \geq \frac{|U|_p \cdot |V|_p}{|U \cap V|_p}=\left(\frac{|U| \cdot |V|}{|U \cap V|}\right)_p=|UV|_p.$$ Since as a set $(P \cap U)(P \cap V) \subseteq P \cap UV$, and $|P \cap UV| \leq |UV|_p$, this forces $(P \cap U)(P \cap V)=P \cap UV$, and $P \cap UV \in Syl_p(UV)$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1833696', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/296345/']}
jdg_370093
stackexchange
llm_judgeable_groundtruth_similarity
28069
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: Water in my electric kettle makes the most noise sixty to ninety seconds before the water comes to a full boil. I have been fooled many times by the noisy kettle, only to discover that the water was not yet hot enough for tea. The kettle is only at a full boil after the noise has subsided . I have noticed the same phenomenon with many other kettles, including conventional kettles on kitchen ranges; it is not a peculiarity of this electric kettle. Why does the boiling become quieter as the water reaches full boil? Now provide the response and nothing else.
There are three phenomena that occur before vigorous boiling of water that produce sound. 1) Air dissolved in water on heating forms small air bubbles at the bottom of the container. These air bubbles get released from the bottom of the container on reaching a sufficient size. The process of release produces a sound of frequency ~ 100 Hz. 2) On boiling, small vapor bubbles get produced at the bottom of the container and also produce sound of ~ 100 Hz on release. However, they cool down before they reach the surface of water and collapse. This collapsing produces a sound of frequency ~ 1 kHz. 3) Collapsing vapor bubbles agitate the water to release small micro air bubbles from water and also from the air trapped in the vapor bubble. This production of micro air bubbles produces a sound of ~ 35–60 kHz. I guess you were talking about either the first or the second case. Both of them occur before you observe vigorous boiling of water and you can hear them. There was an interesting problem posed at APHO 2008 which is the same as your question which estimates the frequencies I just quoted. It also contains references to the experimental measurement of these frequencies. I hope you will find it interesting to solve it than me answering your question: Theoretical Problem 1. Tea Ceremony and Physics of Bubbles You can also find the solutions here in case you need help on this: Theoretical Solution 1, 9 th Asian Physics Olympiad
{}
{'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/28069', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/9062/']}
jdg_370094
stackexchange
llm_judgeable_groundtruth_similarity
27154996
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 making a grid-style game/simulation based on bugs "sensing" and eating food. I am using a gridPane (called worldGrid ) of labels to show the grid of bugs and food. This is obviously going to be constantly updated when a bug moves cells towards food etc. I currently have a function updateGrid(int col, int row, String cellContent) which I want to replace the label at [row,col] with a label that has the new text in cellContent. I have the follow which works worldGrid.add(new Label(cellContent), row,col); however im worried that that is just adding a label on top of the current label and obviously over 100 iterations of the simulation thats not ideal. I have tried this before adding the label: worldGrid.getChildren().remove(row,col); However I then get an IllegalArgumentException when trying to do the add line. Any ideas on how to do this? Or even better, any ideas on how best to show a constantly changing grid that will eventually use sprites instead of text? Now provide the response and nothing else.
The col/row provided by grid.add(node, col, row) (ATTENTION first comes col!) is only a layout constraint. This does not provide any means to access columns or rows like slots in a 2-dimensional array. So to replace a node, you have to know its object itself, e.g. remember them in a separate array. Then you are able to call getChildren().remove(object)... e.g.: GridPane grid = new GridPane();Label first = new Label("first");Label second = new Label("second");grid.add(first, 1, 1);grid.add(second, 2, 2);second.setOnMouseClicked(e -> { grid.getChildren().remove(second); grid.add(new Label("last"), 2, 2);});box.getChildren().addAll(grid);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27154996', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2126847/']}
jdg_370095
stackexchange
llm_judgeable_groundtruth_similarity
5581894
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 anyone know how to match even numbers and odd numbers of letter using regexp in mysql? i need to match like a even number of A's followed by an odd number of G's and then at least one TC? For example: acgtccAAAAGGGTCatg would match up. It's something for dna sequencing Now provide the response and nothing else.
An even number of A's can be expressed as (AA)+ (one or more instance of AA ; so it'll match AA, AAAA, AAAAAA...). An odd number of Gs can be expressed as G(GG)* (one G followed by zero or more instances of GG , so that'll match G, GGG, GGGGG...). Put that together and you've got: /(AA)+G(GG)*TC/ However, since regex engines will try to match as much as possible, this expression will actually match a substring of AAAGGGTC (ie. AAGGGTC )! In order to prevent that, you could use a negative lookbehind to ensure that the character before the first A isn't another A : /(?<!A)(AA)+G(GG)*TC/ ...except that MySQL doesn't support lookarounds in their regexes. What you can do instead is specify that the pattern either starts at the beginning of the string ( anchored by ^ ), or is preceded by a character that's not A: /(^|[^A])(AA)+G(GG)*TC/ But note that with this pattern an extra character will be captured if the pattern isn't found at the start of the string so you'll have to chop of the first character if it's not an A.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5581894', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/696891/']}
jdg_370096
stackexchange
llm_judgeable_groundtruth_similarity
1962718
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been studying Maven in my free time over the last several days but can't seem to figure out how to organize a project so that the JOGL libraries are used. I would preferably like the following: Automatically download, if necessary, the OS-specific JOGL zip file from here (contains 4 jar files and some native library files (.so/.dll)); or depend on a Maven project which is a wrapper of one of the files. Unzip that zip file appropriately, so that: the jar files are added to the classpath and deployed as necessary, and the native library files are added to the final jar file (would this enable them to be automatically used, or would I need something more involved?) I think part of my problem is that I don't fully understand the use of JOGL, where to place the native libraries when running the code, etc. I need to go back to the basics and write a JOGL hello world, compile it from the command line and run it from the command line to see exactly what it requires as far as directory placement of the native libraries; I may go do that right now, actually. With item 1, I've found some OS-specific features; Maven profiles can be activated based on properties of the system, which include the operating system. So then I could activate a Windows profile which has a dependency of the Windows-specific JOGL library, same for the Linux, and both having a 64-bit alter ego. (Activation official docs / unofficial docs .) I have tried creating a Maven repository based on a JOGL jar file, and then adding the JOGL jar file project as a dependency of my project; the dependency is downloaded, but not used. I have no idea where the jar file goes or how to use it, unpack it, etc. Here is the command I used. So, in short: JOGL consists of four .jar files and some native libraries. How can I integrate those files into my Maven project so that I can write a JOGL application with Maven handling my build process? Furthermore, how can I use a different set of files depending on the operating system, because of course the native libraries and even the .jar files differ between Windows, Linux and Mac. Now provide the response and nothing else.
When dealing with JNI and Maven, Projects With JNI is the reference one should start with. It covers a lot more than your current problem (which is "just" using a library that relies on JNI and native libraries) but, well, he who can do more can do less. If you read it carefully, you'll see that one solution to use JNI libraries is to bundle them in architecture specific JARs so that you can depend on them like any other dependency from a Maven point of view. This is actually how JOGL version 1.1.1 is packaged in http://download.java.net/maven/2/net/java/dev/jogl/ , there is one JAR artifact with the Java classes and several architecture specific JARs artifacts with the native libraries. JNI library archived within the jar The solution I ended up using was tostore the compiled jni library in thejar alongside the class files. This means either cross-compiling forall possible architectures, or moresimply, having a different jar foreach architecture. This latter fitsquite well with our setup - wherealmost all of our machines areLinux-i386, with a smattering of win32boxes. Sadly System.load() can't cope withloading libraries from within a jar,so we'll therefore need a customloader which extracts the library to atemporary file at runtime; this isobviously achievable, however. Then, as explained, the idea is to use a custom library loader to load the native library. The good news is that such a loader is "provided" as explained below. Library loader We now have our JNI library on theclass path, so we need a way ofloading it. I created a separateproject which would extract JNIlibraries from the class path, thenload them. Find it at http://opensource.mxtelecom.com/maven/repo/com/wapmx/native/mx-native-loader/1.2/ .This is added as a dependency to thepom, obviously. To use it, call com.wapmx.nativeutils.jniloader.NativeLoader.loadLibrary(libname) .More information is in the javadoc for NativeLoader . I generally prefer to wrap such thingsin a try/catch block, as follows: public class Sqrt { static { try { NativeLoader.loadLibrary("sqrt"); } catch (Throwable e) { e.printStackTrace(); System.exit(1); } } /* ... class body ... */} We should now be at the point whereour junit tests work from maven; a mvntest should work! It should also workfine from an IDE. Now, to answer your questions, how to: Automatically download, if necessary, the OS-specific JOGL zip file from here (contains 4 jar files and some native library files (.so/.dll)); or depend on a Maven project which is a wrapper of one of the files. Sadly, JOGL 2.0 jars aren't available in the Maven repository of java.net so you'll have to deal with that and either make them available in a private repository or install them manually in the local repository of each developer. To do so, use mvn install:install-file as documented in the Guide to installing 3rd party JARs (and not mvn deploy:deploy-file as you did, this goal is used to install artifacts to a remote repository). Personally, I would download JOGL 2.0 ZIPs from the URL you provided, package it as they did with JOGL 1.1.1 (one Java JAR and several specific JARs for native libraries) and install the JARs in each local repository for now. Then, declare a standard dependency on the Java artifact and, indeed, use profiles for the architecture specific dependency. Something like this: <project> ... <dependencies> <dependency> <groupId>net.java.dev.jogl</groupId> <artifactId>jogl</artifactId> <version>2.0-beta10</version> </dependency> ... </dependencies> ... <profiles> <profile> <id>linux-i586</id> <activation> <os> <arch>i386</arch> <family>unix</family> <name>linux</name> </os> </activation> <dependencies> <dependency> <groupId>net.java.dev.jogl.jogl-linux-i586</groupId> <artifactId>jogl-linux-i586</artifactId> <version>2.0-beta10</version> </dependency> </dependencies> </profile> ... </profiles> ...</project> Don't forget to add the repository required for the custom library loader and the dependency: <project> <repositories> <repository> <id>opensource.mxtelecom.com</id> <url>http://opensource.mxtelecom.com/maven/repo</url> </repository> ... <repositories> ... <dependencies> <dependency> <groupId>com.wapmx.native</groupId> <artifactId>mx-native-loader</artifactId> <version>1.2</version> </dependency> ... </dependencies> ...</project> Regarding the second part of your question: Unzip that zip file appropriately, so that (...) As I explained, you actually won't depend on ZIP files but on JARs and you won't need to uncompress them neither during development nor to distribute your project. For the distribution, you'll just need to create a jar including the dependencies. This can be done with the maven-assembly-plugin. See this answer for example for more details on this.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1962718', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/47493/']}
jdg_370097
stackexchange
llm_judgeable_groundtruth_similarity
191456
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is the following (decimal) number irrational? 0.10100100010000100000100000010000000100... etc. My intuition tells me it is irrational. My informal "proof" is simply that it doesn't contain a repeating set of digits. For irrationality, is it both a necessary and sufficient condition that the digits never revert to a repeating sequence? Is there a more formal proof for this case? Now provide the response and nothing else.
A formal justification of your informal proof can be achieved by noting that in the process of long division, the fact that you have a finite number of possible remainders guarantees that eventually a remainder will be repeated. That is, for any rational number its decimal expansion becomes periodic.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/191456', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/39550/']}
jdg_370098
stackexchange
llm_judgeable_groundtruth_similarity
14057780
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Ok so this is really getting frustrated for me here, first of all if my question framing is wrong please do edit it(if you think so)...and ok, as my screens will explain you, but still I would like that my element should stay in a specific shape and not to rotate along with the animation, am missing something really stupid thing? What I Want : What's Happening : jQuery Solutions Are Welcomed (But I Would Love CSS3 Solutions) Note: Don't go on the element's opacity, 1 is made using Paint and other with Photoshop, What Matter's Is Square Should Rotate As Square Shape HTML <div><span></span></div> CSS @keyframes round_round { from { transform: rotate(0deg); } to { transform: rotate(360deg); }}div { width: 50px; height: 50px; animation: round_round 3s linear infinite; margin: 50px auto 0; transform-origin: 50% 150px; background-color: #8FC1E0;}span { display: inline-block; margin: 5px; height: 5px; width: 5px; background: #c00000;} Demo Now provide the response and nothing else.
Position it absolutely, don't change the transform-origin , leave it at 50% 50% . Then simply rotate the element, translate it by the value of the radius and then cancel the first rotation - you can see how chaining transforms works here . @keyframes rot { 0% { transform: rotate(0deg) translate(150px) rotate(0deg); } 100% { transform: rotate(360deg) translate(150px) rotate(-360deg); }} demo
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14057780', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1542290/']}
jdg_370099
stackexchange
llm_judgeable_groundtruth_similarity
21387504
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 understand that in linux cmake, make and make install can be combined together to produce a release. For example: cmake -DCMAKE_BUILD_TYPE=Release ..makemake install In windows, however, I cannot find similar commands that can do the same job. Usually, what is done is to build a .sln project first if Visual Studio is used, after that compile the .sln project and in the end run the INSTALL project. Will it be possible to make a release with several commands as it has been done in Linux. Many thanks. Now provide the response and nothing else.
You can use msbuild instead of make: cmake -G"Visual Studio 12" ..msbuild /P:Configuration=Release INSTALL.vcxproj or you could use CMake's --build argument: cmake -G"Visual Studio 12" ..cmake --build . --target INSTALL --config Release If you need the equivalent of the make command with no args (i.e. make all ) you would build the ALL_BUILD target as well, but this is built as part of the INSTALL target anyway.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21387504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1264018/']}
jdg_370100
stackexchange
llm_judgeable_groundtruth_similarity
48616351
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My Controller class is below. @Controllerpublic class app { @GetMapping(path = "/") public @ResponseBody String hello() { return "Hello app"; }} It works fine when I navigate through url. But when this below code is added it says "Could not autowire. No beans of 'NoteRepository' type found" . @Autowired NoteRepository noteRepository; // Create a new Note @PostMapping("/notes") public Note createNote(@Valid @RequestBody Note note) { return noteRepository.save(note); } App controller class is in the same package where main class(which run the application) is. but when we add above code to a controller in different package it doesn't show error . but it doesn't work when we navigate through url even a simple get method. My main class is below. @SpringBootApplication@EnableJpaAuditingpublic class CrudApplication { public static void main(String[] args) { SpringApplication.run(CrudApplication.class, args); }} My Repository class is @Repositorypublic interface NoteRepository extends JpaRepository<Note, Long> {} My project structure I want to find solution to: Inject an instance of NoteRepository . I always get the message "Could not autowire. No beans of type found" error. Spring cannot inject it, doesn't matter if the interface is in the same or a different package. I am not able to run methods in a controller( MyController ) that are located in a different package than application entry point. Now provide the response and nothing else.
The main symptom is this: App controller class is in the same package where main class(which run the application) is. but when we add above code to a controller in different package it doesn't show error. but it doesn't work when we navigate through url even a simple get method. By default, Spring Boot application will only auto discover beans declared in the same package than the main class. For beans that are in a different package, you need to specify to include them. You can use @ComponentScan for this. package foo.bar.main;//import statements....//this annotation will tell Spring to search for bean definitions//in "foo.bar" package and subpackages.@ComponentScan(basePackages = {"foo.bar"})@SpringBootApplication@EnableJpaAuditingpublic class CrudApplication { public static void main(String[] args) { SpringApplication.run(CrudApplication.class, args); }}package foo.bar.controller;//import statements....//since @ComponentScan, now this bean will be discovered@Controllerpublic class app { @GetMapping(path = "/") public @ResponseBody String hello() { return "Hello app"; }} For Spring Data to recognize which repositories should create, you should add @EnableJpaRepositories annotation to your main class. Also, in order for Spring Data and the JPA implementation to scan the entities, add @EntityScan : @ComponentScan(basePackages = {"foo.bar"})@SpringBootApplication@EnableJpaAuditing@EnableJpaRepositories("your.repository.packagename")@EntityScan("your.domain.packagename")public class CrudApplication { //code...}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48616351', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4991516/']}
jdg_370101
stackexchange
llm_judgeable_groundtruth_similarity
441400
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In ZFC, the axiom of regularity is used to prove that every set is an element of some stage of the cumulative hierarchy. The index of the least such stage is, by definition, the rank of that set. Now suppose we're working in ZFC minus Regularity. Can this idea just become a definition? Like, what happens if we define that a set is ranked iff its an element of some stage of the cumulative hierarchy? I imagine that we'd be able to prove the axiom of regularity relativized to ranked sets. Suppose this idea works. Then, we'd like a nice characterization of the property of being ranked that can be used before the ordinals are even in place, because, for example, if we define $\mathrm{S}(x) := x \cup \{x\},$ well it would be nice to be able to prove that if $x$ is ranked, then $\mathrm{S}(x)$ is distinct from $x$, and that $\mathrm{S}(x)$ is also ranked. So I'm curious as to whether there's a nice characterization of the property of being ranked that does not rely on the ordinals. e.g. does 'no infinite descending membership chains' do the trick? Now provide the response and nothing else.
The usual formulation of the axiom of regularity actually contains the essence of a definition of "ranked" that works in the absence of that axiom. A set $x$ is ranked iff every set $u$ that has $x$ as a member also has a minimal member (i.e., a member $y\in u$ such that $y\cap u=\varnothing$). It is not hard to show that this notion of "ranked" is equivalent to being in some stage of the cumulative hierarchy. Note, though, that when you define the cumulative hierarchy, you must first define the notion of "ordinal" in a way that ensures that the ordinals are well-ordered. "Transitive set of transitive sets" won't do, though it becmes OK if you add that ordinals should be ranked in the sense that I defined above. With the definition of "ranked" that I suggested above, it is fairly easy to prove, in ZFC without regularity, that all the ZFC axioms (including regularity) are true when restricted to ranked sets. I believe this is the simplest way to prove the relative consistency of the axiom of regularity.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/441400', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/42339/']}
jdg_370102
stackexchange
llm_judgeable_groundtruth_similarity
1402770
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 ASP.NET MVC 1.0, there is a new feature for handling cross site request forgery security problem: <%= Html.AntiForgeryToken() %>[ValidateAntiForgeryToken]public ViewResult SubmitUpdate(){ // ... etc} I found the token generated in html form keep changing every time a new form is rendered. I want to know how these token is generated? And when use some software to scan this site, it will report another security problem: Session fixed. Why? Since the token keep changed, how can this problem come ? And there is another function, that is "salt" for the antiForgeryToken , but I really know what this used for, even through we don't use "salt" to generate the token, the token will changes all the time, so why have such function? Now provide the response and nothing else.
Lots of info on the AntiForgeryToken here: http://blog.codeville.net/2008/09/01/prevent-cross-site-request-forgery-csrf-using-aspnet-mvcs-antiforgerytoken-helper/ This is to prevent a Cross-Site Request Forgery (CSRF). It's pretty standard behavior to click 'Save' sumbit a form and perform some action on the server, i.e. save a user's details. How do you know the user submitting the form is the user they claim to be? In most cases you'd use some cookie or windows based auth. What if an attacker lures you to a site which submits exactly the same form in a little hidden IFRAME? Your cookies get submitted intact and the server doesn't see the request as any different to a legit request. (As gmail has discovered: http://www.gnucitizen.org/blog/google-gmail-e-mail-hijack-technique/ ) The anti-forgery token prevents this form of attack by creating a additional cookie token everytime a page is generated. The token is both in the form and the cookie, if the form and cookie don't match we have a CSRF attack (as the attacker wouldn't be able to read the anti-forgery token using the attack described above). And what does the salt do, from the article above: Salt is just an arbitrary string. A different salt value means a different anti-forgery token will be generated. This means that even if an attacker manages to get hold of a valid token somehow, they can’t reuse it in other parts of the application where a different salt value is required. Update: How is the token generated? Download the source , and have a look at the AntiForgeryDataSerializer, AntiForgeryData classes.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1402770', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/140899/']}
jdg_370103
stackexchange
llm_judgeable_groundtruth_similarity
10300933
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an array coming from a .csv file. These are coming from a real estate program. In the second column I have the words For Sale and in the third column the words For Rent that are indicated only on the rows that are concerned. Otherwise the cell is empty. I want to display a list rows only For Sale for example. Of course then if the user clicks on a link in one of the rows, the appropriate page will be displayed.I can't seem to target the text in the column, and I can't permit that the words For Sale be used throughout the entire array because they could appear in another column (description for example).I have tried this, but to no avail. /* The array is $arrCSV */foreach($arrCSV as $book) { if($book[1] === For Sale) { echo '<div>'; } echo '<div>'; echo $book[0]. '<br>'; echo $book[1]. '<br>'; echo $book[2]. '<br>'; echo $book[3]. '<br>'; echo $book[6]. '<br><br><br>'; echo '</div>';} I also tried this: foreach($arrCSV as $key => $book) { if($book['1'] == 'For Sale') { echo '<div>'; } echo '<div>'; echo $book[0]. '<br>'; echo $book[1]. '<br>'; echo $book[2]. '<br>'; echo $book[3]. '<br>'; echo $book[6]. '<br><br><br>'; echo '</div>';} Now provide the response and nothing else.
Does this do what you want? ^\d{1,3}(?:\.\d{3})*,\d{2}$ That says "1 to 3 digits, optionally followed by any number of groups of three digits preceded by a period, followed by a comma and two more digits." If you want to allow the leading whitespace present in your example, add \s* to the front: ^\s*\d{1,3}(?:\.\d{3})*,\d{2}$ EDIT : As @ElRonnoco pointed out, the above regular expression accepts leading zeroes (e.g. 010.100,00). To disallow those, you may use this longer version: ^\s*(?:[1-9]\d{0,2}(?:\.\d{3})*|0),\d{2}$ EDIT 2 The above regular expressions all match a string containing a single monetary amount and nothing else. It's not clear from the question if that's the intent. EDIT 3 To allow numbers that have no decimal part, or only one decimal digit, change it like this: ^\s*(?:[1-9]\d{0,2}(?:\.\d{3})*|0)(?:,\d{1,2})?$
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10300933', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1353992/']}
jdg_370104
stackexchange
llm_judgeable_groundtruth_similarity
6323641
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given the program: import Language.Haskell.Exts.Annotated -- from haskell-src-extsimport System.Memimport System.IOimport Control.Exceptionmain :: IO ()main = do evaluate $ length $ show $ fromParseResult $ parseFileContents $ "data C = C {a :: F {- " ++ replicate 400000 'd' ++ " -} }" performGC performGC performGC Using GHC 7.0.3, when I run: $ ghc --make Temp.hs -rtsopts && Temp.exe +RTS -G1 -S Alloc Copied Live GC GC TOT TOT Page Flts bytes bytes bytes user elap user elap ... 29463264 64 8380480 0.00 0.00 0.64 0.85 0 0 (Gen: 0) 20 56 8380472 0.00 0.00 0.64 0.86 0 0 (Gen: 0) 0 56 8380472 0.00 0.00 0.64 0.87 0 0 (Gen: 0) 42256 780 33452 0.00 0.00 0.64 0.88 0 0 (Gen: 0) 0 0.00 0.00 The performGC call seems to leave 8Mb of memory live, even though it seems like all the memory should be dead. How come? (Without -G1 I see 10Mb live at the end, which I also can't explain.) Now provide the response and nothing else.
Here's what I see (after inserting a print before the last performGC , to help tag when things happen. 524288 524296 32381000 0.00 0.00 1.15 1.95 0 0 (Gen: 0) 524288 524296 31856824 0.00 0.00 1.16 1.96 0 0 (Gen: 0) 368248 808 1032992 0.00 0.02 1.16 1.99 0 0 (Gen: 1) 0 808 1032992 0.00 0.00 1.16 1.99 0 0 (Gen: 1)"performed!" 39464 2200 1058952 0.00 0.00 1.16 1.99 0 0 (Gen: 1) 22264 1560 1075992 0.00 0.00 1.16 2.00 0 0 (Gen: 0) 0 0.00 0.00 So after GCs there is still 1M on the heap (without -G1). With -G1 I see: 34340656 20520040 20524800 0.10 0.12 0.76 0.85 0 0 (Gen: 0) 41697072 24917800 24922560 0.12 0.14 0.91 1.01 0 0 (Gen: 0) 70790776 800 2081568 0.00 0.02 1.04 1.20 0 0 (Gen: 0) 0 800 2081568 0.00 0.00 1.04 1.20 0 0 (Gen: 0)"performed!" 39464 2184 1058952 0.00 0.00 1.05 1.21 0 0 (Gen: 0) 22264 2856 43784 0.00 0.00 1.05 1.21 0 0 (Gen: 0) 0 0.00 0.00 So about 2M. This is on x86_64/Linux. Let's think about the STG machine storage model to see if there's something else on the heap. Things that could be in that 1M of space: CAFs for things like [] , string constants, and the small Int and Char pool, plus things in libraries, the stdin MVar? Thread State Objects (TSOs) for the main thread. Any allocated signal handlers. The IO manager Haskell code. Sparks in the spark pool From experience, this figure of slightly less than 1M seems to be the default "footprint" of a GHC binary. That's about what I've seen in other programs as well (e.g. shootout program smallest footprints are never less than 900K). Perhaps the profiler can say something. Here's the -hT profile (no profiling libs needed), after I insert a minimal busy loop at the end to string out the tail: $ ./A +RTS -K10M -S -hT -i0.001 Results in this graph: Victory! Look at that ~1M thread stack object sitting there! I don't know of a way to make TSOs smaller. The code that produced the above graph: import Language.Haskell.Exts.Annotated -- from haskell-src-extsimport System.Memimport System.IOimport Data.Intimport Control.Exceptionmain :: IO ()main = do evaluate $ length $ show $ fromParseResult $ parseFileContents $ "data C = C {a :: F {- " ++ replicate 400000 'd' ++ " -} }" performGC performGC print "performed!" performGC -- busy loop so we can sample what's left on the heap. let go :: Int32 -> IO () go 0 = return () go n = go $! n-1 go (maxBound :: Int32)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6323641', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/160673/']}
jdg_370105
stackexchange
llm_judgeable_groundtruth_similarity
71251
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: In Europe, there are not many countries that have not sanctioned Russia for attacking Ukraine. Serbia is one of the few that has not so far done so. What reasons have the country's leadership given for this decision? Now provide the response and nothing else.
"They (Russia) were the only country not to have imposed sanctions against us in the 1990s," Vucic said after a National Security Council meeting. "They also supported our territorial integrity in the United Nations. We must not forget that," Vucic said, referring to Russia's stance on Serbia's former province of Kosovo whose independence Moscow refuses to recognise. In full: "As for the sanctions, just tell me how can we simply impose sanctions against Russia overnight just to please someone? Against the only country that did not impose sanctions against us in the 1990s , against the country that has not imposed sanctions against the Republic of Srpska , against the country that saved us in the UN Security Council in 2015? Do you think you have the right to forget such things in state affairs? Let alone that it is dishonest in respect of people who have never done anything wrong against our country ," The Serbian president stressed that Russia is a major guarantor of Serbia’s sovereignty in the UN Security Council and UNSC Resolution 1244 . Serbia has put its gas and oil sectors in Russia's hand s. In 2008 the Balkan country sold a majority stake of its oil company to Gazprom Neft Gazprom is the majority stakeholder in the country's sole gas storage facility . In return, Russia has been blocking membership of Serbia's former province Kosovo in the United Nations. (In 2019, Vladimir Putin presented Aleksandar Vucic with the Order of Alexander Nevsky “for his great personal contribution to the development of multilateral cooperation with Russia.”) However , Vucic said the National Security Council concluded the Republic of Serbia considers "very wrong the violation of territorial integrity of a number of countries including Ukraine." “Serbia respects the norms of international law, but understands its needs well and, despite the wishes of others, has its own national interests, respects traditional friendship,” Vučić said. He added that Serbia is temporarily halting military exercises with all states. After Russia recognized the independence of the LNR and the DNR, Vucic said that this decision “completely changes the world order.” Also: Georgia also refused to impose sanctions against Russia. Prime Minister Irakli Garibashvili said that this “will only harm the country and the population.” He added that Georgia expresses “full solidarity and support” to Ukraine, but will “be guided only by national interests.” https://www.reuters.com/world/europe/serbia-will-not-impose-sanctions-against-moscow-president-says-2022-02-25/ https://hindustannewshub.com/russia-ukraine-news/serbia-refused-to-impose-sanctions-against-russia-so-did-georgia-the-moscow-times-in-russian/ https://tass.com/world/1411539
{}
{'log_upvote_score': 6, 'links': ['https://politics.stackexchange.com/questions/71251', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/42263/']}
jdg_370106
stackexchange
llm_judgeable_groundtruth_similarity
8881
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The pictures of nebulae are always depicted as vividly colored and with a great variety of colors: Source Omega nebula Source Eagle nebula pillars According to the English wikipedia article on nebulae , under the section Formation , «as the material collapses under its own weight, massive stars may form in the center, and their ultraviolet radiation ionizes the surrounding gas, making it visible at optical wavelengths .» This means that we can see the nebulae, but not whether we see them colored or not. Furthermore, in this article on Wired.com, there is a photograph of the Omega Nebula, which states: «Looking more like a painting than an astronomy photograph, the Omega nebula glows with vivid colors in this new image from the European Southern Observatory’s Very Large Telescope. [...] The heart of the Omega nebula contains roughly 35 stars, the hottest of which spew out ultraviolet radiation that causes the surrounding hydrogen gas to glow red and pink.» On another site, seasky.org , the article states: «They are also among the most beautiful objects in the universe, glowing with rich colors and swirls of light. Stars inside these clouds of gas cause them to glow with beautiful reds, blues, and greens.» What I want to know is: if we could observe directly these nebulae, either by telescope or with our own eyes, would they appear like this? If not, how? Now provide the response and nothing else.
From HubbleSite - Behind The Pictures : The Meaning of Color The colors in Hubble images, which are assigned for various reasons, aren't always what we'd see if we were able to visit the imaged objects in a spacecraft . We often use color as a tool, whether it is to enhance an object's detail or to visualize what ordinarily could never be seen by the human eye. Example: The Eagle Nebula Note: The three B&W images each correspond to a certain wavelength (=color). Left : Oxygen - Green Middle : Hydrogen - Red Right : Sulfur - Red Each of these B&W images are then (re-)assigned a unique color, because otherwise the red light from hydrogen and that from sulfur would be hard to tell apart. Choosing Colors Why are the inital images B&W? The digital camera you have at home basically works the same way: Light is "converted" into electrons. From Panasonic : Since a CCD can only distinguish whether light is strong or weak, color filters are used to obtain each color's light and dark information. ( I modified the above picture to make it more clear ) One can see that the yellow flower emits more in red and green (light) and less in blue (dark). [ RGB Color Model on Wikipedia ] Hubble's Color Filters Hubble uses special filters to "screen out" the types of light from an object that astronomers are not currently studying. These filters allow only a certain range of light wavelengths through. Once the unwanted light has been filtered out, the resulting light is allowed to fall onto one or more light-sensitive detectors. This produces a "picture" of the star in the selected wavelength. Since the detectors can detect light outside the visible light spectrum, the use of filters allows scientists to see "invisible" objects — those only visible in ultraviolet and infrared wavelengths. [ Source ] Example: The Eagle Nebula ( Source: ESA ) The Eagle Nebula in Visible Light (Wide Angle) Three-colour (blue, green, red) composite mosaic image of the Eagle Nebula (Messier 16, or NGC 6611), based on images obtained with the wide-field camera on the MPG/ESO 2.2 m-diameter telescope at the La Silla Observatory . At the centre, the Pillars of Creation can be seen. This wide-field image shows not only the central pillars, but also several others in the same star-forming region, as well as a huge number of stars in front of, in and behind the Eagle Nebula. ( Source: ESA ) More Slate - How Do Space Pictures Get So Pretty? Space.com - Truth Behind the Photos: What the Hubble Space Telescope Really Sees Universe Today - True or False (Color): The Art of Extraterrestrial Photography
{}
{'log_upvote_score': 7, 'links': ['https://skeptics.stackexchange.com/questions/8881', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/4727/']}
jdg_370107
stackexchange
llm_judgeable_groundtruth_similarity
256263
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am having difficulties understanding how to implement boolean functions, particularly given that I may only use 2:1 muxes and the variable D as a residual variable. The function is as follows:$$F(A, B, C, D, E) = \sum ( 6, 7, 12, 13, 14, 15, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31)$$ I have created the truth table and, using a Karnaugh map, I have minimized the function to this: $$F(A, B, C, D, E) = AB + BC + CD \bar{E} + CDE$$ I also managed to design a 16:1 MUX with A, B, C and E as selector and D as a residual variable. I understand how a multiplexer works and I am fully capable of deriving a truth table from an existing implementation but I just simply do not understand how to take the truth table, Karnaugh map and the minimized SOP function and implement the function using only 2:1 MUX and D as a residual variable. I am not necessarily asking for the straight up answer, although it would be nice to see. I am more interested in an explanation, an algorithm or really anything that can help me come up with the implementation myself. I want to be able to visualize the connection between the function and the implementation, not just learn how to implement it by heart without understanding why it is the way it is. Thank you for your time! Edit: While I understood the accepted answer and it is the correct answer, I was then required to use just the following inputs for the data lines of my 2:1 muxes: logic 0, logic 1 and the variable D. The variables A, B, C should only be used as selector lines. I created the V-K Map for F(A, B, C, D) = AB + BC + CD and I then used that map to derive a V-K map for F(A, B, C) as can be seen below. Edit: for the map on the right the value for ABC = 000 should be 0, not 1. A mistake I made when I copied over the table from my notebook into excel. Afterwards I created the following mux implementation: The mux design was taken from an electronics book. The implementation, although not terribly efficient, works. I calculated the output of the muxes using the M(X, Y, Z) = XZ' + YZ formula and the output of the rightmost mux is: $$MUX7 = AB\bar{C} + D\bar{B}C + BC$$ Using yet another Karnaugh map, the above simplifies to AB + BC + CD which is the function I needed to implement. The design of the MUXes itself is borrowed from an electronics book. In the book, the data inputs of the leftmost level of MUXes were numbered as can be seen in my diagram and the labels represent the decimal equivalent of the F(A, B, C) V-K map cells. If you look at, for example, the cell 101 (binary for 5) then the value in that cell is the input for the correspondingly labeled MUX input in the implementation, in this case 'D'. Can anyone chime in on why are the data input lines labeled in that particular order (0, 4, 2, 6, 1, 5, 3, 7)? Now provide the response and nothing else.
It's not too complex, I think, assuming you worked out the equation you wanted correctly (I'll assume you did okay there.) Start by looking at the equation for a 2-in MUX: $$\begin{align*}M_2(A,B,S) &= A\cdot \bar{S} + B\cdot S\end{align*}$$ From this, you can derive some useful results: $$\begin{align*}M_2(0,x,y) &= x\cdot y \\M_2(x,0,y) &= x\cdot\bar{y} \\M_2(x,y,0) &= x \\M_2(1,x,y) &= x + \bar{y} \\M_2(x,1,y) &= x + y \\M_2(x,y,1) &= y \\M_2(x,y,x) &= x\cdot y \\M_2(x,y,y) &= x + y \\M_2(0,0,x) &= 0 \\M_2(0,1,x) &= x \\M_2(1,0,x) &= \bar{x} \\M_2(1,1,x) &= 1\end{align*}$$ So it follows that: $$\begin{align*}F &= A B + B C + C D \\x &= A B = M_2(A,B,A) \\y &= B C = M_2(B,C,B) \\z &= C D = M_2(C,D,C) \\\therefore F &= x + y + z \\F &= M_2(M_2(x,y,y),z,z)\end{align*}$$ In short, you will need (5) 2-in muxes: simulate this circuit – Schematic created using CircuitLab There's also a nice symmetry there. Notice it? ADDED: You asked about only being able to use 0, 1, or D as a mux data input source. I assume by this that you mean that all of A, B, C, and D can be used as mux selectors. (Otherwise, I don't think the result can be achieved.) So, this just means you need to use some of the other useful results I'd earlier mentioned. The simplest idea would be to just add three more 2-in muxes: simulate this circuit I'm not sure if there is a way to optimize it further. I haven't examined all of the possibilities. EDIT AGAIN: Yes! Using the OP's newly added solution, the following two just flow out. The left one answers his first part of the question, the right one answers his second part. simulate this circuit EDIT AGAIN AGAIN: The ordering isn't complicated. It's just assigning the letters where they belong. The author took (A) to be the high order bit of a three-bit binary value, so it represents either \$0\cdot 2^2=0\$ or \$1\cdot 2^2=4\$; took (B) to be the middle bit of a three-bit binary value, so it represents either \$0\cdot 2^1=0\$ or \$1\cdot 2^1=2\$; and took (C) to be the low order bit of a three-bit binary value, so it represents either \$0\cdot 2^0=0\$ or \$1\cdot 2^0=1\$. A variety of different perspectives would work equally well. But that's the one they appear to have chosen. So they now started with the first (left) tier, laid out (4) muxes controlled by (A), and stayed mentally convenient by numbering those muxes as ABC="x00", ABC="x01", ABC="x10", and for the bottom one ABC="x11". Now, since for the top one, ABC="x00", this means that it accepts either "000"=0 or "100"=4. So for the "0" input of that mux (mux1), they looked into the table for ABC="000"=0 and placed the table entry into its "0" side input. For the "1" input of that mux, they looked into the table for ABC="100"=4 and placed that table entry into its "1" side input. (That table looks wrong here, as their should be a 0 in that box, confirmed by looking at the earlier expanded columns.) The next mux down (mux2) is for ABC="x10" and therefore used ABC="010"=2 and ABC="110"=6; the next mux down (mux3) is for ABC="x01" and therefore used ABC="001"=1 and ABC="101"=5; and finally the last mux down (mux4) is for ABC="x11" and therefore used ABC="011"=3 and ABC="111"=7. Both mux1 (ABC="x00") and mux2 (ABC="x10") are jointly fed to mux5. You can see here that B is the variation between these, 0 or 1, so that's how they hooked them up here. The output of mux5 will be ABC="xy0", where the first two bits have already been decoded and all that remains is to decode the C=0 situation. So the output of mux5 goes to the "0" input of mux7. Similarly, mux3 (ABC="x01") and mux4 (ABC="x11") are jointly fed to mux6. B again being the variation that mux6 selects between. The output of mux6 is always related to the C=1 case, and that is fed into the "1" input of mux7. All that remains is for mux7 to pick between C=0 and C=1.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/256263', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/100098/']}
jdg_370108
stackexchange
llm_judgeable_groundtruth_similarity
566969
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: Suppose that $G$ is a group that there exists no element $x \neq e$ such that $x^2=e$. Moreover, for every $a,b \in G$ we have $(ab)^2=(ba)^2$. Prove that $G$ is Abelian. Well, I attempted to prove that $(aba^{-1}b^{-1})^2=e$ because then if I could prove it that would imply $aba^{-1}b^{-1}=e$ which is the same as $ab=ba$. In other words I wanted to show the order of $[a,b]=aba^{-1}b^{-1}$ is two for every $a$ and $b$ in $G$. I spent almost an hour trying to show that by anything that came to my mind. I tried to brute force the problem by writing any possible equation that I could come up with but I failed :/ Any ideas? Now provide the response and nothing else.
Set $b=a^{-1}x$. We have $x^2=a^{-1}x^2a$, i.e. $ax^2=x^2a$ for all $x,a$. Since $x^2$ runs all group, then $G$ is Abelian. Correction: This proof is valid only for a finite group. Thanks to DonAntonio . Addendum: I am not sure that this assertion is true for infinite groups. A candidate \for a counter-example is $G=\langle a,b|a^2=b^2, (ab)^2=(ba)^2\rangle$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/566969', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/66733/']}
jdg_370109
stackexchange
llm_judgeable_groundtruth_similarity
49215193
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 write code that runs in high throughput production environments expected to handle a variety of input from multiple users. In this environment, I often need to join (with dplyr) two multi-column dataframes with join columns of mismatched types which produces this error. "Can't join on ... because of incompatible types" The production code is expected to handle input csvs that are 150+ columns by 0-1000 rows, with 12-20 join columns. I use read.table for speed, and because the content of the 150 columns can vary, allow type to be inferred by data content. It would be great to have a general-purpose function that matches join column types programmatically, making no assumptions about column name or location. Now provide the response and nothing else.
This is a frequently viewed question, so many others must run into the error, so deserves a more complete answer. The simple solution for correcting this join error is to simply mutate the class of the column(s) causing the problem. This can be done as follows: glimpse the column classes in the dataframes to be joined mutate the column class to match using as.numeric, as.logical or as.character. For example: df2 <- df2 %>% mutate(column1 = as.numeric(column1)) A solution for production environments is in the matchColClasses function shown, which does the following: Identify columns that share the same name (sharedColNames) Use the master data frame (df1) to identify the shared columns classes Reassign column classes in df2 to match df1 matchColClasses <- function(df1, df2) { sharedColNames <- names(df1)[names(df1) %in% names(df2)] sharedColTypes <- sapply(df1[,sharedColNames], class) for (n in sharedColNames) { class(df2[, n]) <- sharedColTypes[n] } return(df2) } This function works well in our production environment, with heterogenous data types; character, numeric and logical.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49215193', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4882696/']}
jdg_370110
stackexchange
llm_judgeable_groundtruth_similarity
54901478
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: First, I have to mention that I already look through many questions in stackoverflow, but many doesn't answer my question. Not to mention many doesn't even have an answer. How do I achieve the following, making sure functionB() executes after functionA() finishes? Note: I do not want to convert my async functions to new Promise(resolve=>{...}) because I'll have to convert the someServiceThatMakesHTTPCall() as well, and any other async functions within the call stack, which is a big change. function functionThatCannotHaveAsyncKeyword() { functionA() .then(async function() { await functionB(); }) .then(function() { console.log('last'); }); } async function functionA() { console.log('first'); await someServiceThatMakesHTTPCall(); } async function functionB() { console.log('second'); await someServiceThatMakesHTTPCall(); } Now provide the response and nothing else.
Your approach using await in an async then callback will work, but it's unnecessarily complex if all you want to do is call the async function and have its result propagate through the chain. But if you are doing other things and want the syntax benefit of async functions, that's fine. I'll come back to that in a moment. async functions returns promises, so you just return the result of calling your function: function functionThatCannotHaveAsyncKeyword() { functionA() .then(function() { return functionB(someArgument); }) .then(function() { console.log('last'); }); // <=== Note: You need a `catch` here, or this function needs // to return the promise chain to its caller so its caller can // handle errors} If you want to pass functionA 's resolution value into functionB , you can do it even more directly: functionA() .then(functionB) // ... When you return a promise from a then callback, the promise created by the call to then is resolved to the promise you return: it will wait for that other promise to settle, then settle the same way. Example: const wait = (duration, ...args) => new Promise(resolve => { setTimeout(resolve, duration, ...args);});async function functionA() { await wait(500); return 42;}async function functionB() { await wait(200); return "answer";}functionB().then(result => { console.log(result); // "answer" return functionA();}).then(result => { console.log(result); // 42}).catch(error => { // ...handle error...}); Coming back to your approach using an async then callback: That works too, and makes sense when you're doing more stuff: const wait = (duration, ...args) => new Promise(resolve => { setTimeout(resolve, duration, ...args);});async function functionA() { await wait(500); return 42;}async function functionB() { await wait(200); return "answer";}functionB().then(async (result) => { console.log(result); // "answer" const v = await functionA(); if (v < 60) { console.log("Waiting 400ms..."); await wait(400); console.log("Done waiting"); } console.log(v); // 42}).catch(error => { // ...handle error...});
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54901478', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6122411/']}
jdg_370111
stackexchange
llm_judgeable_groundtruth_similarity
5937630
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 follow class and the list that holds it: public class Transport{ public string TransportType { get; set; } public string Mode { get; set; } public class Coordinates { public float ID { get; set; } public float LocX { get; set; } public float LocY { get; set; } public float LocZ { get; set; } public ObjectState State { get; set; } public List<int[]> Connections = new <int[]>(); }}public enum ObjectState{ Fly, Ground, Water}public static List<Transport> Tracking = new List<Transport>(); How do I serialize the Tracking to XML ? I know I can use [Serializable] on the list and serialize it to file but I am not sure on how I define it to be saved as XML. Now provide the response and nothing else.
If both of your classes were tagged with the [Serializable] attribute, then saving things to a file should be as simple as: var serializer = new XmlSerializer(typeof(Transport));using(var writer = new StreamWriter("C:\\Path\\To\\File.xml")){ serializer.Serialize(writer, instance);} Update Sorry, didn't realize you were asking about how to customize the output. That is what the [XmlAttribute] and [XmlElement] attributes are for: public class Transport{ // Store TransportType as an attrribute called Type in the XML [XmlAttribute("Type")] public string TransportType { get; set; } // Rest of Implementation}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5937630', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/450121/']}
jdg_370112
stackexchange
llm_judgeable_groundtruth_similarity
47103
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to understand Cisco ISR 4000 Performance Levels. In the document ISR 4000 , one can read the following paragraph: It's actually quite simple. The router shaper applies only to traffic on the data plane forwarding CPU, and it applies only to egress traffic leaving the data plane. It doesn’t apply to traffic only traversing the Multi-Gigabit Fabric (MGF). Can someone explain this in even more simple terms? For example, given a concrete situation like the following: we have an ISR which default performance level is 50 Mbps (like the ISR4321), some traffic comes from the Internet at a 100 Mbps download speed, some traffic goes out onto the Internet at approximately the same speed (99.07 Mbps), some traffic goes through an IPsec ISAKMP VPN between the ISR and another router. How is the router shaper limitation to 50 Mbps going to impact these traffics? Which traffic belongs to which category: traffic on the data plane forwarding CPU, egress traffic leaving the data plane, traffic only traversing the Multi-Gigabit Fabric (MGF)? Thank you for helping me understand. Best regards. Now provide the response and nothing else.
The 4000 Series routers are all using the Quantumflow Processor from the ASR1000 Series router. This is a Multi-core CPU with very significant routing capability. This is the only way Cisco can deliver iWAN and NBAR/AVC to branch offices. AVC has the ability to check the classification of traffic based on Layer-4 and higher characteristics, so the traffic can be identified and prioritized for what it is. You no longer have to just throw all HTTP and HTTPS into DSCP AF21. You can rip Facebook out of AF21 and put it in CS1 where it belongs, even though its encrypted - thanks to AVC. (AVC: https://www.cisco.com/c/en/us/products/routers/avc-control.html ) Obviously, tearing that deeply into packets requires serious CPU power, which is where that Multi-core CPU comes in. It has so much horsepower they have to rate-limit it in software, which is why after so many years of preferring not to talk about maximum throughput, they are suddenly publishing throughput recommendations for these routers in the public specification sheets. Can someone explain this in even more simple terms? Any routable traffic will be capped. The router will even shut down processors to limit the throughput. Also explained in this video: https://www.youtube.com/watch?v=M2yLg1FZRXU (Fast forward to 11:55 for info on shaper limitations) For example, given a concrete situation like the following: we have an ISR which default performance level is 50 Mbps (like the ISR4321), some traffic comes from the Internet at a 100 Mbps download speed, some traffic goes out onto the Internet at approximately the same speed (99.07 Mbps), some traffic goes through an IPsec ISAKMP VPN between the ISR and another router. How is the router shaper limitation to 50 Mbps going to impact these traffics? Your ingress traffic from the internet of 100 Mbps will not be shaped. But if the traffic will be routed/NATed/etc. the egress will be shaped to 50 Mbps. Your output traffic to the internet of 99.07 Mbps will be shaped to 50 Mbps. Your IPsec VPN will be capped at 50 Mbps egress. Which traffic belongs to which category: traffic on the data plane forwarding CPU, egress traffic leaving the data plane, traffic only traversing the Multi-Gigabit Fabric (MGF)? Will be shaped to 50 Mbps. Will be shaped to 50 Mbps. Will not be shaped.
{}
{'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/47103', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/40438/']}
jdg_370113
stackexchange
llm_judgeable_groundtruth_similarity
3466297
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 large image. But i have to display just some portion of it. How is this possible using Android ImageView? Now provide the response and nothing else.
You could always crop the piece that you need via the Bitmap.createBitmap() static method, and then assign it to the view: Something like... // Set some constantsprivate static final Bitmap SOURCE_BITMAP = BitmapFactory.decodeFile(....); // Get the source Bitmap using your favorite method :-)private static final int START_X = 10;private static final int START_Y = 15;private static final int WIDTH_PX = 100;private static final int HEIGHT_PX = 100;// Crop bitmapBitmap newBitmap = Bitmap.createBitmap(SOURCE_BITMAP, START_X, START_Y, WIDTH_PX, HEIGHT_PX, null, false);// Assign new bitmap to ImageViewImageView image = (ImageView)findViewById(R.id.image_view);image.setImageBitmap(newBitmap);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3466297', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/393792/']}
jdg_370114
stackexchange
llm_judgeable_groundtruth_similarity
23518966
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 convert a Dictionary in code into a url parameter string? e.g. // An example list of parametersDictionary<string, object> parameters ...;foreach (Item in List){ parameters.Add(Item.Name, Item.Value);}string url = "http://www.somesite.com?" + parameters.XX.ToString(); Inside MVC HtmlHelpers you can generate URLs with the UrlHelper (or Url in controllers) but in Web Forms code-behind the this HtmlHelper is not available. string url = UrlHelper.GenerateUrl("Default", "Action", "Controller", new RouteValueDictionary(parameters), htmlHelper.RouteCollection , htmlHelper.ViewContext.RequestContext, true); How could this be done in C# Web Forms code-behind (in an MVC/Web Forms app) without the MVC helper? Now provide the response and nothing else.
One approach would be: var url = string.Format("http://www.yoursite.com?{0}", HttpUtility.UrlEncode(string.Join("&", parameters.Select(kvp => string.Format("{0}={1}", kvp.Key, kvp.Value))))); You could also use string interpolation as introduced in C#6: var url = $"http://www.yoursite.com?{HttpUtility.UrlEncode(string.Join("&", parameters.Select(kvp => $"{kvp.Key}={kvp.Value}")))}"; And you could get rid of the UrlEncode if you don't need it, I just added it for completeness.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/23518966', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/878612/']}
jdg_370115
stackexchange
llm_judgeable_groundtruth_similarity
31367878
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What are the differences between $injector.instantiate , $injector.get and $injector.invoke in AngularJS? Now provide the response and nothing else.
Given the following service: app.service('myService', function ($q, $http) { return { q: $q, http: $http };}); $injector.get(name, [caller]); Returns an instance of the requested service. $injector.get('myService');// { q: $q, http: $http } $injector.invoke(fn, [self], [locals]); Invokes the supplied method and passes along the given arguments from the $injector. $injector.invoke(function (myService, $http) { console.log(myService); // { q: $q, http: $http }; console.log(this); // { v: 'im this!' }; console.log($http); // null}, { v: 'im this!' }, { $http: null }); $injector.instantiate(Type, [locals]); Creates a new instance of the given Type. Takes a constructor function, then invokes the new instance with the arguments specified in the constructor annotation. Assume the following 'class': function Person (fName, lName, $http, $q) { return { first_name: fName, last_name: lName, http: $http, q: $q }} Now, if we wanted to create a new Person in our controller, we could do it like this: app.controller('...', function ($injector) { var $http = $injector.get('$http'); var $q = $injector.get('$q'); var p = new Person('kasper', 'lewau', $http, $q); console.log(p); // { first_name: 'kasper', last_name: 'lewau', http: $http, q: $q };}); Imagine Person had ~20 or so dependencies, and we were fetching each and every one of them with the $injector.get method. Cumbersome! And - you would need to keep your parameters & arguments in sync. ugh . Instead, you can do this: app.controller('...', function ($injector) { var p = $injector.instantiate(Person, { fName: 'kasper', lName: 'lewau' }); console.log(p); // { first_name: 'kasper', last_name: 'lewau', http: $http, q: $q };}); And - if we wanted to, we could supply locals to the .instantiate call, so as to override what the internal $injector.get() would normally get when instantiating. var p = $injector.instantiate(Person, { fName: 'kasper', lName: 'lewau'}, { $http: 'Nothing!', $q: 'Nothing!' });console.log(p); // { first_name: 'kasper', last_name: 'lewau', http: 'Nothing!', q: 'Nothing!' }; I hope that explains the difference between the three. If you need more information regarding their differences I would recommend these articles: http://taoofcode.net/studying-the-angular-injector/ http://taoofcode.net/studying-the-angular-injector-annotate/ http://taoofcode.net/studying-the-angular-injector-invoke/ http://taoofcode.net/studying-the-angular-injector-getservice/ http://taoofcode.net/studying-the-angular-js-injector-instantiate/
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31367878', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4689762/']}
jdg_370116
stackexchange
llm_judgeable_groundtruth_similarity
309768
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 recently learned, that . ./.a.a and ./.a.a is the same. However trying source source .a.a gives an error. IMO, . being Bash alias for source shouldn't behave differently, so what am I missing? Bonus, why is . . OK while source source is not? Now provide the response and nothing else.
You can't just replace . with source everywhere; if . ./.a.a works, you can replace the first . (at least in Bash): source ./.a.a The second . represents the current directory, you can't replace that with source (especially not ./ with source as you've done). source source would be OK if you had a file called source in the current directory, containing something meaningful for your current shell. I can't see how . . would be OK... Also, . ./.a.a and ./.a.a aren't the same, the second form runs .a.a in a separate shell. See What is the difference between sourcing ('.' or 'source') and executing a file in bash? for details.
{}
{'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/309768', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/65176/']}
jdg_370117
stackexchange
llm_judgeable_groundtruth_similarity
376839
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: In his talk, The Future of Mathematics , Dr. Kevin Buzzard states that Lean is the only existing proof assistant suitable for formalizing all of math . In the Q&A part of the talk (at 1:00:00 ) he justifies this as follows: Automation is very difficult with set theory Simple type theory is too simple Univalent type theory hasn't been successful in proof assistants My question is about the first of these: Why is automation very difficult with set theory (compared to dependent type theory)? Now provide the response and nothing else.
I apologize for writing a lengthy answer, but I get the feeling the discussions about foundations for formalized mathematics are often hindered by lack of information. I have used proof assistants for a while now, and also worked on their design and implementation. While I will be quick to tell jokes about set theory, I am bitterly aware of the shortcomings of type theory, very likely more so than the typical set theorist. (Ha, ha, "typical set theorist"!) If anyone can show me how to improve proof assistants with set theory, I will be absolutely deligthed! But it is not enough to just have good ideas – you need to test them in practice on large projects, as many phenomena related to formalized mathematics only appear once we reach a certain level of complexity. The components of a proof assistant The architecture of modern proof assistants is the result of several decades of experimentation, development and practical experience. A proof assistant incorporates not one, but several formal systems. The central component of a proof assistant is the kernel , which validates every inference step and makes sure that proofs are correct. It does so by implementing a formal system $F$ (the foundation ) which is expressive enough to allow formalization of a large amount of mathematics, but also simple enough to allow an efficient and correct implementation. The foundational system implemented in the kernel is too rudimentary to be directly usable for sophisticated mathematics. Instead, the user writes their input in a more expressive formal language $V$ (the vernacular ) that is designed to be practical and useful. Typically $V$ is quite complex so that it can accommodate various notational conventions and other accepted forms of mathematical expression. A second component of the proof assistant, the elaborator , translates $V$ to $F$ and passes the translations to the kernel for verification. A proof assistant may incorporate a third formal language $M$ (the meta-language ), which is used to implement proof search, decision procedures, and other automation techniques. Because the purpose of $M$ is to implement algorithms, it typically resembles a programming language. The distinction between $M$ and $V$ may not be very sharp, and sometimes they are combined into a single formalism. From mathematical point of view, $M$ is less interesting than $F$ and $V$ , so we shall ignore it. Suitability of foundation $F$ The correctness of the entire system depends on the correctness of the kernel. A bug in the kernel allows invalid proofs to be accepted, whereas a bug in any other component is just an annoyance. Therefore, the foundation $F$ should be simple so that we can implement it reliably. It should not be so exotic that logicians cannot tell how it relates to the accepted foundations of mathematics. Computers are fast, so it does not matter (too much) if the translation from $V$ to $F$ creates verbose statements. Also, $F$ need not be directly usable by humans. A suitable variant of set theory or type theory fits these criteria. Indeed Mizar is based on set theory, while HOL, Lean, Coq, and Agda use type theory in the kernel. Since both set theory and type theory are mathematically very well understood, and more or less equally expressive, the choice will hinge on technical criteria, such as availability and efficiency of proof-checking algorithms. Suitability of vernacular $V$ A much more interesting question is what makes the vernacular $V$ suitable. For the vernacular to be useful, it has to reflect mathematical practice as much as possible. It should allow expression of mathematical ideas and concepts directly in familiar terms, and without unnecessary formalistic hassle. On the other hand, $V$ should be a formal language so that the elaborator can translate it to the foundation $F$ . To learn more about what makes $V$ good, we need to carefully observe how mathematicians actually write mathematics. They produce complex webs of definitions, theorems, and constructions, therefore $V$ should support management of large collections of formalized mathematics. In this regards we can learn a great deal by looking at how programmers organize software. For instance, saying that a body of mathematics is "just a series of definitions, theorems and proofs" is a naive idealization that works in certain contexts, but certainly not in practical formalization of mathematics. Mathematicians omit a great deal of information in their writings, and are quite willing to sacrifice formal correctness for succinctness. The reader is expected to fill in the missing details, and to rectify the imprecisions. The proof assistant is expected to do the same. To illustrate this point, consider the following snippet of mathematical text: Let $U$ and $V$ be vector spaces and $f : U \to V$ a linear map. Then $f(2 \cdot x + y) = 2 \cdot f(x) + f(y)$ for all $x$ and $y$ . Did you understand it? Of course. But you might be quite surprised to learn how much guesswork and correction your brain carried out: The field of scalars is not specified, but this does not prevent you from understanding the text. You simply assumed that there is some underlying field of scalars $K$ . You might find out more about $K$ in subsequent text. ( $K$ is an existential variable .) Strictly speaking " $f : U \to V$ " does not make sense because $U$ and $V$ are not sets, but structures $U = (|U|, 0_U, {+}_U, {-}_U, {\cdot}_U)$ and $V = (|V|, 0_V, {+}_V, {-}_V, {\cdot}_V)$ . Of course, you correctly surmised that $f$ is a map between the carriers , i.e., $f : |U| \to |V|$ . (You inserted an implicit coercion from a vector space to its carrier.) What do $x$ and $y$ range over? For $f(x)$ and $f(y)$ to make sense, it must be the case that $x \in |U|$ and $y \in |U|$ . (You inferred the domain of $x$ and $y$ .) In the equation, $+$ on the left-hand side means $+_{U}$ , and $+$ on the right-hand side ${+}_V$ , and similarly for scalar multiplication. (You reconstructed the implicit arguments of $+$ .) The symbol $2$ normally denotes a natural number, as every child knows, but clearly it is meant to denote the scalar $1_K +_K 1_K$ . (You interpreed " $2$ " in the notation scope appropriate for the situation at hand.) The vernacular $V$ must support these techniques, and many more, so that they can be implemented in the elaborator. It cannot be anything as simple as ZFC with first-order logic and definitional extensions, or bare Martin-Löf type theory. You may consider the development of $V$ to be outside of scope of mathematics and logic, but then do not complain when computer scientist fashion it after their technology. I have never seen any serious proposals for a vernacular based on set theory. Or to put it another way, as soon as we start expanding and transforming set theory to fit the requirements for $V$ , we end up with a theoretical framework that looks a lot like type theory. (You may entertain yourself by thinking how set theory could be used to detect that $f : U \to V$ above does not make sense unless we insert coercions – for if everthying is a set then so are $U$ and $V$ , in which case $f : U \to V$ does make sense.) Detecting mistakes An important aspect of suitability of foundation is its ability to detect mistakes. Of course, its purpose is to prevent logical errors, but there is more to mistakes than just violation of logic. There are formally meaningful statements which, with very high probability, are mistakes. Consider the following snippet, and read it carefully: Definition: A set $X$ is jaberwocky when for every $x \in X$ there exists a bryllyg $U \subseteq X$ and an uffish $K \subseteq X$ such that $x \in U$ and $U \in K$ . Even if you have never read Lewis Carroll's works, you should wonder about " $U \in K$ ". It looks like " $U \subseteq K$ " would make more sense, since $U$ and $K$ are both subsets of $X$ . Nevertheless, a proof assistant whose foundation $F$ is based on ZFC will accept the above definition as valid, even though it is very unlikely that the human intended it. A proof assistant based on type theory would reject the definition by stating that " $U \in K$ " is a type error. So suppose we use a set-theoretic foundation $F$ that accepts any syntactically valid formula as meaningful. In such a system writing " $U \in K$ " is meaningful and therefore the above definition will be accepted by the kernel. If we want the proof assistant to actually assist the human, it has to contain an additional mechanism that will flag " $U \in K$ " as suspect, despite the kernel being happy with it. But what is this additional mechanism, if not just a second kernel based on type theory? I am not saying that it is impossible to design a proof assistant based on set theory. After all, Mizar , the most venerable of them all, is designed precisely in this way – set theory with a layer of type-theoretic mechanisms on top. But I cannot help to wonder: why bother with the set-theoretic kernel that requires a type-theoretic fence to insulate the user from the unintended permissiveness of set theory?
{}
{'log_upvote_score': 9, 'links': ['https://mathoverflow.net/questions/376839', 'https://mathoverflow.net', 'https://mathoverflow.net/users/30352/']}
jdg_370118
stackexchange
llm_judgeable_groundtruth_similarity
11502052
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Since we can throw anything with the throw keyword in Javascript, can't we just throw an error message string directly? Does anyone know any catch in this? Let me add some background to this: Very often, in the JavaScript world, people rely on parameter checking as opposed to using the try-catch mechanism, so it makes sense to only throw fatal errors with throw . Still, to be able to catch some system Errors, I have to use a different class for my own errors and instead of creating a subclass of Error, I think I should just use String. Now provide the response and nothing else.
While it is okay possible to throw any value, it is generally considered poor form to throw anything other than an instance of Error or one of its subclasses. There are several reasons for this: Catching code may expect the thrown object to have the usual message , stacktrace , and name properties that appear on Error s. Lack of a stacktrace makes debugging problematic, especially in the case of uncaught exceptions / unhandled rejections. E.g. Debugging an "Uncaught [Object object]" error can be particularly painful.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11502052', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/499922/']}
jdg_370119
stackexchange
llm_judgeable_groundtruth_similarity
632643
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm wondering how I can have a circuit to turn off in the event that one (or even multiple) LEDs fails, causing an open parallel branch. I would like all the LEDS to turn off in that case. The example circuit is attached, however, there will be 18 LED branches rather than the 4 in the example. LEDs: Vf: 3.0 V @ 30 mA The LEDs will have a steady 12 V supply. I will be using only SMD components. The problem I'm having is that when one branch fails, there is not much of a voltage difference to make a circuit with a diode and transistor turn off the circuit (which is how I usually design a circuit with less LEDs). Ideally, I would want to use something like an LED driver with fault detection or comparators, but this is something I am trying to avoid, as that drives cost per piece up a lot. Now provide the response and nothing else.
Move the 100R resistors to the bottom. At 30 mA, each 100R drops 3 V when its LEDs are conducting and 0 V if any of the 3 fail open-circuit. Each 100R's voltage can drive a 3.3 V AND gate input through a 10K current-limiting resistor. A full AND tree can then be made from 4-input or 8-input AND gate ICs, producing the single output. If the final AND tree output is LOW, an LED has gone open-circuit. If multiple LED failures take a gate pin voltage above the MCU's supply rail, its pin clamp diodes will conduct. The 10K series resistor will limit the clamp diode current to a safe level, even if driven with 12 V. simulate this circuit – Schematic created using CircuitLab If a 3.3 V MCU with ADCs and enough channel inputs is used, each 100R's voltage can drive an ADC input through a 10K current-limiting resistor. Then the ADC can check for LEDs gone open-circuit (Vin near 0 V) and LEDs gone short-circuit (Vin above, say, 3.1 V). For better voltage measurement of LEDs gone open-circuit, each 100R could be two 50R in series. The ADCs could then measure across a 50R, getting 1.5 V when all's well and measurable higher voltages from failures.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/632643', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/320659/']}
jdg_370120
stackexchange
llm_judgeable_groundtruth_similarity
23662639
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: After I have fixed this warning, how can I make it an error, so it doesn't slip in again? msbuild /p:TreatWarningsAsErrors doesn't work Now provide the response and nothing else.
No happy answer to give you here. The TreatWarningsAsErrors property only affects the C# and VB.NET compiler (not C++), it determines the value of their /warnaserror command line option. But MSB3277 is generated by an MSBuild task, ResolveAssemblyReference , its internal LogResult() method generates the diagnostic. The only property the class has that helps treat warnings as errors conditionally is WarnOrErrorOnTargetArchitectureMismatch, not what you are trying to achieve. You can have a look-see for yourself with a decompiler, look at C:\Program Files (x86)\MSBuild\12.0\Bin\Microsoft.Build.Tasks.v12.0.dll. The resource name for the localized MSB3277 message is "ResolveAssemblyReference.FoundConflicts". So only way to get ahead here is to write a little utility that parses the log file and looks for the warning.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23662639', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5314/']}
jdg_370121
stackexchange
llm_judgeable_groundtruth_similarity
379179
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: How can I prove that $\mathrm{tr}(\rho^2) $ = 1 if and only if the state is pure? My idea: I know how to show that $\mathrm{tr}(\rho^2) \leq 1$ and from there I am trying to show by contradiction that $\mathrm{tr}(\rho^2) = 1$ can only but true for pure state, but I am kind of stuck. I just need a hint on how to prove this. Now provide the response and nothing else.
Since an arbitrary $\rho$ is self-adjoint, it has the spectral decomposition $\rho = \sum_n \rho_n |\psi_n><\psi_n|$, in terms of an orthonormal basis $\{ |\psi_n>\}$, which here we pick discrete for simplicity. Hermiticity implies $\rho_n = \rho^*_n$. $\mathrm{Tr} \rho = 1$ implies $\sum_n \rho_n =1$. Semi-positivity implies $0 \leq \rho_n$. Together they imply $0 \leq \rho_n \leq 1$, which implies $\rho^2_n \leq \rho_n$. Hence, $\mathrm{Tr} \rho^2 = \sum_n \rho^2_n \leq \sum_n \rho_n = 1$ and so $\mathrm{Tr} \rho^2 \leq 1$ for a generic state, as you mention. Now let's start assuming that $\mathrm{Tr} \rho^2 =1$. Following the inequalities we just wrote, this implies that $\rho^2_n = \rho_n$ for all $n$ i.e. $\rho^2 = \rho$. In particular this implies that $\rho_n = 1$ or $\rho_n = 0$. More precisely, due to the trace condition $\mathrm{Tr} \rho = 1$, only one $\rho_n$ is equal to one while the others vanish. This is a pure state. The reverse implication is direct.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/379179', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/162923/']}
jdg_370122
stackexchange
llm_judgeable_groundtruth_similarity
2067003
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: (Mathematics olympiad Netherlands) Let $A,B$ and $C$ denote chess players in a tournament. The winner of each match plays the next match against the oponent that did not play the current. At the end of the tournament $A$, $B$ and $C$ played $10$, $15$ and $17$ times respectively. Each match only ended up in a win. Question : Which player lost the second match? UPDATE : So I think I got the answer. Denote $n$ as the amount of matches between $A$ and $B$. Since $A$ plays the same amount of matches against $B$ as the otherway around, we have $15 - n = 17 - (10-n) \implies n = 4$. So $A$ plays a total of 10 matches, while there are a total of 21 matches. This is only possible if $A$ plays all the even matches and he loses that match (else contradiction to amount of matches played). Now provide the response and nothing else.
$$\sum_{k=1}^{n}\frac{(-1)^{k+1}}{k(k+1)}=\sum_{k=1}^{n}(-1)^{k+1}\left(\frac1k-\frac1{k+1}\right)=\sum_{k=1}^n\frac{(-1)^{k+1}}{k}+\sum_{k=1}^n\frac{(-1)^{k+2}}{k+1}\\=2\sum_{k=1}^n\frac{(-1)^{k+1}}{k}-1-\frac{(-1)^{n+1}}{n+1}.$$Hence, $$\sum_{n=1}^{\infty}\frac{(-1)^{n+1}}{n(n+1)}=2\sum_{n=1}^\infty\frac{(-1)^{n+1}}{n}-1=2\ln 2-1,$$since$$\sum_{n=1}^n\frac{(-1)^{n+1}}{n}=\ln 2.$$ Proof. If $\lvert x\rvert<1$, then$$\frac{1}{1+x}=\sum_{k=0}^n(-1)^{k}x^k+\frac{(-1)^{n+1}x^{n+1}}{1+x},$$and hence$$\log(1+x)=\int_0^x\frac{dt}{1+t}=\sum_{k=0}^n(-1)^{k}\int_0^tt^k\,dt+\int_0^x\frac{(-1)^{n+1}t^{n+1}\,dt}{1+t} \\=\sum_{k=0}^n\frac{(-1)^kx^{n+1}}{n+1}+R_n(x).$$Clearly, for $x\in [0,1]$ $$\lvert R_n(x)\rvert = \int_0^x\frac{t^{n+1}\,dt}{1+t}\le\int_0^xt^{n+1}\,dt\le \frac{1}{n+2}.$$Hence$$\ln 2=\lim_{x\to 1^-}\ln(1+x)=\lim_{x\to 1^-}\sum_{k=0}^n\frac{(-1)^kx^{n+1}}{n+1}+\lim_{x\to 1^-}R_n(x)=\sum_{k=0}^n\frac{(-1)^k}{n+1}+R_n(1),$$and hence$$\sum_{n=1}^\infty\frac{(-1)^{n+1}}{n}=\lim_{n\to\infty}\sum_{k=0}^n\frac{(-1)^k}{n+1}=\lim_{n\to\infty}\big(\ln 2+R_n(1)\big)=\ln 2.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2067003', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_370123
stackexchange
llm_judgeable_groundtruth_similarity
324923
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 gauge the possibility of a patch to WebKit which would allow all rendered graphics to be rendered onto a fully transparent background. The desired effect is to render web content without any background at all, it should appear to float over the desktop (or whatever is displayed behind the browser window). Has anyone seen an app do this? (I can think of some terminal emulators that can.) If anyone has worked inside of WebKit (or possibly Gecko?) do you think it would be possible to do this? Update: I've come to realize that Mac OSX dashboard widgets use this exact technique. So, this must be possible. Update 2: I've compiled WebKit on linux and noticed the configure options include: --enable-dashboard-supportenable Dashboard support default=yes I'm getting closer. Can anyone help? Update 3: I continue to find references to this in posts on various related mailing lists. https://lists.webkit.org/pipermail/webkit-dev/2008-September/005019.html https://lists.webkit.org/pipermail/webkit-dev/2009-June/008182.html Now provide the response and nothing else.
Solved! Through ongoing research, scouring forums and source code repositories, I peiced together the necessary steps to accomplish this using only libwebkit and a standard compiz desktop (any Xorg desktop with compositing should do). For a current libwebkit (1.1.10-SVN), there is an Ubuntu PPA: deb http://ppa.launchpad.net/webkit-team/ppa/ubuntu jaunty maindeb-src http://ppa.launchpad.net/webkit-team/ppa/ubuntu jaunty main As far as the code goes, the key is calling webkit_web_view_set_transparent . And of course the system you're running it on should have a capable graphics card (intel, radeon, or nvidia) and be running a compositing window manager (like Compiz). And finally, to actually see transparency, the content you're viewing must set a transparent background using CSS3, otherwise it's still completely opaque. It's as simple as: BODY { background-color: rgba(0,0,0,0); } Here' is the full sample for the simplest possible webkit browser app, with transparency support: #include <gtk/gtk.h>#include <webkit/webkit.h>static void destroy_cb(GtkWidget* widget, gpointer data) { gtk_main_quit();}int main(int argc, char* argv[]) { gtk_init(&argc, &argv); if(!g_thread_supported()) g_thread_init(NULL); // Create a Window, set colormap to RGBA GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL); GdkScreen *screen = gtk_widget_get_screen(window); GdkColormap *rgba = gdk_screen_get_rgba_colormap (screen); if (rgba && gdk_screen_is_composited (screen)) { gtk_widget_set_default_colormap(rgba); gtk_widget_set_colormap(GTK_WIDGET(window), rgba); } gtk_window_set_default_size(GTK_WINDOW(window), 800, 800); g_signal_connect(window, "destroy", G_CALLBACK(destroy_cb), NULL); // Optional: for dashboard style borderless windows gtk_window_set_decorated(GTK_WINDOW(window), FALSE); // Create a WebView, set it transparent, add it to the window WebKitWebView* web_view = web_view = WEBKIT_WEB_VIEW(webkit_web_view_new()); webkit_web_view_set_transparent(web_view, TRUE); gtk_container_add (GTK_CONTAINER(window), GTK_WIDGET(web_view)); // Load a default page webkit_web_view_load_uri(web_view, "http://stackoverflow.com/"); // Show it and continue running until the window closes gtk_widget_grab_focus(GTK_WIDGET(web_view)); gtk_widget_show_all(window); gtk_main(); return 0;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/324923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/758/']}
jdg_370124
stackexchange
llm_judgeable_groundtruth_similarity
48743770
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 very new in Voyager. I have got all the controllers inside TCG\\Voyager\\Http\\Controllers while installing Voyager but didn't find other controllers those I have created using BREAD. Besides that I want to create custom controller in my Voyager admin panel inside App\\Http\\Controllers\\Voyager . I also followed the steps of Voyager tutorial in Youtube for making custom controller, but couldn't create. Anybody help please ? Now provide the response and nothing else.
In your config\voyager.php file add your namespace: 'controllers' => [ 'namespace' => 'App\Http\Controllers\Back',], Then publish voyageres controllers to your namespace php artisan voyager:controllers Within that namespace create a new controller derived from VoyagerBreadController namespace App\Http\Controllers\Back;use Illuminate\Http\Request;class SchoolController extends VoyagerBreadController{ Then you can specify the controller in the bread editor. NOTE: I did have to refer to mine as Back\SchoolController instead of just SchoolController as I would have expected.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48743770', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9315627/']}
jdg_370125
stackexchange
llm_judgeable_groundtruth_similarity
170028
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 seems very noisy to me. Five lines of overhead is just too much. m_Lock.EnterReadLock()Try Return m_List.CountFinally m_Lock.ExitReadLock()End Try So how would you simply this? Now provide the response and nothing else.
I was thinking the same, but in C# ;-p using System;using System.Threading;class Program{ static void Main() { ReaderWriterLockSlim sync = new ReaderWriterLockSlim(); using (sync.Read()) { // etc } }}public static class ReaderWriterExt{ sealed class ReadLockToken : IDisposable { private ReaderWriterLockSlim sync; public ReadLockToken(ReaderWriterLockSlim sync) { this.sync = sync; sync.EnterReadLock(); } public void Dispose() { if (sync != null) { sync.ExitReadLock(); sync = null; } } } public static IDisposable Read(this ReaderWriterLockSlim obj) { return new ReadLockToken(obj); }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/170028', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5274/']}
jdg_370126
stackexchange
llm_judgeable_groundtruth_similarity
51213963
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 component with multi-slot transclusion in Angular 6, following this blog post (which is for Angular 2). I created a component: import { Component, OnInit } from '@angular/core';@Component({ selector: 'app-criteria', template: ` <div class="adoption-grid-column adopter"> <div class="adoption-grid-icon "> <ng-content select="level-icon"></ng-content> </div> <div class="adoption-grid-body"> <ng-content select="level-description"></ng-content> </div> </div> `, styles: []})export class CriteriaComponent implements OnInit { constructor() {} ngOnInit() {}} and then I am trying to use it like this <app-criteria> <level-icon> foo </level-icon> <level-description> bar </level-description></app-criteria> But it throws a compile error: ERROR in : 'level-icon' is not a known element What am I missing here? I realize I could create sub-components here, but I'm looking for a solution where I can pass blocks of html into slots in my component (such as bulleted lists, images, etc.) Now provide the response and nothing else.
The easiest solution (the one I prefer) is to create subcomponents with ng-content as you mentioned. If you don't want to create such components, there are two things you can do. CUSTOM_ELEMENTS_SCHEMA You can tell angular to skip over the components it does not recognize by adding CUSTOM_ELEMENTS_SCHEMA to schema array of your feature module. E.g. import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';@NgModule({ imports: [...] schemas: [CUSTOM_ELEMENTS_SCHEMA]})export class CustomModule { } With this way, angular will not complain about level-icon or level-description and transclusion will work just fine. However, setting this option may hide other problems you could have. For example, you can make a typo when using a component and since you told angular you would have CUSTOM_ELEMENTS , it will not give you an error. You end up debugging your code and wondering why the brand new component you just developed is not working. Selecting classes or attributes other than elements. When you write <ng-content select="level-icon"></ng-content> angular will actually look for html elements called level-icon . You can have it search for classes, attributes etc. So what you can do is to change this <ng-content select="level-icon"></ng-content> to <ng-content select="[level-icon]"></ng-content> or <ng-content select=".level-icon"></ng-content> And use your component as follows <app-criteria> <div level-icon> foo </div></app-criteria> or <app-criteria> <div class="level-icon"> foo </div></app-criteria> With this way, you can select for ul , or img . Basically anything you want. If you still want to use <level-icon> as element, you either have to create a subcomponent or use CUSTOM_ELEMENTS_SCHEMA .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51213963', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/187835/']}
jdg_370127
stackexchange
llm_judgeable_groundtruth_similarity
7143299
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: My question is what is condition for the OnFailure callback to be called , how does the runtime know the ajax call is failed (the ajax helper use some http response status code to indicate that? what it would be then?). And if the html of UpdateTargetId is updated no matter the ajax call is failed or success, then how should I handle the error properly then. Very confused... Now provide the response and nothing else.
<script type="text/javascript"> function OnSuccess() { alert('Success'); } function OnFailure(ajaxContext) { var response = ajaxContext.get_response(); var statusCode = response.get_statusCode(); alert('Failure'); Here you can do whatever you want with the div. $('#targetDiv').empty(); } </script> <div id="targetDiv"> @using (Ajax.BeginForm("Index", "Home", new AjaxOptions { UpdateTargetId = "targetDiv", OnSuccess ="OnSuccess", OnFailure ="OnFailure" }) { ... } </div>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7143299', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/376753/']}
jdg_370128
stackexchange
llm_judgeable_groundtruth_similarity
191081
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: Is there any proof of the existence of phase transition in models of statistical mechanics of the Ising type models without using the Peierls' argument and its variations? By models of the Ising type I want to mean Ising models of first and seconds neighbors over lattices $Z^d$ with $d\geq 2$. Now provide the response and nothing else.
wsc's answer (i.e., Onsager's computation of the free energy) provides one alternative road to a proof of a phase transition in the Ising model. It implies the existence of a phase transition in dimension 2 (for the nearest-neighbor model). Combined with correlation inequalities, this implies existence of a phase transition in any dimension d≥2, and interactions of any range (provided that nearest-neighbors also interact). An alternative approach is via reflection positivity, see, for example, these lecture notes . In particular Theorem 3.5 therein implies the existence of a phase transition in all $O(n)$ models in dimensions $3$ and more. This approach (via the so-called infrared bound) cannot yield the result in dimension $2$, however (but notice that the $O(n)$ model do not display spontaneous magnetization in dimension 2 when $n\geq 2$). You can also use slight variants of the Peierls approach, using percolation arguments. For example, you can use a comparison (relying on the FKG inequality available in the random-cluster representation of the Ising model) with the percolation model, in order to show that the existence of a phase transition in the percolation model implies the existence of a phase transition in the Ising model. However, to prove the former, you use again a Peierls-type argument...
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/191081', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/15911/']}
jdg_370129
stackexchange
llm_judgeable_groundtruth_similarity
25817442
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been attempting to change CF7 form fields dynamically without using Contact Form 7 Dynamic Text Extension . I've seen a ton of articles on how to get posted data, just not on how I can overwrite existing values. My goal is to dynamically change the file attachment and add other meta-data associated with each post. Can this be done? Thank you! Here's what I have so far: function wpcf7_custom_before_send(&$cf7) { if ( $cf7->id == 4 ) { $submission = WPCF7_Submission::get_instance(); if ( $submission ) { $data =& $submission->get_posted_data(); // how do I overwrite posted data? } }}add_action("wpcf7_before_send_mail", "wpcf7_custom_before_send"); Now provide the response and nothing else.
You can use my code to do this. Some explanations for your code: 1) Since id $cf7->id property is no longer accessible. Use id() method instead $cf7->id() . 2) No need use & for callback $cf7 and $submission . Use for this return . add_action("wpcf7_before_send_mail", "wpcf7_do_something");function wpcf7_do_something($WPCF7_ContactForm){ if (224 == $WPCF7_ContactForm->id()) { //Get current form $wpcf7 = WPCF7_ContactForm::get_current(); // get current SUBMISSION instance $submission = WPCF7_Submission::get_instance(); // Ok go forward if ($submission) { // get submission data $data = $submission->get_posted_data(); // nothing's here... do nothing... if (empty($data)) return; // extract posted data for example to get name and change it $name = isset($data['your-name']) ? $data['your-name'] : ""; // do some replacements in the cf7 email body $mail = $wpcf7->prop('mail'); // Find/replace the "[your-name]" tag as defined in your CF7 email body // and add changes name $mail['body'] = str_replace('[your-name]', $name . '-tester', $mail['body']); // Save the email body $wpcf7->set_properties(array( "mail" => $mail )); // return current cf7 instance return $wpcf7; } }} That is all, we are changed some tags, and send email with modified tag ;-)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25817442', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1050844/']}
jdg_370130
stackexchange
llm_judgeable_groundtruth_similarity
30095583
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: We have some code in git and I started setting up Jenkins to grab our branches and try a compile. It seems that a few of the branches may have begun to rot in the years since they were last built, as they fail to finish a make. I would like to build all branches that are found, except for a list of excluded ones. Is this possible in Jenkins? This will let me get things up and running, then come back to enable more branches as I try to fix them. What I have tried so far Regex with lookahead Looking at the 'Git > Branches to build' option I was hopeful that I could replace the default '**' wildcard with a :. A bit of digging about and double checking with http://rubular.com/ suggested that the following might do what I wanted. :^(?!origin/exclude\-this\-branch\.v1|origin/exclude\-this\-branch\-too.v2)(\S+) Now there is an assumption here about the regex engine running in the background. I would hope it might understand lookahead, but if it does not that explains why this method fails. It seems to build all the branches, including the one I am try to exclude. Maybe I just need to find some more debug? Looked for similar questions here I came across Jenkins/Hudson Build All Branches With Prioritization which seemed to contain a possible solution in that some added an inverse option to branch matching https://github.com/jenkinsci/git-plugin/pull/45 sounds like what I need. Sadly this does not seem to be in the version of Jenkins I have, which is odd as 2011 is a long time ago. The System I Am Using Ubuntu LTS 14.04. Jenkins ver. 1.611. GNU tool chains to make C/C++ code. Now provide the response and nothing else.
How about using ^(?!.*master).*$ as branch specifier. This regexp means all branches not matching master. Breakdown: ^(?!.*master).*$^ ---> beginning of string (?! ) ---> negative lookahead find all that doesnt match .* ---> zero or more of 'any' character master ---> should not match master .*$ ---> will match anything to the end of string Related: https://stackoverflow.com/a/18709097/109305
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30095583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/741961/']}
jdg_370131
stackexchange
llm_judgeable_groundtruth_similarity
3688993
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 create a video file from a series of images/photos on Android?Can this be done with the current SDK? or do I need a codec library? Now provide the response and nothing else.
I agree with Mark. Among the C/C++ libraries are ffmpeg here or X264 here . I have to say I havn't found them or the Android NDK easy to use but that's probably because I don't really know much about C/C++ and JNI. If you're interested in this route, then the RockPlayer free app for Android has the pre-built shared libraries from ffmpeg ready for use on Android. They claim these libraries only use LGPL components but you'd have to satisfy yourself on this, I guess. With regards to Java, there is a port (of sorts) of ffmpeg called, unsurprisingly, jffmpeg which you can access here but it still calls out to much of the existing ffmpeg framework, so you're back in NDK land. It is possible to convert a series of images to video with the Java Media Framework (JMF) but it has the following drawbacks: Limited number of video formats. Doesn't produce videos which can be played back on most (if not all) Android phones e.g. H264 or MPEG4. The JMF code is now quite old, hasn't progressed in a long time, is bloated and not well structured so there may be additional Java dependencies which are not packaged in Android. Another option I've seen used is Adobe Air, but it's a 17Mb payload which some users complain about. There are lots of other questions here on Stack Overflow regarding ffmpeg and Android NDK. Good luck with the project.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3688993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/203111/']}
jdg_370132
stackexchange
llm_judgeable_groundtruth_similarity
41778623
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: JSONObject jsonObj = {"a":"1","b":null} CASE 1 : jsonObj.getString("a") returns "1"; CASE 2 : jsonObj.getString("b") return nothing ; CASE 3 : jsonObj.getString("c") throws error; How to make case 2 and 3 return null and not "null" ? Now provide the response and nothing else.
You can use get() instead of getString() . This way an Object is returned and JSONObject will guess the right type. Works even for null .Note that there is a difference between Java null and org.json.JSONObject$Null . CASE 3 does not return "nothing", it throws an Exception. So you have to check for the key to exist ( has(key) ) and return null instead. public static Object tryToGet(JSONObject jsonObj, String key) { if (jsonObj.has(key)) return jsonObj.opt(key); return null;} EDIT As you commented, you only want a String or null , which leads to optString(key, default) for fetching. See the modified code: package test;import org.json.JSONObject;public class Test { public static void main(String[] args) { // Does not work // JSONObject jsonObj = {"a":"1","b":null}; JSONObject jsonObj = new JSONObject("{\"a\":\"1\",\"b\":null,\"d\":1}"); printValueAndType(getOrNull(jsonObj, "a")); // >>> 1 -> class java.lang.String printValueAndType(getOrNull(jsonObj, "b")); // >>> null -> class org.json.JSONObject$Null printValueAndType(getOrNull(jsonObj, "d")); // >>> 1 -> class java.lang.Integer printValueAndType(getOrNull(jsonObj, "c")); // >>> null -> null // throws org.json.JSONException: JSONObject["c"] not found. without a check } public static Object getOrNull(JSONObject jsonObj, String key) { return jsonObj.optString(key, null); } public static void printValueAndType(Object obj){ System.out.println(obj + " -> " + ((obj != null) ? obj.getClass() : null)); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41778623', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5058321/']}
jdg_370133
stackexchange
llm_judgeable_groundtruth_similarity
3551242
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm using numpy and want to index a row without losing the dimension information. import numpy as npX = np.zeros((100,10))X.shape # >> (100, 10)xslice = X[10,:]xslice.shape # >> (10,) In this example xslice is now 1 dimension, but I want it to be (1,10).In R, I would use X[10,:,drop=F]. Is there something similar in numpy. I couldn't find it in the documentation and didn't see a similar question asked. Thanks! Now provide the response and nothing else.
It's probably easiest to do x[None, 10, :] or equivalently (but more readable) x[np.newaxis, 10, :] . None or np.newaxis increases the dimension of the array by 1, so that you're back to the original after the slicing eliminates a dimension. As far as why it's not the default, personally, I find that constantly having arrays with singleton dimensions gets annoying very quickly. I'd guess the numpy devs felt the same way. Also, numpy handle broadcasting arrays very well, so there's usually little reason to retain the dimension of the array the slice came from. If you did, then things like: a = np.zeros((100,100,10))b = np.zeros(100,10)a[0,:,:] = b either wouldn't work or would be much more difficult to implement. (Or at least that's my guess at the numpy dev's reasoning behind dropping dimension info when slicing)
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3551242', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/339573/']}
jdg_370134
stackexchange
llm_judgeable_groundtruth_similarity
35367469
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm currently trying to build on Windows (with Intel compiler) a big project compiling very well on UNIX with CMake. Here is a reduced simple example of my problem. Running the following simple example of code using Boost.Python : #include <iostream>#include <Python.h>#include <boost/python.hpp>int main(){ std::string python_home = "C:\\softs\\python\\2.7.9\\64"; char* python_home_char = new char[python_home.length() + 1]; strcpy(python_home_char, python_home.c_str()); Py_SetPythonHome(python_home_char); Py_Initialize(); boost::python::object pyobj_main = boost::python::import("__main__"); boost::python::object glob = pyobj_main.attr("__dict__"); boost::python::exec("print \"Hello from Python\"", glob, glob); Py_Finalize(); return 0;} I get the following error message when executing the code : The program can't start because boost_python-iw-mt-1_57.dll is missing from your computer. Try reinstalling the program to fix this problem. Note that I don't have the error if a remove the 3 lines boost::python::*** at the end of the code. Also, I don't have any error if I compile the following example using Boost.Thread (In my mind, it also use libraries (not header only), is it right ?) : #include <iostream>#include <boost/thread.hpp>boost::mutex mutex_hello;void hello(unsigned long int thread_number){ boost::mutex::scoped_lock lock_hello(mutex_hello); std::cout << "Hello from thread " << thread_number << std::endl;}int main(){ boost::thread_group group; for(unsigned long int i = 0; i < 9; ++i) group.create_thread(boost::bind(hello, i + 1)); group.join_all(); return 0;} Actually, I don't want to use shared libraries, I want my executable more static as possible . I build this code with the following CMake file : cmake_minimum_required(VERSION 2.8.9)# Projectproject(TestBoost)enable_language(C)enable_language(CXX)enable_language(Fortran)# Compiler infoif(CMAKE_SYSTEM_NAME STREQUAL "Windows") set(CompilerName "${CMAKE_CXX_COMPILER_ID}") set(CompilerVersion "${CMAKE_CXX_COMPILER_VERSION}") if(CMAKE_CL_64) set(CompilerArch "64") else() set(CompilerArch "32") endif()endif()string(TOLOWER "${CompilerName}" CompilerName)if("${CompilerVersion}" MATCHES "([0-9]+\\.[0-9]+\\.[0-9]+)\\..*") string(REGEX REPLACE "([0-9]+\\.[0-9]+\\.[0-9]+)\\..*" "\\1" CompilerVersion "${CompilerVersion}")endif()# Libsset(CMAKE_FIND_LIBRARY_SUFFIXES .lib .a ${CMAKE_FIND_LIBRARY_SUFFIXES})# Intelif(CompilerName STREQUAL "intel") string(REGEX REPLACE "(.*)/bin/.*" "\\1" IntelPath "${CMAKE_C_COMPILER}") if(CompilerArch STREQUAL "32") set(IntelArchStr "ia32") elseif(CompilerArch STREQUAL "64") set(IntelArchStr "intel64") endif() set(Compiler_LIBRARY_DIRS "${IntelPath}/compiler/lib/${IntelArchStr}")endif()# Boostset(BOOST_ROOT "C:/softs/boost/1.57.0/${CompilerArch}/${CompilerName}/${CompilerVersion}")set(Boost_USE_MULTITHREAD ON)set(Boost_USE_STATIC_LIBS ON)set(Boost_NO_SYSTEM_PATHS ON)set(Boost_ADDITIONAL_VERSIONS "1.57.0" "1.57")find_package(Boost 1.57.0 REQUIRED COMPONENTS thread system filesystem python)# Pythonset(PythonPath C:/softs/python/2.7.9/${CompilerArch})set(Python_INCLUDE_DIRS ${PythonPath}/include)set(Python_LIBRARY_DIRS ${PythonPath}/libs)set(Python_LIBRARIES python27)# Executableinclude_directories(SYSTEM ${Boost_INCLUDE_DIRS} ${Python_INCLUDE_DIRS})link_directories(${Boost_LIBRARY_DIRS} ${Python_LIBRARY_DIRS} ${Compiler_LIBRARY_DIRS})add_executable(test_boost test_boost.cpp)target_link_libraries(test_boost ${Boost_LIBRARIES} ${Python_LIBRARIES}) I run this CMake script with an initial entry CMAKE_GENERATOR_TOOLSET set to Intel C++ Compiler XE 14.0 , and specifying Intel compiler as native compiler. I have no error or warning while running CMake on it (see the log below). This generates a file TestBoost.sln . When loaded in Visual Studio Professional 2013, I change the compilation type to Release and modify the linker options of the target test_boost to add /NODEFAULTLIB:LIBCMT (workaround due to a bug in CMake). Then I compile without any error. Log from CMake : The C compiler identification is Intel 14.0.4.20140805The CXX compiler identification is Intel 14.0.4.20140805Check for working C compiler using: Visual Studio 12 2013 Win64Check for working C compiler using: Visual Studio 12 2013 Win64 -- worksDetecting C compiler ABI infoDetecting C compiler ABI info - doneCheck for working CXX compiler using: Visual Studio 12 2013 Win64Check for working CXX compiler using: Visual Studio 12 2013 Win64 -- worksDetecting CXX compiler ABI infoDetecting CXX compiler ABI info - doneThe Fortran compiler identification is IntelCheck for working Fortran compiler using: Visual Studio 12 2013 Win64Check for working Fortran compiler using: Visual Studio 12 2013 Win64 -- worksDetecting Fortran compiler ABI infoDetecting Fortran compiler ABI info - doneDetermine Intel Fortran Compiler Implicit Link PathDetermine Intel Fortran Compiler Implicit Link Path -- doneChecking whether C:/Program Files (x86)/Intel/Composer XE 2013 SP1/bin/intel64/icl.exe supports Fortran 90Checking whether C:/Program Files (x86)/Intel/Composer XE 2013 SP1/bin/intel64/icl.exe supports Fortran 90 -- yes[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:515 ] _boost_TEST_VERSIONS = 1.57.0;1.57[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:517 ] Boost_USE_MULTITHREADED = TRUE[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:519 ] Boost_USE_STATIC_LIBS = ON[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:521 ] Boost_USE_STATIC_RUNTIME = [ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:523 ] Boost_ADDITIONAL_VERSIONS = 1.57.0;1.57[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:525 ] Boost_NO_SYSTEM_PATHS = ON[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:577 ] Declared as CMake or Environmental Variables:[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:579 ] BOOST_ROOT = C:/softs/boost/1.57.0/64/intel/14.0.4[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:581 ] BOOST_INCLUDEDIR = [ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:583 ] BOOST_LIBRARYDIR = [ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:585 ] _boost_TEST_VERSIONS = 1.57.0;1.57[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:654 ] Include debugging info:[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:656 ] _boost_INCLUDE_SEARCH_DIRS = C:/softs/boost/1.57.0/64/intel/14.0.4/include;C:/softs/boost/1.57.0/64/intel/14.0.4;NO_CMAKE_SYSTEM_PATH[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:658 ] _boost_PATH_SUFFIXES = boost-1_57_0;boost_1_57_0;boost/boost-1_57_0;boost/boost_1_57_0;boost-1_57;boost_1_57;boost/boost-1_57;boost/boost_1_57[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:678 ] location of version.hpp: C:/softs/boost/1.57.0/64/intel/14.0.4/include/boost-1_57/boost/version.hpp[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:702 ] version.hpp reveals boost 1.57.0[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:787 ] guessed _boost_COMPILER = -iw[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:797 ] _boost_MULTITHREADED = -mt[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:840 ] _boost_RELEASE_ABI_TAG = -[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:842 ] _boost_DEBUG_ABI_TAG = -gd[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:890 ] _boost_LIBRARY_SEARCH_DIRS = C:/softs/boost/1.57.0/64/intel/14.0.4/lib;C:/softs/boost/1.57.0/64/intel/14.0.4/stage/lib;C:/softs/boost/1.57.0/64/intel/14.0.4/include/boost-1_57/lib;C:/softs/boost/1.57.0/64/intel/14.0.4/include/boost-1_57/../lib;C:/softs/boost/1.57.0/64/intel/14.0.4/include/boost-1_57/stage/lib;NO_CMAKE_SYSTEM_PATH[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:1001 ] Searching for THREAD_LIBRARY_RELEASE: libboost_thread-iw-mt-1_57;libboost_thread-iw-mt;libboost_thread-mt-1_57;libboost_thread-mt;libboost_thread;libboost_thread-iw-mt-s-1_57;libboost_thread-iw-mt-s;libboost_thread-mt-s-1_57;libboost_thread-mt-s[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:1037 ] Searching for THREAD_LIBRARY_DEBUG: libboost_thread-iw-mt-gd-1_57;libboost_thread-iw-mt-gd;libboost_thread-mt-gd-1_57;libboost_thread-mt-gd;libboost_thread-mt;libboost_thread;libboost_thread-iw-mt-s-gd-1_57;libboost_thread-iw-mt-s-gd;libboost_thread-mt-s-gd-1_57;libboost_thread-mt-s-gd[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:1001 ] Searching for SYSTEM_LIBRARY_RELEASE: libboost_system-iw-mt-1_57;libboost_system-iw-mt;libboost_system-mt-1_57;libboost_system-mt;libboost_system;libboost_system-iw-mt-s-1_57;libboost_system-iw-mt-s;libboost_system-mt-s-1_57;libboost_system-mt-s[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:1037 ] Searching for SYSTEM_LIBRARY_DEBUG: libboost_system-iw-mt-gd-1_57;libboost_system-iw-mt-gd;libboost_system-mt-gd-1_57;libboost_system-mt-gd;libboost_system-mt;libboost_system;libboost_system-iw-mt-s-gd-1_57;libboost_system-iw-mt-s-gd;libboost_system-mt-s-gd-1_57;libboost_system-mt-s-gd[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:1001 ] Searching for FILESYSTEM_LIBRARY_RELEASE: libboost_filesystem-iw-mt-1_57;libboost_filesystem-iw-mt;libboost_filesystem-mt-1_57;libboost_filesystem-mt;libboost_filesystem;libboost_filesystem-iw-mt-s-1_57;libboost_filesystem-iw-mt-s;libboost_filesystem-mt-s-1_57;libboost_filesystem-mt-s[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:1037 ] Searching for FILESYSTEM_LIBRARY_DEBUG: libboost_filesystem-iw-mt-gd-1_57;libboost_filesystem-iw-mt-gd;libboost_filesystem-mt-gd-1_57;libboost_filesystem-mt-gd;libboost_filesystem-mt;libboost_filesystem;libboost_filesystem-iw-mt-s-gd-1_57;libboost_filesystem-iw-mt-s-gd;libboost_filesystem-mt-s-gd-1_57;libboost_filesystem-mt-s-gd[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:1001 ] Searching for PYTHON_LIBRARY_RELEASE: libboost_python-iw-mt-1_57;libboost_python-iw-mt;libboost_python-mt-1_57;libboost_python-mt;libboost_python;libboost_python-iw-mt-s-1_57;libboost_python-iw-mt-s;libboost_python-mt-s-1_57;libboost_python-mt-s[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:1037 ] Searching for PYTHON_LIBRARY_DEBUG: libboost_python-iw-mt-gd-1_57;libboost_python-iw-mt-gd;libboost_python-mt-gd-1_57;libboost_python-mt-gd;libboost_python-mt;libboost_python;libboost_python-iw-mt-s-gd-1_57;libboost_python-iw-mt-s-gd;libboost_python-mt-s-gd-1_57;libboost_python-mt-s-gd[ C:/Program Files (x86)/CMake/share/cmake-3.1/Modules/FindBoost.cmake:1088 ] Boost_FOUND = 1Boost version: 1.57.0Found the following Boost libraries: thread system filesystem pythonConfiguring done How can I force the compilation to use only static libraries ? I thought it was the case with the options in the CMake file. Moreover, it's working with the example using threads... Maybe something is wrong in the installation of Boost.Python ? Now provide the response and nothing else.
When using Boost.Python, the default configuration is dynamic linking. To force static linking, define BOOST_PYTHON_STATIC_LIB in the compilation. Consider either: Add add_definitions(-DBOOST_PYTHON_STATIC_LIB) within CMake Add #define BOOST_PYTHON_STATIC_LIB before including boost/python.hpp Add #define BOOST_PYTHON_STATIC_LIB in boost/config/user.hpp Boost.Python is an exception to the Boost_USE_STATIC_LIBS CMake variable. The FindBoost documentation notes: On Visual Studio and Borland compilers Boost headers request automatic linking to corresponding libraries. [...] Boost automatic linking typically requests static libraries with a few exceptions (such as Boost.Python). Unfortunately, the BOOST_PYTHON_STATIC_LIB option is neither listed in the Boost user settable options , Choosing a Boost.Python Library Binary , nor Boost.Python Configuration Information documentation. A few other recommendations given your example code: Per Boost.Python's embedding documentation , do not invoke Py_Finalize() . Some internal Boost.Python objects will remain alive during Py_Finalize() , and only attempt to be deleted when Boost.Python unloads, causing the objects to attempt deletion with a non-existent interpreter. Do not directly include, python.h . If you must, consider including boost/python/detail/wrap_python.hpp instead. Do not include any system headers before python.h (or the Boost.Python files). This restriction is imposed by Python (see here ). The latter two recommendations documented in the #include issues section.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35367469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3378179/']}
jdg_370135
stackexchange
llm_judgeable_groundtruth_similarity
49664303
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I try to convert html design to pdf using this <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script> I tried to design table as i want,the table looks in html like but when i try to convert pdf it become my html code <div id="content"><table id="example1" class="display table table-bordered table-striped row- border order-column" cellspacing="0" width="auto"> <thead style="background-color: #b6b37e"> <tr> <th>No</th> <th>PO Number</th> <th>Article Code</th> <th>Description</th> <th>Qty</th> <th>Price</th> <th>Discount</th> </tr> </thead> <tbody> <tr ng-repeat="x in listData"> <td>{{x.nomer}}</td> <td>{{x.po_code}}</td> <td>{{x.article_code}}</td> <td>{{x.long_description}}</td> <td>{{x.qty}}</td> <td >{{x.price | number:0}}</td> <td>{{x.discountpct}}</td> </tr> </tbody> </table> </div> this my Javascript code <script>function onClick() { var pdf = new jsPDF('p', 'pt', 'letter'); pdf.canvas.height = 72 * 11; pdf.canvas.width = 100 * 8.5; var isi = document.getElementById("content"); pdf.fromHTML(isi); pdf.save('Purchase_Order.pdf'); }; var element = document.getElementById("clickbind"); element.addEventListener("click", onClick); </script> how to make my pdf file same like html design? Now provide the response and nothing else.
Use html2canvas with jsPDF . Alone jsPDF can not keep css style. You must need some plugin with jsPDF. Below is working example: <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.5/jspdf.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script><button id="clickbind">Click</button><div id="content"> <table id="example1" class="display table table-bordered table-striped row- border order-column" cellspacing="0" width="auto"> <thead style="background-color: #b6b37e"> <tr> <th>No</th> <th>PO Number</th> <th>Article Code</th> <th>Description</th> <th>Qty</th> <th>Price</th> <th>Discount</th> </tr> </thead> <tbody> <tr ng-repeat="x in listData"> <td>{{x.nomer}}</td> <td>{{x.po_code}}</td> <td>{{x.article_code}}</td> <td>{{x.long_description}}</td> <td>{{x.qty}}</td> <td>{{x.price | number:0}}</td> <td>{{x.discountpct}}</td> </tr> </tbody> </table></div><script> function onClick() { html2canvas(document.body, { onrendered: function(canvas) { var img = canvas.toDataURL("image/png"); var doc = new jsPDF(); doc.addImage(img, 'JPEG', 20, 20); doc.save('test.pdf'); } }); }; var element = document.getElementById("clickbind"); element.addEventListener("click", onClick);</script>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49664303', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9388709/']}
jdg_370136
stackexchange
llm_judgeable_groundtruth_similarity
21002292
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 investigating for another question , I found the following: >>> class A:... def m(self): return 42... >>> a = A() This was expected: >>> A.m == A.mTrue>>> a.m == a.mTrue But this I did not expect: >>> a.m is a.mFalse And especially not this: >>> A.m is A.mFalse Python seems to create new objects for each method access. Why am I seeing this behavior? I.e. what is the reason why it can't reuse one object per class and one per instance? Now provide the response and nothing else.
Yes, Python creates new method objects for each access, because it builds a wrapper object to pass in self . This is called a bound method . Python uses descriptors to do this; function objects have a __get__ method that is called when accessed on a class: >>> A.__dict__['m'].__get__(A(), A)<bound method A.m of <__main__.A object at 0x10c29bc10>>>>> A().m<bound method A.m of <__main__.A object at 0x10c3af450>> Note that Python cannot reuse A().m ; Python is a highly dynamic language and the very act of accessing .m could trigger more code, which could alter behaviour of what A().m would return next time when accessed. The @classmethod and @staticmethod decorators make use of this mechanism to return a method object bound to the class instead, and a plain unbound function, respectively: >>> class Foo:... @classmethod... def bar(cls): pass... @staticmethod... def baz(): pass... >>> Foo.__dict__['bar'].__get__(Foo(), Foo)<bound method type.bar of <class '__main__.Foo'>>>>> Foo.__dict__['baz'].__get__(Foo(), Foo)<function Foo.baz at 0x10c2a1f80>>>> Foo().bar<bound method type.bar of <class '__main__.Foo'>>>>> Foo().baz<function Foo.baz at 0x10c2a1f80> See the Python descriptor howto for more detail. However, Python 3.7 adds a new LOAD_METHOD - CALL_METHOD opcode pair that replaces the current LOAD_ATTRIBUTE - CALL_FUNCTION opcode pair precisely to avoid creating a new method object each time. This optimisation transforms the executon path for instance.foo() from type(instance).__dict__['foo'].__get__(instance, type(instance))() with type(instance).__dict__['foo'](instance) , so 'manually' passing in the instance directly to the function object. The optimisation falls back to the normal attribute access path (including binding descriptors) if the attribute found is not a pure-python function object.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21002292', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/292477/']}
jdg_370137
stackexchange
llm_judgeable_groundtruth_similarity
10074016
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 filter on tags when agenda constructs its view? I have tried the following to show only work related appointments: ("j" "Jobb" ((agenda "" ((org-agenda-skip-function '(org-agenda-skip-entry-if 'notregexp":jobb:")))) (tags-todo "jobb")) ((org-agenda-compact-blocks nil))) This works only if the actual appointment is directly tagged, but not if the appointment inherits its tag from a parent headline like this: * Tider :jobb: ** Millas arbetstider <2012-04-11 ons 05:00-09:00> <2012-04-12 tor 04:15-08:30> <2012-04-13 fre 14:30-18:30> Is there another way to do this so that appointments that inherits its tag shows up? Now provide the response and nothing else.
The issue is in how org-agenda-skip-entries-if interacts with 'notregexp . It will skip any entries that do not match :jobb: . Even though the later entries inherit the tag, it is not explicitly listed and so they are skipped. There also does not seem to be any built-in method to match (or not match) on tags using org-agenda-skip-entries-if . If there is such a function it would likely be the more efficient method of looking for the tags, but I'm not aware of such a function. You instead have to create a custom function that will provide the desired search-format. If you change your agenda command to: ("j" "Jobb" ((agenda "" ((org-agenda-skip-function '(zin/org-agenda-skip-tag "jobb" 't)))) (tags-todo "jobb")) ((org-agenda-compact-blocks nil))) and define zin/org-agenda-skip-tag as: (defun zin/org-agenda-skip-tag (tag &optional others) "Skip all entries that correspond to TAG.If OTHERS is true, skip all entries that do not correspond to TAG." (let ((next-headline (save-excursion (or (outline-next-heading) (point-max)))) (current-headline (or (and (org-at-heading-p) (point)) (save-excursion (org-back-to-heading))))) (if others (if (not (member tag (org-get-tags-at current-headline))) next-headline nil) (if (member tag (org-get-tags-at current-headline)) next-headline nil)))) You will get what I understand to be your desired agenda view. If I have it backwards and the entries on the next 3 days should not be present, you simply have to change the function to (zin/org-agenda-skip-tag "jobb") or (zin/org-agenda-skip-tag "jobb" 'nil) , they are equivalent in this case. Agenda View In this case test-new is the name of the org-file I was using, it can be ignored. I also set both headlines to TODO to have them visible when testing the function, since I was restricting the agenda to only the one file. Week-agenda (W15):Monday 9 April 2012 W15Tuesday 10 April 2012Wednesday 11 April 2012 test-new: 5:00- 9:00 TODO Millas arbetstider :jobb::Thursday 12 April 2012 test-new: 4:15- 8:30 TODO Millas arbetstider :jobb::Friday 13 April 2012 test-new: 14:30-18:30 TODO Millas arbetstider :jobb::Saturday 14 April 2012Sunday 15 April 2012================================================================================Headlines with TAGS match: jobb test-new: TODO Tider :jobb: test-new: TODO Millas arbetstider :jobb::
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10074016', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/757537/']}
jdg_370138
stackexchange
llm_judgeable_groundtruth_similarity
4986673
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to understand rvalue references and move semantics of C++11. What is the difference between these examples, and which of them is going to do no vector copy? First example std::vector<int> return_vector(void){ std::vector<int> tmp {1,2,3,4,5}; return tmp;}std::vector<int> &&rval_ref = return_vector(); Second example std::vector<int>&& return_vector(void){ std::vector<int> tmp {1,2,3,4,5}; return std::move(tmp);}std::vector<int> &&rval_ref = return_vector(); Third example std::vector<int> return_vector(void){ std::vector<int> tmp {1,2,3,4,5}; return std::move(tmp);}std::vector<int> &&rval_ref = return_vector(); Now provide the response and nothing else.
First example std::vector<int> return_vector(void){ std::vector<int> tmp {1,2,3,4,5}; return tmp;}std::vector<int> &&rval_ref = return_vector(); The first example returns a temporary which is caught by rval_ref . That temporary will have its life extended beyond the rval_ref definition and you can use it as if you had caught it by value. This is very similar to the following: const std::vector<int>& rval_ref = return_vector(); except that in my rewrite you obviously can't use rval_ref in a non-const manner. Second example std::vector<int>&& return_vector(void){ std::vector<int> tmp {1,2,3,4,5}; return std::move(tmp);}std::vector<int> &&rval_ref = return_vector(); In the second example you have created a run time error. rval_ref now holds a reference to the destructed tmp inside the function. With any luck, this code would immediately crash. Third example std::vector<int> return_vector(void){ std::vector<int> tmp {1,2,3,4,5}; return std::move(tmp);}std::vector<int> &&rval_ref = return_vector(); Your third example is roughly equivalent to your first. The std::move on tmp is unnecessary and can actually be a performance pessimization as it will inhibit return value optimization. The best way to code what you're doing is: Best practice std::vector<int> return_vector(void){ std::vector<int> tmp {1,2,3,4,5}; return tmp;}std::vector<int> rval_ref = return_vector(); I.e. just as you would in C++03. tmp is implicitly treated as an rvalue in the return statement. It will either be returned via return-value-optimization (no copy, no move), or if the compiler decides it can not perform RVO, then it will use vector's move constructor to do the return . Only if RVO is not performed, and if the returned type did not have a move constructor would the copy constructor be used for the return.
{}
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/4986673', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/179372/']}
jdg_370139
stackexchange
llm_judgeable_groundtruth_similarity
1674219
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 some reason, during my development cycle I find myself deleting NSLog statements that I had inserted to aid in debugging. I don't really know why I have this habit, I just do it. On occasion, during development I'll find that I'll run into a problem I've had before, and then wind up re-adding an old NSLog statement. And then deleting it again later. Is there any good reason to delete NSLog statements? From my experience leaving one or two in hasn't caused any app rejection. And since, to my knowledge, they don't log anything anywhere when an app is in distribution (please correct me if I am wrong on this), it doesn't seem like they are harming anything. Is there a performance hit that I should be worried about? Now provide the response and nothing else.
What I do is add a macro that does the logging only when I am in Debug mode. Put this in your <APP_NAME>_Prefix.pch file #ifdef DEBUG#define DebugLog( s, ... ) NSLog( @"<%p %@:%d (%@)> %@", self, [[NSString stringWithUTF8String:__FILE__] lastPathComponent], __LINE__, NSStringFromSelector(_cmd), [NSString stringWithFormat:(s), ##__VA_ARGS__] )#else#define DebugLog( s, ... ) #endif As a bonus to the regular log, you get filename, method name, and line number. Then in the project info, add this under the debug build only. It goes in the User-defined sections under GCC_PREPROCESSOR_DEFINITIONS: DEBUG Then replace any of the NSLog's you have in your project with DebugLog (it takes the same args as NSLog) and you won't have to worry about releasing debug statements live. In answer to your question, logging can slow down the performance of an app and unless you require them for help debugging in the wild, I would leave them out.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1674219', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/543/']}
jdg_370140