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 | 57036131 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to override the exclude / include of a webpack rule. The project has been created with vue-cli-sevice and therefore only has a vue.config.js . I am able to hook into the configuration with chainWebpack , but I'm not able to edit the rule itself. The output of vue-cli-service inspect contains the rule I want to edit: /* config.module.rule('js') */ { test: /\.jsx?$/, exclude: [ function () { /* omitted long function */ } ], use: [ { loader: 'cache-loader', options: { cacheDirectory: '/Users/m/projects/echo/.../.cache/babel-loader', cacheIdentifier: '4b5cee3d' } }, { loader: 'babel-loader' } ] }, I now want to edit this configuration from my vue.config.js (the commented out part shows how I found it in the documentation but it's not working): const chainWebpack = (config) => { config.module.rule('js'); // .include // .add('node-modules/blubb') // .end();};module.exports = { chainWebpack}; How can I add an include or override the exclude property of this rule configuration?
Now provide the response and nothing else.
| I got it working like so. This clears the whole exclude and adds an include. const chainWebpack = (config) => { config.module .rule('js') .test(/\.jsx?$/) .exclude .clear() .end() .include .add(function() { return [ 'node_modules/include-me', 'src' ] }) .end()}; The easiest way to check if everything works as expected is IMO to run vue-cli-service inspect . Change the config, check if inspect fails and, if it doesn't, check if the output contains the desired changes. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57036131', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4410144/']} | jdg_71341 |
stackexchange | llm_judgeable_groundtruth_similarity | 614128 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I read all sudo posts on serverfault, but I still cannot figure out what I'm doing wrong. Normally I finally find the solution but not this time : I want apache user to be able to execute this command as user "hremotessh" : sudo /home/hremotessh/scripts/redirect.sh 8892 8893 Therefore I added this in visudo : apache ALL=(hremotessh) NOPASSWD: /home/hremotessh/scripts/redirect.sh But sudo is still asking the password ? sudo /home/hremotessh/scripts/redirect.sh[sudo] password for apache: I tried this, but not better : sudo -u hremotessh /home/hremotessh/scripts/redirect.shhremotessh is not in the sudoers file. This incident will be reported. Any idea would be warmly welcomed :-) Denis
Now provide the response and nothing else.
| Unless you want to run the command as root you need to specify the username, so su - apache -s /bin/bash sudo -u hremotessh /home/hremotessh/scripts/redirect.sh 8892 8893 is the correct syntax to test the sudo command. Since you're not prompted for the apache user's password sudo seems to be configured correctly. The resulting warning: hremotessh is not in the sudoers file. indicates that another sudo command is used in the redirect.sh script. And there's no (valid) sudo policy for that user. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/614128', 'https://serverfault.com', 'https://serverfault.com/users/59404/']} | jdg_71342 |
stackexchange | llm_judgeable_groundtruth_similarity | 271672 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I inherited a lower-level open source Java network library. The library is intended to be used by higher-level application protocol libraries which are in turn used by application code. My library, as left by the previous maintainer, has no dependencies and is built via Ant. The build artifact is a simple jar that others can drop into their projects. I am in the process of converting the library to be built with Maven. As I'm doing this, I'm considering possibly adding slf4j as a dependency. Currently, when something goes wrong, stack traces or other information is spit out to System.out or System.err. I know that that's not always very helpful, but these outputs only happen at 10 to 15 places in the code and are rarely executed. So what do you think? Keep the library simple with zero dependencies or introduce slf4j?
Now provide the response and nothing else.
| If you use the Maven Assembly Plugin , you can include the slf4j jar (along with whichever implementation you prefer) inside your deployed jar. There are more complicated options if you want to allow users to choose the logging library, but it will run perfectly well if you make a fat jar with or without the slf4j implementation. Users are much more likely to be annoyed - unless hard drive space is really (and I mean really) at a premium - if they have to deal with System.out and System.err output than if there's a provided logging framework, even if it's just the default no-op implementation and the have to add log4j or logback if they want to see the logs. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/271672', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/166032/']} | jdg_71343 |
stackexchange | llm_judgeable_groundtruth_similarity | 7626 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
This seems like an obvious fact, but I'm not sure what the necessary meaning of "nice" is to get a result like this. I'm wondering if there is a theorem of the form: For any <1> field extension $K/F$, a map from $\phi:K\rightarrow F$ that satisfies <2> is the field norm (or trace). where <1> could be something like finite, algebraic, etc., and <2> could be anything (obviously there would be different <2>'s for norm and trace).
Now provide the response and nothing else.
| The field norm and trace exist when $K$ is a finite algebraic extension of $F$. In this case, an element $\alpha \in K$ can be interpreted as an $F$-linear map on $K$ by multiplication. The field norm is just the determinant of $\alpha$ as a linear map, while the trace is the trace of $\alpha$ as a linear map. This yields an evident generalization: Norm and trace are part of a family of nice maps, namely the coefficients of the characteristic polynomial of $\alpha$. Since Zev asks for a uniqueness theorem in the comments, here is one that shows both the merits and limitations of the characteristic polynomial as an answer. For simplicity let $F$ have characteristic 0. Let $K$ be a field extension of degree $n$ which is generic in the sense that the Galois group is $S_n$. Then any Galois-invariant polynomial in $\alpha \in K$ and its Galois conjugates, is a symmetric polynomial. The theorem is that the algebra of symmetric polynomials is generated by elementary symmetric polynomials, which are exactly the coefficients of the characteristic polynomial of $\alpha$. (This is using the fact that the eigenvalues of $\alpha$ as a map are itself and its Galois conjugates.) In particular, the trace is the unique linear such map up to a scalar; and any multiplicative polynomial of this type is a power of the norm. You can also describe the norm as the last Galois-invariant polynomial (the one of degree $n$) that provides new information. But if the Galois group is smaller, then the ring of invariant polynomials in $\alpha$ and its Galois conjugates is larger, and any of these other invariant polynomials is also "nice". These extras are somewhat hidden by the fact that, for any Galois group, the trace is still the only linear example and the norm is still the only multiplicative example. Well, the original question was open-ended. I think that this answer does fit one interpretation of the question, but maybe it is too standard and maybe there are also other interesting answers. | {} | {'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/7626', 'https://mathoverflow.net', 'https://mathoverflow.net/users/1916/']} | jdg_71344 |
stackexchange | llm_judgeable_groundtruth_similarity | 13955157 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I just want to declare a static property in typescript interface? I have not found anywhere regarding this. interface myInterface { static Name:string;} Is it possible?
Now provide the response and nothing else.
| Follow @Duncan's @Bartvds's answer, here to provide a workable way after years passed. At this point after Typescript 1.5 released (@Jun 15 '15), your helpful interface interface MyType { instanceMethod();}interface MyTypeStatic { new():MyType; staticMethod();} can be implemented this way with the help of decorator. /* class decorator */function staticImplements<T>() { return <U extends T>(constructor: U) => {constructor};}@staticImplements<MyTypeStatic>() /* this statement implements both normal interface & static interface */class MyTypeClass { /* implements MyType { */ /* so this become optional not required */ public static staticMethod() {} instanceMethod() {}} Refer to my comment at github issue 13462 . visual result:Compile error with a hint of static method missing. After static method implemented, hint for method missing. Compilation passed after both static interface and normal interface fulfilled. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/13955157', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1116467/']} | jdg_71345 |
stackexchange | llm_judgeable_groundtruth_similarity | 2600492 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm looking for an algebraic solution for $x$. $$ \frac{x}{x+2} -3 = \frac{5x}{x^2-4}+x$$ My first go at this involved converting this into an expression with a cubic numerator and $(x+2)(x-2)$ as the denominator. To find the roots, I then tried to divide each factor in the denominator into to cubic. No success. I've converted this expression to: $$ x(x-7)= (x+3)(x+2)(x-2)$$ which illustrates the futility of my first approach. There are no common factors. Can I solve this without invoking the cubic formula? Edit: To clarify, the the Precalculus textbook calls for an algebraic and graphic solution. If you have an algebraic solution that would be accessible to a precalculus student, please provide it.
Now provide the response and nothing else.
| Assuming $x^2\neq 4$, you end with the cubic equation$$x^3+2 x^2+3 x-12=0$$ So, consider the function $$f(x)=x^3+2 x^2+3 x-12 \implies f'(x)=3 x^2+4 x+3$$ The first derivative does not cancel which means that there is only one real root. Now, use inspection : $f(0)=-12$, $f(1)=-6$, $f(2)=10$. So, the root is between $1$ and $2$. Looking deeper $f(\frac 32)=\frac 38$ telling that the root is slightly below $1.5$. Make $x=y+\frac 32$ which makes the equation to be$$g(y)=y^3+\frac{13 y^2}{2}+\frac{63 y}{4}+\frac{3}{8}$$ if we admit that $y$ is small, then $$g(y) \approx \frac{63 y}{4}+\frac{3}{8}=0 \implies y=-\frac{1}{42}$$ So, an approximate solution is $$x \approx \frac 32-\frac{1}{42}=\frac{31}{21}\implies f(\frac{31}{21})=\frac{34}{9261}$$ which is now quite small. Repeat the process making now $x=y+\frac{31}{21}$ giving$$g(y)=y^3+\frac{45 y^2}{7}+\frac{2270 y}{147}+\frac{34}{9261}$$ then $$g(y) \approx \frac{2270 y}{147}+\frac{34}{9261}=0 \implies y=-\frac{17}{71505}$$ So, an approximate solution is $$x \approx \frac{31}{21}-\frac{17}{71505}=\frac{105538}{71505}\approx 1.47595$$ while the exact solution (solving the cubic) would be $\approx 1.47595$ ! | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2600492', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/266049/']} | jdg_71346 |
stackexchange | llm_judgeable_groundtruth_similarity | 2251964 |
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 MSDN, the description of the Thread.Abort() method says: "Calling this method usually terminates the thread." Why not ALWAYS? In which cases it doesn't terminate the thread? Are there any other possibility to terminate threads?
Now provide the response and nothing else.
| Thread.Abort() injects a ThreadAbortException on the thread. The thread may cancel the request by calling Thread.ResetAbort() . Also, there are certain code parts, such as finally block that will execute before the exception is handled. If for some reason the thread is stuck in such a block the exception will never be raised on the thread. As the caller has very little control over the state of the thread when calling Abort() , it is generally not advisable to do so. Pass a message to the thread requesting termination instead. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2251964', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/101375/']} | jdg_71347 |
stackexchange | llm_judgeable_groundtruth_similarity | 35901915 |
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--B--C master \ D branch0 Then I squash B and C into B' .How do I rebase branch0 such that it looks like this: A--B' master \ D branch0
Now provide the response and nothing else.
| Use the --onto argument to git rebase, which changes the baseline that git replays work on. git checkout branch0 At this state you should still see C in your git history. git rebase --onto B' C This translates to: Take all commits in my current branch since commit C (In your case that's just D ) and play back on top of B' You can also use the optional <branch> argument to do both the checkout and rebase at once: git rebase --onto B' C branch0 | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/35901915', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1954235/']} | jdg_71348 |
stackexchange | llm_judgeable_groundtruth_similarity | 17557074 |
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 do something fairly simple, reading a large csv file into a pandas dataframe. data = pandas.read_csv(filepath, header = 0, sep = DELIMITER,skiprows = 2) The code either fails with a MemoryError , or just never finishes. Mem usage in the task manager stopped at 506 Mb and after 5 minutes of no change and no CPU activity in the process I stopped it. I am using pandas version 0.11.0. I am aware that there used to be a memory problem with the file parser, but according to http://wesmckinney.com/blog/?p=543 this should have been fixed. The file I am trying to read is 366 Mb, the code above works if I cut the file down to something short (25 Mb). It has also happened that I get a pop up telling me that it can't write to address 0x1e0baf93... Stacktrace: Traceback (most recent call last): File "F:\QA ALM\Python\new WIM data\new WIM data\new_WIM_data.py", line 25, in <module> wimdata = pandas.read_csv(filepath, header = 0, sep = DELIMITER,skiprows = 2) File "C:\Program Files\Python\Anaconda\lib\site-packages\pandas\io\parsers.py", line 401, in parser_f return _read(filepath_or_buffer, kwds) File "C:\Program Files\Python\Anaconda\lib\site-packages\pandas\io\parsers.py", line 216, in _read return parser.read() File "C:\Program Files\Python\Anaconda\lib\site-packages\pandas\io\parsers.py", line 643, in read df = DataFrame(col_dict, columns=columns, index=index) File "C:\Program Files\Python\Anaconda\lib\site-packages\pandas\core\frame.py", line 394, in __init__ mgr = self._init_dict(data, index, columns, dtype=dtype) File "C:\Program Files\Python\Anaconda\lib\site-packages\pandas\core\frame.py", line 525, in _init_dict dtype=dtype) File "C:\Program Files\Python\Anaconda\lib\site-packages\pandas\core\frame.py", line 5338, in _arrays_to_mgr return create_block_manager_from_arrays(arrays, arr_names, axes) File "C:\Program Files\Python\Anaconda\lib\site-packages\pandas\core\internals.py", line 1820, in create_block_manager_from_arrays blocks = form_blocks(arrays, names, axes) File "C:\Program Files\Python\Anaconda\lib\site-packages\pandas\core\internals.py", line 1872, in form_blocks float_blocks = _multi_blockify(float_items, items) File "C:\Program Files\Python\Anaconda\lib\site-packages\pandas\core\internals.py", line 1930, in _multi_blockify block_items, values = _stack_arrays(list(tup_block), ref_items, dtype) File "C:\Program Files\Python\Anaconda\lib\site-packages\pandas\core\internals.py", line 1962, in _stack_arrays stacked = np.empty(shape, dtype=dtype)MemoryErrorPress any key to continue . . . A bit of background - I am trying to convince people that Python can do the same as R. For this I am trying to replicate an R script that does data <- read.table(paste(INPUTDIR,config[i,]$TOEXTRACT,sep=""), HASHEADER, DELIMITER,skip=2,fill=TRUE) R not only manages to read the above file just fine, it even reads several of these files in a for loop (and then does some stuff with the data). If Python does have a problem with files of that size I might be fighting a loosing battle...
Now provide the response and nothing else.
| Windows memory limitation Memory errors happens a lot with python when using the 32bit version in Windows. This is because 32bit processes only gets 2GB of memory to play with by default. Tricks for lowering memory usage If you are not using 32bit python in windows but are looking to improve on your memory efficiency while reading csv files, there is a trick. The pandas.read_csv function takes an option called dtype . This lets pandas know what types exist inside your csv data. How this works By default, pandas will try to guess what dtypes your csv file has. This is a very heavy operation because while it is determining the dtype, it has to keep all raw data as objects (strings) in memory. Example Let's say your csv looks like this: name, age, birthdayAlice, 30, 1985-01-01Bob, 35, 1980-01-01Charlie, 25, 1990-01-01 This example is of course no problem to read into memory, but it's just an example. If pandas were to read the above csv file without any dtype option, the age would be stored as strings in memory until pandas has read enough lines of the csv file to make a qualified guess. I think the default in pandas is to read 1,000,000 rows before guessing the dtype. Solution By specifying dtype={'age':int} as an option to the .read_csv() will let pandas know that age should be interpreted as a number. This saves you lots of memory. Problem with corrupt data However, if your csv file would be corrupted, like this: name, age, birthdayAlice, 30, 1985-01-01Bob, 35, 1980-01-01Charlie, 25, 1990-01-01Dennis, 40+, None-Ur-Bz Then specifying dtype={'age':int} will break the .read_csv() command, because it cannot cast "40+" to int. So sanitize your data carefully! Here you can see how the memory usage of a pandas dataframe is a lot higher when floats are kept as strings: Try it yourself df = pd.DataFrame(pd.np.random.choice(['1.0', '0.6666667', '150000.1'],(100000, 10)))resource.getrusage(resource.RUSAGE_SELF).ru_maxrss# 224544 (~224 MB)df = pd.DataFrame(pd.np.random.choice([1.0, 0.6666667, 150000.1],(100000, 10)))resource.getrusage(resource.RUSAGE_SELF).ru_maxrss# 79560 (~79 MB) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17557074', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2565842/']} | jdg_71349 |
stackexchange | llm_judgeable_groundtruth_similarity | 2463528 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $R$ be a commutative unitary ring and $P_1,P_2,...,P_m$ a finite family of prime ideals in $R$ such that$$\bigcap_{k=1}^m P_k \subseteq P$$for a prime ideal $P$ in $R$.Then $P_k\subseteq P$ for some $k\in\{1,2,...,m\}$ because $P_1P_2...P_m\subseteq \bigcap_{k=1}^m P_k$ and $P$ is prime. Is the same true for an arbitrary infinite intersection $\bigcap_M P_k$ of prime ideals? More precisely, let $P_k$ with $k\in M$ and $J$ be prime ideals in $R$ with $\bigcap_M P_k\subseteq P$. Do we have $P_k\subseteq P$ for some $k\in M$?
Now provide the response and nothing else.
| No: let $R=\mathbb{Z}$, $P=(0)$, and let $P_1=2\mathbb{Z},P_2=3\mathbb{Z},P_3=5\mathbb{Z}$, and so on. Then $$ \bigcap_{k=1}^{\infty}P_k=(0)=P$$but none of the $P_k$ are contained in $P$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2463528', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/112173/']} | jdg_71350 |
stackexchange | llm_judgeable_groundtruth_similarity | 127983 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Here are two equations: eq1 = D[z[x], {x, 4}] + z[x] == 0;eq2 = D[z[x], {x, 4}] + q^4*z[x] == 0; They only differ from one another by the scale factor q^4, where q>0. I need to solve them in real numbers. If I solve the first one I get DSolveValue[eq1, z[x], x](* E^(x/Sqrt[2]) C[1] Cos[x/Sqrt[2]] + E^(-(x/Sqrt[2])) C[2] Cos[x/Sqrt[2]] + E^(-(x/Sqrt[2])) C[3] Sin[x/Sqrt[2]] + E^(x/Sqrt[2]) C[4] Sin[x/Sqrt[2]] *) which is convenient to look at. However, if I solve the second one, I get: DSolveValue[eq2, z[x], x](* E^((-1)^(3/4) q x) C[1] + E^(-(-1)^(1/4) q x) C[2] + E^(-(-1)^(3/4) q x) C[3] + E^((-1)^(1/4) q x) C[4] *) which is alredy less convenient. Since q is real and positive, it is obvious, that the solution is like the solution of eq1, in which we make a replacement: x->q*x : DSolveValue[eq1, z[x], x] /. x -> q*x(* E^((q x)/Sqrt[2]) C[1] Cos[(q x)/Sqrt[2]] + E^(-((q x)/Sqrt[2])) C[2] Cos[(q x)/Sqrt[2]] + E^(-((q x)/Sqrt[2])) C[3] Sin[(q x)/Sqrt[2]] + E^((q x)/Sqrt[2]) C[4] Sin[(q x)/Sqrt[2]] *) However, I cannot find a regular operation which would transform the solution of eq2 into this form. Any idea?
Now provide the response and nothing else.
| This post contains several code blocks, you can copy them easily with the help of importCode . Analytic Solution The analytic solution can be obtained with LaplaceTransform and FourierSinCoefficient . First, make a Laplace transform on the equation and b.c.s and plug in the i.c.s: Clear[f];f[x_] = x (1 - x);eqn = D[u[t, x], {t, 2}] + D[u[t, x], {x, 4}] == 0;ic = {u[0, x] == f@x, Derivative[1, 0][u][0, x] == 0};bc = {u[t, 0] == 0, u[t, 1] == 0, Derivative[0, 2][u][t, 0] == 0, Derivative[0, 2][u][t, 1] == 0};teqn = LaplaceTransform[{eqn, bc}, t, s] /. Rule @@@ ic Now we have an ODE, solve it with DSolve : tsol = u[t, x] /. First@DSolve[teqn/. HoldPattern@LaplaceTransform[a_, __] :> a, u[t, x], x] // Simplify Notice the replacement HoldPattern@LaplaceTransform[a_, __] :> a is necessary because DSolve has trouble in handling expression containing LaplaceTransform . The last step is to transform the solution back, but sadly InverseLaplaceTransform can't handle tsol . At this point, one work-around is to turn to numeric inverse Laplace transform, you can use this or this package for this task. But for your specific problem, we can circumvent the issue by expanding tsol with Fourier sine series: easyFourierSinCoefficient[expr_, t_, {a_, b_}, n_] := FourierSinCoefficient[expr /. t -> t + a, t, n, FourierParameters -> {1, Pi/(b - a)}] /. t -> t - aeasyTerm[t_, {a_, b_}, n_] := Sin[Pi/(b - a) n (t - a)]term = easyTerm[x, {0, 1}, n];coe = easyFourierSinCoefficient[tsol, x, {0, 1}, n] $$-\left(i\left(\frac{(1+i) (-1)^n e^{i \sqrt{2} \sqrt{s}}}{(1+i) \pi n+i \sqrt{2} \sqrt{s}}\right.\right....$$ coe still looks complex, but inspired by those (-1)^n s in it, we split it to odd and even part and simplify: oddcoe = Simplify[coe /. n -> 2 m - 1, m > 0 && m ∈ Integers] /. m -> (1 + n)/2(* (8 s)/(n^3 π^3 (n^4 π^4 + s^2)) *)evencoe = Simplify[coe /. n -> 2 m, m ∈ Integers] /. m -> n/2(* 0 *) InverseLaplaceTransform can handle the series form of the transformed solution without difficulty: soloddterm = Function[n, #] &@InverseLaplaceTransform[oddcoe term, s, t](* Function[n, (8 Cos[n^2 π^2 t] Sin[n π x])/(n^3 π^3)] *) To find the final solution, just summate: solgenerator[n_] := Compile[{t, x}, #] &@Total@soloddterm@Range[1, n, 2];sol = solgenerator[200];Animate[Plot[sol[t, x], {x, 0, 1}, PlotRange -> .3], {t, 0, 1}] The animation is similar to the one in the subsequent solution so I'd like to omit it. Fully NDSolve -based Numeric Solution Go back to the old-fashioned "TensorProductGrid" , set "DifferentiateBoundaryConditions" -> {True, "ScaleFactor" -> 100} (or NDSolve will set "ScaleFactor" to 0 so the inconsistent b.c.s will be severely ignored, for more information, check the obscure tutorial ) and DifferenceOrder -> 2 : mol[n_Integer, o_:"Pseudospectral"] := {"MethodOfLines", "SpatialDiscretization" -> {"TensorProductGrid", "MaxPoints" -> n, "MinPoints" -> n, "DifferenceOrder" -> o}}mol[tf:False|True,sf_:Automatic]:={"MethodOfLines","DifferentiateBoundaryConditions"->{tf,"ScaleFactor"->sf}}tu = NDSolveValue[{eqn, ic, bc}, u, {t, 0, 10}, {x, 0, 1}, Method -> Union[mol[27, 2], mol[True, 100], {Method -> StiffnessSwitching}], MaxSteps -> Infinity];Animate[Plot[tu[t, x], {x, 0, 1}, PlotRange -> .3], {t, 0, 10}] NDSolve spits out the NDSolveValue::eerr warning, but in many cases NDSolveValue::eerr isn't a big deal, and the result indeed looks OK: Remark The {Method -> StiffnessSwitching} option is not necessary in v9 , but becomes necessary to obtain a reasonable solution at least since v12.3 . The performance of this approach backslides severely at least since v12.3 . For {t, 0, 2} , the timing is about 16 seconds in v9 , but about 275 seconds in v12.3 . I haven't found out the reason so far, but the posteriori error estimation is 604.34 in v12.3 , which is smaller than the 1802.02 in v9.0.1 . Partly NDSolve -based Numeric Solution Theoretically we can also set "DifferentiateBoundaryConditions" -> False to avoid the inconsistent b.c.s being ignored, but strangely NDSolve spits out the icfail warning and fails. I'm not sure about reason, but found that we can manually discretize the spatial derivative and solve the obtained ODE set with NDSolve to avoid the issue. First, let's define a function pdetoode that discretizes PDEs to ODEs (Additionally, though not related to OP's problem, I've also define a function pdetoae that discretizes differential equations to algebraic equations based on pdetoode . A diffbc function is defined to transform b.c. to (almost) equivalent ODE, in certain cases you may need it to avoid the fragile DAE solver of NDSolve . A rebuild function is also created to combine the list of InterpolatingFunction s to a single InterpolatingFunction ): Clear[fdd, pdetoode, tooderule, pdetoae, diffbc, rebuild]fdd[{}, grid_, value_, order_, periodic_] := value;fdd[a__] := NDSolve`FiniteDifferenceDerivative@a;pdetoode[funcvalue_List, rest__] := pdetoode[(Alternatives @@ Head /@ funcvalue) @@ funcvalue[[1]], rest];pdetoode[{func__}[var__], rest__] := pdetoode[Alternatives[func][var], rest];pdetoode[front__, grid_?VectorQ, o_Integer, periodic_: False] := pdetoode[front, {grid}, o, periodic];pdetoode[func_[var__], time_, {grid : {__} ..}, o_Integer, periodic : True | False | {(True | False) ..} : False] := With[{pos = Position[{var}, time][[1, 1]]}, With[{bound = #[[{1, -1}]] & /@ {grid}, pat = Repeated[_, {pos - 1}], spacevar = Alternatives @@ Delete[{var}, pos]}, With[{coordtoindex = Function[coord, MapThread[Piecewise[{{1, PossibleZeroQ[# - #2[[1]]]}, {-1, PossibleZeroQ[# - #2[[-1]]]}}, All] &, {coord, bound}]]}, tooderule@Flatten@{ ((u : func) | Derivative[dx1 : pat, dt_, dx2___][(u : func)])[x1 : pat, t_, x2___] :> (Sow@coordtoindex@{x1, x2}; fdd[{dx1, dx2}, {grid}, Outer[Derivative[dt][u@##]@t &, grid], "DifferenceOrder" -> o, PeriodicInterpolation -> periodic]), inde : spacevar :> With[{i = Position[spacevar, inde][[1, 1]]}, Outer[Slot@i &, grid]]}]]];tooderule[rule_][pde_List] := tooderule[rule] /@ pde;tooderule[rule_]@Equal[a_, b_] := Equal[tooderule[rule][a - b], 0] //. eqn : HoldPattern@Equal[_, _] :> Thread@eqn;tooderule[rule_][expr_] := #[[Sequence @@ #2[[1, 1]]]] & @@ Reap[expr /. rule]pdetoae[funcvalue_List, rest__] := pdetoae[(Alternatives @@ Head /@ funcvalue) @@ funcvalue[[1]], rest];pdetoae[{func__}[var__], rest__] := pdetoae[Alternatives[func][var], rest];pdetoae[func_[var__], rest__] := Module[{t}, Function[pde, #[ pde /. {Derivative[d__][u : func][inde__] :> Derivative[d, 0][u][inde, t], (u : func)[inde__] :> u[inde, t]}] /. (u : func)[ i__][t] :> u[i]] &@pdetoode[func[var, t], t, rest]]diffbc[rst__][a : _List | _Equal] := diffbc[rst] /@ adiffbc[dvar : {t_, order_} | (t_) .., sf_: 0][a_] /; sf =!= t := sf a + D[a, dvar]rebuild[funcarray_, grid_?VectorQ, timeposition_: 1] := rebuild[funcarray, {grid}, timeposition]rebuild[funcarray_, grid_, timeposition_?Negative] := rebuild[funcarray, grid, Range[Length@grid + 1][[timeposition]]]rebuild[funcarray_, grid_, timeposition_: 1] /; Dimensions@funcarray === Length /@ grid := With[{depth = Length@grid}, ListInterpolation[ Transpose[Map[Developer`ToPackedArray@#["ValuesOnGrid"] &, #, {depth}], Append[Delete[Range[depth + 1], timeposition], timeposition]], Insert[grid, Flatten[#][[1]]["Coordinates"][[1]], timeposition]] &@funcarray] The syntax of pdetoode is as follows: 1st argument is the function to be discretized (which can be a list i.e. pdetoode can handle PDE system), 2nd argument is the independent variable in the resulting ODE system (usually it's the variable playing the role of "time" in the underlying model), 3rd argument is the list of spatial grid, 4th argument is difference order, 5th argument is to determine whether periodic b.c. should be set or not. (5th argument is optional, the default setting is False . ) Notice pdetoode is a general purpose function. You may feel some part of the source code confusing. To understand it, just notice the following truth: a /. a | b[m_] :> {m} outputs {} . Derivative[][u] outputs u . Then discretize eqn , ic and bc and remove redundant equations: lb = 0; rb = 1;(* Difference order of x: *)xdifforder = 2;points = 25;grid = Array[# &, points, {lb, rb}];(* There're 4 b.c.s, so we need to remove 4 equations from every PDE/i.c., usually the difference equations that are the "closest" ones to the b.c.s are to be removed: *)removeredundant = #[[3 ;; -3]] &;(* Use pdetoode to generate a "function" that discretizes the spatial derivatives of PDE(s) and corresponding i.c.(s) and b.c.(s): *)ptoofunc = pdetoode[u[t, x], t, grid, xdifforder];odeqn = eqn // ptoofunc // removeredundant;odeic = removeredundant/@ptoofunc@ic;odebc = bc // ptoofunc;sollst = NDSolveValue[{odebc, odeic, odeqn}, u /@ grid, {t, 0, 10}, MaxSteps -> Infinity];(* Rebuild the solution for the PDE from the solution for the ODE set: *)sol = rebuild[sollst, grid];Animate[Plot[sol[t, x], {x, 0, 1}, PlotRange -> .3], {t, 0, 10}] The animation is similar to the one in the aforementioned solution so I'd like to omit it. This approach seems to be more robust than the fully NDSolve -based one, because even if the xordereqn i.e. the difference order for spatial derivative is set to 4 , it's still stable, while the fully NDSolve -based one becomes wild when t is large. | {} | {'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/127983', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/788/']} | jdg_71351 |
stackexchange | llm_judgeable_groundtruth_similarity | 12512603 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to maintain a staging as well as a production environment in azure. Each should have it's own blob storage and sql storage. What wod be the best way to achive this? setup a staging and a production sql server as well as two blob storage accounts?
Now provide the response and nothing else.
| This is how I manage my production/acceptance/test environments (note that I'm not using the word staging ). For each environment, I create the following (depending on the project): Cloud Service Storage Account SQL Azure Server + Database AppFabric (ACS, ...) Namespace Virtual Machines So let's assume I have an app called myapp , then my environments would look like this: Production Cloud Service: myapp-prod .cloudapp.net Storage Account: myapp-prod SQL Azure Server containing 1 database: MyApp Acceptance Cloud Service: myapp-acce .cloudapp.net Storage Account: myapp-acce SQL Azure Server containing 1 database: MyAppAcce Test ... So all environments have a version of the app running in the production deployment slot. I only use the staging deployment slot whenever I want to do a VIP swap for my production environment (note the difference between production deployment slot and production environment). There are a few advantages to this approach where you have dedicated components (like storage accounts) per environment: It's easy to test new releases without impacting the real application. You can have different security per environment (for example, all developers have access to the keys for the test storage account) If you're testing your application you can work with real URLs + SSL instead of that long and ugly staging URL. It's easy to test the integration with ACS since each environment will have its dedicated namespace. Using Visual Studio you can easiliy manage settings per environment. And last but not least, you have to know that the scalability targets of Windows Azure Storage apply to the storage account level. This means that if you use a single storage account for all your environments, you might be reducing the performance of your app in production because you're doing stress tests on the app running in staging. If you use a storage account per environment, you won't impact other environments when you do something. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12512603', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/147946/']} | jdg_71352 |
stackexchange | llm_judgeable_groundtruth_similarity | 39568412 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If i create a secret from an id_rsa file using kubectl as: kubectl create secret generic hcom-secret --from-file=ssh-privatekey=./.ssh/id_rsa And then mount the secret into the container "volumeMounts": [ {"name": "cfg", "readOnly": false, "mountPath": "/home/hcom/.ssh"} ]"volumes": [ {"name": "cfg", "secret": { "secretName": "hcom-ssh" }} ], The resultant file is not id_rsa but ssh-privatekey and the permits that are on it are not 600 which ssh expects Is this a correct approach, or can anyone please detail how this should be done?
Now provide the response and nothing else.
| The official Kubernetes docs for secrets cover this exact use-case . To create the secret, use: $ kubectl create secret generic my-secret --from-file=ssh-privatekey=/path/to/.ssh/id_rsa --from-file=ssh-publickey=/path/to/.ssh/id_rsa.pub To mount the secret in your containers, use the following Pod config: { "kind": "Pod", "apiVersion": "v1", "metadata": { "name": "secret-test-pod", "labels": { "name": "secret-test" } }, "spec": { "volumes": [ { "name": "secret-volume", "secret": { "secretName": "my-secret" } } ], "containers": [ { "name": "ssh-test-container", "image": "mySshImage", "volumeMounts": [ { "name": "secret-volume", "readOnly": true, "mountPath": "/etc/secret-volume" } ] } ] }} Kubernetes doesn't actually have a way to control file permissions for a secret as of now, but a recent Pull Request did add support for changing the path of secrets. This support was added with 1.3 as per this comment Here are the permissions related Github Issues: https://github.com/kubernetes/kubernetes/issues/4789 https://github.com/kubernetes/kubernetes/issues/28317 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39568412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6699021/']} | jdg_71353 |
stackexchange | llm_judgeable_groundtruth_similarity | 45327293 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In my appsettings.json, when I use this snippet: "ConnectionStrings": { "CssDatabase": "Server=BLUEJAY\\MSSQLSERVER2014;Database=CSS;Trusted_Connection=True;" } I can connect to the db as expected... no issues. However, when I change that to use the SQL Alias (CSSDB), like so: "ConnectionStrings": { "CssDatabase": "Server=CSSDB;Database=CSS;Trusted_Connection=True;" } It is properly configured since I can use this SQL Alias in SSMS to connect to DB without an issue. This returns: The server was not found or was not accessible. Verify that theinstance name is correct and that SQL Server is configured to allowremote connections. (provider: Named Pipes Provider, error: 40 -Could not open a connection to SQL Server) --->System.ComponentModel.Win32Exception: The network path was not found I am using Microsoft.EntityFrameworkCore .
Now provide the response and nothing else.
| Since information about SQL Aliases stored in Windows registry the Microsoft team decided to drop its support in .NET Core, because it is not cross-platform solution. Here the link to discussion about it . However there is workaround(also from this discussion), which worked fine for me, but bear in mind it is still Windows only solution: var builder = new SqlConnectionStringBuilder(config.ConnectionString);var key = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE") == "x86" ? @"HKEY_LOCAL_MACHINE\SOFTWARE\ Microsoft\MSSQLServer\Client\ConnectTo" : @"HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\MSSQLServer\Client\ConnectTo";var newSource = (string)Microsoft.Win32.Registry.GetValue(key, builder.DataSource, null);if (newSource != null) builder.DataSource = newSource.Substring(newSource.IndexOf(',') + 1);config.ConnectionString = builder.ConnectionString; If you not storing ConnectionString in the distinct C# class you can just pass the builder.ConnectionString to services in ConfigureServices method like I did below: services.AddDbContext<AppDbContext>( opt => opt.UseSqlServer(builder.ConnectionString)); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45327293', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2051886/']} | jdg_71354 |
stackexchange | llm_judgeable_groundtruth_similarity | 11461650 |
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 Android Jelly Bean doesn't support the logs reading permission (according to this google io 2012 video and this one too ) , i would like to know if it's possible for rooted devices (or non-rooted devices) to be able to bypass this restriction and be able to read the logs. How do i do that? Do i really need to make the app a system app, or is rooting enough?
Now provide the response and nothing else.
| You can obtain the permission on a rooted device by executing the pm grant command from your app. Probably you will have to restart the app after that for the change to take effect, though: String pname = getPackageName();String[] CMDLINE_GRANTPERMS = { "su", "-c", null };if (getPackageManager().checkPermission(android.Manifest.permission.READ_LOGS, pname) != 0) { Log.d(TAG, "we do not have the READ_LOGS permission!"); if (android.os.Build.VERSION.SDK_INT >= 16) { Log.d(TAG, "Working around JellyBeans 'feature'..."); try { // format the commandline parameter CMDLINE_GRANTPERMS[2] = String.format("pm grant %s android.permission.READ_LOGS", pname); java.lang.Process p = Runtime.getRuntime().exec(CMDLINE_GRANTPERMS); int res = p.waitFor(); Log.d(TAG, "exec returned: " + res); if (res != 0) throw new Exception("failed to become root"); } catch (Exception e) { Log.d(TAG, "exec(): " + e); Toast.makeText(context, "Failed to obtain READ_LOGS permission", Toast.LENGTH_LONG).show(); } }} else Log.d(TAG, "we have the READ_LOGS permission already!"); This code should be called from your onCreate(). Once the permission is granted, no more root powers are required. P.S: The p.waitFor() blocks on the Superuser app, delaying your app start and potentially cause an ANR. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11461650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/878126/']} | jdg_71355 |
stackexchange | llm_judgeable_groundtruth_similarity | 181471 |
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 new awesome Ctrl + . keyboard shortcut to show smart tags has suddenly stopped working, a week or so after I discovered it :( I am missing it badly, having had to revert back to Ctrl + Alt + F10 , which really just isn't the same. I recently installed F# CTP 1.9.6.2 Has anyone else installed this CTP and still has Ctrl + . Lost Ctrl + . without installing F# Even better, found how to get it back again? EDIT In attempting John Sheehan recommendation, I have noticed that my available mapping schemes only include Visual C# 2005 , should I not have a 2008? Also the mapped shortcut to this is OtherContextMenus.FSIConsoleContext.CancelEvaluation
Now provide the response and nothing else.
| From the documentation : Use of NSCalendarDate strongly discouraged. It is not deprecated yet, however it may be in the next major OS release after Mac OS X v10.5. For calendrical calculations, you should use suitable combinations of NSCalendar, NSDate, and NSDateComponents, as described in Calendars in Dates and Times Programming Topics for Cocoa . Following that advice: NSDate *today = [NSDate date];NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];NSDateComponents *components = [[NSDateComponents alloc] init];components.day = 1;NSDate *tomorrow = [gregorian dateByAddingComponents:components toDate:today options:0];[components release];NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;components = [gregorian components:unitFlags fromDate:tomorrow];components.hour = 0;components.minute = 0;NSDate *tomorrowMidnight = [gregorian dateFromComponents:components];[gregorian release];[components release]; (I'm not sure offhand if this is the most efficient implementation, but it should serve as a pointer in the right direction.) Note: In theory you can reduce the amount of code here by allowing a date components object with values greater than the range of normal values for the component (e.g. simply adding 1 to the day component, which might result in its having a value of 32). However, although dateFromComponents: may tolerate out-of-bounds values, it's not guaranteed to. You're strongly encouraged not to rely on it. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/181471', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5302/']} | jdg_71356 |
stackexchange | llm_judgeable_groundtruth_similarity | 158803 |
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:
Can anyone provide me with a physical interpretation of $\oint E\cdot d\ell=0$ in electrostatics?
Now provide the response and nothing else.
| The vanishing of closed line integrals means that the field is conservative . Since $\oint \vec E \cdot \mathrm{d}\vec l$ is equivalent to $\vec \nabla \times \vec E = 0$, the "physical interpretation" is the the electric field is irrotational , i.e. it has no "vortices". The, more valuable, mathematical implication is that there is a scalar potential whose gradient is the electric field. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/158803', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/43698/']} | jdg_71357 |
stackexchange | llm_judgeable_groundtruth_similarity | 51377851 |
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 my example, having car object and found that min and max price value based on model (group by). List<Car> carsDetails = UserDB.getCarsDetails();Map<String, DoubleSummaryStatistics> collect4 = carsDetails.stream() .collect(Collectors.groupingBy(Car::getMake, Collectors.summarizingDouble(Car::getPrice)));collect4.entrySet().forEach(e->System.out.println(e.getKey()+" "+e.getValue().getMax()+" "+e.getValue().getMin()));output :Lexus 94837.79 17569.59Subaru 96583.25 8498.41Chevrolet 99892.59 6861.85 But I couldn't find which car objects have max and min price. How can I do that?
Now provide the response and nothing else.
| If you were interested in only one Car per group, you could use, e.g. Map<String, Car> mostExpensives = carsDetails.stream() .collect(Collectors.toMap(Car::getMake, Function.identity(), BinaryOperator.maxBy(Comparator.comparing(Car::getPrice))));mostExpensives.forEach((make,car) -> System.out.println(make+" "+car)); But since you want the most expensive and the cheapest, you need something like this: Map<String, List<Car>> mostExpensivesAndCheapest = carsDetails.stream() .collect(Collectors.toMap(Car::getMake, car -> Arrays.asList(car, car), (l1,l2) -> Arrays.asList( (l1.get(0).getPrice()>l2.get(0).getPrice()? l2: l1).get(0), (l1.get(1).getPrice()<l2.get(1).getPrice()? l2: l1).get(1))));mostExpensivesAndCheapest.forEach((make,cars) -> System.out.println(make +" cheapest: "+cars.get(0)+" most expensive: "+cars.get(1))); This solution bears a bit of inconvenience due to the fact that there is no generic statistics object equivalent to DoubleSummaryStatistics . If this happens more than once, it’s worth filling the gap with a class like this: /** * Like {@code DoubleSummaryStatistics}, {@code IntSummaryStatistics}, and * {@code LongSummaryStatistics}, but for an arbitrary type {@code T}. */public class SummaryStatistics<T> implements Consumer<T> { /** * Collect to a {@code SummaryStatistics} for natural order. */ public static <T extends Comparable<? super T>> Collector<T,?,SummaryStatistics<T>> statistics() { return statistics(Comparator.<T>naturalOrder()); } /** * Collect to a {@code SummaryStatistics} using the specified comparator. */ public static <T> Collector<T,?,SummaryStatistics<T>> statistics(Comparator<T> comparator) { Objects.requireNonNull(comparator); return Collector.of(() -> new SummaryStatistics<>(comparator), SummaryStatistics::accept, SummaryStatistics::merge); } private final Comparator<T> c; private T min, max; private long count; public SummaryStatistics(Comparator<T> comparator) { c = Objects.requireNonNull(comparator); } public void accept(T t) { if(count == 0) { count = 1; min = t; max = t; } else { if(c.compare(min, t) > 0) min = t; if(c.compare(max, t) < 0) max = t; count++; } } public SummaryStatistics<T> merge(SummaryStatistics<T> s) { if(s.count > 0) { if(count == 0) { count = s.count; min = s.min; max = s.max; } else { if(c.compare(min, s.min) > 0) min = s.min; if(c.compare(max, s.max) < 0) max = s.max; count += s.count; } } return this; } public long getCount() { return count; } public T getMin() { return min; } public T getMax() { return max; } @Override public String toString() { return count == 0? "empty": (count+" elements between "+min+" and "+max); }} After adding this to your code base, you may use it like Map<String, SummaryStatistics<Car>> mostExpensives = carsDetails.stream() .collect(Collectors.groupingBy(Car::getMake, SummaryStatistics.statistics(Comparator.comparing(Car::getPrice))));mostExpensives.forEach((make,cars) -> System.out.println(make+": "+cars)); If getPrice returns double , it may be more efficient to use Comparator.comparingDouble(Car::getPrice) instead of Comparator.comparing(Car::getPrice) . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51377851', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8726488/']} | jdg_71358 |
stackexchange | llm_judgeable_groundtruth_similarity | 236251 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In mark-sweep-compact garbage collection algorithm you have to stop-the-world when relocating objects because reference graph becomes inconsistent and you have to replace values of all references pointing to the object. But what if you had a hash table with object ID as a key and pointer as value, and references would point to said ID instead of object address... then fixing references would only require changing one value and pause would only be needed if object is tried to be written into during copying... Is there a mistake in my line of thought?
Now provide the response and nothing else.
| Updating references is not the only thing that requires a pause. The standard algorithms commonly grouped under "mark-sweep" all assume that the entire object graph remains unaltered while it's being marked. Correctly handling modifications (new objects created, references changed) requires rather tricky alternative algorithms, like as the tri-color algorithm. The umbrella term is "concurrent garbage collection". But yes, updating references after compaction also needs a pause. And yes, using indirection (e.g. via a persistent object ID and a hash table to real pointers) can greatly reduce the pausing. It might even be possible to make this part lock-free if one so desires. It would still be as tricky to get right as any low-level shared-memory concurrency, but there is no fundamental reason it wouldn't work. However , it would have severe disadvantages. Aside from taking extra space ( at least two extra words for all objects), it makes every dereference much more expensive. Even something as simple as getting an attribute now involves a full hash table search. I'd estimate the performance hit to be way worse than for incremental tracing. | {} | {'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/236251', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/33996/']} | jdg_71359 |
stackexchange | llm_judgeable_groundtruth_similarity | 43153530 |
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 storyboard segue on TableViewCell, which I use for transfering to another VC on cell click in didSelectRowAt method. Now I made double tap TapGestureRecognizer to handle touble tap on cell. Problem is that on single tap, segue is performing and double tap is not working. Double tap works fine with clicking out of cell. Is possible to solve this somehow with my code so far? Or I need to delete segue and handle single tap and double tap separately. Thanks for any suggestions override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let doubleTap = UITapGestureRecognizer(target: self, action: #selector(handleDoubleTap)) doubleTap.numberOfTapsRequired = 2 view.addGestureRecognizer(doubleTap)}func handleDoubleTap(recognizer: UIGestureRecognizer) { let p = recognizer.location(in: tableView) let indexPath = tableView.indexPathForRow(at: p) if let _ = indexPath { tableView.deselectRow(at: indexPath!, animated: true) update(index: (indexPath?.row)!, isFinished: true) } print ("doubke")}override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if (segue.identifier == "showSingleTask") { if let indexPath = tableView.indexPathForSelectedRow { let nav = segue.destination as! UINavigationController let destinationVC = nav.topViewController as! ShowTaskVC destinationVC.singleTask = tasks[indexPath.row] } }}func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath as IndexPath, animated: true) self.selectedTask = tasks[indexPath.row]}
Now provide the response and nothing else.
| Details Xcode 10.2.1 (10E1001), Swift 5 Solution protocol MultiTappableDelegate: class { func singleTapDetected(in view: MultiTappable) func doubleTapDetected(in view: MultiTappable)}class ThreadSafeValue<T> { private var _value: T private lazy var semaphore = DispatchSemaphore(value: 1) init(value: T) { _value = value } var value: T { get { semaphore.signal(); defer { semaphore.wait() } return _value } set(value) { semaphore.signal(); defer { semaphore.wait() } _value = value } }}protocol MultiTappable: UIView { var multiTapDelegate: MultiTappableDelegate? { get set } var tapCounter: ThreadSafeValue<Int> { get set }}extension MultiTappable { func initMultiTap() { if let delegate = self as? MultiTappableDelegate { multiTapDelegate = delegate } let tap = UITapGestureRecognizer(target: self, action: #selector(UIView.multitapActionHandler)) addGestureRecognizer(tap) } func multitapAction() { if tapCounter.value == 0 { DispatchQueue.global(qos: .utility).async { usleep(250_000) DispatchQueue.main.async { [weak self] in guard let self = self else { return } if self.tapCounter.value > 1 { self.multiTapDelegate?.doubleTapDetected(in: self) } else { self.multiTapDelegate?.singleTapDetected(in: self) } self.tapCounter.value = 0 } } } tapCounter.value += 1 }}private extension UIView { @objc func multitapActionHandler() { if let tappable = self as? MultiTappable { tappable.multitapAction() } }} Usage class MyView: UIView, MultiTappable { weak var multiTapDelegate: MultiTappableDelegate? lazy var tapCounter = ThreadSafeValue(value: 0) override func awakeFromNib() { super.awakeFromNib() initMultiTap() }} Full sample ViewController.swift import UIKitclass ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self tableView.tableFooterView = UIView() }}extension ViewController: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell") as! TableViewCell cell.label.text = "\(indexPath)" cell.delegate = self return cell }}extension ViewController: TableViewCellDelegate { func singleTapDetected(in cell: TableViewCell) { if let indexPath = tableView.indexPath(for: cell) { print("singleTap \(indexPath) ") } } func doubleTapDetected(in cell: TableViewCell) { if let indexPath = tableView.indexPath(for: cell) { print("doubleTap \(indexPath) ") } }} TableViewCell.swift import UIKitprotocol TableViewCellDelegate: class { func singleTapDetected(in cell: TableViewCell) func doubleTapDetected(in cell: TableViewCell)}class TableViewCell: UITableViewCell, MultiTappable { weak var multiTapDelegate: MultiTappableDelegate? lazy var tapCounter = ThreadSafeValue(value: 0) @IBOutlet weak var label: UILabel! weak var delegate: TableViewCellDelegate? override func awakeFromNib() { super.awakeFromNib() initMultiTap() }}extension TableViewCell: MultiTappableDelegate { func singleTapDetected(in view: MultiTappable) { self.delegate?.singleTapDetected(in: self) } func doubleTapDetected(in view: MultiTappable) { self.delegate?.doubleTapDetected(in: self) }} Main.storyboard <?xml version="1.0" encoding="UTF-8"?><document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="12118" systemVersion="16E195" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="g2V-T0-sqD"> <device id="retina4_7" orientation="portrait"> <adaptation id="fullscreen"/> </device> <dependencies> <deployment identifier="iOS"/> <plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="12086"/> <capability name="Constraints to layout margins" minToolsVersion="6.0"/> <capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/> </dependencies> <scenes> <!--View Controller--> <scene sceneID="tne-QT-ifu"> <objects> <viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackoverflow_43153530" customModuleProvider="target" sceneMemberID="viewController"> <layoutGuides> <viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/> <viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/> </layoutGuides> <view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC"> <rect key="frame" x="0.0" y="0.0" width="375" height="667"/> <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/> <subviews> <tableView clipsSubviews="YES" contentMode="scaleToFill" alwaysBounceVertical="YES" dataMode="prototypes" style="plain" separatorStyle="default" rowHeight="44" sectionHeaderHeight="28" sectionFooterHeight="28" translatesAutoresizingMaskIntoConstraints="NO" id="fQm-mQ-a9u"> <rect key="frame" x="0.0" y="0.0" width="375" height="667"/> <color key="backgroundColor" white="1" alpha="1" colorSpace="calibratedWhite"/> <prototypes> <tableViewCell clipsSubviews="YES" contentMode="scaleToFill" selectionStyle="default" indentationWidth="10" reuseIdentifier="TableViewCell" id="nsF-ue-0bK" customClass="TableViewCell" customModule="stackoverflow_43153530" customModuleProvider="target"> <rect key="frame" x="0.0" y="28" width="375" height="44"/> <autoresizingMask key="autoresizingMask"/> <tableViewCellContentView key="contentView" opaque="NO" clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" tableViewCell="nsF-ue-0bK" id="pT6-2N-oTC"> <rect key="frame" x="0.0" y="0.0" width="375" height="44"/> <autoresizingMask key="autoresizingMask"/> <subviews> <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="fEK-J3-oqH"> <rect key="frame" x="8" y="8" width="42" height="21"/> <fontDescription key="fontDescription" type="system" pointSize="17"/> <nil key="textColor"/> <nil key="highlightedColor"/> </label> </subviews> <constraints> <constraint firstItem="fEK-J3-oqH" firstAttribute="leading" secondItem="pT6-2N-oTC" secondAttribute="leadingMargin" id="Vfg-Ij-f6c"/> <constraint firstItem="fEK-J3-oqH" firstAttribute="top" secondItem="pT6-2N-oTC" secondAttribute="topMargin" id="tc0-qJ-N1n"/> </constraints> </tableViewCellContentView> <connections> <outlet property="label" destination="fEK-J3-oqH" id="YBJ-tG-J5T"/> </connections> </tableViewCell> </prototypes> </tableView> </subviews> <color key="backgroundColor" red="1" green="1" blue="1" alpha="1" colorSpace="custom" customColorSpace="sRGB"/> <constraints> <constraint firstItem="fQm-mQ-a9u" firstAttribute="bottom" secondItem="wfy-db-euE" secondAttribute="top" id="8Vy-l8-jpB"/> <constraint firstItem="fQm-mQ-a9u" firstAttribute="leading" secondItem="8bC-Xf-vdC" secondAttribute="leading" id="Wwr-ox-Qbd"/> <constraint firstItem="fQm-mQ-a9u" firstAttribute="top" secondItem="y3c-jy-aDJ" secondAttribute="bottom" constant="-64" id="xJR-Uk-rbj"/> <constraint firstAttribute="trailing" secondItem="fQm-mQ-a9u" secondAttribute="trailing" id="zxs-ED-Whb"/> </constraints> </view> <navigationItem key="navigationItem" id="pLJ-Bz-NIm"/> <connections> <outlet property="tableView" destination="fQm-mQ-a9u" id="DhZ-jj-zmB"/> </connections> </viewController> <placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="1079.2" y="137.18140929535232"/> </scene> <!--Navigation Controller--> <scene sceneID="w7e-Wj-oUR"> <objects> <navigationController automaticallyAdjustsScrollViewInsets="NO" id="g2V-T0-sqD" sceneMemberID="viewController"> <toolbarItems/> <navigationBar key="navigationBar" contentMode="scaleToFill" id="7qG-8v-S0O"> <rect key="frame" x="0.0" y="0.0" width="375" height="44"/> <autoresizingMask key="autoresizingMask"/> </navigationBar> <nil name="viewControllers"/> <connections> <segue destination="BYZ-38-t0r" kind="relationship" relationship="rootViewController" id="yqZ-pK-Yf3"/> </connections> </navigationController> <placeholder placeholderIdentifier="IBFirstResponder" id="tnz-x0-vDN" userLabel="First Responder" sceneMemberID="firstResponder"/> </objects> <point key="canvasLocation" x="140" y="137.18140929535232"/> </scene> </scenes></document> Result | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43153530', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7494328/']} | jdg_71360 |
stackexchange | llm_judgeable_groundtruth_similarity | 26698587 |
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 display the logout button only if any user is logged in. following is the code: <?php if(isset($_SESSION['user'])) { echo '<li><a href='logout.php'>Logout</li>'; }?> But it is giving error.Error:Parse error: syntax error, unexpected 'logout' (T_STRING), expecting ',' or ';' in C:\xampp\htdocs\index.php on line 42Help me to display this link.
Now provide the response and nothing else.
| You cannot keep the jar in HDFS when executing the same using hadoop command, Jar should be available in the local path If the jar is not runnable try the following (Need to specify the package.mainclass) hadoop jar /home/hduser/Desktop/Files/WordCount.jar wordPackage.WordCount /Projects/input /Projects/output If the jar is runnable following can be used hadoop jar /home/hduser/Desktop/Files/WordCount.jar /Projects/input /Projects/output If the issue still persists, you need to rebuild this jar(WordCount.jar) in eclipse again | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26698587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4108151/']} | jdg_71361 |
stackexchange | llm_judgeable_groundtruth_similarity | 13202161 |
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 asked a few questions on stack overflow about subclassing a UIButton , and a couple of people have informed me that I shouldn't subclass a UIButton . What are the negatives of subclassing a UIButton ? And I know it's vague, but what are other alternatives to subclassing a UIButton ?
Now provide the response and nothing else.
| The Cocoa frameworks take the approach that the Object Composition pattern is more appropriate than traditional class hierarchy. In general, this means that there is likely to be a property on UIButton where you can set another object to handle various aspects of the button. This is the preferred way to "customize" how your button works. One of the main reasons for this pattern is that many library components create buttons and don't know that you want them to create instances of your subclass. edit, your own factory method I noticed your comment above about saving time when you have the same button config across many buttons in your app. This is a great time to use the Factory Method design pattern, and in Objective-C you can implement it with a Category so it's available directly on UIButton. @interface UIButton ( MyCompanyFactory )+(UIButton *) buttonWithMyCompanyStyles;@end@implementation UIButton+(UIButton *) buttonWithMyCompanyStyles { UIButton *theButton = [UIButton buttonWithType:UIButtonTypeCustom]; // [theButton set... return theButton;}@end | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13202161', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/996110/']} | jdg_71362 |
stackexchange | llm_judgeable_groundtruth_similarity | 9324338 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm pretty new to the Spring framework and web applications, though I'm experienced with Java. When I run my site on a local tomcat server the URL is: http://localhost:8080/myApp/ Now a request mapping delegates me to my home page with: @RequestMapping(value = "/", method = RequestMethod.GET)public String someMethod(Model model) { ... return "index"; } Now within a file index.xhtml I link to another page with <a href="apps/">link</a> but when I want to link back to the index page I have to use <a href="../index/">link</a> . I searched for a solution and found: <spring:url value='/apps' var="apps_url" /><a href="${apps_url}">link</a> But spring:url always resolves to http://localhost:8080/myApp/ - the page that I'm currently on. In addition, when I just use a link like this: <a href="/otherSite">link</a> , it always resolves to http://localhost:8080/otherSite and not http://localhost:8080/myApp/otherSite like I expected. How can I get my link to work? Is http://localhost:8080/myApp implicitly defined as my context or can/should it be changed to http://localhost:8080/ ? Also, is there any connection between the URL on local tomcat server and the URL the web application will have when it's published? Here are some of my application files: servlet-context.xml: <?xml version="1.0" encoding="UTF-8"?><beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --> <!-- Enables the Spring MVC @Controller programming model --> <annotation-driven /> <context:component-scan base-package="myApp" /> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- Handles HTTP GET requests for /resources/** and /css/** by efficiently serving up static resources in the ${webappRoot}/resources directory --> <resources mapping="/resources/**" location="/resources/" /> <resources mapping="/css/**" location="/css/" /> <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <beans:property name="prefix" value="/WEB-INF/views/" /> <beans:property name="suffix" value=".xhtml" /> </beans:bean></beans:beans> excerpt from web.xml: <!-- The definition of the Root Spring Container shared by all Servlets and Filters --><context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value></context-param><!-- Creates the Spring Container shared by all Servlets and Filters --><listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!-- Processes application requests --><servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup></servlet><servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern></servlet-mapping>
Now provide the response and nothing else.
| It is good practice to put all your links as follows <a href="${pageContext.servletContext.contextPath}/othersite"> Other site </a> ${pageContext.servletContext.contextPath} always gives your application root, when you are developing use http://localhost:8080/myApp , then your application root is /myapp , but when you want to place your application in production generally your application root will be / , using ${pageContext.servletContext.contextPath} before links you ensure it will work in both cases | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9324338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1215526/']} | jdg_71363 |
stackexchange | llm_judgeable_groundtruth_similarity | 12497199 |
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 Python console: >>> a = 0>>> if a:... print "L"... >>> a = 1>>> if a:... print "L"... L>>> a = 2>>> if a:... print "L"... L Why does this happen?
Now provide the response and nothing else.
| In Python, bool is a subclass of int , and False has the value 0 ; even if values weren't implicitly cast to bool in an if statement (which they are), False == 0 is true. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12497199', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/515902/']} | jdg_71364 |
stackexchange | llm_judgeable_groundtruth_similarity | 10422244 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am having a problem with a simple callback function in jQuery ajax. Google won't help and stack overflow wouldn't either, so I guess this might not be something specific but rather something I am too ignorant to see. To me the code looks exactly like it should. So, here's the code: function sendMessage(message){//Establish connection to php script$.ajax({ type: 'POST', url: 'action/chat/test.php', success: function(feedback){ alert(feedback); }}).error(function(){ //Do some error handling here});} In test.php it simply says <?php echo "called";?> As far as I am concerned "called" should be alerted - but it isn't.I have checked already that the function sendMessage() is called (and the parameter message doesn't matter for now). Does anyone have any idea?
Now provide the response and nothing else.
| Update: One thing to note also, make sure you use some kind of debugger like firebug. Then you can go to the network tab and look at the request url and response manually to see if its getting a 200 response or internal server error, etc. Try adding a console.log(data); in your success function to see if anything is being returned. You could also use .always(data) : function sendMessage(message){ //Establish connection to php script $.ajax({ type: 'POST', url: 'action/chat/test.php' }).done(function(data) { console.log(data); }) .fail(function() { alert("error"); }) .always(function() { alert("complete"); });} From the docs: Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks will be deprecated in jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10422244', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1371131/']} | jdg_71365 |
stackexchange | llm_judgeable_groundtruth_similarity | 4261583 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
For a category $C$ , $Set^{C^{op}}$ , the category of presheaves on $C$ , can be considered the free cocompletion of $C$ . I wonder: If $Set^{C^{op}}$ is equivalent to $Set^{D^{op}}$ , does it follow that $C$ is equivalent to $D$ ?
Now provide the response and nothing else.
| The phrase you're looking for is "Morita equivalence (of categories)" and the answer is no. All you can say is that the Cauchy completions (or more particularly, the Karoubi envelopes ) of $\mathcal C$ and $\mathcal D$ are equivalent (see this Mathoverflow question). The idea is that every presheaf preserves certain limits called absolute limits . This implies that adding these limits to the category (if they don't already exist) changes the category, but not the category of presheaves. Extending the presheaves to these new limits doesn't add any information because the presheaves have to preserve these new limits anyway. The main example of an absolute limit is the splitting of an idempotent. This is a morphism from an object to itself satisfying $f \circ f = f$ . That the idempotent splits means there are two further morphisms $r$ and $s$ (this time they don't necessary have the same domain and codomain) such that $s \circ r = f$ and $r \circ s = \operatorname{id}$ . It's easy to come up with a category where not every idempotent splits (consider the minimal category with an idempotent). Then adding in the splitting (the two extra morphisms) gives an inequivalent category whose presheaves are equivalent. Conservativity of a functor $F \colon \mathcal C \to \mathcal D$ is the property that for any morphism $g$ in $\mathcal C$ , if $F(g)$ is an isomorphism, then so is $g$ . As Zhen Lin pointed out in the comments, this isn't quite the same as saying that if $F(c) \cong F(c')$ , then $c \cong c'$ because the isomorphism $F(c) \cong F(c')$ doesn't necessarily come from a morphism in $\mathcal C$ . For an example, consider the inclusion of the discrete two-object category into the category with two objects and an isomorphism between those objects. Now presumably you want the "pseudo" version of conservativity so that isomorphisms are replaced with equivalences. Regarded as a pseudofunctor from small categories to locally small cocomplete categories, $\operatorname{PSh}$ takes a functor $F$ to the Yoneda extension of $Y \circ F \colon \mathcal C \to \operatorname{PSh}(\mathcal D)$ . There are several ways to think of this more explicitly; the one I prefer is $\operatorname{PSh}(F)(G)(d) = \int^{c \in C} \mathcal D(d, F(c)) \times G(c)$ , written using a coend . It can also be written just using colimits. So the question becomes: if $\operatorname{PSh}(F)$ is an equivalence, is $F$ also an equivalence? The same example shows that this is false too. There's an inclusion from the category without split idempotents to the category with them and this induces an equivalence between the two presheaf categories. But the inclusion is not itself an equivalence. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4261583', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/973439/']} | jdg_71366 |
stackexchange | llm_judgeable_groundtruth_similarity | 1459021 |
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 use the Maven assembly plugin to build a jar-with-dependencies, except those that have provided scope. I have copied the jar-with-dependencies into an assembly.xml file and configured its use in my pom. Here it is for reference: <?xml version="1.0" encoding="UTF-8"?><assembly> <id>injectable-jar</id> <formats> <format>jar</format> </formats> <includeBaseDirectory>false</includeBaseDirectory> <dependencySets> <dependencySet> <unpack>true</unpack> <scope>runtime</scope> </dependencySet> </dependencySets> <fileSets> <fileSet> <directory>${project.build.outputDirectory}</directory> </fileSet> </fileSets></assembly> I have found out, that if I set the scope to provided , then I can build a jar that contains exactly what I don't want, but I cannot figure out how to get inverse behavior of that.
Now provide the response and nothing else.
| This is a bit clunky, but you can use the maven-dependency-plugin to copy/unpack all the dependencies into your project, then use the assembly plugin to do the packaging. The copy-dependencies and unpack-dependencies goals both have an optional excludeScope property you can set to omit the provided dependencies. The configuration below copies all dependencies into target/lib, your assembly plugin descriptor can be modified to use a fileSet to include those jars. Update: Just tested this to confirm it works. Added the configuration for binding the assembly plugin to the package phase, and the relevant modifications to the assembly descriptor. <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <executions> <execution> <id>copy-dependencies</id> <phase>process-resources</phase> <goals> <goal>copy-dependencies</goal> </goals> <configuration> <excludeScope>provided</excludeScope> <outputDirectory>${project.build.directory}/lib</outputDirectory> </configuration> </execution> </executions></plugin><plugin> <artifactId>maven-assembly-plugin</artifactId> <version>2.2-beta-4</version> <executions> <execution> <id>jar-with-deps</id> <phase>package</phase> <goals> <goal>single</goal> </goals> </execution> </executions> <configuration> <descriptors> <descriptor>src/main/assembly/my-assembly.xml</descriptor> </descriptors> </configuration></plugin> The fileSet section of the my-assembly descriptor would look like this: <assembly> <fileSets> <fileSet> <directory>${project.build.directory}/lib</directory> <outputDirectory>/</outputDirectory> <includes> <include>*.*</include> </includes> </fileSet> </fileSets>...</assembly> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1459021', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13251/']} | jdg_71367 |
stackexchange | llm_judgeable_groundtruth_similarity | 16009584 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can someone help me figure out what i am doing wrong in my SELECT statement? SELECT *FROM groupWHERE login = 'admin' My error is: right syntax to use near 'group WHERE login = 'admin'' at line 1 It should fail but because of the fact that admin is not in the database but when I plug in data that is in the database it still fails.
Now provide the response and nothing else.
| GROUP is a reserved keyword. You need to escape it using back to avoid from syntax error. SELECT * FROM `group` WHERE login = '$username' MySQL Reserved Keywords List If you have the privilege to alter the table name, change it to which it is not a reserved keyword to avoid from getting another syntax error again in the future. :D As a sidenote, the query is vulnerable with SQL Injection if the value( s ) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values. How to prevent SQL injection in PHP? | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16009584', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2234705/']} | jdg_71368 |
stackexchange | llm_judgeable_groundtruth_similarity | 19408011 |
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 noticed the same question was asked a few times here, I tried so solve it but nothing helps. I'm following this tutorial with the egghead videos. But when I get at the section of Controllers and Sharing data between controllers, I can't get it to work. When I run it with Chrome, I get this error in the console: 'argument 'FirstCtrl' is not a function, got undefined'. I really don't know what's wrong. The code is the same from in the tutorial. HTML <!DOCTYPE html><html ng-app> <head> <title>AngularJS Tutorials: Controllers</title> <link rel="stylesheet" href="mystyle.css"> <script src="http://code.angularjs.org/1.2.0-rc.2/angular.min.js"></script> </head> <body> <div ng-app=""> <div ng-controller="FirstCtrl"> <h1> {{data.message + " world"}}</h1> <div class="{{data.message}}"> Wrap me in a foundation component </div> </div> </div> <script type="text/javascript" src="main.js"></script> </body></html> main.js function FirstCtrl($scope){ $scope.data = { message: "Hello" };}
Now provide the response and nothing else.
| You have 2 unnamed ng-app directives in your html. Lose the one in your div. Update Let's try a different approach. Define a module in your js file and assign the ng-app directive to it. After that, define the controller like an ng component, not as a simple function: <div ng-app="myAppName"> <!-- or what's the root node of your angular app --> and the js part: angular.module('myAppName', []) .controller('FirstCtrl', function($scope) { $scope.data = {message: 'Hello'}; }); Here's an online demo that is doing just that : http://jsfiddle.net/FssbL/1/ | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/19408011', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2887070/']} | jdg_71369 |
stackexchange | llm_judgeable_groundtruth_similarity | 176592 |
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 relation to this question about the "fundamental" character of possible logical systems, I realized that I just had an intuitive (and so, inadequate) understanding of the way logics higher than FOL can unambiguously specify the kind of semantics which make up the intended interpretation of their formalisms, inside the formalisms themselves . This is quite a meaningful question, since the ability of an automated system of reasoning at the object-language level can only recognize what is coded in the formalism itself, at that level; and so, those approaches which start from the construction of a model at the meta-level, are a priori ruled out in the sense I'm describing here. What I'm thinking about are computer systems reasoning with the logic, such as the HOL-based proof assistants, as Isabelle . So, how are the intended semantics of SOL and HOL specified in a computer system? P.S. : I have realized that this topic isn't actually new in this site, and has been brought up in other questions like this one .
Now provide the response and nothing else.
| From the point of view of derivability and syntax, there is no distinction between full higher order semantics and first-order (Henkin) semantics. This is, in one sense, the reason that there is no completeness theorem for full semantics - because the completeness theorem matches derivability with Henkin semantics, and so any genuinely different semantics will not match up with derivability. Syntactic things like proof assistants, which only care about derivability, are somewhat indifferent to semantic issues. I believe that the main benefit of using higher order logic in proof assistants is that it makes it easier to formalize theorems that have been proven in ordinary mathematics. Even if these theorems could be formalized in, say, Peano arithmetic, by creating entirely new proofs, it is often easier to modify the existing proof to work in higher order logic. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/176592', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/36691/']} | jdg_71370 |
stackexchange | llm_judgeable_groundtruth_similarity | 33509131 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We are using Flyway to migrate the database schema and we already have more than 100 migration scripts. Once we "squashed" multiple migrations into a single first-version migration, this is ok during development, as we drop and recreate the schema. But in production this wouldn't work, as Flyway won't be able to validate the migrations. I couldn't find any documentation or best practice of what to do in this case. The problem is that the file quantity increases constantly, I don't want to see thousands of migration files everytime, essentially if production is already in the latest version. I mean, the migration scripts that have a version number that is lower than the version in production are irrelevant to us, it would be awesome if we could squash those files into a single migration. We are using MySQL. How should we handle this?
Now provide the response and nothing else.
| Isn't that what re-baselining would do? I'm still new to flyway, but this is how I think it would work. Please test the following first before taking my word for it. Delete the schema_version table.Delete your migration scripts. Run flyway baseline(this recreates the schema_version table and adds a baseline record as version 1) Now you're good to go. Bear in mind that you will not be able to 'migrate' to any prior version as you've removed all of your migration scripts, but this might not be a problem for you. Step by step solution: drop table schema_version; Export database structure as a script via MySQL Workbench, for example. Name this script V1__Baseline.sql Delete all migration scripts and add V1__Baseline.sql to your scripts folder, so it is the only script available for Flyway Run Flyway's "baseline" command Done | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/33509131', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/663280/']} | jdg_71371 |
stackexchange | llm_judgeable_groundtruth_similarity | 11758081 |
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 JSP page with a form. When I submit the form, it build and gerenates a JSON string that I do an AJAX post with. I have a problem though, I need to get multiple values out of the form,and I am using the following to do this: .find('input[name=item1]) .not('input[type=hidden]') How can I do this to get inputs with names item1, item2 and item3? I tried this but it didn't work? .find('input[name=item1][name=item2][name=item3]') Below is my code for this: // Create JSON based data object $.fn.serializeObject = function() { var o = {}; var a = this.serializeArray(); $.each(a, function() { if (o[this.name] !== undefined) { if (!o[this.name].push) { o[this.name] = [o[this.name]]; } o[this.name].push(this.value || ''); } else { o[this.name] = this.value || ''; } }); return o; }; // Form Submission $('#form').submit( function() { // Create data array, used for building request message var data = { request: { requestType: "request", fields: [ { itemX1 : '1', itemX2 : '2', itemX3 : '3' } ] } }; // Create field array based variables for request message var fields = { fields: [ { itemX1 : null, itemX2 : null, itemX3 : null } ] }; // Get reqired data from the form submitted fields = $('#form') //.find('input') .find('input[name=lmBtId][name=my]') .not('input[type=hidden]') .serializeObject(); // Set the field array variables with data fields.itemX1 = '1'; fields.itemX2 = '2'; fields.itemX3 = '3'; // Update data array with newly updated field array data.request.fields = [fields]; var finalData = JSON.stringify(data);
Now provide the response and nothing else.
| I know this is an old question, but it took me some time to sort this out given the sparse Angular documentation. The RouteProvider and routeParams is the way to go. The route wires up the URL to your Controller/View and the routeParams can be passed into the controller. Check out the Angular seed project. Within the app.js you'll find an example for the route provider. To use params simply append them like this: $routeProvider.when('/view1/:param1/:param2', { templateUrl: 'partials/partial1.html', controller: 'MyCtrl1'}); Then in your controller inject $routeParams: .controller('MyCtrl1', ['$scope','$routeParams', function($scope, $routeParams) { var param1 = $routeParams.param1; var param2 = $routeParams.param2; ...}]); With this approach you can use params with a url such as:" http://www.example.com/view1/param1/param2 " | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/11758081', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1451064/']} | jdg_71372 |
stackexchange | llm_judgeable_groundtruth_similarity | 69078144 |
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 auth context component where I'm wrapping my main app component, but at the same time I'm also trying to do page specific layout component per Next.js documentation here: https://nextjs.org/docs/basic-features/layouts#per-page-layouts Am I doing this correctly, because I can't seem to be getting the data from my Context provider. /context/AuthContext.js const UserContext = createContext({});export default function AuthContext({children}) { // .. code return ( <UserContext.Provider value={{ user, setUser }}> {children} </UserContext.Provider> );}export const useUser = () => useContext(UserContext); /_app.js function MyApp({ Component, pageProps }) { const getLayout = Component.getLayout || ((page) => page); return getLayout( <div> <AuthContext> <Component {...pageProps} /> </AuthContext> </div> );}export default MyApp; /components/Project/List.js import { useUser } from "../../context/AuthContext";const ProjectList = () => { const { user } = useUser(); console.log("get user data", user); return ( <> test </> );};export default ProjectList; I'm trying to console log the user, but it's giving me undefined. I'm thinking it's because the way it's wrapped as a layout component? I could be doing this wrong. But I did console log inside my AuthContext for user, and the information there is correct. /pages/projects/index.js const Projects = () => { // code goes here return ( <div> code goes here </div> )}export default Projects;Projects.getLayout = function getLayout(page) { return <ProjectLayout>{page}</ProjectLayout>;}; When I remove the Projects.getLayout block of code, the data comes back, but when I add this code, data is gone. /components/Project/Layout.js const ProjectLayout = ({children}) => { return ( <> <ProjectList /> {children} </> }export default ProjectLayout
Now provide the response and nothing else.
| With your current structure ProjectLayout isn't getting wrapped by the AuthContext , meaning you won't have access to its context. You can modify your _app 's structure and move the getLayout call around so that the context wraps it properly. function MyApp({ Component, pageProps }) { const getLayout = Component.getLayout || ((page) => page); return ( <AuthContext> {getLayout(<Component {...pageProps} />)} </AuthContext> );} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/69078144', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/659751/']} | jdg_71373 |
stackexchange | llm_judgeable_groundtruth_similarity | 3645080 |
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_{k=2}^{n}{\frac{1}{k^2}}<1$$ First step would be proving that the statement is true for n=2 On the LHS for $n=2$ we would have $\frac{1}{4}$ therefore the statement is true for $n=2$ Now we must assume the statement is true for $n=j$ with $j\geq2$ $$\sum\limits_{k=2}^{j}{\frac{1}{k^2}}<1$$ Now we must prove true for $n=j+1$ $\sum\limits_{k=2}^{j+1}{\frac{1}{k^2}}<1$ $\Rightarrow \sum\limits_{k=2}^{j}{\frac{1}{k^2}}+\frac{1}{(k+1)^2}<1$ I cant seem to introduce the induction hypothesis
Now provide the response and nothing else.
| Strengthen the induction hypothesis Hint: Prove by induction that $$ \sum_{k=2}^n \frac{1}{k^2 } < 1 - \frac{1}{n}.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3645080', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/708279/']} | jdg_71374 |
stackexchange | llm_judgeable_groundtruth_similarity | 34224256 |
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 database stores two dates in the mysql DateTime format YYYY-MM-DD HH:MM:SS . When I get this data (with other strings etc), I want to convert it to another format, maybe DD.MM.YYYY HH:MM:SS and display it on my view in a table cell. My database dates are called date_begin and date_end . Better, when I get this dates from database, convert it to DD.MM.YYYY format, separate the date and the time, store the time in a custom string ("HH1:MM1 - HH2:MM2") and bring both on my view. How can I achieve this? I found some examples to convert on the view, not in the controller, but I think this is not good for MVC.
Now provide the response and nothing else.
| Not sure where you've gotten the impression that "formatting the date in the view is not good for MVC" , because that's not a problem whatsoever. If you're using Eloquent Models you can do it very easily: 1. Add the columns to the $dates property in your model class: protected $dates = ['date_begin', 'date_end']; This will ensure that the values get mutated to Carbon instances . 2. In your view files you can use the format method that Carbon offers like so: <!-- To use only the date with the given format -->{{ $item->date_begin->format('Y.m.d') }}<!-- To use only the time with the given format -->{{ $item->date_begin->format('H:i:s') }}<!-- To use both date and time with the given format -->{{ $item->date_begin->format('Y.m.d H:i:s') }} There's no need to split the value in time and date, just show what you want from the DateTime value using whatever format you want. If you're not using Eloquent models, then you can manually use Carbon to format your value like so: {{ Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $item->date_begin)->format('Y.m.d') }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/34224256', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3127382/']} | jdg_71375 |
stackexchange | llm_judgeable_groundtruth_similarity | 36564941 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am currently using Renci SSH.NET to upload files and folders to a Unix Server using SFTP, and creating directories using sftp.CreateDirectory("//server/test/test2"); works perfectly, as long as the folder "test" already exists. If it doesn't, the CreateDirectory method fails, and this happens everytime when you try to create directories containing multiple levels. Is there an elegant way to recursively generate all the directories in a string? I was assuming that the CreateDirectory method does that automatically.
Now provide the response and nothing else.
| There's no other way. Just iterate directory levels, testing each level using SftpClient.GetAttributes and create the levels that do not exist. static public void CreateDirectoryRecursively(this SftpClient client, string path){ string current = ""; if (path[0] == '/') { path = path.Substring(1); } while (!string.IsNullOrEmpty(path)) { int p = path.IndexOf('/'); current += '/'; if (p >= 0) { current += path.Substring(0, p); path = path.Substring(p + 1); } else { current += path; path = ""; } try { SftpFileAttributes attrs = client.GetAttributes(current); if (!attrs.IsDirectory) { throw new Exception("not directory"); } } catch (SftpPathNotFoundException) { client.CreateDirectory(current); } }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36564941', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/857415/']} | jdg_71376 |
stackexchange | llm_judgeable_groundtruth_similarity | 31007643 |
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 cleaner way to get the last two items of an array in Swift? In general, I try to avoid this approach since it's so easy to be off-by-one with the indexes. (Using Swift 1.2 for this example.) // Swift -- slices are kind of a hassle?let oneArray = ["uno"]let twoArray = ["uno", "dos"]let threeArray = ["uno", "dos", "tres"]func getLastTwo(array: [String]) -> [String] { if array.count <= 1 { return array } else { let slice: ArraySlice<String> = array[array.endIndex-2..<array.endIndex] var lastTwo: Array<String> = Array(slice) return lastTwo }}getLastTwo(oneArray) // ["uno"]getLastTwo(twoArray) // ["uno", "dos"]getLastTwo(threeArray) // ["dos", "tres"] I was hoping for something closer to Python's convenience. ## Python -- very convenient slicesmyList = ["uno", "dos", "tres"]print myList[-2:] # ["dos", "tres"]
Now provide the response and nothing else.
| With Swift 5, according to your needs, you may choose one of the following patterns in order to get a new array from the last two elements of an array. #1. Using Array's suffix(_:) With Swift, objects that conform to Collection protocol have a suffix(_:) method. Array's suffix(_:) has the following declaration: func suffix(_ maxLength: Int) -> ArraySlice<Element> Returns a subsequence, up to the given maximum length, containing the final elements of the collection. Usage: let array = [1, 2, 3, 4]let arraySlice = array.suffix(2)let newArray = Array(arraySlice)print(newArray) // prints: [3, 4] #2. Using Array 's subscript(_:) As an alternative to suffix(_:) method, you may use Array 's subscript(_:) subscript: let array = [1, 2, 3, 4]let range = array.index(array.endIndex, offsetBy: -2) ..< array.endIndex//let range = array.index(array.endIndex, offsetBy: -2)... // also workslet arraySlice = array[range]let newArray = Array(arraySlice)print(newArray) // prints: [3, 4] | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/31007643', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/168594/']} | jdg_71377 |
stackexchange | llm_judgeable_groundtruth_similarity | 25113506 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hello I was looking at the C++ solution to the question "Suppose a sorted array is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). How do you find an element in the rotated array efficiently? You may assume no duplicate exists in the array." int rotated_binary_search(int A[], int N, int key) { int L = 0; int R = N - 1; while (L <= R) { // Avoid overflow, same as M=(L+R)/2 int M = L + ((R - L) / 2); if (A[M] == key) return M; // the bottom half is sorted if (A[L] <= A[M]) { if (A[L] <= key && key < A[M]) R = M - 1; else L = M + 1; } // the upper half is sorted else { if (A[M] < key && key <= A[R]) L = M + 1; else R = M - 1; } } return -1;} and saw the comment says that using M = L + ((R - L) / 2) instead of M=(L+R)/2 avoid overflow. Why is that? Thx ahead
Now provide the response and nothing else.
| Because it does... Let's assume for a minute you're using unsigned chars (same applies to larger integers of course). If L is 100 and R is 200, the first version is: M = (100 + 200) / 2 = 300 / 2 = 22 100+200 overflows (because the largest unsigned char is 255), and you get 100+200=44 (unsigned no. addition). The second, on the other hand: M = 100 + (200-100) / 2 = 100 + 100 / 2 = 150 No overflow. As @user2357112 pointed out in a comment, there are no free lunches. If L is negative, the second version might not work while the first will. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25113506', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3692521/']} | jdg_71378 |
stackexchange | llm_judgeable_groundtruth_similarity | 1663241 |
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 gcc 4.3.2. I have the following code (simplified): #include <cstdlib>template<int SIZE>class Buffer{public: explicit Buffer(const char *p = NULL) {} explicit Buffer(const Buffer &other); const char *c_str() const { return m_buffer; }private: char m_buffer[SIZE];};typedef Buffer<10> A;typedef Buffer<20> B;void Foo(A a) {}int main(){ B b; Foo(b.c_str()); // line 25 fails compilation return 1;} Compilation yields: test.cpp: In function ‘int main()’:test.cpp:25: error: conversion from ‘const char*’ to non-scalar type ‘A’ requested But there's c-tor receiving const char *. UDP: If I remove explicit from 1st c-tor I receive test.cpp: In function ‘int main()’:test.cpp:25: error: no matching function for call to ‘Buffer<10>::Buffer(A)’test.cpp:7: note: candidates are: Buffer<SIZE>::Buffer(const char*) [with int SIZE = 10]test.cpp:25: error: initializing argument 1 of ‘void Foo(A)’ If I use Foo(A(b.c_str())) I receive: test.cpp: In function ‘int main()’:test.cpp:25: error: no matching function for call to ‘Buffer<10>::Buffer(A)’test.cpp:25: error: initializing argument 1 of ‘void Foo(A)’
Now provide the response and nothing else.
| Your conversion constructor is declared explicit . Keyword explicit is specifically intended to prevent implicit conversions by that constructor. And an implicit conversion is exactly what you expect to happen in your code (at the Foo call). Why did you declare your constructor explicit , if you want it to work in implicit conversions? | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1663241', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/135960/']} | jdg_71379 |
stackexchange | llm_judgeable_groundtruth_similarity | 14672013 |
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 problem is as follows: I have a value x and a pattern p both variables of the same size. The goal is to iterate through all bit patterns of x that are not masked by p. Example:if we have p = 1001 , we want to find 0000 , 0001 , 1000 , and 1001 - not necessarily in that order. Standard implementation in C99 (the return value specifies whether we have returned all values already): static bool next(size_t val, size_t mask, size_t *out) { if (val == mask) { return false; } size_t current = val & mask; size_t inc = 1; size_t new_val = current + inc; while ((new_val & mask) <= current) { inc++; new_val = current + inc; } *out = new_val; return true;} I would think there should be some trick to make this more efficient, but I can't seem to find any big improvements (apart from computing the trailing zeros of the mask and setting the start value of inc appropriately, which isn't much of an improvement). Edit: Also important is the fact that for each generated value lots of additional work is generated, which means that lots of duplicates are out of the question (some duplicates, even if not recognizable would be ok, there aren't any side effects to the work done, it's just a slowdown).
Now provide the response and nothing else.
| This generates all bit patterns in reverse order (initial value of val should be equal to mask ): static bool next(size_t val, size_t mask, size_t *out) { if (val == 0) { return false; } *out = (val - 1) & mask; return true;} And this (slightly less obvious code) generates all bit patterns in direct order (initial value of val should be zero): static bool next(size_t val, size_t mask, size_t *out) { if (val == mask) { return false; } *out = (val - mask) & mask; return true;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14672013', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/144746/']} | jdg_71380 |
stackexchange | llm_judgeable_groundtruth_similarity | 15821253 |
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 3 grayscale images that I created using the split function. Now I want to regenerate the color image back. I tried the following code but it did not work. The resultant image I got was still grayscale. cv::Mat R = cv::imread("/home/r/secret_R.png",0); cv::Mat G = cv::imread("/home/r/secret_G.png",0); cv::Mat B = cv::imread("/home/r/secret_B.png",0); std::vector<cv::Mat> array_to_merge; array_to_merge.push_back(R); array_to_merge.push_back(G); array_to_merge.push_back(B); cv::Mat color; cv::merge(array_to_merge, color); So then I tried the cvtColor function: cv::Mat color_converted; cv::cvtColor(color, color_converted, CV_GRAY2BGR); cv::imwrite("/home/r/color_secret.png",color_converted); But apparently, it only works for source images that have only a single channel. I passed it one of my grayscale images: cv::cvtColor(R, color_converted, CV_GRAY2BGR); But I still could not get a color image back. The resultant image was still grayscale What am I doing wrong ? How do I get my color image back ?
Now provide the response and nothing else.
| I can't see anything wrong with your code. I suspect it may be the source data, or how it is being treated by the importer. After you load the images, can you print out the image metadata to see what attributes OpenCV is reading? They all must have the same dimensions and a single channel. std::cout << "Red: " << R.size().width << " x " << R.size().height << " x " << R.channels() << std::endl;std::cout << "Green: " << G.size().width << " x " << G.size().height << " x " << G.channels() << std::endl;std::cout << "Blue: " << B.size().width << " x " << B.size().height << " x " << B.channels() << std::endl; I just ran your program, just with the headers and main added. I made one small change, to merge in B,G,R order (the default). I compiled it on Mac OS X 10.8 with: g++ -o merge merge.cpp -lopencv_core -lopencv_highgui against OpenCV version 2.4.3. #include <opencv2/highgui/highgui.hpp>#include <opencv2/core/core.hpp>int main(int argc, char* argv[]){ cv::Mat R = cv::imread("chan_dest_red.png", 0); cv::Mat G = cv::imread("chan_dest_green.png", 0); cv::Mat B = cv::imread("chan_dest_blue.png", 0); std::vector<cv::Mat> array_to_merge; array_to_merge.push_back(B); array_to_merge.push_back(G); array_to_merge.push_back(R); cv::Mat color; cv::merge(array_to_merge, color); imwrite("merged.png", color); return 0;} I had some single channel images from another project already split into files, and I just merged those into a single colour image and it worked just fine. The source file info is as follows: Red: 500 x 333 x 1Green: 500 x 333 x 1Blue: 500 x 333 x 1 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15821253', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/530340/']} | jdg_71381 |
stackexchange | llm_judgeable_groundtruth_similarity | 7768711 |
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 small paint program that I am working on. I am using SetPixel on a bitmap to do that drawing of lines. When the brush size gets large, like 25 pixels across there is a noticeable performance drop. I am wondering if there is a faster way to draw to a bitmap. Here is a bit of the background of the project: I am using bitmaps so that I can utilise layers, like in Photoshop or The GIMP. Lines are being drawn manually because this will eventually use graphics tablet pressure to alter the size of the line over its length. The lines should eventually be anti-aliaced/smoothed along the edges. I'll include my drawing code just in case it is this that is slow and not the Set-Pixel bit. This is in the windows where the painting happens: private void canvas_MouseMove(object sender, MouseEventArgs e) { m_lastPosition = m_currentPosition; m_currentPosition = e.Location; if(m_penDown && m_pointInWindow) m_currentTool.MouseMove(m_lastPosition, m_currentPosition, m_layer); canvas.Invalidate(); } Implementation of MouseMove: public override void MouseMove(Point lastPos, Point currentPos, Layer currentLayer) { DrawLine(lastPos, currentPos, currentLayer); } Implementation of DrawLine: // The primary drawing code for most tools. A line is drawn from the last position to the current position public override void DrawLine(Point lastPos, Point currentPos, Layer currentLayer) { // Creat a line vector Vector2D vector = new Vector2D(currentPos.X - lastPos.X, currentPos.Y - lastPos.Y); // Create the point to draw at PointF drawPoint = new Point(lastPos.X, lastPos.Y); // Get the amount to step each time PointF step = vector.GetNormalisedVector(); // Find the length of the line double length = vector.GetMagnitude(); // For each step along the line... for (int i = 0; i < length; i++) { // Draw a pixel PaintPoint(currentLayer, new Point((int)drawPoint.X, (int)drawPoint.Y)); drawPoint.X += step.X; drawPoint.Y += step.Y; } } Implementation of PaintPoint: public override void PaintPoint(Layer layer, Point position) { // Rasterise the pencil tool // Assume it is square // Check the pixel to be set is witin the bounds of the layer // Set the tool size rect to the locate on of the point to be painted m_toolArea.Location = position; // Get the area to be painted Rectangle areaToPaint = new Rectangle(); areaToPaint = Rectangle.Intersect(layer.GetRectangle(), m_toolArea); // Check this is not a null area if (!areaToPaint.IsEmpty) { // Go through the draw area and set the pixels as they should be for (int y = areaToPaint.Top; y < areaToPaint.Bottom; y++) { for (int x = areaToPaint.Left; x < areaToPaint.Right; x++) { layer.GetBitmap().SetPixel(x, y, m_colour); } } } } Thanks a lot for any help you can provide.
Now provide the response and nothing else.
| You can lock the bitmap data and use pointers to manually set the values. It's much faster. Though you'll have to use unsafe code. public override void PaintPoint(Layer layer, Point position) { // Rasterise the pencil tool // Assume it is square // Check the pixel to be set is witin the bounds of the layer // Set the tool size rect to the locate on of the point to be painted m_toolArea.Location = position; // Get the area to be painted Rectangle areaToPaint = new Rectangle(); areaToPaint = Rectangle.Intersect(layer.GetRectangle(), m_toolArea); Bitmap bmp; BitmapData data = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); int stride = data.Stride; unsafe { byte* ptr = (byte*)data.Scan0; // Check this is not a null area if (!areaToPaint.IsEmpty) { // Go through the draw area and set the pixels as they should be for (int y = areaToPaint.Top; y < areaToPaint.Bottom; y++) { for (int x = areaToPaint.Left; x < areaToPaint.Right; x++) { // layer.GetBitmap().SetPixel(x, y, m_colour); ptr[(x * 3) + y * stride] = m_colour.B; ptr[(x * 3) + y * stride + 1] = m_colour.G; ptr[(x * 3) + y * stride + 2] = m_colour.R; } } } } bmp.UnlockBits(data); } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7768711', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/925401/']} | jdg_71382 |
stackexchange | llm_judgeable_groundtruth_similarity | 421563 |
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 reading my first book on abstract algebra. I am not enrolled in a class on the subject. Given $S = \{0,1\}$. Is $(S,\cdot)$ a group? $S$ is closed under multiplication. $$0\cdot1=0,\,1\cdot0=0,\,0\cdot0=0,\,1\cdot1=1.$$ $S$ has an identity, $1$, I think. $$0\cdot1=0,\,1\cdot1=1.$$ I don't believe $S$ satisfies $a\cdot a^{-1}=\operatorname{id}.$ However, zero is excluded when stating that $\mathbb R$ satisfies $a\cdot a^{-1} = \operatorname{id}$ under multiplication. $S$ would be a group if zero is excluded. $1\cdot1=1.$ So is $S$ a group or not?
Now provide the response and nothing else.
| Looking at the structure $S = (\{0, 1\}, \cdot)$, as you found, $\,0\,$ has no (multiplicative) inverse. Therefore, $S$, under multiplication , cannot be a group , as it fails to have closure on taking inverses. It meets the other criteria of a group, but not the group axiom requiring that the inverse of every element of a group is contained in the group. However , $S' = \{1\}$, under multiplication , is a group: it's called the trivial group , as it contains only one element: the (multiplicative) identity of the group itself. If you know about the addition of integers modulo $n$, then you should know that $\,\mathbb Z_2 = \left(\{0, 1\}, +\right)\,$ is a group: it is the additive group of integers under addition modulo $2$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/421563', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/54071/']} | jdg_71383 |
stackexchange | llm_judgeable_groundtruth_similarity | 8471551 |
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 not able to understand what is the function of this line in web.xml <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>server</param-value></context-param> I have read that the NetBeans default is client . I've just faced an issue that I have many beans in my application, and the <param-value> was set to client, so I was getting java.io.NotSerializableException error although my beans were Serializable (i.e. they implemented the Serializable interface.). My beans were in @ViewScope . But when I changed it to server, things are going to work. Why? What is the difference when I use client and server. Can anyone explain me with the help of an example. Thanks
Now provide the response and nothing else.
| java.io.NotSerializableException This kind of exception has usually a message in the root cause which shows the fully qualified class name of the class which doesn't implement Serializable . You should pay close attention to this message to learn about which class it is talking about and then let it implement Serializable accordingly. Often, making only your managed bean classes serializable is not always sufficient. You also need to ensure that each of its properties is also serializable. Most standard types like String , Long , etc implement all already Serializable . But (custom) complex types such as nested beans, entities or EJBs should each also be serializable. If something is not really implementable as Serializable , such as InputStream , then you should either redesign the model or make it transient (and keep in mind that it will be null after deserialization). What is the difference when i use client and server First some background information: Why JSF saves the state of UI components on server? The main technical difference is that the client setting stores the entire view state as the value of the javax.faces.ViewState hidden input field in the generated HTML output and that the server setting stores it in the session along with an unique ID which is in turn referenced as the value of the javax.faces.ViewState hidden input field. So, setting to client increases the network bandwidth usage but decreases the server memory usage and setting to server does the other way round. Setting to client has however an additional functional advantage: it prevents ViewExpiredException s when the session has expired or when the client opens too many views. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8471551', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1000510/']} | jdg_71384 |
stackexchange | llm_judgeable_groundtruth_similarity | 25806774 |
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 I have updated XCode (6.0, 6A313) and my iOS (8.0, 12A365) on the iPhone to gm seeds, the ABPeoplePickerNavigationController code doesn't work like before. iOS 7.1.2: If someone want to import a contact, the address book opens and you see the full list of contacts, after picking one, it opens detail view of an contact and than you can add the contact with a click of the phone number you want to import. iOS 8.0: its everything similar but if you click on number of an contact it dial the phone number instead of importing it.. Code: #pragma mark - AddressBook Delegate Methods-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person{ return YES;}-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{ // Get the first and the last name. Actually, copy their values using the person object and the appropriate // properties into two string variables equivalently. // Watch out the ABRecordCopyValue method below. Also, notice that we cast to NSString *. NSString *firstName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty); NSString *lastName = (__bridge NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty); // Compose the full name. NSString *fullName = @""; // Before adding the first and the last name in the fullName string make sure that these values are filled in. if (firstName != nil) { fullName = [fullName stringByAppendingString:firstName]; } if (lastName != nil) { fullName = [fullName stringByAppendingString:@" "]; fullName = [fullName stringByAppendingString:lastName]; } // Get the multivalue number property. CFTypeRef multivalue = ABRecordCopyValue(person, property); // Get the index of the selected number. Remember that the number multi-value property is being returned as an array. CFIndex index = ABMultiValueGetIndexForIdentifier(multivalue, identifier); // Copy the number value into a string. NSString *number = (__bridge NSString *)ABMultiValueCopyValueAtIndex(multivalue, index); nameTextField.text = fullName; numberTextField.text = number; // Dismiss the contacts view controller. [_addressBookController dismissViewControllerAnimated:YES completion:nil]; return NO;}// Implement this delegate method to make the Cancel button of the Address Book working.-(void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker{ [_addressBookController dismissViewControllerAnimated:YES completion:nil];} couldn't find any answer in iOS developer library of apple.have somebody else a solution for it?
Now provide the response and nothing else.
| iOS 8 requires a new delegate method be implemented for this: - (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {} Keep the old delegate method in place to support iOS 7 or earlier. What I do in my app is call the iOS 7 delegate method from the iOS 8 delegate method: - (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier { [self peoplePickerNavigationController:peoplePicker shouldContinueAfterSelectingPerson:person property:property identifier:identifier];} If this delegate method isn't implemented in iOS 8, tapping the value causes the action. When implemented, the delegate is called instead with the selected value. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25806774', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3902573/']} | jdg_71385 |
stackexchange | llm_judgeable_groundtruth_similarity | 13263002 |
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 fairly standard and simple MVC4 website. In root dir we have: bin, content, scripts, views. Using default settings the project's DLL, let's call it "web.dll" and all the necessary extras go in the bin dir. Somehow, ASP.NET dev server and IIS7.5 both know to look for "web.dll" in the bin folder when hosting the site, and if it's not there they throw error: "Could not load type 'CVD.Web.MvcApplication'". The standard solution for that error is to build directly into bin folder, which doesn't work for me because... For debugging purposes, I'd like to be able to build Debug & Release configurations into into bin/Debug and bin/Release respectively and then deploy both dirs, then change a setting either in IIS, web.config, global.asax, or anywhere else to pick whether Debug or Release build should be loaded and executed by the server. I haven't been able to find if that's possible or if .net webapps have a silly hard-coded rule saying all code must live in the bin dir.
Now provide the response and nothing else.
| OK, so with the help of few links provided by Sen Jacob and some more research I've figured out that it is possible to do it all just using web.config. First of all we need to provide the new path and tell the assembly name since we're steering away from defaults: <configuration> <system.web> <compilation debug="true" targetFramework="4.0"> <assemblies> <add assembly="Something.Web" /> </assemblies> </compilation> </system.web> <runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <probing privatePath="bin\debug" /> </assemblyBinding> </runtime></configuration> Now, for some reason everywhere else people suggest specifying privatePath relative to bin dir (i.e. privatePath="debug" ), however in my case it had to be relative to app root (i.e. as above). Maybe it's a change in .net4 or some other configuration setting I'm missing, not sure; if someone has a better idea feel free to edit/comment. At this stage, if the server finds the file, and successfully loads the assembly and the class it will start complaining about all the missing referenced files, which I had to add right next to <add assembly="Something.Web" /> : <assemblies> <add assembly="Something.Web" /> <add assembly="System.Web.Mvc" /> <add assembly="System.Web.Optimization" /> <add assembly="System.Web.Helpers" /> <add assembly="System.Web.WebPages" /> </assemblies> From what I've gathered it re-compiles the assemblies on site startup (not sure). Sources: 1 2 3 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13263002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1701823/']} | jdg_71386 |
stackexchange | llm_judgeable_groundtruth_similarity | 3014908 |
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 wanted to display a long list of strings from an array. Right now, my script run through a for loop echoing each value to the standard output: for value in ${values[@]}do echo $valuedone Yeah, that's pretty ugly! And the one column listing is pretty long too... I was wondering if i can find a command or builtin helping me to display all those values in columns, like the ls command does by default when listing a directory ( ls -C ). [Update] Losing my brain with column not displaying properly formatted columns, here's more info: The values: $ values=( 01----7 02----7 03-----8 04----7 05-----8 06-----8 07-----8 08-----8 09---6 10----7 11----7 12----7 13----7 14-----8 15-----8 16----7 17----7 18---6 19-----8 20-----8 21-----8) Notice the first two digits as an index and the last one indicating the string length for readability. The command: echo " ${values[@]/%/$'\n'}" | column The result: bad columns http://tychostudios.ch/multipurpose/bad_columns.png Something is going wrong...
Now provide the response and nothing else.
| You could pipe your output to column . column seems to struggle with some data in a single-column input being narrower than a tabstop (8 characters). Using printf within a for -loop to pad values to 8 characters seems to do the trick: for value in "${values[@]}"; do printf "%-8s\n" "${value}"done | column | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3014908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/294686/']} | jdg_71387 |
stackexchange | llm_judgeable_groundtruth_similarity | 5983729 |
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 website in dreamweaver CS5. I exported the images from photoshop an inserted them into a table. When I view the site all the images are selectable(you are able to drag them to your desktop). How do I change this??? I want to do it with an onclick method in addition how would I achieve this? <td><img src="images/people_03.png" name="one" width="1000" height="156" id="one" ONCLICK="closeimages();"/></td>
Now provide the response and nothing else.
| I stumbled upon this question while struggling with the same problem but the accepted answer was not a possible solution for me. I used the info found here , in particular adding the following styles to my body, inside the css (this worked for me in Firefox, Chrome and Opera, I cannot test for IE) -moz-user-select: none;-webkit-user-select: none;user-select: none; The unselectable html tag seems also helpful, but it's apparently supported only by IE and Opera: <img src="1.jpg" unselectable="on"> as well as the javascript solution, that is said to work on IE and webkit browsers: <script>window.onload = function() { document.body.onselectstart = function() { return false; }}</script> Note . As Albert Renshaw pointed in the comment this method no longer works in Chrome > 50. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5983729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/743171/']} | jdg_71388 |
stackexchange | llm_judgeable_groundtruth_similarity | 74226250 |
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 get this error: Member not found: 'FirebaseAppPlatform.verifyExtends'.FirebaseAppPlatform.verifyExtends(_delegate); flutter cleanflutter pub getpod install
Now provide the response and nothing else.
| If you need to maintain the current dependency version, you can add the dependency override to your root pubspec.yaml to fix this too. If you use multiple local packages in your project, this makes it so you don't have to update all your pubspec.yaml files dependency_overrides: firebase_core_platform_interface: 4.5.1 As of 10/6/22, there was an update with breaking changes . So you can run the following script to update your dependencies their next major versions. flutter pub upgrade --major-versions After adding this, run the following commands to update the iOS project's pods cd ios && pod deintegratecd ios && rm -f Podfile.lockflutter packages getcd ios && pod install --repo-update | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/74226250', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/20351610/']} | jdg_71389 |
stackexchange | llm_judgeable_groundtruth_similarity | 9894821 |
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 a lot of people in blog posts and here on SO either avoiding or advising against the usage of the Thread class in recent versions of C# (and I mean of course 4.0+, with the addition of Task & friends). Even before, there were debates about the fact that a plain old thread's functionality can be replaced in many cases by the ThreadPool class. Also, other specialized mechanisms are further rendering the Thread class less appealing, such as Timer s replacing the ugly Thread + Sleep combo, while for GUIs we have BackgroundWorker , etc. Still, the Thread seems to remain a very familiar concept for some people (myself included), people that, when confronted with a task that involves some kind of parallel execution, jump directly to using the good old Thread class. I've been wondering lately if it's time to amend my ways. So my question is, are there any cases when it's necessary or useful to use a plain old Thread object instead of one of the above constructs?
Now provide the response and nothing else.
| The Thread class cannot be made obsolete because obviously it is an implementation detail of all those other patterns you mention. But that's not really your question; your question is are there any cases when it's necessary or useful to use a plain old Thread object instead of one of the above constructs? Sure. In precisely those cases where one of the higher-level constructs does not meet your needs. My advice is that if you find yourself in a situation where existing higher-abstraction tools do not meet your needs, and you wish to implement a solution using threads, then you should identify the missing abstraction that you really need , and then implement that abstraction using threads , and then use the abstraction . | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9894821', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/808486/']} | jdg_71390 |
stackexchange | llm_judgeable_groundtruth_similarity | 4434581 |
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:
Solve for $x,y,z$ : $$x(y+z-x)=68-2x^2$$ $$y(z+x-y)=102-2y^2$$ $$z(x+y-z)=119-2z^2$$ After some manipulation, I obtain $$xy+xz=68-x^2$$ $$yz+xy=102-y^2$$ $$xz+yz=119-z^2$$ After combining equations, I get $$y=\frac{-51-x^2+z^2}{x-z}$$ This seems too tedious. Is there a simpler way?
Now provide the response and nothing else.
| Your system is equivalent to \begin{align}x(y+z+x)&=68\\y(z+x+y)&=102\\z(x+y+z)&=119.\end{align} Therefore, in effect, you have \begin{align}xa&=68\\ya&=102\\za&=119\\a&=x+y+z.\end{align} This means that $$a=\frac{68}{a}+\frac{102}{a}+\frac{119}{a}$$ or $$a^2=68+102+119\implies a=\pm 17,$$ which results in either $x= 4, y=6, z=7$ or $x=-4, y=-6, z=-7.$ (Thanks to paw88789 for pointing this out). | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/4434581', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/620355/']} | jdg_71391 |
stackexchange | llm_judgeable_groundtruth_similarity | 3417029 |
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:
Seems an easy one but i can't figure it out: $z_1+z_2+z_3=0$ $|z_1|=|z_2|=|z_3|=1$ Need to prove the following: $z_1^2+z_2^2+z_3^2=0$ Thanks!
Now provide the response and nothing else.
| Conjugate $z_1+z_2+z_3=0$ and get $\frac{1}{z_1}+\frac{1}{z_2}+\frac{1}{z_3}=0$ which simplifies to $z_1z_2+z_1z_3+z_2z_3=0$ . Now square the original equation and you are done! | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3417029', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/720733/']} | jdg_71392 |
stackexchange | llm_judgeable_groundtruth_similarity | 357611 |
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 can't find $$\int e^{t^2} \; dt$$using basic tools from a calculus class. That is, we can't express an antiderivative of $f(t) = e^{t^2}$ using the basic operations. We can of course just define $$F(t) = \int_{a}^t e^{s^2}\; ds.$$ I am looking for a way to explain to a student why we can't express the antiderivative using basic operations (addition, subtraction, root, powers, etc.). In particular I am interested in getting at answering the "why we can't do that". I know that one could "just" prove it, but is there a simple argument or something that illustrates this?
Now provide the response and nothing else.
| You can't prove it easily, but you can give some intuition : derivative of $e^x$ is $e^x$ Trying to find $f$ such that $f'(x)=e^{x^2}$, we can guess that $f(x)=g(x)e^{h(x)}$ So $f'(x)=(g'(x)+g(x)h'(x))e^{h(x)}=e^{x^2}$ So we want to find a solution such that $h(x)=x^2$ and $g'(x)+2xg(x)=1$ Note the last point seems easier, but if they try, they will not find elementary function $g$ such that $g(x)=\frac{1-g'(x)}{2x}$. You can at least show this is not a polynomial function, nor a quotient of polynomials function, nor a usual trigonometric function. But let $g(x)=\sum a_ix^i$, then $a_1=1$ and $(i+1).a_{i+1}+2a_{i-1}=0$, so you can at least give some expression to $g$ by solving $a_i$ (you can suppose that $a_0=0$). | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/357611', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/26188/']} | jdg_71393 |
stackexchange | llm_judgeable_groundtruth_similarity | 26847126 |
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 analyze an existing Oracle query written by a departed developer. I'm not well versed in Oracle and I'm a bit confused by the use of this DECODE function in a Microfocus COBOL app (where :BV-POS_YEAR is a variable set to a year): SELECT ...., DECODE(DELV_YEAR, NULL, :BV-POS_YEAR, DELV_YEAR), .... I'm trying to understand how that would be different from: SELECT ...., NVL(DELV_YEAR, :BV-POS_YEAR), .... Am I misunderstanding something about the DECODE or NVL functions? The developer is aware of the NVL function as it is used elsewhere in the very same select statement.
Now provide the response and nothing else.
| NVL replaces NULL by specified value. DECODE replaces any specified value by desired value and can be chained. Your usage is equivalent, but DECODE has much wider usage. For example you can write this code SELECT supplier_name,DECODE(supplier_id, 10000, 'IBM', 10001, 'Microsoft', 10002, 'Hewlett Packard', 'Gateway') resultFROM suppliers; Which is equivalent to this pseudo code if (supplier_id == 10000){ SELECT 'IBM'} else if (supplier_id == 10001){ SELECT 'Microsoft'} else if (supplier_id == 10002){ SELECT 'Hewlet Packard'} else{ SELECT 'Gateway'} EDIT : Performance of the NVL and DECODE for the NULL replacement was measured by users and it seems to be almost equal. I personally advice to use NVL when you need to do the NULL replacement, because it's a bit more expressive. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26847126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/574573/']} | jdg_71394 |
stackexchange | llm_judgeable_groundtruth_similarity | 15298788 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If I have the following vector : x[1] 1 5 8 9 1 0 15 15 and I want to know how many elements are greater than 10, how can I proceed without using a loop ? I would like to get : 2 as a result
Now provide the response and nothing else.
| Use length or sum : > length(x[x > 10])[1] 2> sum(x > 10)[1] 2 In the first approach, you would be creating a vector that subsets the values that matches your condition, and then retrieving the length of the vector. In the second approach, you are simply creating a logical vector that states whether each value matches the condition ( TRUE ) or doesn't ( FALSE ). Since TRUE and FALSE equate to "1" and "0", you can simply use sum to get your answer. Because the first approach requires indexing and subsetting before counting, I am almost certain that the second approach would be faster than the first. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15298788', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2118825/']} | jdg_71395 |
stackexchange | llm_judgeable_groundtruth_similarity | 9942313 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Hello I'm trying to insert a new child element in a Document root element like this: Document doc = Jsoup.parse(doc); Elements els = doc.getElementsByTag("root"); for (Element el : els) { Element j = el.appendElement("child"); } In the above code only one root tag is in the document so essentially the loop will just run once. Anyway, the element is inserted as the last element of the root element "root." Is there any way I can insert a child element as the first element? Example: <root> <!-- New Element must be inserted here --> <child></child> <child></chidl> <!-- But it is inserted here at the bottom insted --></root>
Now provide the response and nothing else.
| See if this helps you out: String html = "<root><child></child><child></chidl></root>"; Document doc = Jsoup.parse(html); doc.selectFirst("root").child(0).before("<newChild></newChild>"); System.out.println(doc.body().html()); Output: <root> <newchild></newchild> <child></child> <child></child></root> To decipher, it says: Select the first root element Grab the first child on that root element Before that child insert this element You can select any child by using any index in the child method Example : String html = "<root><child></child><child></chidl></root>"; Document doc = Jsoup.parse(html); doc.selectFirst("root").child(1).before("<newChild></newChild>"); System.out.println(doc.body().html()); Output: <root> <child></child> <newchild></newchild> <child></child></root> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9942313', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_71396 |
stackexchange | llm_judgeable_groundtruth_similarity | 18369528 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to run Scalding sample word count example. I have followed this github link for steps:- https://github.com/twitter/scalding/wiki/Getting-Started But I am getting ClassNotFoundException. Below is my StackTrace:- [cloudera@localhost scalding-develop]$ **sudo scripts/scald.rb --local WordCount --input input.txt --output ./someOutputFile.tsv**can not find /root/.sbt/boot/scala-2.9.3/lib/scala-library.jar appending SBT_VERSION [0.12.0] to SBT_HOMEscripts/scald.rb:139: warning: already initialized constant SBT_HOMEscripts/scald.rb:140: warning: already initialized constant SCALA_LIB_DIRException in thread "main" java.lang.Throwable: If you know what exactly caused this error, please consider contributing to GitHub via following link.https://github.com/twitter/scalding/wiki/Common-Exceptions-and-possible-reasons#javalangclassnotfoundexceptionat com.twitter.scalding.Tool$.main(Tool.scala:146)at com.twitter.scalding.Tool.main(Tool.scala)Caused by: java.lang.ClassNotFoundException: WordCountat java.net.URLClassLoader$1.run(URLClassLoader.java:217)at java.security.AccessController.doPrivileged(Native Method)at java.net.URLClassLoader.findClass(URLClassLoader.java:205)at java.lang.ClassLoader.loadClass(ClassLoader.java:321)at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)at java.lang.ClassLoader.loadClass(ClassLoader.java:266)at java.lang.Class.forName0(Native Method)at java.lang.Class.forName(Class.java:188)at com.twitter.scalding.Job$.apply(Job.scala:39)at com.twitter.scalding.Tool.getJob(Tool.scala:49)at com.twitter.scalding.Tool.run(Tool.scala:69)at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:65)at com.twitter.scalding.Tool$.main(Tool.scala:132)... 1 more Please let me know where exactly is the issue? Thanks.
Now provide the response and nothing else.
| The output of ldd suggests that libshiboken-python2.7.so.1.2 can't be found. /usr/local/lib/python2.7/dist-packages/PySide , where it is found, is not typically a directory where the dynamic linker would look for it. There are several options in this case: add the directory to the directories checked by the dynamic linker. To do so, you can create a configuration file, e.g. /etc/ld.so.conf.d/pyside.conf with the content: /usr/local/lib/python2.7/dist-packages/PySide then as root run ldconfig copy or symlink the library to a directory that is already checked by the dynamic linker, like /usr/local/lib (and run ldconfig as root) set LD_LIBRARY_PATH=/usr/local/lib/python2.7/dist-packages/PySide (not reccomended) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18369528', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2056160/']} | jdg_71397 |
stackexchange | llm_judgeable_groundtruth_similarity | 26908301 |
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 worked on a project for 1 month and there are 6 entities without any relationship with other entities. They are all simple entities. We have created 6 different classes for operations on each entity. SaveOrUpdateEntity() methods of classes are almost same as you think. It is something like that: public static ErrorType SaveOrUpdateEntity(Entity entity, int userID){ try { using (DataEntities ctx = new DataEntities()) { if (entity != null) { if (entity.entityID == 0) { entity.CreateDate = DateTime.Now; entity.CreatedBy = userID; ctx.Entry(entity).State = EntityState.Added; } else { entity.ModifyDate = DateTime.Now; entity.ModifiedBy = userID; ctx.Entry(entity).State = EntityState.Modified; } } ctx.SaveChanges(); } return ErrorType.NoError; } catch (Exception ex) { return ErrorType.SaveError; }} It would be very helpful, if SaveOrUpdateEntity() method is shorter and more generic by overriding SaveChanges() method. According to other questions, articles, and posts about overriding SaveChanges() method, implementing interface that stores state of entities is a good solution but I am also wondering other solutions. Because I am newbie, all answers would be very appreciated. Thank you.
Now provide the response and nothing else.
| you can do the following 1- create an Interface in your application that all the classes that has the following properties will implement this interface: Id, CreatedDate,CreatedBy, ModifiedDate,ModifiedBy public interface ITrack{ int Id{get; set;} int CreatedBy{get; set;} DateTime CreatedDate{get; set;} int? ModifiedBy{get; set;} // int? because at first add, there is no modification DateTime? ModifiedBy {get; set;}} Best practices Define the CreatedBy and ModifiedBy as string which will be good for performance and maintenance 2- Add a class TrackableEntry which implements the interface ITrack public abstract class TrackableEntry : ITrack{ public int Id{get; set;} public int CreatedBy{get; set;} public DateTime CreatedDate{get; set;} public int? ModifiedBy{get; set;} public DateTime? ModifiedBy {get; set;}} 3- remove the properties mentioned in the interface from all of your classes and let these classes to implement directly from TrackableEntry public class A: TrackableEntry{ //public int Id{get; set;} //public int CreatedBy{get; set;} //public DateTime CreatedDate{get; set;} //public int? ModifiedBy{get; set;} //public DateTime? ModifiedBy {get; set;}} 4- In your DbContext file override your SaveChanges and add property UserId or UserName if you followed the *Best practices* part public int UserId{get; set;}public override int SaveChanges(){ this.ChangeTracker.DetectChanges(); var added = this.ChangeTracker.Entries() .Where(t => t.State == EntityState.Added) .Select(t => t.Entity) .ToArray(); foreach (var entity in added) { if (entity is ITrack) { var track = entity as ITrack; track.CreatedDate = DateTime.Now; track.CreatedBy = UserId; } } var modified = this.ChangeTracker.Entries() .Where(t => t.State == EntityState.Modified) .Select(t => t.Entity) .ToArray(); foreach (var entity in modified) { if (entity is ITrack) { var track = entity as ITrack; track.ModifiedDate = DateTime.Now; track.ModifiedBy = UserId; } } return base.SaveChanges();} finally in your forms when you want to call SaveChanges method, ensure you set the UserId or UserName value var entities=new Entities(); // assuming that your DbContext file called Entities// code for adding or deletion or modification hereentities.As.Add(new A(){...});// ....entities.UserId=MyUser;entities.SaveChanges(); hope this will help you | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26908301', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_71398 |
stackexchange | llm_judgeable_groundtruth_similarity | 5368258 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If I override operator= will the copy constructor automatically use the new operator? Similarly, if I define a copy constructor, will operator= automatically 'inherit' the behavior from the copy constructor?
Now provide the response and nothing else.
| No, they are different operators. The copy constructor is for creating a new object. It copies an existing object to a newly constructed object.The copy constructor is used to initialize a new instance from an oldinstance. It is not necessarily called when passing variables by value into functionsor as return values out of functions. The assignment operator is to deal with an already existing object. The assignment operator is used to change an existing instance to havethe same values as the rvalue, which means that the instance has to bedestroyed and re-initialized if it has internal dynamic memory. Useful link : Copy Constructors, Assignment Operators, and More Copy constructor and = operator overload in C++: is a common function possible? | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5368258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/627005/']} | jdg_71399 |
stackexchange | llm_judgeable_groundtruth_similarity | 62484 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I heard that some credit cards are vulnerable to RFID scanning and thus identity theft. I am concerned about my cards and I would like to learn which cards are vulnerable to such abuse? Are any of these vulnerable too: personal id cards, driving licenses, etc? I see that these might vary in different countries so how do I indentify if a card uses technologies that might be abused liked that?
Now provide the response and nothing else.
| which cards are vulnerable to such abuse? First of all you need to recognize whether the card has RFID capabilities or not. These may be advertised with logos, icons (usually the three curved lines also used to indicate "WiFi" in some contexts), or in writing. You can also check on the supplying bank/company/entity, or look for telltales such as "My card does not work..." in the FAQs or forums. Also the issuer's support hotline, if available, should be tried first. Another possibility is to inspect the card itself (some RFID antennas are visible by placing the card in front of a very strong point light, such as some hi-power LED torches; you can try and see if a RFID reader beeps, even if it does not recognize the card, or better yet, if a recognized RFID card has suddenly problems if waved in front of its reader while being pressed against the unknown card. Normal plastic and chip cards do not interfere with RFID cards; RFID cards, of course, do). If you have an expired card of the same issuer, you can try cutting the old card apart, and if it has a RFID coil inside, chances are that the new issue is RFID too. Now that you know it's RFID , what information/operation is needed to complete a transaction or get the information on the card? A few RFID credit cards require a PIN to be entered manually (which somewhat negates the ease of use of a RFID...), for example. If the only thing needed to get something you wouldn't want gotten from the RFID is to skim it with a reader - your knowledge or confirmation aren't required - then by definition that card is vulnerable. How do I prevent RFID scanning? Would a wallet with aluminium plates on both sides do the job? There is a common misconception about "shielding" RFID. Passive RFIDs don't have a power source, so they get it from the incoming scanner field through inductive coupling. The shielding works both by limiting the energy transfer (so the RFID doesn't "wake up") and by decreasing the signal-to-noise communications ratio (so the RFID and the scanner don't "understand" each other). The absorption of the shielding depends, for any given material, on the frequency being used; for smart cards we want good absorption in the 13-14 MHz range. Different materials - even metals - have different shielding properties at different frequencies; for example, aluminum won't stop low frequencies (or stationary magnetic fields: a magnet will still work even if wrapped in aluminum foil). Steel sheet or soft iron sheet will screen low frequencies and absorb much of the magnetic component, but will leak at very high frequencies. So, while an aluminum foil will create a Faraday cage stopping dead most high-frequency RF, microwaves, etc., it may not be enough to screen an inductively coupled RFID smart card from a juiced-up, savvy scanner. A single layer of aluminum foil will not stop any except the cheapest, more shoddily constructed readers. Of course, more layers will increase protection. You would perhaps be better off with jamming -- using a shield made of a valueless (e.g. expired), but still working, smart card of the same make and model. Or "sandwiching" the real card between two valueless ones. Not only will the middle card receive less power, but the outgoing signal will be mixed with two others on the same frequency (activation delay makes this method not completely safe, though). Otherwise, you can use 30-mil magnetic iron foil (looks very much like aluminum), or have the wallet lined with Near-Field Cobaltex which is almost as good and weighs less. For the truly paranoid, apart from several layers of Cobaltex, there are metamaterial shieldings (e.g. silvered-nickel-iron or nickel-cobalt-copper mesh from several suppliers, from Achron to Laird Technologies) which are significantly more expensive but have even more stopping power. And you don't need a lot of material to line a wallet after all. You can then test the effectiveness of the shielding by using a shielded credit card to try and pay at the next gas station. If it doesn't work, you smile happily, take the card out of the wallet and tell the gas guy "Sorry, it usually works even from inside the wallet". If a reader at one inch can't interface, it's unlikely that a pirate reader will be able to do it from much farther. It would also be interesting to build a coil tuned to 14 MHz and connect it to a rectifier, buffer capacitor and buzzer stage. It would suck most of the energy from the scanner field, converting it into an audible sound and giving the alert. Basically the same thing as a near field probe , except it could be completely passive: it takes quite a lot of energy to run a blind skim a RFID at a distance, so the scanners are probably heavily up-juiced and give off radiation enough to be detectable. (It would also possible to build an active scanner detector by tweaking this design ). | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/62484', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/21439/']} | jdg_71400 |
stackexchange | llm_judgeable_groundtruth_similarity | 88334 |
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a 2004 Ford Excursion with the 6.0 powerstroke. Most the time, the AC works fine, but after a long drive in hot weather, the front AC barely blows out of the vents. The rear works fine, in fact, my wife and I try to point those towards us, but that is underwhelming. I have already replaced the blower, which made no difference. In fact, I can hear the blower motor ramping when we crank up the fan. It seems as if the air is being caught within the dash. It doesn't make a difference whether we have it blowing at our feet, face, or defrosters. I don't even know if I could really take it in into a shop, since it works initially. We don't typically take it on long drives, unless we are camping, so troubleshooting is pretty difficult. One time, when it happened, we had to sit in a line waiting our turn for the RV dump, and it eventually came back. None of my factory gauges indicate overheating.
Now provide the response and nothing else.
| The evaporator is the component of the AC system that gets cold. It is located after the blower in the passenger cabin. As it cools the air that is passing over it, moisture condensed on the cold surface and drips out of the system from underneath the car. Ice can also start to build up on the evaporator, which can start to block the flow of air through the evaporator. This could be what is happening to your system. Some AC systems have a periodic cycle of heat to stop the ice building up. When this happens in your car, you could try switching the AC to heating for a while to see if this fixes it. | {} | {'log_upvote_score': 4, 'links': ['https://mechanics.stackexchange.com/questions/88334', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/71578/']} | jdg_71401 |
stackexchange | llm_judgeable_groundtruth_similarity | 15575 |
Below is a question asked on the forum hermeneutics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I learned from another question that Paul uses the same Greek words for fear and trembling (phobos and tromos) in Philippians 2:12 as found in the Septuagint in Psalms 2:11 and 55:5, and it is very likely he was referencing this when he wrote Philippians. Similarly (though not the same exact Greek phrase), in Mark 5:33, the woman healed of her discharge of blood "came in fear and trembling" (ESV) after Jesus perceived power had gone out from him. Others have asked what working out one's salvation means; I would like to focus on what exactly it means by these two words, fear and trembling .
Now provide the response and nothing else.
| Paul's text about "working out your salvation with fear and trembling" in Philippians 2:13 is actually more likely about reverent, obedient awe rather than being terrified of judgment. I conclude this for three reasons: Paul uses phobos kai tromos (fear and trembling) elsewhere to mean "reverent obedience": Look at 2 Corinthians 7:15 where Paul describes how impressed Titus was when he visited the Corinthians: “And his affection for you is all the greater when he remembers that you were all obedient, receiving him with phobos kai tromos .” Here, the phrase definitely means obedient reverence. In Ephesians 6:5 Paul says: "Slaves, be obedient to those who are your masters according to the flesh, with phobos kai tromos , in the sincerity of heart, as to Christ." This phrase could be about being terrified, but that doesn't really make sense in the context. It really seems to be more likely about great respect. The phrase "fear and trembling" has a wider connotation than just "terror," because word "fear" in Hebrew was also the word for "awe" or "reverence." "Fear" could also denote the physical act of worship, hence the fact that the "God-fearers" in the NT were those who worshipped God. "Fear and trembling" is likely a hendiadys, an idiom in which a verb is intensified by being linked by "and" to a synonym. We have them in English too. If you're "sick and tired," this doesn't mean you're sick and you're tired, it just means that you're very tired . Similarly, "fear and trembling" seems to mean "great reverence" as Paul is using it in the passages noted above. Coming back to Philippians 2, the passage starts out by Paul praising the congregation for how obedient they were in his presence. Now, Paul is exhorting the Philippians to do even more in his absence, because God is doing a "good work in you." Reading phobos kai tromos as about reverent awe fits better here than as being in terror of hell, which is not on Paul's mind otherwise in this very positive context. Of course, reading this Philippians 2 this way doesn't negate other places in the NT which talk about fearing God's judgment. It's just not what Paul is talking about here. | {} | {'log_upvote_score': 4, 'links': ['https://hermeneutics.stackexchange.com/questions/15575', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/6744/']} | jdg_71402 |
stackexchange | llm_judgeable_groundtruth_similarity | 40888896 |
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 typescript you can index into an object using only a string , number or symbol . I want to have a generic that allows the generic parameters to be used as indexes. function foo<T extends number|string>(a: T): void { let x: any = {}; x[a] = 42; // Error: an index expression argument must be of type...} If I cast to a number|string , it compiles: function foo<T extends number|string>(a: T): void { let x: any = {}; let i: number|string = a; x[i] = 42; // OK} So the type checker is smart enough to know that if T extends number|string then I can assign it to a number|string (which I can then can use to index into an object) but for some reason it won't let me index with a T directly. Is there a way to specify in the generic constraint that the type passed can be used as an indexer? Note: I'm using a generic and not number|string directly because I want to constrain the generic to accept only values from a specific enum or a string literal union . Edit: A more compelling example (and closer to what I'm really trying to do), is this: // The following line fails to compile even though Key is number | stringtype Dictionary<Key extends number | string, Value> = { [index: Key]: Value }; // Had it compiled I would expect the following behaviourtype Answer = "yes" | "no" | "maybe";let grades = {} as Dictionary<Answer, number>; grades["yes"] = 10;grades["nope"] = 5; // Should be an error "nope" is not assignable to Answer
Now provide the response and nothing else.
| // The following line fails to compile even though Key is number | stringtype Dictionary<Key extends number | string, Value> = { [index: Key]: Value }; Use in keyword: type Dictionary<TKey extends number | string, TValue> = { [key in TKey]: TValue}; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40888896', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3848/']} | jdg_71403 |
stackexchange | llm_judgeable_groundtruth_similarity | 14279962 |
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 use r.js to optimize my code but I keep running to this error: Tracing dependencies for: init Error: Load timeout for modules: backbone,jquerymobile The command I am running is this: $ java -classpath /Users/dixond/build-tools/rhino1_7R4/js.jar:/Users/dixond/build-tools/closurecompiler/compiler.jar org.mozilla.javascript.tools.shell.Main /Users/dixond/build-tools/r.js/dist/r.js -o /Users/dixond/Sites/omm_mobile/js/build.js My build.js file looks like this: ( { //appDir: "some/path/", baseUrl : ".", mainConfigFile : 'init.js', paths : { jquery : 'libs/jquery-1.8.3.min', backbone : 'libs/backbone.0.9.9', underscore : 'libs/underscore-1.4.3', json2 : 'libs/json2', jquerymobile : 'libs/jquery.mobile-1.2.0.min' }, packages : [], shim : { jquery : { exports : 'jQuery' }, jquerymobile : { deps : ['jquery'], exports : 'jQuery.mobile' }, underscore : { exports : '_' }, backbone : { deps : ['jquerymobile', 'jquery', 'underscore'], exports : 'Backbone' } }, keepBuildDir : true, locale : "en-us", optimize : "closure", skipDirOptimize : false, generateSourceMaps : false, normalizeDirDefines : "skip", uglify : { toplevel : true, ascii_only : true, beautify : true, max_line_length : 1000, defines : { DEBUG : ['name', 'false'] }, no_mangle : true }, uglify2 : {}, closure : { CompilerOptions : {}, CompilationLevel : 'SIMPLE_OPTIMIZATIONS', loggingLevel : 'WARNING' }, cssImportIgnore : null, inlineText : true, useStrict : false, pragmas : { fooExclude : true }, pragmasOnSave : { //Just an example excludeCoffeeScript : true }, has : { 'function-bind' : true, 'string-trim' : false }, hasOnSave : { 'function-bind' : true, 'string-trim' : false }, //namespace: 'foo', skipPragmas : false, skipModuleInsertion : false, optimizeAllPluginResources : false, findNestedDependencies : false, removeCombined : false, name : "init", out : "main-built.js", wrap : { start : "(function() {", end : "}());" }, preserveLicenseComments : true, logLevel : 0, cjsTranslate : true, useSourceUrl : true}) And my init.js looks like this: requirejs.config({ //libraries paths: { jquery: 'libs/jquery-1.8.3.min', backbone: 'libs/backbone.0.9.9', underscore: 'libs/underscore-1.4.3', json2 : 'libs/json2', jquerymobile: 'libs/jquery.mobile-1.2.0.min' }, //shimming enables loading non-AMD modules //define dependencies and an export object shim: { jquerymobile: { deps: ['jquery'], exports: 'jQuery.mobile' }, underscore: { exports: '_' }, backbone: { deps: ['jquerymobile', 'jquery', 'underscore', 'json2'], exports: 'Backbone' } } });requirejs(["backbone",], function(Backbone) { //Execute code here}); What am I doing wrong in this build process?
Now provide the response and nothing else.
| Require.js has a Config option called waitSeconds. This may help. RequireJS waitSeconds Here's an example where waitSeconds is used: requirejs.config({ baseUrl: "scripts", enforceDefine: true, urlArgs: "bust=" + (new Date()).getTime(), waitSeconds: 200, paths: { "jquery": "libs/jquery-1.8.3", "underscore": "libs/underscore", "backbone": "libs/backbone" }, shim: { "underscore": { deps: [], exports: "_" }, "backbone": { deps: ["jquery", "underscore"], exports: "Backbone" }, }});define(["jquery", "underscore", "backbone"], function ($, _, Backbone) { console.log("Test output"); console.log("$: " + typeof $); console.log("_: " + typeof _); console.log("Backbone: " + typeof Backbone); }); | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14279962', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/456850/']} | jdg_71404 |
stackexchange | llm_judgeable_groundtruth_similarity | 15557908 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to get started with libsvm under MATLAB? I've downloaded the library, and extracted it in C:\Program Files\MATLAB\R2012a\toolbox\ ,but then I don't know how to use it in MATLAB.
Now provide the response and nothing else.
| Download and extract libsvm in a directory of your choosing, say C:\libsvm As described in the C:\libsvm\matlab\README file, first you have to make sure a supported C/C++ compiler is installed. Note that on 64-bit systems, you need the correct 64-bit version of the compiler (e.g. Windows SDK is needed for Visual Studio Express edition) >> mex -setup Once you have selected a compiler, you need to compile the MEX-files: >> cd('C:\libsvm\matlab')>> make Finally add the folder with the generated binaries to the MATLAB search path: >> addpath('C:\libsvm\matlab') Test the library with a simple example (fake data): >> labels = double(rand(10,1)>0.5);>> data = rand(10,5);>> model = svmtrain(labels, data, '-s 0 -t 2 -c 1 -g 0.1') Note that the current version of libsvm includes pre-compiled 64-bit MEX-files for Windows. The binaries are located in C:\libsvm\windows\*.mexw64 (copy those to the matlab subfolder from above) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15557908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2157806/']} | jdg_71405 |
stackexchange | llm_judgeable_groundtruth_similarity | 980264 |
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 $G$ be a group and $\phi$ a Homomorphism $$\phi:G\to G'$$ Now I know that the size of the kernel tells you how many elements in $G$ map to the same element in $G'$ I couldn't find this in my book, but I have concluded the following. $$\frac{|G|}{| \:\text{ker} \: \phi \:|} = |G'|$$ Is that true?
Now provide the response and nothing else.
| If $G, G^\prime$ finite and $\phi$ is surjective then this is a straightforward consequence of the First Isomorphism Theorem, which states that $G/\ker\phi\cong G^\prime$. Calculating the index on the left side by Lagrange's Theorem gives you exactly what you have. If $\phi$ is not surjective, however, this would not hold. Instead, you must replace $G^\prime$ with $\phi(G)$, the image of $G$ under $\phi$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/980264', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/175634/']} | jdg_71406 |
stackexchange | llm_judgeable_groundtruth_similarity | 50683248 |
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 large web apps npm install resp. yarn install does take a lot of time, mostly in a step called Linking Dependencies . What is happening here? Is it fetching the dependencies of the dependencies? Or something completely different? Which files are created during this step?
Now provide the response and nothing else.
| When you call yarn install , the following things happen in order: Resolution : Yarn starts resolving dependencies by making requests to the registry and recursively looking up each dependency. Downloading/Fetching : Next, Yarn looks in a global cache directory to see if the package needed has already been downloaded. If it hasn't, Yarn fetches the tarball for the package and places it in the global cache so it can work offline and won't need to download dependencies more than once. Dependencies can also be placed in source control as tarballs for full offline installs. Linking : Finally, Yarn links everything together by copying all the files needed from the global cache into the local node_modules directory after identifying what's already there and what's not there. yarn install does take a lot of time, mostly in a step called Linking Dependencies You should notice that Step 3: Linking is taking more time than Step 1: Resolution and Step 2: Fetching where the actual download happens. During by this step we already have things that we need ready and downloaded, then why is it taking long, did we miss anything? Yes, COPY to local project into node_modules folder...! The reason for this is that this copy is not equivalent to copying one large 4.7GB ISO file. Instead it's multiple super small files (Don't take it light when I say multiple, it can be 15k+ files :P ), hence take a lot of time to copy. (Also, it is important to note that when you download the packages, you download one large tar file per package, whose contents should then be extracted into the cache which also takes time) It is slower due to Anti-virus : Your antivirus is sitting in the middle and doing a quick inspect (in addition to our yarn checking if it already exists) on every single file yarn is trying to copy cutting its speed by so much. If you are on Windows, try adding your project's parent folder as exception to Windows Defender. Storage medium's transfer rate : SSDs can improve this speed hugely (Sorry, SSHDs and FireCudas will not help either, this is gonna be one time). But is this efficient? Can I have it taken from the global node_modules (after creating one)? Nope for both questions. Because of the way node works each package finds its dependencies only relative to its own location. Also because each project may want to use different versions of the same package to ensure its working properly and not broken by package updates. Ideally, the project folder should be lean. An efficient way of doing this would be to have a global node_modules folder. Any and all requested packages are downloaded if not already present AND used from this location. Actually Ruby does it this way. Here's my global Ruby 's equivalent of node_modules folder. Notice the presence of different versions of the same package for use in different projects. But keep in mind that it would reduce project portability. It's a trade-off that any manager (be it rubygems or node modules) has to make. I can just copy the node project folder (which in fact may take hours because you will be copying the (local) node_modules folder as well, but I can expect it to work if I have just that project folder, as opposed to copying a ruby project would only some seconds to few minutes, as there is no local packages (or gems as they call them) folder, but running the project on different system would require those packages to be present on the global gems folder. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/50683248', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/166229/']} | jdg_71407 |
stackexchange | llm_judgeable_groundtruth_similarity | 28166565 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working on a project that has been built with both gcc and msvc so far. We recently started building with clang as well. There are some parts in the code, where platform-specific things are done: #ifndef _WIN32// ignore this in msvc#endif Since gcc has previously been the only non-windows build, this was equivalent to saying "do this only for gcc". But now it means "do this only for gcc and clang". However there are still situations, where I would like to handle something specifically for gcc, and not for clang. Is there a simple and robust way to detect gcc, i.e. #ifdef ???// do this *only* for gcc#endif
Now provide the response and nothing else.
| __GNUC____GNUC_MINOR____GNUC_PATCHLEVEL__ These macros are defined by all GNU compilers that use the C preprocessor: C, C++, Objective-C and Fortran. Their values are the major version, minor version, and patch level of the compiler, as integer constants. For example, GCC 3.2.1 will define __GNUC__ to 3, __GNUC_MINOR__ to 2, and __GNUC_PATCHLEVEL__ to 1. These macros are also defined if you invoke the preprocessor directly. Also: __GNUG__ The GNU C++ compiler defines this. Testing it is equivalent to testing (__GNUC__ && __cplusplus). Source Apparently, clang uses them too. However it also defines: __clang____clang_major____clang_minor____clang_patchlevel__ So you can do: #ifdef __GNUC__ #ifndef __clang__... Or even better (note the order): #if defined(__clang__)....#elif defined(__GNUC__) || defined(__GNUG__)....#elif defined(_MSC_VER).... | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/28166565', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1805388/']} | jdg_71408 |
stackexchange | llm_judgeable_groundtruth_similarity | 334478 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Today I had a dicussion with a colleague. I tend to believe that a value in a property should be a meaningful part of the state of an object at any given time. This automatically almost always makes the constructor fully responsible for the initial assignment of all the properties in a class. Other methods may subsequently change the state to another valid state, but it is usually not their task to initialize values on class properties. My colleague believes that class properties may also be useful to increase readability by decreasing the parameter count of internal private functions. Class properties are then used as temporary variables, potentially used by multiple private functions. My way (php code example - I left out the private method declarations): class Example { private $valueFromConstructor; public function __construct($valueFromConstructor) { $this->valueFromConstructor = $valueFromConstructor; } public function doSomething() { $value1 = $this->computeValue1(); $value2 = $this->computeValue2(); $value3 = $this->computeValue3WithValue1AndValue2($value1, $value2); $value4 = $this->computeValue4WithValue1AndValue3($value1, $value3); return $this->doSomethingWithValue4($value4); }} Colleague's way class Example { private $valueFromConstructor; private $value1; private $value2; private $value3; private $value4; public function __construct($valueFromConstructor) { $this->valueFromConstructor = $valueFromConstructor; } public function doSomething() { $this->computeValue1(); $this->computeValue2(); $this->computeValue3WithValue1AndValue2(); $this->computeValue4WithValue1AndValue3(); $this->doSomethingWithValue4(); return $this->value4; }} To me, there is a pretty clear distinction as to when one should assign a value to a class property and when values should be parameterized. I do not see them as immediate alternatives to each other. It is confusing to me to see variables that live longer than the execution of the method to which they belong. The necessity for these variables to exist as class properties when they are used in private methods seems to create a temporal coupling. Do any guidelines exist on this matter? Or is it a matter of style? And does it matter if the object does not live very long and has only few public methods? To clarify: as seen from the outside, the class works correctly.
Now provide the response and nothing else.
| Nope. Your way is better. Here's why: the variables are properly confined to only the scope in which they are used. While your colleague's way will work perfectly fine, it will add cognitive dissonance (even if it's only a small amount) to the programmer coming after him, who will read the code and have to figure out why there are what amounts to "global variables" within the class. Are they used anywhere else? What will happen if I change one of them? And so forth. | {} | {'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/334478', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/233992/']} | jdg_71409 |
stackexchange | llm_judgeable_groundtruth_similarity | 928 |
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm writing a major mode for a programming language, but I want to support older Emacs versions. prog-mode is relatively new. I want to inherit from prog-mode if it's defined, but still do something sensible otherwise. What's the best approach? Should I defalias prog-mode on older Emacsen, or will that interfere with other modes if they do the same thing?
Now provide the response and nothing else.
| At the cost of an extra top-level symbol binding, there's a very neat solution which avoids repeating the define-derived-mode form: (defalias 'my-fancy-parent-mode (if (fboundp 'prog-mode) 'prog-mode 'fundamental-mode))(define-derived-mode my-fancy-mode my-fancy-parent-mode ...) Works fine in any Emacs >= 23. I came up with this for haml-mode a couple of years ago IIRC, and it seems to have spread from there to several other major modes. The main thing the define-derived-mode macro does with the parent mode symbol is generate code which calls its function: in this sense, defalias makes the new variable exactly equivalent to the aliased function. One caveat is that this can confuse derived-mode-p , so code which checks to see if your mode is derived from prog-mode might not work correctly. In practice I haven't encountered any problems: it's more usual for such code to hook into prog-mode-hook , which still gets run. (As Jorgen points out in the comments, define-derived-mode also uses the mode-class property from the parent mode symbol, and defalias will not copy it. At the time of writing, this property only seems to be used for special-mode .) Update: these days I'd simply suggest requiring at least Emacs 24, since older versions are long obsolete. | {} | {'log_upvote_score': 5, 'links': ['https://emacs.stackexchange.com/questions/928', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/304/']} | jdg_71410 |
stackexchange | llm_judgeable_groundtruth_similarity | 57827 |
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:
Zsh in Emacs edit mode comes with the default key binding ALT + Backspace to delete a word on the right side of the cursor and ALT + D to delete a word on the left side. I would like to add the latter function to ALT + DEL additionally. I tried to use the terminfo database to set the escape sequence for the key combination for every $TERM correctly. In man terminfo I read about kDC3 being the Capname which I probably need to use for ALT + DEL . I added the following line to my ~/.zshrc : bindkey -e `tput kDC3` kill-word This works nicely when I connect to my machine directly through SSH ( $TERM is xterm ). But when I start Zsh inside a Tmux-session ( $TERM is screen ) I get the following error message: tput: unknown terminfo capability 'kDC3' Could that really mean that it's impossible to bind anything to ALT + DEL in Tmux? Or am I just doing something wrong? Maybe kDC3 is not the correct sequence? I'm running Debian Wheezy Beta 4 x86_64.
Now provide the response and nothing else.
| The first problem is that your terminfo entry for screen does not define a kDC3 capability; this is probably typical. You can either add this capability to your own custom screen entry, or you can “hard code” the sequences in your bindkey commands. Adding the capabilities may help other programs know about the keys, but it decentralizes your configuration (it would be easy to forget about this customization when you manually replicate your configuration to a new machine or user account). You can extract the appropriate entries with infocmp and build a new entry with tic : { infocmp -xT screen ; infocmp -x1T xterm | grep -E '^\tkDC[3-8]?=' ; } >/tmp/stic -x /tmp/s If you run tic as a user that has write access to your terminfo directory (e.g. /usr/share/terminfo ), then the new entry will be placed there (probably overwriting the original entry); otherwise, it will be placed under ~/.terminfo (or TERMINFO, if you have that environment variable set). For completeness, you may want to use (UP|DN|RIT|LFT|PRV|NXT|HOM|END|IC|DC) instead of DC in the grep pattern to capture the modified versions of Up, Down, Right, Left, PageUp, PageDown, Home, End, Insert, and Delete. If you dislike the configuration decentralization caused by customizing your terminfo entry, then you can “hard code” the value instead. To make it a bit better, you can check for kDC3 first: bindkey -e ${$(tput kDC3 2>/dev/null):-'\e[3;3~'} kill-word To restrict this “hard coding” to just screen -based TERM values: altdel=$(tput kDC3 2>/dev/null)[[ -z $altdel && $TERM == screen(|-*) ]] && altdel='\e[3;3~'[[ -n $altdel ]] && bindkey -e $altdel kill-wordunset altdel This will work as long as your terminal emulator (stack) ends up generating the xterm -style sequence for the modified key. Once to have a binding, you will still need to turn on the xterm-keys option in tmux so that it will generate the xterm -style sequences for keys passed into its panes. E.g. in your ~/.tmux.conf : set-option -wg xterm-keys on | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/57827', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/26814/']} | jdg_71411 |
stackexchange | llm_judgeable_groundtruth_similarity | 65266948 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Disclaimer: I admit this is more of a broad-ish best practice question, rather then a specific programming issue, however, I believe the SO bunch is the best audience for it. I am aware of this similar question ( Should I be using Express.js in a Serverless app? ), but the answers don't seem to answer mine. I want to move an Express.js from AWS Lightsail/EC2 to serverless for typical reasons, and Lambda is my weapon of choice. However, a whole framework together with an app on top of it may be a bit hefty to be still considered a function and so possibly unsuitable to be run as such on AWS Lambda, or Google/Azure Functions. While I'm convinced it is doable , is it a good idea? Wouldn't this setup kill efficiency and complicate handling things such as sessions states, ultimately defeat the purpose of serverless functions?
Now provide the response and nothing else.
| The answer to your question depends upon your current and future needs. I think you should always plan ahead and make sure that the current infrastructure that you will implement can be upgradable for future needs. You should ask yourself those questions: In the future do I want to have some websocket connection? Do I need any proxy in my request routing? How big will become my application over time? Which AWS Service will I expect to use in the future Scalability Using Express.js in a lambda is not a good idea for many reasons: You will pay more for the execution of your Lambda because it will take more time to run and maybe more memory Latency is higher Doing a small modification means redeploying all your application code on 1 lambda so only 1 point of failure. Normally overtime your application's code base will grow as you add more features. The maintenance of that monolithic repo will be a pain in the ass and you will deploy less than you want because of the bugs you might encounter. Cost effectiveness Express.js on Lambda is more expensive because you need to proxy any method into your lambda using a API Gateway REST API rather then using API Gateway HTTP API HTTP APIs are up to 71% cheaper compared to REST APIs Latency Lambda isn't magically executing your code without server even tho they market it like it is. When an event occur, AWS will launch a docker container, wait for it to fully load all your dependencies and then run your handler. With a normal Node.js server on AWS EC2 or AWS ECS it's a one time cost because your server is always running and all your dependencies are already loaded but not on your lambda. As AWS says: This approach [Express.js and proxy all requests to your lambda] is generally unnecessary, and it’s often better to take advantage of the native routing functionality available in API Gateway. In many cases, there is no need for the web framework in the Lambda function, which increases the size of the deployment package. API Gateway is also capable of validating parameters, reducing the need for checking parameters with custom code. It can also provide protection against unauthorized access, and a range of other features more suited to be handled at the service level. Best practices for organizing larger serverless applications How to convert Express framework into plan Lambda To simplify your life, I would suggest you to use SAM CLI. It's very simple to get started with it. Install SAM CLI If you're following the MVC pattern for your Express app. You only need to take your service files where your core logic live. The folder structure I like to use for the lambda is the following Suppose it's a small calendar app ──src-ts ├───handlers │ getEvent.ts │ ├───tests │ │ getEvent.tests.ts │ │ │ └───utils │ utils.ts │ └───utils utils.ts validation.ts It's important that your handler returns 3 thing Headers (JSON) statusCode (number) Body (stringified) You also need a template.yml file to describe the infrastructure that your lambda need AWSTemplateFormatVersion: 2010-09-09Description: Describe the lambda goalTransform: - AWS::Serverless-2016-10-31Resources: # API Gateway LambdaAPI: Type: AWS::Serverless::Api Properties: StageName: StageName Cors: AllowMethods: "'POST, GET, OPTIONS'" AllowHeaders: "'*'" AllowOrigin: "'*'" # IAM Role LambdaRole: Type: AWS::IAM::Role Properties: AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Action: - 'sts:AssumeRole' Effect: Allow Principal: Service: - lambda.amazonaws.com ManagedPolicyArns: - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole - arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess - arn:aws:iam::aws:policy/AmazonAPIGatewayInvokeFullAccess GetEvent: Type: AWS::Serverless::Function Properties: Runtime: nodejs12.x Timeout: 180 FunctionName: youLambdaName Handler: src/handlers/getEvent.handler Role: !GetAtt LambdaRole.Arn Events: Get: Type: Api Properties: RestApiId: !Ref LambdaAPI Path: /events/{eventid} Method: GET Note I used typescript and but when compiled it's creating an src folder Some resource to help you more in depth: https://aws.amazon.com/blogs/compute/going-serverless-migrating-an-express-application-to-amazon-api-gateway-and-aws-lambda/ https://dev.to/brightdevs/how-to-convert-an-express-app-to-aws-lambda--44gc https://medium.com/hackernoon/how-to-deploy-a-node-js-application-to-aws-lambda-using-serverless-ae7e7ebe0996 https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html To Conclude The upside of using lambdas without Express are: better scalability cost optimization lower latency higher availability because you have multiple lambda for each business logic instead of one that run it all The downside of using lambdas without Express are: You need to modify your existing code Init time of your lambda needs to be part of your thinking when developing your logic You need to learn SAM yaml template and read the AWS doc when you wanna add more functionality to your API infrastructure. Take advantage of the AWS infrastructure, don't try to go against it. All AWS Services are working together in a seamless and low latency way. You should remove Express from your infrastructure if you wanna go "Serverless". | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/65266948', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6280857/']} | jdg_71412 |
stackexchange | llm_judgeable_groundtruth_similarity | 3037052 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following problem: If today is a sunny day, a probability that it will rain tomorrow is $0.2$ . If today is a rainy day, a probability that it will be sunny tomorrow is $0.4$ . I need to find the probability that if it's rainy on the third of May, it will also rain on the third of June. My initial idea was to write a program that will create the binary tree with all possible combinations and then I just traverse through all of them and sum the probabilities accordingly, but unfortunately, I have to do this by hand, so any help is very welcome.
Now provide the response and nothing else.
| A binary tree is definitely a possible way to solve this problem. Another way to think about it though is maybe in the language or linear algebra. We can represent day as the vector: $\begin{pmatrix} s \\ r\end{pmatrix}$ where $s$ is the probability of sun on that day and $r$ represents the chance of rain, and then the matrix: $$\begin{pmatrix} 0.8 & 0.4 \\ 0.2 & 0.6 \end{pmatrix}$$ would represent the transition function from one day to another. So if we have rain on the 3rd of May, the probability vector for the 4th of May will be $\begin{pmatrix} 0.8 & 0.4 \\ 0.2 & 0.6 \end{pmatrix} \begin{pmatrix} 0 \\ 1\end{pmatrix}$ . More generally, $$\begin{pmatrix} 0.8 & 0.4 \\ 0.2 & 0.6 \end{pmatrix}^n \begin{pmatrix} 0 \\ 1\end{pmatrix}$$ the probability vector for the nth day after the 3rd of May. For your problem, I think $n = 31$ . edit I notice now that SmileyCraft makes a good point to diagonize this transition matrix and this makes the power easier to work with. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3037052', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/595949/']} | jdg_71413 |
stackexchange | llm_judgeable_groundtruth_similarity | 7552677 |
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 function that returns same kind of objects (query results) but with no properties or methods in common. In order to have a common type I resorted using an empty interface as a return type and "implemented" that on both. That doesn't sound right of course. I can only console myself by clinging to hope that someday those classes will have something in common and I will move that common logic to my empty interface. Yet I'm not satisfied and thinking about whether I should have two different methods and conditionally call next. Would that be a better approach? I've been also told that .NET Framework uses empty interfaces for tagging purposes. My question is: is an empty interface a strong sign of a design problem or is it widely used? EDIT : For those interested, I later found out that discriminated unions in functional languages are the perfect solution for what I was trying to achieve. C# doesn't seem friendly to that concept yet. EDIT : I wrote a longer piece about this issue, explaining the issue and the solution in detail.
Now provide the response and nothing else.
| Although it seems there exists a design pattern (a lot have mentioned "marker interface" now) for that use case, i believe that the usage of such a practice is an indication of a code smell (most of the time at least). As @V4Vendetta posted, there is a static analysis rule that targets this: http://msdn.microsoft.com/en-us/library/ms182128(v=VS.100).aspx If your design includes empty interfaces that types are expected to implement, you are probably using an interface as a marker or a way to identify a group of types. If this identification will occur at run time, the correct way to accomplish this is to use a custom attribute. Use the presence or absence of the attribute, or the properties of the attribute, to identify the target types. If the identification must occur at compile time, then it is acceptable to use an empty interface. This is the quoted MSDN recommendation: Remove the interface or add members to it. If the empty interface is being used to label a set of types, replace the interface with a custom attribute. This also reflects the Critique section of the already posted wikipedia link. A major problem with marker interfaces is that an interface defines a contract for implementing classes, and that contract is inherited by all subclasses. This means that you cannot "unimplement" a marker. In the example given, if you create a subclass that you do not want to serialize (perhaps because it depends on transient state), you must resort to explicitly throwing NotSerializableException (per ObjectOutputStream docs). | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7552677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/54937/']} | jdg_71414 |
stackexchange | llm_judgeable_groundtruth_similarity | 951547 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm running Apache 2.2. I have 10 apache processes running, and it's taxing my limited resources. I have searched for the config option that controls how many processes are spawned, but I could use some help. Is it MaxRequestWorkers ? Is it ThreadsPerChild ? Something else? (Neither appears to be set in my config files.) Here's an example of one of my apache processes: F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD5 S 33 26099 25513 0 80 0 - 56951 poll_s ? 1:42 /usr/sbin/apache2 -k start Edit: I'm sorry. I am running apache 2.2, not 2.4. list of mods-enabled: lrwxrwxrwx 1 root root 28 Sep 5 2014 alias.conf -> ../mods-available/alias.conflrwxrwxrwx 1 root root 28 Sep 5 2014 alias.load -> ../mods-available/alias.loadlrwxrwxrwx 1 root root 33 Sep 5 2014 auth_basic.load -> ../mods-available/auth_basic.loadlrwxrwxrwx 1 root root 33 Sep 5 2014 authn_file.load -> ../mods-available/authn_file.loadlrwxrwxrwx 1 root root 36 Sep 5 2014 authz_default.load -> ../mods-available/authz_default.loadlrwxrwxrwx 1 root root 38 Sep 5 2014 authz_groupfile.load -> ../mods-available/authz_groupfile.loadlrwxrwxrwx 1 root root 33 Sep 5 2014 authz_host.load -> ../mods-available/authz_host.loadlrwxrwxrwx 1 root root 33 Sep 5 2014 authz_user.load -> ../mods-available/authz_user.loadlrwxrwxrwx 1 root root 32 Sep 5 2014 autoindex.conf -> ../mods-available/autoindex.conflrwxrwxrwx 1 root root 32 Sep 5 2014 autoindex.load -> ../mods-available/autoindex.loadlrwxrwxrwx 1 root root 26 Sep 5 2014 cgi.load -> ../mods-available/cgi.loadlrwxrwxrwx 1 root root 30 Sep 5 2014 deflate.conf -> ../mods-available/deflate.conflrwxrwxrwx 1 root root 30 Sep 5 2014 deflate.load -> ../mods-available/deflate.loadlrwxrwxrwx 1 root root 26 Sep 5 2014 dir.conf -> ../mods-available/dir.conflrwxrwxrwx 1 root root 26 Sep 5 2014 dir.load -> ../mods-available/dir.loadlrwxrwxrwx 1 root root 26 Sep 5 2014 env.load -> ../mods-available/env.loadlrwxrwxrwx 1 root root 27 Sep 5 2014 mime.conf -> ../mods-available/mime.conflrwxrwxrwx 1 root root 27 Sep 5 2014 mime.load -> ../mods-available/mime.loadlrwxrwxrwx 1 root root 34 Sep 5 2014 negotiation.conf -> ../mods-available/negotiation.conflrwxrwxrwx 1 root root 34 Sep 5 2014 negotiation.load -> ../mods-available/negotiation.loadlrwxrwxrwx 1 root root 32 Sep 12 2014 passenger.conf -> ../mods-available/passenger.conflrwxrwxrwx 1 root root 32 Sep 12 2014 passenger.load -> ../mods-available/passenger.loadlrwxrwxrwx 1 root root 27 Sep 5 2014 php5.conf -> ../mods-available/php5.conflrwxrwxrwx 1 root root 27 Sep 5 2014 php5.load -> ../mods-available/php5.loadlrwxrwxrwx 1 root root 33 Sep 5 2014 reqtimeout.conf -> ../mods-available/reqtimeout.conflrwxrwxrwx 1 root root 33 Sep 5 2014 reqtimeout.load -> ../mods-available/reqtimeout.loadlrwxrwxrwx 1 root root 40 Sep 14 2014 rewrite.load -> /etc/apache2/mods-available/rewrite.loadlrwxrwxrwx 1 root root 31 Sep 5 2014 setenvif.conf -> ../mods-available/setenvif.conflrwxrwxrwx 1 root root 31 Sep 5 2014 setenvif.load -> ../mods-available/setenvif.loadlrwxrwxrwx 1 root root 36 Jun 7 2015 ssl.conf -> /etc/apache2/mods-available/ssl.conflrwxrwxrwx 1 root root 36 Jun 7 2015 ssl.load -> /etc/apache2/mods-available/ssl.loadlrwxrwxrwx 1 root root 29 Sep 5 2014 status.conf -> ../mods-available/status.conflrwxrwxrwx 1 root root 29 Sep 5 2014 status.load -> ../mods-available/status.load
Now provide the response and nothing else.
| It depends which mpm module (mpm_worker/mpm_prefork/mpm_event) your apache is using. If you are unsure, then post the output of cat /etc/apache2/mods-enabled/mpm*.conf which reveals the number of StartServers/MinSpareServers/MaxSpareServers , MaxRequestWorkers and maybe ThreadsPerChild and ThreadLimit . If the filenames should be different in your linux distro, then post an output of your enabled modules ls -l /etc/apache2/mods-enabled . It should look like something like this and explains itself (Debian, Apache2.4): root@debian:/# cat /etc/apache2/mods-enabled/mpm*.conf# prefork MPM# StartServers: number of server processes to start# MinSpareServers: minimum number of server processes which are kept spare# MaxSpareServers: maximum number of server processes which are kept spare# MaxRequestWorkers: maximum number of server processes allowed to start# MaxConnectionsPerChild: maximum number of requests a server process serves<IfModule mpm_prefork_module> StartServers 5 MinSpareServers 5 MaxSpareServers 10 # same as MaxClients in Apache 2.2 MaxRequestWorkers 150 MaxConnectionsPerChild 0</IfModule># vim: syntax=apache ts=4 sw=4 sts=4 sr noet See Reducing Apache Memory usage and Average Process Size Value The documentation says (as described in the link above): You can, and should, control the MaxClients setting so that your server does not spawn so many children that it starts swapping. The procedure for doing this is simple: determine the size of your average Apache process, by looking at your process list via a tool such as top, and divide this into your total available memory, leaving some room for other processes. https://httpd.apache.org/docs/2.2/misc/perf-tuning.html Example: Tasks: 207 total, 1 running, 206 sleeping, 0 stopped, 0 zombie%Cpu(s): 2.4 us, 0.8 sy, 0.0 ni, 96.7 id, 0.0 wa, 0.0 hi, 0.0 si, 0.0 stKiB Mem : 16307588 total, 14360744 free, 1188636 used, 758208 buff/cacheKiB Swap: 0 total, 0 free, 0 used. 14686936 avail Mem PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 6567 www-data 20 0 296028 15288 5616 S 0.0 0.1 0:00.07 apache2 6569 www-data 20 0 296040 15360 5676 S 0.0 0.1 0:00.08 apache2 6571 www-data 20 0 295996 15200 5676 S 0.0 0.1 0:00.07 apache2 6572 www-data 20 0 296028 15348 5676 S 0.0 0.1 0:00.08 apache2 6573 www-data 20 0 296040 15356 5676 S 0.0 0.1 0:00.07 apache2 Running the cool script from the linked page above gives me: root@debian:~# ps -ylC apache2 | awk '{x += $8;y += 1} END {print "Apache Memory Usage (MB): "x/1024; print "Average Process Size (MB): "x/((y-1)*1024)}'Apache Memory Usage (MB): 100.711Average Process Size (MB): 16.7852 Note: "Average Process Size" is the "RES" value when you run top . To determine MaxClients (aka MaxRequestWorkers ), I need to calculate: Maxclients=X/Y where X=Max. Available Memory Reserved for Apache Y=Average Process Size | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/951547', 'https://serverfault.com', 'https://serverfault.com/users/149693/']} | jdg_71415 |
stackexchange | llm_judgeable_groundtruth_similarity | 1257555 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The Mandelbrot set is defined as follows: given the function f(z, c) = z 2 + c, a number z in the complex plane is in the Mandelbrot set if and only if the sequence defined by z 0 = z, z n+1 = f(z n , z 0 ) is bounded. There are numerous programs that draw images computed from such definitions, including my own "HTML 5 Fractal Playground", written by me. My software runs in a web browser, and I will provide deep-links in my question to see the software draw various fractals that I refer to. However, I do not guarantee that these links will work forever. The Mandelbrot set can be graphed by clicking this link: http://danielsadventure.info/html5fractal/index.html#0,-2,2,-2,2,2,341,true,z%5E2%20%2B%20c,-2,2,-2,2 . My software, as well as every other fractal-graphing program that I know of, takes advantage of a particular fact about the generating equation: once the absolute value of any value in the sequence is known to have absolute value greater than 2, we immediately know that the sequence is unbounded (We say that the sequence "escapes"). If we compute many values in the sequence and don't see this happen, we assume that the number is in the Mandelbrot set. We call 2 the "bailout number". We know that the above rule works because once the absolute value of the sequence exceeds 2, the exponential part of the equation dominates. The Mandelbrot set is generalized into any set that can be generated by an equation such as the function f given above. One of the best-known generalizations are the "Multibrot" sets. We simply replace the exponent 2 in f with some other number. When the exponent is increased above 2, the same rule above about the absolute value of the sequence can still be used to generate graphs. I refer to these Multibrot sets as M(n), where n is the exponent used in place of two, so for instance, M(2) is the original Mandelbrot set. Here are a few more clickable graph links: M(3) , M(8) I wanted to compute negative Multibrot sets such as M(-2). Here, my above method does not work. Now, using the equation f(z, c) = z -2 + c, we cannot use the above method because if the value of the sequence becomes very large and c is small, the next value in the sequence will be small, then the next value large, and the sequence "bounces" back and forth between small and large. A little bit of analysis reveals that any number z with absolute value greater than 2 is actually inside M(-2). That's because the addition part of the equation overtakes the negative exponentiation, preventing the value from escaping. That means that even the number 1,000,000 is in M(-2); the sequence simply "bounces" back and forth between very small and very large numbers. The problem I have is that I frequently see images using the "bailout" method used to represent these sets and I know they are wrong. Heck, my own software will draw such a figure, and I know it's wrong, yet my graph , known to be incorrect, looks similar to others that Google will find . That was a long wall, but I wanted to show my own research before posing the question: given that I can't compute them the same way that I compute ordinary positive Multibrot sets, how can I compute negative Multibrot sets? Edit in response to the answers and comments below. The answers below indicate that I can draw a negative Multibrot fractal by using a completely different algorithm. Rather than checking that the iterating function generates a sequence that "escapes", I can check that the sequence is periodic. Interestingly, this provides variable values for coloring points inside the set, rather than outside the set, as the escape time algorithm does. I have modified my program to use this algorithm and generated the following image for f(z,c) = z -2 + c: The above image colors the set based on how many iterations were computed to detect periodicity. However, it was also pointed out that a different plot may be drawn by using the detected period.
Now provide the response and nothing else.
| As you say, if your objective is to study the dynamical behavior of functions of the form $f_c(z)=z^p+c$ for negative values of $p$, then there is really no reason to expect an "escape radius" to exist at all. To understand why, and to try to figure out what we should do, let's look at the specific case of $p=-2$; that is, we'll try to understand the parameter plane for the family $f_c(z)=z^{-2}+c$. To do so, perhaps we should step back a bit first to make sure we understand why we care about the escape radius for the Mandelbrot set. The Mandelbrot set (and other bifurcation locuses ) arises in the context of complex dynamics. That is, we study the iteration of a function $f$ mapping the complex plane $\mathbb C$ to itself. The theory of this type of iteration is well developed for rational functions . Note that our function $z^{-2}+c$ is a rational function but not a polynomial, like $z^2+c$. This complicates things a bit. Regardless of whether we are dealing with just polynomials or more general rational functions, the critical orbits dominate the global dynamics. A critical orbit is just the orbit of a root of the derivative of the function. For $f_c(z)=z^2+c$, we have $f_c'(z)=2z$ so the only (finite) critical point is $z=0$ no matter what $c$ is. That's why we care so much about the orbit of zero in that context. Now, given a rational function, if all the critical orbits are attracted to some attractive fixed point, then it can be shown that the Julia set of the function is totally disconnected. For a polynomial, the point at infinity is always a super-attractive fixed point and if all the critical orbits escape to infinity, then the Julia set will be totally disconnected. That's why we care about the escape radius in the context of $z^2+c$; that single question (does the critical orbit escape or not) tells us whether the Julia set is totally disconnected or connected. Now, for rational functions, things are a little trickier. We've really got to move from the complex plane to the Riemann sphere and deal properly with the point at infinity. There's no longer any reason to suppose that the point at infinity is fixed. Indeed, for our function $f_c(z)=z^{-2}+c$, we have $f_c(\infty)=c$; the point at infinity isn't even a fixed point, let alone an attractive fixed point so we don't care at all if zero converges to infinity under iteration. For that matter, zero isn't a critical point so we don't even care about the orbit of zero at all. So what do we do? Well, $f_c'(z)=-2/z^3$ so it looks like there are no critical points. In fact, though, it turns out that $\infty$ is a critical point. To understand this, we must conjugate $f_c$ by the function $\varphi(z)=1/z$ to obtain a function $F_c(z)=1/f_c(1/z)$ whose behavior at zero indicates the behavior of $f_c$ at $\infty$:$$F_c(z) = \frac{1}{(1/z)^{-2}+c} = \frac{1}{z^2+c}.$$Note that $F_c(0)=c$, as expected. More importantly, $$F_c'(z) = -\frac{2 z}{\left(c+z^2\right)^2}$$so that $F_c'(0)=0$. This is why $\infty$ is a critical point for $f_c$. A similar analysis shows that the point at infinity is a critical point for $z^p+c$ for all integers less than $-1$. Furthermore, the techniques sketched below for computing the bifurcation locus of $z^{-2}+c$ should work fine for those other negative values of $p$. Taking all this into consideration, here's how your algorithm should proceed. For a fixed value of $c$, follow the orbit of $\infty$. Equivalently, since $f_c(\infty)=c$, follow the orbit of $c$. Iterate until you detect periodic behavior. You've just got to code it; there is no simple test for this other than saving a lot of terms and comparing your current iterate to previous terms. You might also need to deal gracefully with the possibility of landing on zero. If you do, then that means that $\infty$ has eventually mapped back to itself which implies that it lies on a super-attractive orbit. In any event, if you do detect periodic behavior, then shade $c$ according to how long it took. If you don't, then shade $c$ some default color. Implementing this, I came up with the following image: The colored regions corresponds to points where some periodic behavior was detected and regions of a common color should have the same period. The shading indicates how long it took to detect the period. The black region indicates that no periodicity was detected. I iterated 2000 times and searched for orbits up to length 100. The numbers indicate the length of the detected orbits. If we start in the exterior portion labeled 1, we are guaranteed to find an attractive fixed point and the corresponding Julia set will be totally disconnected. If we start in the circle labeled 2, we are guaranteed to find an attractive orbit of length two and the Julia set will be a topologically a circle. If we start in the regions labeled 3 or 4, we will find orbits of those length. The Julia sets will be more complicated but if we stay in any connected domain, the Julia set will stay topologically the same. Here are representative Julia sets, labeled by $c$, for those four regions (corresponding to the positions of the text labels, in fact): I've implemented all the above in Javascript and placed it here: https://www.marksmath.org/visualization/negabrot/ . To emphasize the difficulties inherent in this family, let's examine some dynamical behavior in that occurs in this family that cannot happen in the quadratic family, $z^2+c$. First, suppose that $c=-2^{1/3}$. Then, direct computation shows that under iteration of $f_{-2^{1/3}}(z)=z^{-2}-2^{1/3}$, we have$$-2^{1/3} \to -1/2^{2/3} \to 2^{1/3} \to -1/2^{2/3} \to \cdots$$Not that the orbit is not periodic (the first point never repeats) but it has landed on a periodic orbit. Such an orbit is called pre-periodic . Furthermore, Theorem 4.3.1 in Beardon's Iteration of Rational Functions states that, if every critical point of a rational function is pre-periodic, then the Julia set of the function is the entire Riemann sphere. Thus, the Julia set of this function is everything ! Finally, let's consider the $c$ value $c=-1/2^{2/3}$, which lies on the left boundary of the period two disk in the figure of the parameter space above. For this value of $c$, the points $2^{1/3} + 2^{5/6}$ and $2^{1/3} - 2^{5/6}$ form a neutral period two orbit. Since there is only one critical point which must be lie in the immediate basin of any attractive or neutral orbit, the existence of a neutral orbit precludes the existence of an attractive orbit. Thus, this function has no attractive behavior at all, which makes drawing it's Julia set something of a challenge. I used the techniques outlined in the paper described in this answer . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1257555', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/21684/']} | jdg_71416 |
stackexchange | llm_judgeable_groundtruth_similarity | 36479158 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is not what I want from enumerate: >>> seasons = ['Spring', 'summer', 'fall', 'winter']>>> list(enumerate(seasons, start =2))[(2, 'Spring'), (3, 'summer'), (4, 'fall'), (5, 'winter')] This IS the functionality I want from enumerate: >>> list(enumerate(seasons, start =2))[(2, 'fall'), (3, 'winter')] See the difference? The first one just says, "fine I'll call your 0th element 2 if you really want me to" The second one says, "I understand that you just want to begin the loop at the second index, much like range(2, len(seasons)) would do" Is there no way to do this simply with enumerate?
Now provide the response and nothing else.
| Why not just slice the first two elements? print(list(enumerate(seasons[2:], start=2))) Output: [(2, 'fall'), (3, 'winter')] To understand what is going on with enumerate and the start. Try iterating over it to see what it outputs: for i, v in enumerate(seasons, start=2): print(i, v) As you can see your i , which simply increments along iterating through your seasons list is what starts at 2. But each value in the list is actually from the start of your list. This just further proves that start does not have anything to do with the actual starting point of your list iteration. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36479158', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_71417 |
stackexchange | llm_judgeable_groundtruth_similarity | 1533645 |
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 fragment $\{\vee,\land,\Rightarrow\}$ (no $\neg$) of intuitionistic propositional logic equivalent to the corresponding fragment of classical propositional logic, i.e. a formula is intuitionistic provable iff it is classically valid? If yes, where can I find such a proof?
Now provide the response and nothing else.
| Classical and intuitionistic propositional logic do not prove the same formulas, even in the purely implicational fragment. Most famously, Peirce's Law $((P\to Q)\to P)\to P$ is a classical tautology, but is not intuitionistically valid. (That is, classical logic proves it, but intuitionistic logic doesn't). The two logics are equivalent for the $\{\land,\lor\}$ fragment, though. In terms of which formulas are theorem of the pure calculus, this is not very interesting (because no formula in the $\{\land,\lor\}$ fragment are theorems), but it also holds if you consider non-empty theories: Classical and intuitionistic entailment coincide for this fragment. See this question which shows that the only change to the classical sequent calculus LK that is necessary to get intuitionistic logic instead is to the ${\to}R$ rule. However a cut-free proof in the sequent calculus never uses rules for connectives that don't appear in the conclusion, so the valid (cut-free) proofs in the classical LK for conclusions in the $\{\land,\lor\}$ fragment are the same as the valid proofs in the intuitionistic variant. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1533645', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/72335/']} | jdg_71418 |
stackexchange | llm_judgeable_groundtruth_similarity | 22363268 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I've got this Go http handler that stores some POST content into the datastore and retrieves some other info in response. On the back-end I use: func handleMessageQueue(w http.ResponseWriter, r *http.Request) { w.Header().Set("Access-Control-Allow-Origin", "*") if r.Method == "POST" { c := appengine.NewContext(r) body, _ := ioutil.ReadAll(r.Body) auth := string(body[:]) r.Body.Close() q := datastore.NewQuery("Message").Order("-Date") var msg []Message key, err := q.GetAll(c, &msg) if err != nil { c.Errorf("fetching msg: %v", err) return } w.Header().Set("Content-Type", "application/json") jsonMsg, err := json.Marshal(msg) msgstr := string(jsonMsg) fmt.Fprint(w, msgstr) return }} In my firefox OS app I use: var message = "content";request = new XMLHttpRequest();request.open('POST', 'http://localhost:8080/msgs', true);request.onload = function () { if (request.status >= 200 && request.status < 400) { // Success! data = JSON.parse(request.responseText); console.log(data); } else { // We reached our target server, but it returned an error console.log("server error"); }};request.onerror = function () { // There was a connection error of some sort console.log("connection error");};request.send(message); The incoming part all works along and such. However, my response is getting blocked. Giving me the following message: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/msgs. This can be fixed by moving the resource to the same domain or enabling CORS. I tried a lot of other things but there is no way I can just get a response from the server. However when I change my Go POST method into GET and access the page through the browser I get the data that I want so bad. I can't really decide which side goes wrong and why: it might be that Go shouldn't block these kinds of requests, but it also might be that my javascript is illegal.
Now provide the response and nothing else.
| @Egidius, when creating an XMLHttpRequest, you should use var xhr = new XMLHttpRequest({mozSystem: true}); What is mozSystem? mozSystem Boolean: Setting this flag to true allows making cross-site connections without requiring the server to opt-in using CORS. Requires setting mozAnon: true, i.e. this can't be combined with sending cookies or other user credentials. This only works in privileged (reviewed) apps; it does not work on arbitrary webpages loaded in Firefox. Changes to your Manifest On your manifest, do not forget to include this line on your permissions: "permissions": { "systemXHR" : {},} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22363268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1632676/']} | jdg_71419 |
stackexchange | llm_judgeable_groundtruth_similarity | 35831496 |
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 read in a CSV file into a pandas dataframe and select a column, but keep getting a key error. The file reads in successfully and I can view the dataframe in an iPython notebook, but when I want to select a column any other than the first one, it throws a key error. I am using this code: import pandas as pdtransactions = pd.read_csv('transactions.csv',low_memory=False, delimiter=',', header=0, encoding='ascii')transactions['quarter'] This is the file I'm working on: https://www.dropbox.com/s/81iwm4f2hsohsq3/transactions.csv?dl=0 Thank you!
Now provide the response and nothing else.
| use sep='\s*,\s*' so that you will take care of spaces in column-names: transactions = pd.read_csv('transactions.csv', sep=r'\s*,\s*', header=0, encoding='ascii', engine='python') alternatively you can make sure that you don't have unquoted spaces in your CSV file and use your command (unchanged) prove: print(transactions.columns.tolist()) Output: ['product_id', 'customer_id', 'store_id', 'promotion_id', 'month_of_year', 'quarter', 'the_year', 'store_sales', 'store_cost', 'unit_sales', 'fact_count'] | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/35831496', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1883468/']} | jdg_71420 |
stackexchange | llm_judgeable_groundtruth_similarity | 750303 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the difference between SQL Server Authentication and Windows Authentication? Is there a specific use case for each type of authentication?
Now provide the response and nothing else.
| SQL Server has its own built in system for security that covers logins and roles. This is separate and parallel to Windows users and groups. You can use just SQL security and then all administration will occur within SQL server and there's no connection between those logins and the Windows users. If you use mixed mode then Windows users are treated just like SQL logins. There are a number of features of each approach - If you want to use connection pooling you have to use SQL logins, or all share the same Windows user - not a good idea. If you want to track what a particular user is doing, then using the Windows authentication makes sense. Using the Windows tools to administer users is much more powerful than SQL, but the link between the two is tenuous, for instance if you remove a Windows user then the related data within SQL isn't updated. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/750303', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/57884/']} | jdg_71421 |
stackexchange | llm_judgeable_groundtruth_similarity | 2907245 |
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 simple yield use case and for some unknown reason the default case is never shown: In my super_admin layout I have: <%= yield :body_id || 'super_admin_main' %> My controller class Superadmin::GolfsController < ApplicationController layout "super_admin" def show endend My show view With or without <% content_for(:body_id) do %>sadmin_golfs<% end %> With : sadmin_golfs is shown. without : empty string is shown instead of super_admin_main Can anyone reproduce the same behavior ?
Now provide the response and nothing else.
| Use parentheses: <%= (yield :body_id) || 'super_admin_main' %> Or <%= yield(:body_id) || 'super_admin_main' %> Without them it is assuming yield (:body_id || 'super_admin_main') EDIT: Rails 3 uses ActiveSupport::SafeBuffer instead of string/nil (Rails 2), so the output is not nil even if there is no content_for provided. So try: <%= yield(:body_id).empty? ? 'super_admin_main' : yield(:body_id)%> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2907245', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32032/']} | jdg_71422 |
stackexchange | llm_judgeable_groundtruth_similarity | 1322401 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like to download a picture and afterwards show it in a picturebox. at first I did like this: WebClient client = new WebClient();client.DownloadFile(url, localFile);pictureBox2.Picture = localFile; But that wasn't perfect because for the time while the download is performed the app is kinda freezing. Then I changed to this: public class ParamForDownload{ public string Url { get; set; } public string LocalFile { get; set; }}ParamForDownload param = new ParamForDownload() { Url = url, LocalFile = localFile }; ThreadStart starter = delegate { DownloadMap (param); }; new Thread(starter).Start(); pictureBox2.Picture = localFile; private static void DownloadMap(ParamForDownload p) { WebClient client = new WebClient(); client.DownloadFile(p.Url, p.LocalFile); } But now I have to do something like a "wait for thread ending" because the file is accessed in the thread and to same time there's downloaded something to the file by the DownloadMap method. What would be the best wait to solve that problem?
Now provide the response and nothing else.
| Basically, What was happening originally, was the UI Thread was completing the download, and because it was working away on that, it couldn't be refreshed or painted (working synchronously). Now what is happening is that you're starting the thread then the UI thread is continuing, then trying to assign the local file (which hasn't finished downloading) to the picture box. You should try either of the following: You should use a background worker to complete your download task. It has events that will be very handy. DoWork, where you can start the download. There is also a RunWorkerCompleted event that is fired when the Work has completed. Where you can set the image there ( pictureBox2.Picture = localFile; ). It's definitely worth checking out, I think it's the most appropriate way to complete what you are trying to achieve. Or If you want to stick with using a Thread. You could take out the Image assignment after you've done the Thread.Start() , and put this in to your Worker Thread function: private delegate void MyFunctionCaller();private static void DownloadMap(ParamForDownload p) { WebClient client = new WebClient(); client.DownloadFile(p.Url, p.LocalFile); DownloadMapComplete(p);}private void DownloadMapComplete(ParamForDownload p){if (InvokeRequired == true) { MyFunctionCaller InvokeCall = delegate { DownloadMapComplete(p); }; Invoke(InvokeCall); }else { pictureBox2.Picture = p.LocalFile; }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1322401', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/154011/']} | jdg_71423 |
stackexchange | llm_judgeable_groundtruth_similarity | 14640045 |
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 getting this error on my CI server: error MSB4019: The imported project "C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\WCF\Microsoft.VisualStudio.ServiceModel.targets" was not found It seems my WCF service library project references that file, but the VisualStudio folder on Program Files\MSBuild\Microsoft doesn't contain a WCF folder. I guess I need to install something on the server. What do I need to install?
Now provide the response and nothing else.
| Well this ruined my morning, but let's not allow it to ruin anyone else's. I couldn't find this information anywhere else. You need to copy a few files from a development machine with VS Pro 2012. As aphexddb mentions, you need to copy some targets from C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\WCF to the same location on your CI server. This then references an assembly called Microsoft.VisualStudio.ServiceModel.Core . You can find this assembly in either the GAC or in the IDE directory at C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE . Copy this to your CI server and execute gacutil.exe -i Microsoft.VisualStudio.ServiceModel.Core.dll This was enough to fix it for me. This isn't the first time I found targets missing from my VS express install in my CI server. I can't help but feel that there is some sort of package I can download from somewhere that fills all this in. Does anyone know of such a thing? If not, perhaps we should create one. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14640045', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979293/']} | jdg_71424 |
stackexchange | llm_judgeable_groundtruth_similarity | 5053073 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've heard that it is a good technique to define your variables at the top of a function, so you don't end up with variable hoisting problems. This: // Beginning of filefunction something(){ var a, b, c = 1, d, e; // Do something}// End of file is a good example (excluding the bad variable names, of course). My question is: Is this always the best approach? What if you are working with a lot of variables? Should they really all just be plopped on one line?
Now provide the response and nothing else.
| I'd highly suggest giving Code Complete 2 by Steve McConnell a read. His argument is that you should neither declare all of your variables in one line , nor should should declare them all at the top of a routine. So, don't do this: function foo() { var a, b, c, d; /** * 20 lines that use a and b */ /** * 10 lines that use c and d */} Instead, you should declare your variables close to where they are needed. In the above code, that might look like this: function foo() { var a, b; /** * 20 lines that use a and b */ var c, d; /** * 10 lines that use c and d */} The benefits are that you can understand at a quick glance what variables are used by a block of code by just looking at the declarations above it. You don't need to read the code to see what variables are set, just which are declared. Don't write code for the compiler or for the computer. Write it for developers. Your code should be as easy to read as possible, and require as little effort as possible to understand a particular section of code. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5053073', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221061/']} | jdg_71425 |
stackexchange | llm_judgeable_groundtruth_similarity | 35242735 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
import cv2import numpy as npcap = cv2.VideoCapture('traffic.avi')retval, frame = cap.read()print retval================ RESTART: J:\Python For DIP\traffic_video.py ================False>>> The Value of retval is always False, which means the video is not read by the command. It must be True to read frames. I don't know what to do. However when I use my default webcam it turns to be True. I tried many videos and the same problem appears. Note: I have installed the ffmpeg correctly. Note: This is not the full code, in this step I am only validating cap.read() either True or False
Now provide the response and nothing else.
| This method is guaranteed 100% first of all check your version of OpenCV, say for instance 2.4.11. you can check it by typing the following commands in your Python Shell: >>> from cv2 import __version__>>> __version__'2.4.11'>>> Then go to C:\opencv\build\x86\vc12\bin and copy opencv_ffmpeg2411.dll .Finally go to root directory of Python ex: C:\Python27 and paste opencv_ffmpeg2411.dll in it check the name of the file opencv_ffmpeg2411.dll, whether the version of opencv is written or not, if not do the following opencv_ffmpeg(version of your opencv without dots).dll After that create a new Python file and copy this code and paste it loading your own video import numpy as npimport cv2# Capture video from filecap = cv2.VideoCapture('your video')while True: ret, frame = cap.read() if ret == True: gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame',gray) if cv2.waitKey(30) & 0xFF == ord('q'): break else: breakcap.release()cv2.destroyAllWindows() you will have an output video for example like this: Result | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35242735', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5865393/']} | jdg_71426 |
stackexchange | llm_judgeable_groundtruth_similarity | 335319 |
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:
An electron has a mass of $m_e = \; 9.1094 × 10^{-31} kg$. A positron has the same mass. So during electron positron low-energy annihilation, won't the law of conservation of mass be violated? Note: I am a high school student interested in physics and read about electron positron annihilation in a book. So if there is a flaw in a concept behind the question, please do point it out.
Now provide the response and nothing else.
| won't the law of conservation of mass be violated? One has to understand that presently there is classical physics, to which belong Newtonian physics , thermodynamics and some other branches of mathematically modeling nature, and quantum physics, which models the data coming from the microcosm of particles : molecules atoms nuclei and elementary particles. Special relativity is much more important in the quantum mechanical framework. For ordinary velocities it reduces to Newtonian mechanics. The law of conservation of mass belongs to classical macroscopic descriptions of nature. There mass is conserved. The electron positron annihilation belongs to the quantum mechanical and special relativity framework. In quantum mechanics and special relativity mass is not conserved; only energy and momentum are retained from the newtonian conservation laws. Mass is the "length" of the four vector describing a system of particles, called invariant mass , which is not the sum of individual masses. Invariant mass of single particle characterizes it uniquely. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/335319', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/82178/']} | jdg_71427 |
stackexchange | llm_judgeable_groundtruth_similarity | 67896 |
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 trying to understand the derivation here kiwi.atmos.colostate.edu/group/dave/pdf/TaylorSeries.pdf I understand how first, second total differentials are derived. I do not understand how they are plugged into a form that is compatible with the single variable Taylor Series, which is $f(x) = f(a) + f'(a)(x-a) + \frac{1}{2!}f''(a) (x-a)^2 + ...$ The coefficients of multivariate expansion are exactly the same as the single variable version. Sure given the total differential, $(x-a)$ is substituted for $dx$, $(y-b)$ for $dy$, but it's not shown why, or how the rest of $f(x,y)$ expansion should mirror the single variable form based on the total differential. Expansion for $f(x,y)$ is below $f(x,y) = f(a,b) + \bigg[(x-a)\frac{\partial}{\partial x} + (y-b)\frac{\partial}{\partial x}\bigg]f + \frac{1}{2!}\bigg[(x-a)\frac{\partial}{\partial x} + (y-b)\frac{\partial}{\partial x}\bigg]^2 f + ...$ If you know a better 2D Taylor Series derivation, that would be welcome as well. Thanks,
Now provide the response and nothing else.
| So we want to express $f(a+u,b+v)$ in terms of $f(a,b)$, the increment $(u,v)$ and the partial derivatives of $f$ at $(a,b)$. To this end we look at the auxiliary function$$\phi(t):=f(a+t u, b+t v)\qquad(0\leq t\leq 1)\ .$$By the one-variable Taylor theorem we have$$f(a+u,b+v)=\phi(1)=\sum_{r=0}^n{1\over r!}\phi^{(r)}(0)+{\rm error\ term}\ .\qquad(*)$$Therefore we have to compute the successive derivatives of $\phi$ at $t=0$. Obviously $$\phi^{(0)}(t)=\phi(t)=f(a+tu,b+tv)$$ and therefore $\phi^{(0)}(0)=f(a,b)$. To compute $\phi'(t)$ we need the chain rule:$$\phi'(t)={d\over dt}\phi(t)={d\over dt}f(a+t u,b+ t v)=f_1(a+t u,b+ tv)u+f_2(a+ tu, b+ tv) v\ ,$$whence $\phi'(0)=f_1(a,b)u+f_2(a,b)v$. Proceeding in this manner we get$$\eqalign{\phi''(t)&={d\over dt}\bigl(f_1(a+t u,b+ tv)u+f_2(a+ tu, b+ tv) v\bigr) \cr &=f_{11}(a+tu,b+tv)u^2+2f_{12}(a+tu,b+tv) uv +f_{22}(a+tu,b+tv)v^2\cr}$$and therefore$\phi''(0)=f_{11}(a,b)u^2 + 2f_{12}(a,b)uv+f_{22}(a,b) v^2\ .$And so on for the higher derivatives of $\phi$. The values $\phi(0)$, $\phi'(0)$, $\phi''(0)$, $\ldots$ so obtained have to be plugged into the equation $(*)$ Of course all of this could be written up more elegantly using vector notation. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/67896', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/6786/']} | jdg_71428 |
stackexchange | llm_judgeable_groundtruth_similarity | 9784118 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Basically, what I'm trying to do is click on a button that becomes visible when hovering another element (its parent). I have tried to use trigger.('mouseover') on the parent of the hidden button, but that doesn't seem to work. Here's a code snippet from the spec: # label[for ... ] -> the parent element page.execute_script("$('label[for=\"department_#{department.id}\"]').trigger(\"mouseover\")") # le hidden button find(".actions").click # some <li> on a list that drops down when clicking the hidden button click_on("Edit department") And the error ... Failure/Error: click_on("Edit department") Selenium::WebDriver::Error::ElementNotVisibleError: Element is not currently visible and so may not be interacted with I would like to know how can I make the .actions button visible on the page, in order to click it afterwards. Any help would be much appreciated.
Now provide the response and nothing else.
| Capybara provides Element#hover method from version 2.1: find('.some_class').hover This method is implemented in Capybara::Selenium::Driver in almost the same way as in @AlexD's answer. Note that to use #hover in Selenium it's usually better to turn native events on : Capybara.register_driver :selenium do |app| profile = Selenium::WebDriver::Firefox::Profile.new profile.native_events = true Capybara::Selenium::Driver.new(app, :browser => :firefox, profile: profile)end | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9784118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/889453/']} | jdg_71429 |
stackexchange | llm_judgeable_groundtruth_similarity | 180066 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have some files in a directory. And I want to add some lines at top and end of file using awk . Example: My awk command: awk 'BEGIN { print "line1\nline2" } { print $0 } END { print "line3\nline4" }' file |tee file By using above command I can add line1 & line2 at the top & line3 , line4 at the end of file Now I want to do same action for all files that are exist in current directory. If I use : awk 'BEGIN { print "line1\nline2" } { print $0 } END { print "line3\nline4" }' * Then I get output on terminal screen but I can't redirect to (or overwrite) all files . So, I tried following (To find + awk ): find -type f -exec awk 'BEGIN { print "line1\nline2" } { print $0 } END { print "line3\nline4" }' '{}' \; By using above command I can print output on screen and hence to overwrite files , I've tried following (To find + awk + overwrite with tee ), but it getting error: $ find -type f -exec awk 'BEGIN { print "line1\nline2" } { print $0 } END { print "line3\nline4" }' '{}' | tee '{}' \;find: missing argument to `-exec' Hence, How can I use awk to overwrite (i.e: with |tee or something else) for all files in current directory by command?
Now provide the response and nothing else.
| With GNU awk 4.1 or above: find . -type f -exec awk ' @load "inplace" BEGINFILE { inplace_begin(FILENAME, "") print "line1\nline2" } {print} ENDFILE { print "line3\nline4" inplace_end(FILENAME, "") }' {} + | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/180066', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/66803/']} | jdg_71430 |
stackexchange | llm_judgeable_groundtruth_similarity | 2923809 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I haven't found any MYSQL many-to-many relationships examples here and in google. What I am looking is to see a very simple example with php+mysql showing database's results. Can anybody write a very simple example?
Now provide the response and nothing else.
| Example scenario: students and courses at a university. A given student might be on several courses, and naturally a course will usually have many students. Example tables, simple design: CREATE TABLE `Student` ( `StudentID` INT UNSIGNED NOT NULL AUTO_INCREMENT, `FirstName` VARCHAR(25), `LastName` VARCHAR(25) NOT NULL, PRIMARY KEY (`StudentID`)) ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_general_ciCREATE TABLE `Course` ( `CourseID` SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, `Code` VARCHAR(10) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL, `Name` VARCHAR(100) NOT NULL, PRIMARY KEY (`CourseID`)) ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_general_ciCREATE TABLE `CourseMembership` ( `Student` INT UNSIGNED NOT NULL, `Course` SMALLINT UNSIGNED NOT NULL, PRIMARY KEY (`Student`, `Course`), CONSTRAINT `Constr_CourseMembership_Student_fk` FOREIGN KEY `Student_fk` (`Student`) REFERENCES `Student` (`StudentID`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `Constr_CourseMembership_Course_fk` FOREIGN KEY `Course_fk` (`Course`) REFERENCES `Course` (`CourseID`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=INNODB CHARACTER SET ascii COLLATE ascii_general_ci Find all students registered for a course: SELECT `Student`.*FROM `Student` JOIN `CourseMembership` ON `Student`.`StudentID` = `CourseMembership`.`Student`WHERE `CourseMembership`.`Course` = 1234 Find all courses taken by a given student: SELECT `Course`.*FROM `Course` JOIN `CourseMembership` ON `Course`.`CourseID` = `CourseMembership`.`Course`WHERE `CourseMembership`.`Student` = 5678 | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2923809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/237681/']} | jdg_71431 |
stackexchange | llm_judgeable_groundtruth_similarity | 96999 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
People on this site keep telling me that good MMa practice avoids the use of loops. The code below calculates the same Table of derivatives two different ways, and the one with the Do loops is much faster. I think the first, slower version is calculating the nth derivative from scratch without using the (n-1)th derivative as a starting point. Derivative[q_, 1][y][x, v] = D[(D[y[x, v], {x, 2}] + D[y[x, v], x]^2), {x, q}]/2;ord = 9;Print[Timing[dgdv1 = Table[D[y[x, v], {v, i}], {i, 0, ord - 1}];]];dgdv2 = Flatten[{y[x, v], Table[0, {i, 2, ord}]}];Print[Timing[Do[dgdv2[[i]] = D[dgdv2[[i - 1]], v], {i, 2, ord}];]]; (*{3.931225,Null} {2.449216,Null}*) So how can one efficiently calculate the first several derivatives of g[x,v] wrt v without using a loop? Bonus Question: Is there some even faster way to do this calculation? OP's EDIT : Some commentors below were confused by the first line of my code, in which I define a derivative relationship for g[x,v]. It's not really relevant to the computation speed issue this Question is about, but here is a link for people who want to learn about defining derivatives.
Now provide the response and nothing else.
| ord = 9;Timing[d1 = Table[D[y[x, v], {v, i}], {i, 0, ord - 1}];][[1]](* 2.06537 *) Rather than using Table , mapping onto a Range is often more efficient Timing[ d12 = D[y[x, v], {v, #}] & /@ Range[0, ord - 1];][[1]](* 2.03747 *) For a fair timing comparison, the initialization of the array should be included in the timing Timing[ d2 = Flatten[{y[x, v], Table[0, {i, 2, ord}]}]; Do[d2[[i]] = D[d2[[i - 1]], v], {i, 2, ord}];][[1]](* 1.70694 *) With symbolic operations it can sometimes be faster to Simplify intermediate steps d22 = Flatten[{y[x, v], Table[0, {i, 2, ord}]}];Timing[ Do[d22[[i]] = Simplify[D[d22[[i - 1]], v]], {i, 2, ord}];][[1]](* 0.307888 *) However, for this type of problem NestList is faster (and "more Mathematica-like") Timing[d3 = NestList[D[#, v] &, y[x, v], ord - 1];][[1]](* 1.58817 *) Again using Simplify Timing[d32 = NestList[Simplify[D[#, v]] &, y[x, v], ord - 1];][[1]](* 0.060246 *) Verifying that all approaches return the same results d1 == d12 == d2 == d22 == d3 == d32 // Simplify(* True *) | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/96999', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/20042/']} | jdg_71432 |
stackexchange | llm_judgeable_groundtruth_similarity | 15429418 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Which rule do I have to follow when extracting numbers out of DOM and calcluation with them? How does javascript knows that a value is a number or not? Should I always use parseInt? Given following Code: HTML <div id="myvalue">5</div><div id="withParseInt"></div><div id="withoutParseInt"></div><div id="withoutParseIntButIncrement"></div> JS & jQuery: var value = $('#myvalue').text();$('#withParseInt').text(parseInt(value) + 1);$('#withoutParseInt').text(value + 1);$('#withoutParseIntButIncrement').text(value++); Gives following output: 56515 Fiddle: http://jsfiddle.net/ytxKU/3/
Now provide the response and nothing else.
| The .text() method will always return a string. Some operators, like the + operator, are overloaded to perform both arithmetic and string operations. In the case of strings, it performs concatenation, hence the "51" result. If you have a string and need to use a non-coercing operator, you will have to use parseInt (or some other method of converting to a number). However, the * operator for example implicity performs this coercion, so you wouldn't need the parseInt call in that situation (see an updated fiddle for example). Note that the increment ++ operator does coerce its operand, but you've used the postfix operator so it won't have any effect. Use the prefix operator and you can see it working: $('#withoutParseIntButIncrement').text(++value); So, to summarise: // Parses string to number and adds 1$('#withParseInt').text(parseInt(value) + 1);// Coerces number 1 to string "1" and concatenates$('#withoutParseInt').text(value + 1);// Implicity coerces string to number, but after it's been inserted into the DOM$('#withoutParseIntButIncrement').text(value++);// Implicity coerces string to number, before it's been inserted into the DOM$('#withoutParseIntButIncrement').text(++value);// Implicity coerces to number$('#withoutParseIntButMultiply').text(value * 2); Side note: it's considered good practice to always pass the second argument (the radix) to parseInt . This ensures the number is parsed in the correct base: parseInt(value, 10); // For base 10 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15429418', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1014281/']} | jdg_71433 |
stackexchange | llm_judgeable_groundtruth_similarity | 508627 |
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 sqlite with python 2.5. I get a sqlite error with the syntax below. I looked around and saw AUTOINCREMENT on this page http://www.sqlite.org/syntaxdiagrams.html#column-constraint but that did not work either. Without AUTO_INCREMENT my table can be created. An error occurred: near "AUTO_INCREMENT": syntax error CREATE TABLE fileInfo(fileId int NOT NULL AUTO_INCREMENT,name varchar(255),status int NOT NULL,PRIMARY KEY (fileId));
Now provide the response and nothing else.
| This is addressed in the SQLite FAQ . Question #1 . Which states: How do I create an AUTOINCREMENT field? Short answer: A column declared INTEGER PRIMARY KEY will autoincrement. Here is the long answer: If you declare a column of a table to be INTEGER PRIMARY KEY, then whenever you insert a NULL into that column of the table, the NULL is automatically converted into an integer which is one greater than the largest value of that column over all other rows in the table, or 1 if the table is empty. (If the largest possible integer key, 9223372036854775807, then an unused key value is chosen at random.) For example, suppose you have a table like this: CREATE TABLE t1( a INTEGER PRIMARY KEY, b INTEGER ); With this table, the statement INSERT INTO t1 VALUES(NULL,123); is logically equivalent to saying: INSERT INTO t1 VALUES((SELECT max(a) FROM t1)+1,123); There is a function named sqlite3_last_insert_rowid() which will return the integer key for the most recent insert operation. Note that the integer key is one greater than the largest key that was in the table just prior to the insert. The new key will be unique over all keys currently in the table, but it might overlap with keys that have been previously deleted from the table. To create keys that are unique over the lifetime of the table, add the AUTOINCREMENT keyword to the INTEGER PRIMARY KEY declaration. Then the key chosen will be one more than than the largest key that has ever existed in that table. If the largest possible key has previously existed in that table, then the INSERT will fail with an SQLITE_FULL error code. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/508627', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_71434 |
stackexchange | llm_judgeable_groundtruth_similarity | 12344218 |
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 starting to learn php+mysql after making a query like this: $sql = "SELECT * FROM clients";$query = $mysqli->query($sql); I need to put in a array to access information right? $result = mysqli_fetch_all($query); Do I need to use an array or can I search within $query for info?
Now provide the response and nothing else.
| While you can't cast enum to integer as Catcall explained, you can use the PostgreSQL-specific and possibly not-version-to-version compatible pg_enum system catalog table to get an ordinal representation. regress=# CREATE TYPE happiness AS ENUM ('happy', 'very happy', 'ecstatic');regress=# select enumsortorder, enumlabel from pg_catalog.pg_enum regress-# WHERE enumtypid = 'happiness'::regtype ORDER BY enumsortorder; enumsortorder | enumlabel ---------------+------------ 1 | happy 2 | very happy 3 | ecstatic(3 rows) This looks easy, but it isn't. Observe: regress=# ALTER TYPE happiness ADD VALUE 'sad' BEFORE 'happy';regress=# ALTER TYPE happiness ADD VALUE 'miserable' BEFORE 'very happy';regress=# SELECT * FROM pg_enum ; enumtypid | enumsortorder | enumlabel -----------+---------------+------------ 185300 | 1 | happy 185300 | 2 | very happy 185300 | 3 | ecstatic 185300 | 0 | sad 185300 | 1.5 | miserable(5 rows) From this you can see that enumsortorder provides ordering, but no fixed 'distance'. If support for removing values from enums is ever added, it'll likely create 'holes' in the sequence, too. To get the enum position you'll need to use the row_number() window function to get the ordering, and the pg_typeof to get the oid ( regtype ) of the enum type. You need this to make sure that you return the right ordinal when there are multiple enums with the same label. This function does the job: CREATE OR REPLACE FUNCTION enum_to_position(anyenum) RETURNS integer AS $$SELECT enumpos::integer FROM ( SELECT row_number() OVER (order by enumsortorder) AS enumpos, enumsortorder, enumlabel FROM pg_catalog.pg_enum WHERE enumtypid = pg_typeof($1) ) enum_ordering WHERE enumlabel = ($1::text);$$ LANGUAGE 'SQL' STABLE STRICT; Note: It's STABLE not IMMUTABLE , because adding (or if support in Pg is later added, removing) values from enums would change the ordering and break indexes relying on the ordering; so You cannot use this in an index expression; and It's STRICT because it should return null for a null input You can now use this function to CREATE CAST for specific enums to integer . You cannot create a generic cast for all enums to integer , because the anyenum pseudo-type cannot be used for casts. For example, if I want to allow the demo happiness to be cast to integer, I would write: CREATE CAST (happiness AS integer) WITH FUNCTION enum_to_position(anyenum); after which I could successfully execute: regress=# SELECT ('happy'::happiness)::integer; int4 ------ 2(1 row) Note that this is probably an insane thing to do, is unsupported, and is quite likely a terrible idea. Your code must be aware that the ordinal values will change when you add or (if later supported) remove a value from the enum. Indexes created based on this cast (only possible if the function is defined immutable) will begin producing crazy and wrong results if you change the definition of the enum (except by appending new values to the end of it) because PostgreSQL believes you when you say a function is immutable. Don't do that. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12344218', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1291483/']} | jdg_71435 |
stackexchange | llm_judgeable_groundtruth_similarity | 35041478 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is TaskEx ? In http://www.i-programmer.info/programming/c/1514-async-await-and-the-ui-problem.html?start=1 or await TaskEx.Delay or Await async clarification . I use Task DoWork(){ return Task.Run(() => { for (int i = 0; i < 30; i++) { Thread.Sleep(1000 * 60 * 30); } });} Examples use this Task DoWork(){ return TaskEx.Run(() => { for (int i = 0; i < 10; i++) { Thread.Sleep(500); } } }); I call it like await DoWork(); If you use just Task , await returns nothing and there is no response. If I use TaskEx it says it doesn't exist in context.Should TaskEx be a class or something with some sort of function?Fists one Works it's my mistake.
Now provide the response and nothing else.
| TaskEx was just an extra class which initially shipped with the CTPs of the async/await extensions for C# 5 before .NET 4.5 shipped... and is now part of the Async Targeting Pack (aka the Microsoft.Bcl.Async NuGet package ) in case you want to use async/await but are targeting .NET 4.0 (which doesn't have some of the code required for it). If you're using .NET 4.5 or later, just use Task.Run , which does the same thing. (You won't be using the targeting pack, so you won't have TaskEx .) The async targeting pack can't add a static method to the existing Task class, hence the need for TaskEx existing at all. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35041478', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5247132/']} | jdg_71436 |
stackexchange | llm_judgeable_groundtruth_similarity | 5130246 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I had a look at question already which talk about algorithm to find loop in a linked list. I have read Floyd's cycle-finding algorithm solution, mentioned at lot of places that we have to take two pointers. One pointer( slower/tortoise ) is increased by one and other pointer( faster/hare ) is increased by 2. When they are equal we find the loop and if faster pointer reaches null there is no loop in the linked list. Now my question is why we increase faster pointer by 2. Why not something else? Increasing by 2 is necessary or we can increase it by X to get the result. Is it necessary that we will find a loop if we increment faster pointer by 2 or there can be the case where we need to increment by 3 or 5 or x.
Now provide the response and nothing else.
| From a correctness perspective, there is no reason that you need to use the number two. Any choice of step size will work (except for one, of course). However, choosing a step of size two maximizes efficiency. To see this, let's take a look at why Floyd's algorithm works in the first place. The idea is to think about the sequence x 0 , x 1 , x 2 , ..., x n , ... of the elements of the linked list that you'll visit if you start at the beginning of the list and then keep on walking down it until you reach the end. If the list does not contain a cycle, then all these values are distinct. If it does contain a cycle, though, then this sequence will repeat endlessly. Here's the theorem that makes Floyd's algorithm work: The linked list contains a cycle if and only if there is a positive integer j such that for any positive integer k, x j = x jk . Let's go prove this; it's not that hard. For the "if" case, if such a j exists, pick k = 2. Then we have that for some positive j, x j = x 2j and j ≠ 2j, and so the list contains a cycle. For the other direction, assume that the list contains a cycle of length l starting at position s. Let j be the smallest multiple of l greater than s. Then for any k, if we consider x j and x jk , since j is a multiple of the loop length, we can think of x jk as the element formed by starting at position j in the list, then taking j steps k-1 times. But each of these times you take j steps, you end up right back where you started in the list because j is a multiple of the loop length. Consequently, x j = x jk . This proof guarantees you that if you take any constant number of steps on each iteration, you will indeed hit the slow pointer. More precisely, if you're taking k steps on each iteration, then you will eventually find the points x j and x kj and will detect the cycle. Intuitively, people tend to pick k = 2 to minimize the runtime, since you take the fewest number of steps on each iteration. We can analyze the runtime more formally as follows. If the list does not contain a cycle, then the fast pointer will hit the end of the list after n steps for O(n) time, where n is the number of elements in the list. Otherwise, the two pointers will meet after the slow pointer has taken j steps. Remember that j is the smallest multiple of l greater than s. If s ≤ l, then j = l; otherwise if s > l, then j will be at most 2s, and so the value of j is O(s + l). Since l and s can be no greater than the number of elements in the list, this means than j = O(n). However, after the slow pointer has taken j steps, the fast pointer will have taken k steps for each of the j steps taken by the slower pointer so it will have taken O(kj) steps. Since j = O(n), the net runtime is at most O(nk). Notice that this says that the more steps we take with the fast pointer, the longer the algorithm takes to finish (though only proportionally so). Picking k = 2 thus minimizes the overall runtime of the algorithm. Hope this helps! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5130246', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/164933/']} | jdg_71437 |
stackexchange | llm_judgeable_groundtruth_similarity | 2420683 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Given that: $$\sum_{k=2}^{\infty}{\lambda(k)-1\over k}\tag1$$ Where $\lambda(k)$ is Dirichlet Lambda Function We are seeking to determine the closed form $(1)$ and came close to estimates it to $1-{\frac12}\left(\gamma+\ln{\pi}\right)$. where $\gamma=0.5772156...$ is Euler-Mascheroni Constant How can we evalauate the exact closed form for $(1)$?
Now provide the response and nothing else.
| You have found it. Interchange the order of summation, and a few rewrites plus Wallis's product yield the result: \begin{align}\sum_{k = 2}^{\infty} \frac{1}{k}\bigl(\lambda(k) - 1\bigr)&= \sum_{k = 2}^{\infty} \frac{1}{k} \sum_{n = 1}^{\infty} \frac{1}{(2n+1)^k} \\&= \sum_{n = 1}^{\infty} \sum_{k = 2}^{\infty} \frac{1}{k(2n+1)^k} \\&= \sum_{n = 1}^{\infty}\Biggl(-\frac{1}{2n+1} - \log \biggl(1 - \frac{1}{2n+1}\biggr)\Biggr) \\&= \sum_{n = 1}^{\infty} \Biggl(\log \biggl(1 + \frac{1}{2n}\biggr) - \frac{1}{2n+1}\Biggr) \\&= \sum_{n = 1}^{\infty} \Biggl(\frac{1}{2}\log \biggl(1 + \frac{1}{n}\biggr) - \frac{1}{2n} + \frac{1}{2n} - \frac{1}{2n+1} \\&\qquad\quad - \frac{1}{2}\biggl(\log\biggl(1 + \frac{1}{n}\biggr) - 2\log \biggl(1 + \frac{1}{2n}\biggr)\biggr)\Biggr) \\&= -\frac{1}{2}\gamma + 1 - \log 2 - \frac{1}{2} \log \prod_{n = 1}^{\infty} \frac{(2n+1)^2n}{(2n)^2(n+1)} \\&= - \frac{1}{2}\gamma + 1 - \log 2 - \frac{1}{2} \log \Biggl(\prod_{k = 2}^{\infty}\biggl(1 - \frac{1}{k^2}\biggr)\prod_{m = 1}^{\infty}\biggl(1 - \frac{1}{(2m)^2}\biggr)^{-1}\Biggr) \\&= - \frac{1}{2}\gamma + 1 - \log 2 - \frac{1}{2} \log \biggl( \frac{1}{2}\cdot \frac{\pi}{2}\biggr) \\&= 1 - \frac{1}{2}\bigl(\gamma + \log \pi\bigr).\end{align} | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2420683', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/343408/']} | jdg_71438 |
stackexchange | llm_judgeable_groundtruth_similarity | 12912912 |
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 any one know how to use the package.Saveas function? package.SaveAs(tempFolderPathAlt + saveas + ".xlsx"); At the moment this is underlined in red with the following error: The best overloaded method match for 'OfficeOpenXml.ExcelPackage.SaveAs(System.IO.Stream)' has some invalid arguments At the moment i'm saving the file in the following way. FileStream aFile = new FileStream(tempFolderPathAlt + saveas + ".xls", FileMode.Create);byte[] byData = package.GetAsByteArray();aFile.Seek(0, SeekOrigin.Begin);aFile.Write(byData, 0, byData.Length);aFile.Close(); But this way the package remains open and i cant work with files it has used. The save as will close the package properly, but its not accepting my file path. Edit I tried this: using (FileStream aFile = new FileStream(tempFolderPathAlt + saveas + ".xlsx", FileMode.Create)){ byte[] byData = package.GetAsByteArray(); aFile.Seek(0, SeekOrigin.Begin); package.SaveAs(aFile); //aFile.Write(byData, 0, byData.Length); aFile.Close();} But Get the following error? Package object was closed and disposed, so cannot carry out operations on this object or any stream opened on a part of this package.
Now provide the response and nothing else.
| The package will be closed & disposed after you call any of functions GetAsByteArray , Save , SaveAs . That is the reason why you got message Package object was closed and disposed, so cannot carry out operations on this object or any stream opened on a part of this package. The solution is that after the saving you call Load function to continue processing on excel file. Or if you just want to get both ByteArray & FileOutput, I'm sure with you they both are same. You can read data after have saved file to the disk: string path = @"C:\test1.xlsx";Stream stream = File.Create(path);package.SaveAs(stream);stream.Close();byte[] data = File.ReadAllBytes(path); Or you can save data to disk after get the ByteArray: byte[] data = package.GetAsByteArray();string path = @"C:\test1.xlsx";File.WriteAllBytes(path, data); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12912912', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1356321/']} | jdg_71439 |
stackexchange | llm_judgeable_groundtruth_similarity | 507141 |
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:
At the bottom of this page says (my emphasis): It's interesting to note the speeds in the cartoon. The propeller-beanie kid sees his tennis ball moving away from him at 30 miles per hour. So does the Sun, sitting on the stationary platform. The engineer driving the train sees the ball coming at about 80 MPH, since the train is moving 50 MPH with respect to the ground. The train and ball interact at 80 MPH. The ball rebounds from the front of the train at nearly the same 80 MPH, which can be added to the 50 MPH speed of the train, because it acquired it from the train . The result approaches a total of 130 MPH. This scenario is analogous the velocity of a spacecraft being added to the velocity of the massive speeding planet, and "rebounding" with a higher velocity still (although the spacecraft's "rebound" is a gravitational, rather than a mechanical, interaction, like in the baseball analogy). I do not totally understand why the speed of the train has to be added (again?). It seems to me that the ball has to leave (rebound) at 80 MPH (30 plus 50). A clearer explanation is really appreciate. It can be a silly question, but I cannot see it :(
Now provide the response and nothing else.
| If you throw a ball off an immovable wall it bounces back at approximately the same speed according to Newton’s laws. If we are in the reference frame of the train then we can treat the train like an immovable wall. So in that reference frame the ball comes in at 80 mph and bounces back at 80 mph (again, still in the reference frame of the train ). In order to convert this to the speed perceived by the propeller-beanie kid in his stationary reference frame, we need to add the speed of the train. Hence the 130mph. A flipped version of this would be if the kid was on the train and throwing the ball at a stationary wall. From the wall, the kid would be throwing the ball at 30 + 50 = 80mph, and it would rebound back at 80mph in the wall’s reference frame. But from the kid on the train’s reference frame, the ball would be bouncing away at 130mph because the train is moving 50mph away from the 80mph traveling ball. One final alternative example that would be more in line with how you’re thinking about it. Imagine the kid is on top of the train, throwing the ball at a wall that is also on top of the train. If he throws it at 30mph, it rebounds at 30mph relative to the train. Relative to the ground it would be going 80mph because the train is traveling 50mph. The only difference between this example and the original is the kid is now on the train so we don’t have to add the trains speed at the end of the calculation to get the speed of the ball relative to the ground. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/507141', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/243869/']} | jdg_71440 |
Subsets and Splits