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
|
94886
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am studying classification and regression trees, and one of the measures for the split location is the GINI score. Now I am used to determining best split location when the log of the likelihood ratio of the same data between two distributions is zero, meaning the likelihood of membership is equally likely. My intuition says that there must be a connection of some sort, that GINI has to have a good foundation in a mathematical theory of information (Shannon) but I don't understand GINI well enough to derive the relationship myself. Questions: What is the "first principles" derivation of GINI impurity score as a measure for splitting? How does the GINI score relate to log of likelihood ratio or other information-theoretic fundamentals (Shannon Entropy, pdf , and cross entropy are part of those)? References: How is the Weighted Gini Criterion defined? Mathematics behind classification and regression trees http://www.cs.put.poznan.pl/jstefanowski/sed/DM-5-newtrees.pdf (added) http://www.ibe.med.uni-muenchen.de/organisation/mitarbeiter/020_professuren/boulesteix/pdf/gini.pdf https://www.youtube.com/watch?v=UMtBWQ2m04g http://www.ius-migration.ch/files/content/sites/imi/files/shared/documents/papers/Gini_index_fulltext.pdf https://stackoverflow.com/questions/4936788/decision-tree-learning-and-impurity Shannon's entropy is described as: $$H \left(x \right) = \Sigma_{i} P\left(x_{i} \right)\log_{b} P\left(x_{i} \right)$$ Extending this to the multivariate case we get: $$H \left(X,Y \right)= \Sigma_{x}\Sigma_{y} P\left(x,y \right)\log_{b} P\left(x,y \right) $$ Conditional Entropy is defined as follows: \begin{align}H \left(X|Y \right) &= \Sigma_{y} p\left(x,y \right)\log_{b} \frac {p\left(x \right)} {p\left(x,y \right)} \newline&\text{or,} \newlineH \left(X|Y \right) &= H \left(X,Y \right) - H \left(Y \right)\end{align} The log of the ratio of likelihoods is used for abrupt change detection and is derived using these. (I don't have derivation in front of me.) GINI Impurity: The general form of GINI impurity is $ I = \sum_{i=1}^m f_{i} \cdot \left( 1-f_{i}\right) $ Thoughts: Splitting is done on a measure of impurity. High "purity" is likely the same as low entropy. The approach is likely related to entropy minimization. It is likely that the assumed basis distribution is uniform, or possibly with hand-waving, Gaussian. They are likely making a mixture of distributions. I wonder if the Shewhart chart derivation can apply here? The GINI Impurity looks like the integral of the probability density function for a binomial distribution with 2 trials, and one success. $P(x=k)= \begin{pmatrix} 2\\ 1\end{pmatrix} p \left( 1-p \right) $ (additional) The form is also consistent with a Beta-binomial distribution which is a conjugate prior for a Hypergeometric distribution. Hypergeometric tests are often used to determine which samples are over or under represented in a sample. There is also a relationship to Fisher's exact test, whatever that is (note to self, go learn more about this). Edit:I suspect that there is a form of the GINI that works very well with digital logic and/or rb-trees. I hope to explore this in a class project this fall.
Now provide the response and nothing else.
|
I will use the same notation I used here: Mathematics behind classification and regression trees Gini Gain and Information Gain ($IG$) are both impurity based splitting criteria. The only difference is in the impurity function $I$: $\textit{Gini}: \mathit{Gini}(E) = 1 - \sum_{j=1}^{c}p_j^2$ $\textit{Entropy}: H(E) = -\sum_{j=1}^{c}p_j\log p_j$ They actually are particular values of a more general entropy measure (Tsallis' Entropy) parametrized in $\beta$: $$H_\beta (E) = \frac{1}{\beta-1} \left( 1 - \sum_{j=1}^{c}p_j^\beta \right)$$ $\textit{Gini}$ is obtained with $\beta = 2$ and $H$ with $\beta \rightarrow 1$. The log-likelihood, also called $G$-statistic, is a linear transformation of Information Gain: $$G\text{-statistic} = 2 \cdot |E| \cdot IG$$ Depending on the community (statistics/data mining) people prefer one measure or the the other (Related question here ). They might be pretty much equivalent in the decision tree induction process. Log-likelihood might give higher scores to balanced partitions when there are many classes though [Technical Note: Some Properties of Splitting Criteria. Breiman 1996]. Gini Gain can be nicer because it doesn't have logarithms and you can find the closed form for its expected value and variance under random split assumption [Alin Dobra, Johannes Gehrke: Bias Correction in Classification Tree Construction. ICML 2001: 90-97]. It is not as easy for Information Gain (If you are interested, see here ).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/94886', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/22452/']}
|
jdg_373441
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
40274353
|
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 use Spring Boot and included jackson-datatype-jsr310 with Maven: <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> <version>2.7.3</version></dependency> When I try to use a RequestParam with a Java 8 Date/Time type, @GetMapping("/test")public Page<User> get( @RequestParam(value = "start", required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime start) {//...} and test it with this URL: /test?start=2016-10-8T00:00 I get the following error: { "timestamp": 1477528408379, "status": 400, "error": "Bad Request", "exception": "org.springframework.web.method.annotation.MethodArgumentTypeMismatchException", "message": "Failed to convert value of type [java.lang.String] to required type [java.time.LocalDateTime]; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [@org.springframework.web.bind.annotation.RequestParam @org.springframework.format.annotation.DateTimeFormat java.time.LocalDateTime] for value '2016-10-8T00:00'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2016-10-8T00:00]", "path": "/test"}
Now provide the response and nothing else.
|
TL;DR - you can capture it as a string with just @RequestParam , or you can have Spring additionally parse the string into a java date / time class via @DateTimeFormat on the parameter as well. the @RequestParam is enough to grab the date you supply after the = sign, however, it comes into the method as a String . That is why it is throwing the cast exception. There are a few ways to achieve this: parse the date yourself, grabbing the value as a string. @GetMapping("/test")public Page<User> get(@RequestParam(value="start", required = false) String start){ //Create a DateTimeFormatter with your required format: DateTimeFormatter dateTimeFormat = new DateTimeFormatter(DateTimeFormatter.BASIC_ISO_DATE); //Next parse the date from the @RequestParam, specifying the TO type as a TemporalQuery: LocalDateTime date = dateTimeFormat.parse(start, LocalDateTime::from); //Do the rest of your code...} Leverage Spring's ability to automatically parse and expect date formats: @GetMapping("/test")public void processDateTime(@RequestParam("start") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime date) { // The rest of your code (Spring already parsed the date).}
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/40274353', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5097551/']}
|
jdg_373442
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4345680
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm currently working on some HTML5 themes for a few of my websites, and I keep running into problems with the way <h1> 's can be used multiple times. I can't seem to predict in what elements the headings will show up, but I do want to try and size them automatically based on their position in the DOM... I was thinking about using something like h1 { font-size: 3em; }h2,body > * > header h1 { font-size: 2.5em; }h3,body > * > header h2,body > * > * > header h1 { font-size: 2em; } But obviously that's far from waterproof. Having an extra element around an h1 that doesn't really mean it's deeper in the page structure will tend to pick way too small sizes. For example an unordered list with blocks that each have their own title will have something like <section> <ul> <li> <header> <h1>Title of a block</h1> </header> content </li> </ul></section> Which makes the <h1> appear much deeper than it actually is. What are good ways to handle this?
Now provide the response and nothing else.
|
You should style the h1 s based on the type of elements they are in, not just the depth. For example, if you have general headings, article headings and sidebar item headings, you could do this: h1 { font-size: 3em }h2 { font-size: 2.5em }article h1 { font-size: 2em }article h2 { font-size: 1.5em }aside h1 { font-size: 2.5em } You would use whatever selector you use to select the articles or sidebar for layout (in my example, the article and aside tags, it might be section.sidebar or something else) to differentiate between different h1 tags. There is not much of a connection between the depth of the tag, and the size (although there seems to be a pattern; deeper is smaller). There is however a connection between the convention used for marking up your sidebar, and the size of the headings in the sidebar. The CSS selectors for the headings will match up with the selectors for the layout, which shows the connection.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4345680', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/124238/']}
|
jdg_373443
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43651167
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Usually I set -Xms512m and -Xmx1g so that when JVM starts it allocates 512MB and gradually increases heap to 1GB as necessary. But I see these values set to same say 1g in a dedicated server instance. Is there any advantage for the having both set to the same value?
Now provide the response and nothing else.
|
Well there are couple of things. Program will start with -Xms value and if the value is lesser it will eventually force GC to occur more frequently Once the program reaches -Xms heap, jvm request OS for additional memory and eventually grabs -Xmx that requires additional time leading to performance issue, you might as well set it to that at the beginning avoiding jvm to request additional memory. It is very nicely answered here - https://developer.jboss.org/thread/149559?_sscc=t
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43651167', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_373444
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48656993
|
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 Vuex + axios, I want to know the best practice in handling errors for vuex + axios. What I am doing now is that when I request using axios and it returns an error, it will be committed in mutation and update my state. What I want to do is, If there's an response error from my request it will return to my component so that I can handle the error much faster. Like in angular, there's a dependency injection and the response will return to the component.
Now provide the response and nothing else.
|
Have your cake and eat it too. Assuming you are already using an interceptor ... axios.interceptors.response.use(function (response) { return response;}, function (error) { store.commit('ERROR', error) // just taking some guesses here return Promise.reject(error) // this is the important part}) This will keep the promise rejection going back to the caller so in your component, something like... axios.whatever(...).then(res => { // happy days}, err => { // oh noes!})
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48656993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7489991/']}
|
jdg_373445
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
69578685
|
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 VSCode, and when I add the line 'react-hooks/exhaustive-deps': 'warn' to my .eslintrc.js, I get the following in the ESLint output: Rules with suggestions must set the `meta.hasSuggestions` property to `true`. Occurred while lintingC:\Users\filepath.jsx:72 Rule: "react-hooks/exhaustive-deps" This breaks all other linting. I've tried adding the following to my .eslintrc.js: meta: { hasSuggestions: true}, which gives me the following error: UnhandledPromiseRejectionWarning: Error: ESLint configuration in .eslintrc.js is invalid: - Unexpected top-level property "meta". Any help would be appreciated. Here is my .eslintrc.js: module.exports = { env: { browser: true, es2021: true, }, extends: ['eslint:recommended', 'plugin:react/recommended', 'plugin:react-hooks/recommended'], settings: { 'react': { 'version': 'detect' } }, parserOptions: { ecmaFeatures: { jsx: true, }, ecmaVersion: 13, sourceType: 'module', }, plugins: ['react-hooks', 'react'], rules: { 'react/prop-types': [0], quotes: ['error', 'single'], semi: [1], 'react/jsx-indent': [1], 'no-multi-spaces': [1], 'indent': [2], 'react/jsx-newline': [2, { prevent: true }], 'no-trailing-spaces': [1], 'no-multiple-empty-lines': [1, { max: 1 }], 'space-infix-ops': [1], 'object-curly-spacing': [1, 'always'], 'comma-spacing': [1], 'react-hooks/rules-of-hooks': 'error', 'react/self-closing-comp': 1, 'react/jsx-closing-tag-location': 1, 'no-unreachable': 1, 'react-hooks/exhaustive-deps': 'warn' },}; Here's is my package.json: { "name": "app", "private": true, "dependencies": { "@babel/preset-react": "^7.14.5", "@emotion/react": "^11.4.1", "@emotion/styled": "^11.3.0", "@mui/icons-material": "^5.0.4", "@mui/material": "^5.0.3", "@mui/styles": "^5.0.1", "@rails/actioncable": "^6.1.4-1", "@rails/activestorage": "^6.1.4-1", "@rails/ujs": "^6.1.4-1", "@rails/webpacker": "^6.0.0-rc.5", "babel-plugin-macros": "^3.1.0", "prop-types": "^15.7.2", "react": "^17.0.2", "react-dom": "^17.0.2", "react-on-rails": "12.3.0", "react-player": "^2.9.0", "turbolinks": "^5.2.0", "webpack": "^5.53.0", "webpack-cli": "^4.8.0" }, "version": "0.1.0", "babel": { "presets": [ "./node_modules/@rails/webpacker/package/babel/preset.js" ] }, "browserslist": [ "defaults" ], "devDependencies": { "@webpack-cli/serve": "^1.6.0", "eslint": "^8.0.0", "eslint-plugin-react": "^7.26.1", "eslint-plugin-react-hooks": "^4.2.0", "webpack-dev-server": "^4.3.1" }}
Now provide the response and nothing else.
|
ESLint 8.0.0 comes with a breaking change for rules that provide suggestions . There is nothing you can put into your .eslintrc.js to make it work if you use rules that haven't been updated to work after this change. What you can do: Use ESLint 7 until the plugin is updated to work with ESLint 8. In case of eslint-plugin-react-hooks , the offending rule has already been updated (check this line on GitHub ), it's just that there hasn't been a stable release of the package since. However there have been daily alpha releases, at the time of writing the latest version is 4.2.1-alpha-c3a19e5af-20211014 . If you really need both ESLint 8 and this plugin, you can use an alpha version until the next stable version comes out.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/69578685', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5424359/']}
|
jdg_373446
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10282
|
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:
As a physics student, I've come across mathematical objects called tensors in several different contexts. Perhaps confusingly, I've also been given both the mathematician's and physicist's definition, which I believe are slightly different. I currently think of them in the following ways, but have a tough time reconciling the different views: An extension/abstraction of scalars, vectors, and matrices in mathematics. A multi-dimensional array of elements. A mapping between vector spaces that represents a co-ordinate independent transformation. In fact, I'm not even sure how correct these three definitions are. Is there a particularly relevant (rigorous, even) definition of tensors and their uses, that might be suitable for a mathematical physicist? Direct answers/explanations, as well as links to good introductory articles, would be much appreciated.
Now provide the response and nothing else.
|
At least to me, it is helpful to think in terms of bases.(I'll only be talking about tensor products of finite-dimensional vectorspaces here.)This makes the universal mapping property that Zach Conn talks abouta bit less abstract (in fact, almost trivial). First recall that if $L: V \to U$ is a linear map, then $L$ is completely determinedby what it does to a basis $\{ e_i \}$ for $V$:$$L(x)=L\left( \sum_i x_i e_i \right) = \sum_i x_i L(e_i).$$(The coefficients of $L(e_i)$ in a basis for $U$ give the $i$th columnin the matrix for $L$ with respect to the given bases.) Tensors come into the picture when one studies multilinear maps.If $B: V \times W \to U$ is a bilinear map, then $B$is completely determined by the values $B(e_i,f_j)$ where$\{ e_i \}$ is a basis for $V$and $\{ f_j \}$ is a basis for $W$:$$B(x,y) = B\left( \sum_i x_i e_i,\sum_j y_j f_j \right) = \sum_i \sum_j x_i y_j B(e_i,f_j).$$For simplicity, consider the particular case when $U=\mathbf{R}$;then the values $B(e_i,f_j)$make up a set of $N=mn$ real numbers (where $m$ and $n$ are thedimensions of $V$ and $W$), and these numbers are all that we need to keeptrack of in order to know everything about the bilinear map $B:V \times W \to \mathbf{R}$. Notice that in order to compute $B(x,y)$ we don't really need to know theindividual vectors $x$ and $y$, but rather the $N=mn$ numbers $\{ x_i y_j \}$.Another pair of vectors $v$ and $w$ with $v_i w_j = x_i y_j$ for all $i$ and $j$will satisfy $B(v,w)=B(x,y)$. This leads to the idea of splitting the computation of $B(x,y)$ into two stages.Take an $N$-dimensional vector space $T$ (they're all isomorphic so it doesn't matterwhich one we take) with a basis $(g_1,\dots,g_N)$.Given $x=\sum x_i e_i$ and $y=\sum y_j f_j$,first form the vector in $T$whose coordinates with respect to the basis $\{ g_k \}$ are given by the column vector$$(x_1 y_1,\dots,x_1 y_m,x_2 y_1,\dots,x_2 y_m,\dots,x_n y_1,\dots,x_n y_m)^T.$$Then run this vector through the linear map $\tilde{B}:T\to\mathbf{R}$ whose matrixis the row vector$$(B_{11},\dots,B_{1m},B_{21},\dots,B_{2m},\dots,B_{n1},\dots,B_{nm}),$$where $B_{ij}=B(e_i,f_j)$.This gives, by construction, $\sum\sum B_{ij} x_i y_j=B(x,y)$. We'll call the space $T$ the tensor product of the vector spaces $V$ and $W$and denote it by $T=V \otimes W$;it is “uniquely defined up to isomorphism”,and its elements are called tensors .The vector in $T$ that we formed from $x\in V$ and $y\in W$ in the first stage abovewill be denoted $x \otimes y$;it's a “bilinear mixture” of $x$ and $y$ which doesn't allow us toreconstruct $x$ and $y$ individually,but still contains exactly all the information neededin order to compute $B(x,y)$ for any bilinear map $B$;we have $B(x,y)=\tilde{B}(x \otimes y)$.This is the “universal property”; any bilinear map $B$ from $V \times W$can be computed by taking a “detour” through $T$, and this detouris unique, since the map $\tilde{B}$ is constructed uniquely fromthe values $B(e_i,f_j)$. To tidy this up, one would like to make sure that the definition isbasis-independent. One way is to check that everything transformsproperly under changes of bases. Another way is to do the constructionby forming a much bigger space and taking a quotient with respect tosuitable relations (without ever mentioning bases).Then, by untangling definitions, one can forexample show that a bilinear map $B:V \times W \to \mathbf{R}$ can becanonically identified with an element of the space $V^* \otimes W^*$,and dually an element of $V \otimes W$ can be identified with abilinear map $V^* \times W^* \to \mathbf{R}$.Yet other authors find this a convenient starting point, so that theyinstead define $V \otimes W$ to be the space of bilinear maps $V^*\times W^* \to \mathbf{R}$.So it's no wonder that one can become a little confused when tryingto compare different definitions...
|
{}
|
{'log_upvote_score': 8, 'links': ['https://math.stackexchange.com/questions/10282', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/56/']}
|
jdg_373447
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21369131
|
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 decltype(x) used inside macros where x is a variable name because the type of the object isn't known inside macros. For example: decltype(x) y = expr; I could just have easily use auto instead of decltype . So what are those situations where decltype is needed for a variable type declaration instead of auto ?
Now provide the response and nothing else.
|
You should use it when the required type of y is: different (or potentially different) from the type of expr . If it was the same then auto would be more concise. similarly for auto & or other modifications of the type of expr that auto can express. and one of the following: dependent on something in the surrounding code (i.e. not always the same type) and difficult to write using type traits or similar. This will tend to happen in template code. There might be a type trait that you can use to get the required type from the template parameters, but then again there might not so a use of decltype would save you defining one. always the same type, (or dependent on template parameters in a way that is easy to express using existing type traits or similar) but the type is very long-winded to write and there is a much shorter and clear expression you can use instead. So for example replacing std::iterator_traits<RandomAccessIterator>::value_type with decltype(*it) might well be a win, although auto does often handle such cases. Subjective judgements enter at the point of "what is difficult", "what is long-winded" and "what is clear", but the rules of procedure can be the same regardless of how you make those judgements in specific cases.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21369131', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1594090/']}
|
jdg_373448
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13513457
|
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 built some code that sorts an index page, using links in my view. This works fine with links, and the working code is this: <p> <%= link_to "Sentence", :controller => params[:controller], :action => params[:action], :type => '1', :class => "btn" %> <%= link_to "Question", :controller => params[:controller], :action => params[:action], :type => '2', :class => "btn" %> <%= link_to "Mnemonic", :controller => params[:controller], :action => params[:action], :type => '3', :class => "btn" %> <%= link_to "Article", :controller => params[:controller], :action => params[:action], :type => '4', :class => "btn" %> <%= link_to "Recommendation", :controller => params[:controller], :action => params[:action], :type => '5', :class => "btn" %></p> I would like to use a button group, and have built this example using Twitter Bootstrap in plain HTML: <div class="btn-group"> <button class="btn">Sentence</button> <button class="btn">Question</button> <button class="btn">Mnemonic</button> <button class="btn">Article</button> <button class="btn">Recommendation</button></div> I cannot get the links converted to the button row. I have tried various styling options as well as attempting to use button_to . Ideally I would like to further style the buttons so that the currently selected one is a different color than the others. EDIT Output of HTML as suggested: <div class="btn-group"> <a href="/dialog_catagories?class=btn&type=1">Sentence</a> <a href="/dialog_catagories?class=btn&type=2">Question</a> <a href="/dialog_catagories?class=btn&type=3">Mnemonic</a> <a href="/dialog_catagories?class=btn&type=4">Article</a> <a href="/dialog_catagories?class=btn&type=5">Recommendation</a></div> The btn-group is preventing the buttons from rendering on the page for some reason, even though it is in the html. EDIT 2 HTML code as per Varun's answer: <div class="btn-group"> <a href="/dialog_catagories?html%5Bclass%5D=btn&type=1">Sentence</a> <a href="/dialog_catagories?html%5Bclass%5D=btn&type=2">Question</a> <a href="/dialog_catagories?html%5Bclass%5D=btn&type=3">Mnemonic</a> <a href="/dialog_catagories?html%5Bclass%5D=btn&type=4">Article</a> <a href="/dialog_catagories?html%5Bclass%5D=btn&type=5">Recommendation</a></div> SOLUTION @Varun's suggested answer worked in the end: <div class="btn-group"> <%= link_to "Sentence", "?type=1", :class => "btn" %> <%= link_to "Question", "?type=2", :class => "btn" %></div> I am a bit unclear how the functionality is still working, as the following is not being explicitly passed: :controller => params[:controller], :action => params[:action] But it is working fine. Thank you.
Now provide the response and nothing else.
|
Try this: <div class="btn-group"> <%= link_to "Sentence", :controller => params[:controller], :action => params[:action], :type => '1', :html => { :class => "btn" } %> <%= link_to "Question", :controller => params[:controller], :action => params[:action], :type => '2', :html => { :class => "btn" } %> <%= link_to "Mnemonic", :controller => params[:controller], :action => params[:action], :type => '3', :html => { :class => "btn" } %> <%= link_to "Article", :controller => params[:controller], :action => params[:action], :type => '4', :html => { :class => "btn" } %> <%= link_to "Recommendation", :controller => params[:controller], :action => params[:action], :type => '5', :html => { :class => "btn" } %></div> Edit Try this: <div class="btn-group"> <%= link_to "Sentence", "?type=1", :class => "btn" %> <%= link_to "Question", "?type=2", :class => "btn" %></div>
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13513457', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/993592/']}
|
jdg_373449
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
51501405
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to get META information of All the tables present in my schema dynamically , Meta infos are such as table , entity ,column name etc. I have followed the following tutorial https://vladmihalcea.com/how-to-get-the-entity-mapping-to-database-table-binding-metadata-from-hibernate/ as said in the above link i have created the Integrator called MetadataExtractorIntegrator.java package com.test.ttv;import org.hibernate.boot.Metadata;import org.hibernate.boot.model.relational.Database;import org.hibernate.engine.spi.SessionFactoryImplementor;import org.hibernate.service.spi.SessionFactoryServiceRegistry;public class MetadataExtractorIntegrator implements org.hibernate.integrator.spi.Integrator { public static final MetadataExtractorIntegrator INSTANCE = new MetadataExtractorIntegrator(); private Database database; private Metadata metadata; public Database getDatabase() { return database; } public Metadata getMetadata() { return metadata; } @Override public void integrate( Metadata metadata, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) { this.database = metadata.getDatabase(); this.metadata = metadata; } @Override public void disintegrate( SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) { }} And trying to register it in my application by following config application.yml jpa: properties: hibernate.integrator_provider: com.test.ttv.MetadataExtractorIntegrator And i am getting the following Exception while Starting the build Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to org.hibernate.jpa.boot.spi.IntegratorProvider More StackTrace org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.lang.ClassCastException: java.lang.String cannot be cast to org.hibernate.jpa.boot.spi.IntegratorProvider at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1710) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE] at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE] at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1085) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:858) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.0.4.RELEASE.jar:5.0.4.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:752) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:388) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1246) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1234) [spring-boot-2.0.0.RELEASE.jar:2.0.0.RELEASE] at testtest(Test.java:31) [main/:na]Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to org.hibernate.jpa.boot.spi.IntegratorProvider at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.buildBootstrapServiceRegistry(EntityManagerFactoryBuilderImpl.java:339) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final] at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:196) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final] at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:164) ~[hibernate-core-5.2.14.Final.jar:5.2.14.Final] at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:51) ~[spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE] at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE] at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:388) ~[spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE] at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) ~[spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE] at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.0.4.RELEASE.jar:5.0.4.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1769) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1706) ~[spring-beans-5.0.4.RELEASE.jar:5.0.4.RELEASE] ... 16 common frames omitted Could anyone help me to solve this issue?? Thanks
Now provide the response and nothing else.
|
In Spring Boot, spring.jpa.properties points to a Map<String, String> , so it can only contain String values. However in Hibernate, when the EntityManagerFactoryBuilderImpl reads hibernate.integrator_provider it expects to find an instance of IntegratorProvider and not a Class name, hence the exception. You can however add a bean that implements HibernatePropertiesCustomizer to add the IntegrationProvider instance to the Hibernate properties: @Componentpublic class HibernateConfig implements HibernatePropertiesCustomizer { @Override public void customize(Map<String, Object> hibernateProperties) { hibernateProperties.put("hibernate.integrator_provider", (IntegratorProvider) () -> Collections.singletonList(MetadataExtractorIntegrator.INSTANCE)); }} I have created a working example in this repository .
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51501405', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4553898/']}
|
jdg_373450
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
48222
|
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Can a planet that has absolutely no atmosphere be orbited by a spacecraft at extremely low "altitudes" (if you'd even call it altitude at such a low orbit. For instance, if this planet's highest peak was 1km above sea level , could a spacecraft orbit this planet at 1.75km altitude? For sake of discussion the spacecraft can reach whatever speed necessary to stay in that orbit around that planet- regardless the size/radius. Notes 1.) When I say no atmosphere- I mean literally like absolutely no atmosphere. Not even 1 single particle of air or gas of any type or element. Absolutely nothing that can cause any drag or force on the spacecraft 2.)As I mentioned earlier- lets just assume the speeds needed to orbit planet are attainable no matter how large or small this planet would be. My guess: Im no astrophysics guru but from what I've learned through my non-professional astronomy and astrophysics obsession is that, yes, it can be orbited. But never mind what i think. I'd love for someone with he knowledge to tell me what are the facts here.
Now provide the response and nothing else.
|
Yes, but. Firstly the 400km orbits of the ISS are already extremely low, in comparison to the 6400km radius of the Earth. See https://what-if.xkcd.com/58/ for pictures of orbits. So if you rephrase in terms of orbital radii it becomes "We can orbit at 6800km. Can we orbit at 6401.75km?" And the answer is certainly "yes" However take care, because although you said the highest mountain was 1km, is the planet spherical. A rotating planet won't be spherical, because an equilibrium shape will be an oblate spheroid. The Earth's radius is 20km more at the equator than at the pole. If you are orbiting an planet like the Earth, but with no atmosphere, and your altitude is 750m above Mt Everest, you might get a surprise when you pass over the Andes, as Mount Chimborazo has a peak that is more than 2000m further from the center of the Earth. But let's say you're being careful about that. Then you will be able to orbit. However there is very little margin of error. Planets don't have a perfectly even gravitational field. Mountains, mantle plumes, mass-concentrations all distort the orbit. And in the case of Earth, your orbit will also be perturbed by lunar and solar tides. Now if the gravity of a mantle plume only has to change your velocity by a very small amount to lower your orbit by 750 m (which is only about 1 part in 8000) and crash your space craft. So, while arbitrary low orbits are possible in principle, you wouldn't plan to orbit a planet with only a few meters of leeway. What this also means is that you'd be very surprised to find a moon with such a low orbit. Such a moon would probably not stay in orbit for long.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://astronomy.stackexchange.com/questions/48222', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/41196/']}
|
jdg_373451
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35876947
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to create a 2D array of Uint64s in Julia 0.4. This worked in 0.3: s = 128a = zeros(Uint64, s, s)::Array{Uint64,2} It continues to compile but gives me the notice WARNING: Base.Uint64 is deprecated, use UInt64 instead. I don't know what this message means. I've tried googling the error message but haven't found anything helpful. What is an equivalent line of code that will not produce any warnings?
Now provide the response and nothing else.
|
Assuming you don't want window chrome, you can accomplish this by removing the frame around Electron and filling the rest in with html/css/js. I wrote an article that achieves what you are looking for on my blog here: http://mylifeforthecode.github.io/making-the-electron-shell-as-pretty-as-the-visual-studio-shell/ . Code to get you started is also hosted here: https://github.com/srakowski/ElectronLikeVS To summarize, you need to pass frame: false when you create the BrowserWindow: mainWindow = new BrowserWindow({width: 800, height: 600, frame: false}); Then create and add control buttons for your title bar: <div id="title-bar"> <div id="title">My Life For The Code</div> <div id="title-bar-btns"> <button id="min-btn">-</button> <button id="max-btn">+</button> <button id="close-btn">x</button> </div> </div> Bind in the max/min/close functions in js: (function () { var remote = require('remote'); var BrowserWindow = remote.require('browser-window'); function init() { document.getElementById("min-btn").addEventListener("click", function (e) { var window = BrowserWindow.getFocusedWindow(); window.minimize(); }); document.getElementById("max-btn").addEventListener("click", function (e) { var window = BrowserWindow.getFocusedWindow(); window.maximize(); }); document.getElementById("close-btn").addEventListener("click", function (e) { var window = BrowserWindow.getFocusedWindow(); window.close(); }); }; document.onreadystatechange = function () { if (document.readyState == "complete") { init(); } };})(); Styling the window can be tricky, but the key use to use special properties from webkit. Here is some minimal CSS: body { padding: 0px; margin: 0px; }#title-bar { -webkit-app-region: drag; height: 24px; background-color: darkviolet; padding: none; margin: 0px; }#title { position: fixed; top: 0px; left: 6px; }#title-bar-btns { -webkit-app-region: no-drag; position: fixed; top: 0px; right: 6px;} Note that these are important: -webkit-app-region: drag;-webkit-app-region: no-drag; -webkit-app-region: drag on your 'title bar' region will make it so that you can drag it around as is common with windows. The no-drag is applied to the buttons so that they do not cause dragging.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/35876947', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1086127/']}
|
jdg_373452
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8901445
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I test the onreadystatechange on XMLHttpRequest or pure Javascript AJAX without jQuery? I'm doing this because I'm developing Firefox extension. I guess I have to use spies, but couldn't figure out how because my ajax won't return anything. submit : function() { var url = window.arguments[0]; var request = new XMLHttpRequest(); request.open("POST", 'http://'+this.host+'/doSomething', true); request.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); request.send("param="+param+"&emotions="+this.getParams()); request.onreadystatechange = function() { if(this.readyState == 4) { // alert(this.responseText); } }; }
Now provide the response and nothing else.
|
And what about this one? beforeEach(function() { // spyOn(XMLHttpRequest.prototype, 'open').andCallThrough(); // Jasmine 1.x spyOn(XMLHttpRequest.prototype, 'open').and.callThrough(); // Jasmine 2.x spyOn(XMLHttpRequest.prototype, 'send');});...it("should call proper YQL! API", function() { podcast.load_feed('http://www.faif.us/feeds/cast-ogg/'); expect(XMLHttpRequest.prototype.open).toHaveBeenCalled();}); Pure Jasmine without need to use any external library.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8901445', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/635162/']}
|
jdg_373453
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
101737
|
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 $E$ be a vector bundle over $M$ and denote by $\mathcal{A}^k(E)$ the space of sections of $\Lambda^k (TM)^* \otimes E$, i.e. the space $k$-forms with values in $E$. A connection $\nabla:\mathcal{A}^0(E) \to \mathcal{A}^1(E)$ extends to a map $\nabla:\mathcal{A}^k(E) \to \mathcal{A}^{k+1}(E)$ by setting $\nabla(\alpha \otimes s)= d \alpha \otimes s + (-1)^k \alpha \wedge\nabla s$ and we can define the curvature of $\nabla$ as the composition $F_\nabla=\nabla \circ \nabla: \mathcal{A}^0(E) \to \mathcal{A}^2(E)$. From the Leibniz rule one can see that $F_{\nabla}(fs) = f F_{\nabla}(s)$ and therefore we can view $F_\nabla$ as an element of $\mathcal{A}^2(\text{End}(E))$ ($F_\nabla$ evaluated at a pair of tangent vectors is the endomorphism $s \mapsto F_\nabla(X,Y)(s)$. My question is whether the formula$F_{\nabla}(X,Y) = \nabla_X \nabla_Y - \nabla_Y \nabla_Y - \nabla_{[X,Y]}$ holds true. I could prove it when $E=TM$ and $\nabla$ is a torsion free connection (because in that case we have a formula relating the exterior derivative with $\nabla$) but I don't know how to deal with the general case.
Now provide the response and nothing else.
|
Short answer: the formula is true. Long answer: see below for the calculation. Choose local coordinates $(x^1, \ldots, x^n)$ and a local frame field $(e_1, \ldots, e_r)$ for $E$, both of these over an open neighbourhood $U$, and let$\newcommand{\Tud}[3]{{#1}^{#2}_{\phantom{#2}{#3}}}$$$\nabla e_\mu = \Tud{\omega}{\nu}{\mu} \otimes e_\nu$$for some $\Tud{\omega}{\nu}{\mu} \in \Omega^1(U)$. (I am using the summation convention for repeated indices.) Let $\Tud{\Omega}{\nu}{\mu} \in \Omega^2(U)$ be such that$$\nabla \nabla e_\mu = \Tud{\Omega}{\nu}{\mu} \otimes e_\nu$$Now, by the Leibniz rule, we have$$\nabla \nabla e_\mu = \mathrm{d}\Tud{\omega}{\nu}{\mu} \otimes e_\nu - \Tud{\omega}{\nu}{\mu} \wedge \Tud{\omega}{\rho}{\nu} \otimes e_\rho$$thus,$$\Tud{\Omega}{\nu}{\mu} = \mathrm{d}\Tud{\omega}{\nu}{\mu} + \Tud{\omega}{\nu}{\rho} \wedge \Tud{\omega}{\rho}{\mu}$$ Since$$\nabla (W^\mu e_\mu) = \mathrm{d} W^\mu \otimes e_\mu + W^\mu \Tud{\omega}{\nu}{\mu} \otimes e_\nu$$we have$$\nabla \nabla (W^\mu e_\mu) = \mathrm{d} W^\mu \wedge \Tud{\omega}{\nu}{\mu} \otimes e_\nu + W^\mu \, \mathrm{d} \Tud{\omega}{\nu}{\mu} \otimes e_\nu - \mathrm{d}W^\mu \wedge \Tud{\omega}{\nu}{\mu} \otimes e_\nu - W^\mu \Tud{\omega}{\nu}{\mu} \wedge \Tud{\omega}{\rho}{\nu} \otimes e_\rho$$thus, $\nabla \nabla$ is indeed $C^\infty(U)$-linear, with$$\nabla \nabla (W^\mu e_\mu) = W^\mu \Tud{\Omega}{\nu}{\mu} \otimes e_\nu = W^\mu \nabla \nabla e_\mu$$This means we only need to check the formula for the frame field instead of arbitrary sections of $E$. Now, observe that, if $X$ and $Y$ are vector fields,$$\begin{align}\nabla_X \nabla_Y e_\mu = \nabla_X ( \langle \Tud{\omega}{\nu}{\mu} , Y \rangle e_\nu) & = \langle \mathrm{d} \langle \Tud{\omega}{\nu}{\mu} , Y \rangle, X \rangle e_\nu + \langle \Tud{\omega}{\nu}{\mu} , Y \rangle \langle \Tud{\omega}{\rho}{\nu} , X \rangle e_\rho \\\nabla_Y \nabla_X e_\mu = \nabla_Y ( \langle \Tud{\omega}{\nu}{\mu} , Y \rangle e_\nu) & = \langle \mathrm{d} \langle \Tud{\omega}{\nu}{\mu} , X \rangle, Y \rangle e_\nu + \langle \Tud{\omega}{\nu}{\mu} , X \rangle \langle \Tud{\omega}{\rho}{\nu} , Y \rangle e_\rho \\\nabla_{[X, Y]} e_\mu & = \langle \Tud{\omega}{\nu}{\mu} , [X, Y] \rangle e_\nu\end{align}$$where I have written $\langle - , - \rangle$ for the canonical pairing of a 1-form and a vector field. So we have$$\begin{align}(\nabla_X \nabla_Y - \nabla_Y \nabla_X - \nabla_{[X, Y]}) e_\mu & = (\langle \mathrm{d} \langle \Tud{\omega}{\nu}{\mu} , Y \rangle, X \rangle - \langle \mathrm{d} \langle \Tud{\omega}{\nu}{\mu} , X \rangle, Y \rangle - \langle \Tud{\omega}{\nu}{\mu} , [X, Y] \rangle) \, e_\nu \\& \phantom{=} + (\langle \Tud{\omega}{\nu}{\rho} , X \rangle \langle \Tud{\omega}{\rho}{\mu} , Y \rangle - \langle \Tud{\omega}{\nu}{\rho} , Y \rangle \langle \Tud{\omega}{\rho}{\mu} , X \rangle) \, e_\nu\end{align}$$while on the other hand$$\Tud{\Omega}{\nu}{\mu} (X, Y) = \langle \Tud{\Omega}{\nu}{\mu} , X \wedge Y \rangle = \langle \mathrm{d}\Tud{\omega}{\nu}{\mu} , X \wedge Y \rangle + \langle \Tud{\omega}{\nu}{\rho} \wedge \Tud{\omega}{\rho}{\mu} , X \wedge Y \rangle$$but by Cartan's formula for the exterior derivative$$\langle \mathrm{d}\Tud{\omega}{\nu}{\mu} , X \wedge Y \rangle = \langle \mathrm{d} \langle \Tud{\omega}{\nu}{\mu} , Y \rangle , X \rangle - \langle \mathrm{d} \langle \Tud{\omega}{\nu}{\mu} , X \rangle , Y \rangle - \langle \Tud{\omega}{\nu}{\mu} , [X, Y] \rangle$$Now, by definition$$\langle \Tud{\omega}{\nu}{\rho} \wedge \Tud{\omega}{\rho}{\mu} , X \wedge Y \rangle = \langle \Tud{\omega}{\nu}{\rho} , X \rangle \langle \Tud{\omega}{\rho}{\mu}, Y \rangle - \langle \Tud{\omega}{\nu}{\rho} , Y \rangle \langle \Tud{\omega}{\rho}{\mu}, X \rangle $$and so$$\Tud{\Omega}{\nu}{\mu} (X, Y) e_\nu = (\nabla_X \nabla_Y - \nabla_Y \nabla_X - \nabla_{[X, Y]}) e_\mu $$which is exactly what we want.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/101737', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/12501/']}
|
jdg_373454
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52994
|
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:
Similar to this thread and this one , I want to show an agenda view with all items marked as "DONE" in the last two weeks, but without the lines Clocked: (1:00) DONE Some task (because for that I only care about the totals and use a clock-report dynamic block). I would also like to restrict to second-level items only. I tried this code and succeeded in restricting to second-level headings only: (add-to-list 'org-agenda-custom-commands '("W" "Weekly review" agenda "" ((org-agenda-span 'week) (org-agenda-start-on-weekday 1) (org-agenda-start-with-log-mode nil) (org-agenda-skip-function '(org-agenda-skip-entry-if 'notregexp "^\\*\\* DONE ")) ))) If I set org-agenda-start-with-log-mode to t , then Clocked: ... lines show, e.g.: Monday 30 September 2019 W40 gtd: 10:49-10:59 Clocked: (0:10) DONE some task gtd: 10:50...... Closed: DONE Some other task If I set it to nil , then Closed: ... lines do not show. Also, if I set org-agenda-span to 14, to include the past 14 days, it shows 14 days starting from today. How can I include only Closed: ... lines, and list tasks in the past?
Now provide the response and nothing else.
|
To include only Closed: ... use: (org-agenda-start-with-log-mode '(closed)) To show the past 14 days offset the start day: (org-agenda-start-day "-14d") This results in: (add-to-list 'org-agenda-custom-commands '("W" "Weekly review" agenda "" ((org-agenda-start-day "-14d") (org-agenda-span 14) (org-agenda-start-on-weekday 1) (org-agenda-start-with-log-mode '(closed)) (org-agenda-skip-function '(org-agenda-skip-entry-if 'notregexp "^\\*\\* DONE "))))) You might also want to include archived items with: (org-agenda-archives-mode t) Note:Use C-h v to describe a variable like org-agenda-start-with-log-mode to see the possibilities or M-x custmoize-variable to customize it (this shows all possibilities in the customize interface).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/52994', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/19424/']}
|
jdg_373455
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2915
|
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:
There are a handful of Aramaic passages in the Bible; notably in Daniel and Ezra. Since the writing system of these two was the same, how are the Aramaic sections identified?
Now provide the response and nothing else.
|
The two languages are related (both are Northwest Semtic languages) and eventually shared a script. Hebrew, prior to the exile used its own script called Paleo-Hebrew. It was still used afterwards in isolated places and instances, but what we now call Aramaic Square replaced it for the most part. Though they share many common words and large pieces of grammar (noun states are the same and verbal stems are similar), there are differences. It is these differences in grammar that allow us to tell them apart: The definite article differs between the two languages. In Hebrew, the definite article is prefixed to the noun as a he . In Aramaic, the definite article is attached to the end of the noun as an aleph . Aramaic has a particle "diy" that can be used in at least 5 ways (Hebrew does not use this until postexilic times and even then rarely). To mark the genitive - Daniel 4:23 "roots of the tree." As a particle of relation (who, which, that) - Dan 2:24 " whom the king had appointed." As the conjunction "as"- Dan 4:23 "And as it was commanded...". To function as opening quotation marks - Dan 2:24 "Said to him, 'I found...". As an idiom - Dan 2:29 " whatever will be". Aramaic uses "l" in 3 ways. As a preposition, "to, for" - Dan 3:20 " to the furnance." To mark the infinitive - Dan 3:20 "ordered to bind ...". As the mark of the accusative - Dan 3:20 "to bind Shadrack ." (Yes, it gets a lot of use in that verse.) Aramaic can use "diy" and "l" to mark that part of a construct chain is indefinite (in Biblical Hebrew, such a chain must be either all definite or all indefinite). Dan 6:15 "Remember, O King, that a law of the Medes and Persians.. does not change." The "a" comes from law being indefinite even though Medes and Persians is not (by definition, even without the article). However, the "l" prefixed to Medes tells us that the first part is not definite. The participle can be used in Aramaic in ways that Hebrew does not. With immediate future meaning "about to" Dan 4:22 " About to be driven." As a 'past tense' — very common in the phrase "answered and said." There are letter changes. Hebrew words with "sh" will often appear in Aramaic spelt with a "t." For example, Daniel 5:25 contains "mene, mene, teqel upharsin." "teqel" is the Aramaic spelling of "sheqel." Aramaic did not experience the Canaanite vowel shift from a to o that Hebrew did.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://hermeneutics.stackexchange.com/questions/2915', 'https://hermeneutics.stackexchange.com', 'https://hermeneutics.stackexchange.com/users/331/']}
|
jdg_373456
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
405041
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Usually in logistic regression, we fit a model and get some predictions on the training set. We then cross-validate on those training predictions (something like here ) and decide the optimal threshold value based on something like the ROC curve. Why don't we incorporate cross-validation of the threshold INTO the actual model, and train the whole thing end-to-end?
Now provide the response and nothing else.
|
A threshold isn't trained with the model because logistic regression isn't a classifier (cf., Why isn't Logistic Regression called Logistic Classification? ). It is a model to estimate the parameter, $p$ , that governs the behavior of the Bernoulli distribution. That is, you are assuming that the response distribution, conditional on the covariates, is Bernoulli, and so you want to estimate how the parameter that controls that variable changes as a function of the covariates. It is a direct probability model only . Of course, it can be used as a classifier subsequently, and sometimes is in certain contexts, but it is still a probability model.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/405041', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/85697/']}
|
jdg_373457
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50160377
|
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 this code from W3Schools for sorting all table rows by clicking on column header. As expected, this orders all rows by that col value. I'm shure this has already been answered somewere but I't has been difficult for me to filter serarch results to find a similar way (hopefully in pure javascript) of sorting columns by clicking on a first column row. That should order all columns by that clicked row values. I'm hoping for some combined method that could order by column AND by row depending on user click, but just a Sort by Row method would be OK. Thanks in advace! Expected behavior Unsorted table: <table id="myTable"> <tbody> <tr> <th onclick="sortTableRows(0)">Name</th> <th onclick="sortTableRows(1)">Col 1</th> <th onclick="sortTableRows(2)">Col 2</th> <th onclick="sortTableRows(3)">Col 3</th> </tr> <tr> <td onclick="sortTableCols(1)">Alan Brado</td> <td>2</td> <td>3</td> <td>1</td> </tr> <tr> <td onclick="sortTableCols(2)">Kevin Chuca</td> <td>1</td> <td>3</td> <td>2</td> </tr> <tr> <td onclick="sortTableCols(3)">Pamela Chu</td> <td>3</td> <td>2</td> <td>1</td> </tr> </tbody></table> NORMAL : Sorted table by COLUMN (Col 1): <table id="myTable"> <tbody> <tr> <th onclick="sortTableRows(0)">Name</th> <th onclick="sortTableRows(1)">*Col 1*</th> <th onclick="sortTableRows(2)">Col 2</th> <th onclick="sortTableRows(3)">Col 3</th> </tr> <tr> <td onclick="sortTableCols(1)">Kevin Chuca</td> <td>1</td> <td>3</td> <td>2</td> </tr> <tr> <td onclick="sortTableCols(1)">Alan Brado</td> <td>2</td> <td>3</td> <td>1</td> </tr> <tr> <td onclick="sortTableCols(3)">Pamela Chu</td> <td>3</td> <td>2</td> <td>1</td> </tr> </tbody></table> DESIRED : Sorted table by ROW (Alan Brado): <table id="myTable"> <tbody> <tr> <th onclick="sortTableRows(0)">Name</th> <th onclick="sortTableRows(1)">Col 3</th> <th onclick="sortTableRows(2)">Col 1</th> <th onclick="sortTableRows(3)">Col 2</th> </tr> <tr> <td onclick="sortTableCols(1)">*Alan Brado*</td> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td onclick="sortTableCols(2)">Kevin Chuca</td> <td>2</td> <td>1</td> <td>3</td> </tr> <tr> <td onclick="sortTableCols(3)">Pamela Chu</td> <td>1</td> <td>3</td> <td>2</td> </tr> </tbody></table> And here is my snippet: function sortTableRows(n) { var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0; table = document.getElementById("myTable"); switching = true; dir = "asc"; while (switching) { switching = false; rows = table.getElementsByTagName("TR"); for (i = 1; i < (rows.length - 1); i++) { shouldSwitch = false; x = rows[i].getElementsByTagName("TD")[n]; y = rows[i + 1].getElementsByTagName("TD")[n]; if (dir == "asc") { if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) { shouldSwitch= true; break; } } else if (dir == "desc") { if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) { shouldSwitch= true; break; } } } if (shouldSwitch) { rows[i].parentNode.insertBefore(rows[i + 1], rows[i]); switching = true; switchcount ++; } else { if (switchcount == 0 && dir == "asc") { dir = "desc"; switching = true; } } }}function sortTableCols(n) { alert("This should sort cols by row #"+n+" values");} /* Just for beauty */ #myTable { border: none; } #myTable th { cursor: pointer; width: 5%; border: none; background-color: #e0e0e0; } #myTable tr td { border: none; border-bottom: 1px solid #aaa; text-align: center; } #myTable tr td:first-child { cursor: pointer; background-color: #e0e0e0; border-bottom: 1px solid #aaa; text-align: center; } #myTable tr:last-child td { border: none; } <table id="myTable"> <tbody> <tr> <th onclick="sortTableRows(0)">Name</th> <th onclick="sortTableRows(1)">Col 1</th> <th onclick="sortTableRows(2)">Col 2</th> <th onclick="sortTableRows(3)">Col 3</th> </tr> <tr> <td onclick="sortTableCols(1)">Alan Brado</td> <td>2</td> <td>3</td> <td>1</td> </tr> <tr> <td onclick="sortTableCols(2)">Kevin Chuca</td> <td>1</td> <td>3</td> <td>2</td> </tr> <tr> <td onclick="sortTableCols(3)">Pamela Chu</td> <td>3</td> <td>2</td> <td>1</td> </tr> </tbody></table>
Now provide the response and nothing else.
|
Your SizedBox will essentially be ignored right now, because you don't tell flutter where to render it within its parent. So you need to wrap it in a center (or other alignment). You also need to use a ClipRect to wrap your SizedBox, so that the BackdropFilter effect is clipped to that size. import 'dart:ui' as ui;import 'package:flutter/material.dart';/// This is just so that you can copy/paste this and have it run.void main() => runApp(new MyApp());class MyApp extends StatefulWidget { @override State<StatefulWidget> createState() => MyAppState();}class MyAppState extends State<MyApp> { @override Widget build(BuildContext context) { return new MaterialApp( title: 'Flutter Demo', home: new Container( decoration: new BoxDecoration( image: new DecorationImage( image: new NetworkImage( "https://images.pexels.com/photos/668196/pexels-photo-668196.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"), fit: BoxFit.cover)), child: new Center( child: new ClipRect( child: new SizedBox( height: 200.0, width: 200.0, child: new BackdropFilter( filter: new ui.ImageFilter.blur( sigmaX: 5.0, sigmaY: 5.0, ), child: new Center( child: new Text("Hi"), ), ), ), ), ), ), ); }} This is very tangential, but as to why the text is yellow and underlined, I believe that's the default if you don't specify a theme but I could be wrong about that.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50160377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3424892/']}
|
jdg_373458
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
242561
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $T_{n}(b)$ be the $n\times n$ Toeplitz matrix determined by the symbol$$ b(z)=\frac{1}{z}+\sum_{j=0}^{k}a_{j}z^{j}$$where $k\in\mathbb{N}$ and $a_{0},\dots,a_{k}\in\mathbb{R}$, $a_{k}\neq0$. That means $T_{n}(b)$ is the $n\times n$ left-top truncation of the banded Toeplitz Hessenberg matrix$$ T(b)=\begin{pmatrix} a_{0} & 1 & 0 & 0 & \\ a_{1} & a_{0} & 1 & 0 & \ddots \\ a_{2} & a_{1} & a_{0} & 1 & \ddots \\ a_{3} & a_{2} & a_{1} & a_{0} & 1 & \ddots \\ & \ddots & \ddots & \ddots & \ddots\\ \vdots & & \\ a_{k} \\ & \ddots \\ \end{pmatrix}\!.$$ Further, for $\lambda\in\mathbb{C}$, let $z_{0}(\lambda),\dots,z_{k}(\lambda)$ denote the roots of the equation $b(z)=\lambda$ (repeated according to their multiplicity) arranged such that$$|z_{0}(\lambda)|\leq|z_{1}(\lambda)|\leq\dots|z_{k}(\lambda)|.$$Schmidt and Spitzer (1960) showed that the set$$\Lambda(b):=\{\lambda\in\mathbb{C} \mid |z_{0}(\lambda)|=|z_{1}(\lambda)|\}$$coincides with the set of limit points of eigenvalues of matrices $T_{n}(b)$, as $n\to\infty$. There is a strong numerical evidence (I add 3 pictures approx. $\Lambda(b)$ below) that the set $\mathbb{C}\setminus\Lambda(b)$ is connected though all my attempts to prove this assertion failed. So my question is:$$\textbf{Is the set } \mathbb{C}\setminus\Lambda(b) \textbf{ connected?}$$ Relevant remarks: If $b$ is a general Laurent polynomial in $z$ (the Schmidt and Spitzer Theorem holds as well), the set $\mathbb{C}\setminus\Lambda(b)$ need not be connected as shown, e.g., in Proposition 5.2. in Böttcher, Grudsky, LAA, 2002. So the particular form of $b$ (or the Hessenberg form of $T(b)$), which we assume, is essential. If $a_{1}=\dots=a_{k-1}=0$, the set $\mathbb{C}\setminus\Lambda(b)$ is know to be connected. The set $\Lambda(b)$ is always connected, Ullman, Bull. AMS, 1967.
Now provide the response and nothing else.
|
By the Eilenberg-Watts theorem, the 2-group of invertible $(A, A)$-bimodules is naturally equivalent to the 2-group of automorphisms of $\text{Mod}(A)$. There is a natural map $$\text{Aut}(A) \to \pi_0 \text{Aut}(\text{Mod}(A))$$ whose kernel is the subgroup of inner automorphisms. So it suffices to find $A$ whose outer automorphism group is nonabelian, and these are plentiful. (This conclusion does not require the Eilenberg-Watts theorem to reach, but it's convenient to phrase things this way.) For a commutative example, we can let $A$ be a Galois extension of some field with nonabelian Galois group. For a noncommutative example we can let $A$ be a matrix algebra over such a thing.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/242561', 'https://mathoverflow.net', 'https://mathoverflow.net/users/56553/']}
|
jdg_373459
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28646629
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I take an array with days of week from the system (from NSDate , I think)? Until now, I can only take the current day, but I'd like to be able to take all weekdays in an array. If the first day of week is set to Monday, my array would look like: [ Mon, Tue, Wed... ] If the first day of week is Sunday, my array would look like: [Sun, Mon, Tue... ] Code: let dateNow = NSDate()let calendar = NSCalendar.currentCalendar()let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond | .CalendarUnitYear , fromDate: dateNow) /*This is the way how i take system time */ let format = NSDateFormatter()format.dateFormat = "EEE"stringDay = format.stringFromDate(dateNow)
Now provide the response and nothing else.
|
Try these properties : let fmt = NSDateFormatter()fmt.weekdaySymbols // -> ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]fmt.shortWeekdaySymbols // -> ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]fmt.veryShortWeekdaySymbols // -> ["S", "M", "T", "W", "T", "F", "S"]fmt.standaloneWeekdaySymbols // -> ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]fmt.shortStandaloneWeekdaySymbols // -> ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]fmt.veryShortStandaloneWeekdaySymbols // -> ["S", "M", "T", "W", "T", "F", "S"] It seems they always return Sun ... Sat array regardless .firstWeekday property of the .calendar . So, you have to rotate it manually. let firstWeekday = 2 // -> Mondayvar symbols = fmt.shortWeekdaySymbolssymbols = Array(symbols[firstWeekday-1..<symbols.count]) + symbols[0..<firstWeekday-1]// -> ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/28646629', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3771480/']}
|
jdg_373460
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7999259
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I perform the equivalent of the TFS 'Undo pending changes' in Git, on one or multiple files? That basically means to do these steps: Undo changes on disk Resetting any changes Git has discovered Getting the latest changes on the file from Git It would be good to know the differences (if there are any) in commands for doing this if you've (1) just changed it on disk, without adding it , but also when you've (2) done the add-command and for a bonus, (3) even when you have commit the change .
Now provide the response and nothing else.
|
For 1 and 2, all you need to do is: git stash -u #same effect as git reset --hard, but can be undone this will throw away any changes. Be careful if you use reset . Read up on manipulating the index and the permutations of the hard, soft and mixed options with the reset and checkout. The progit book explains this in detail: http://progit.org/2011/07/11/reset.html For 3, git reset --hard HEAD^ but would be better to issue a git stash -u before this - just in case you have pending changes. This will reset the current branch to the parent of the current commit. Look up "tree-ish" online. ^ and ~N after a reference will allow you to point to any reachable points in the history of that reference. To understand how history is tracked in git, "Git for computer scientists" explains the Directed Acyclic Graph well: http://eagain.net/articles/git-for-computer-scientists/ To get individual files from the state of the current commit (ie, throw away changes), you can use checkout git checkout HEAD -- <a list of files> If you issued the last reset command above in error, you're not in trouble. Git keeps track of where the branches used to point in the reflog. git reflog will list you the history. You can see in that output how to reference each, so: git reset --hard HEAD@{1} will reset the branch to where it used to be 1 change before. To add, if you want to wipe ignored files and untracked files, you can wipe with this: git clean -xdf
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7999259', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2429/']}
|
jdg_373461
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
34048691
|
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 an UPDATE query to make changes to my database. The updates I make to a particular cell in a row get inserted into the database. What's happening though is any blank date spaces that come after that cell get entered as 0000-00-00. For example, when I update the final review date this is what I should get Before UpdateDate Received Final Review Date Date Delivered Date Accepted 2015-03-03 After UpdateDate Received Final Review Date Date Delivered Date Accepted 2015-03-03 2015-08-05Instead I get this:Date Received Final Review Date Date Delivered Date Accepted 2015-03-03 2015-08-05 0000-00-00 0000-00-00 I've tried troubleshooting this but I'm fairly new to mysqli/php so I know I'm probably missing something simple. Any help resolving this would be appreciated. <?php$servername = "localhost";$username = "xxx";$password = "xxx";$dbname = "oldga740_SeniorProject";// Create connection$conn = new mysqli($servername, $username, $password, $dbname);// Check connectionif ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);}if (isset($_POST['update'])){$UpdateQuery = "UPDATE Projects SET Project='$_POST[project]', Client='$_POST[client]', LastName='$_POST[lastname]', DateReceived='$_POST[datereceived]', FinalReviewDate='$_POST[finalreviewdate]', DateDelivered='$_POST[datedelivered]', DateAccepted='$_POST[dateaccepted]' WHERE Project='$_POST[hidden]'";mysqli_query($conn, $UpdateQuery);};$sql = "SELECT * FROM Projects";$result = $conn->query($sql);echo "<table><tr><th>Project</th><th>Client</th><th>Last Name</th><th>Date Received</th><th>Final Review Date</th><th>Date Delivered</th><th>Date Accepted</th></tr>";while($record = mysqli_fetch_array($result)){if ($result->num_rows > 0){echo "<form action='mynewform.php' method='post'>";echo "<tr>"; echo "<td>" . "<input type='text' name='project' value='" . $record['Project'] . "' /></td>";echo "<td>" . "<input type='text' name='client' value='" . $record['Client'] . "'/></td>";echo "<td>" . "<input type='text' name='lastname' value='" . $record['LastName'] . "' /></td>";echo "<td>" . "<input type='text' name='datereceived' value='" . $record['DateReceived'] . "' /></td>";echo "<td>" . "<input type='text' name='finalreviewdate' value='" . $record['FinalReviewDate'] . "' /></td>";echo "<td>" . "<input type='text' name='datedelivered' value='" . $record['DateDelivered'] . "' /></td>";echo "<td>" . "<input type='text' name='dateaccepted' value='" . $record['DateAccepted'] . "' /></td>";echo "<td>" . "<input type='hidden' name='hidden' value='" . $record['Project'] . "' /></td>";echo "<td>" . "<input type='submit' name='update' value='update' /></td>";echo "<td>" . "<input type='submit' name='delete' value='delete' /></td>";echo "</tr>";echo "</form>";}}echo "</table>";?><?php $conn->close();?></body></html>
Now provide the response and nothing else.
|
Problem: The updates I make to a particular cell in a row get inserted into the database. What's happening though is any blank date spaces that come after that cell get entered as 0000-00-00. Solution: From your comments, The database already has those columns set to default as NULL . The only one that doesn't is the DateReceived column. I'm assuming that the Project , Client , LastName and DateReceived have already been set. So the solution is to insert NULL values if the user doesn't specify any data to update, like this: // your codeif (isset($_POST['update'])){ $project = trim($_POST['project']); $client = trim($_POST['client']); $lastname = trim($_POST['lastname']); $datereceived = $_POST['datereceived']; $UpdateQuery = "UPDATE Projects SET Project='{$project}', Client='{$client}', LastName='{$lastname}', DateReceived='{$datereceived}'"; if(empty($_POST['finalreviewdate'])){ $UpdateQuery .= ", FinalReviewDate = NULL"; }else{ $UpdateQuery .= ", FinalReviewDate = '{$_POST['finalreviewdate']}'"; } if(empty($_POST['datedelivered'])){ $UpdateQuery .= ", DateDelivered = NULL"; }else{ $UpdateQuery .= ", DateDelivered = '{$_POST['datedelivered']}'"; } if(empty($_POST['dateaccepted'])){ $UpdateQuery .= ", DateAccepted = NULL"; }else{ $UpdateQuery .= ", DateAccepted = '{$_POST['dateaccepted']}'"; } $UpdateQuery .= " WHERE Project='{$_POST['hidden']}'"; mysqli_query($conn, $UpdateQuery);};// your code Here's the complete code: ( tested ) <?php$servername = "localhost";$username = "xxx";$password = "xxx";$dbname = "oldga740_SeniorProject";// Create connection$conn = new mysqli($servername, $username, $password, $dbname);// Check connectionif ($conn->connect_error) { die("Connection failed: " . $conn->connect_error);}if (isset($_POST['update'])){ $project = trim($_POST['project']); $client = trim($_POST['client']); $lastname = trim($_POST['lastname']); $datereceived = $_POST['datereceived']; $UpdateQuery = "UPDATE Projects SET Project='{$project}', Client='{$client}', LastName='{$lastname}', DateReceived='{$datereceived}'"; if(empty($_POST['finalreviewdate'])){ $UpdateQuery .= ", FinalReviewDate = NULL"; }else{ $UpdateQuery .= ", FinalReviewDate = '{$_POST['finalreviewdate']}'"; } if(empty($_POST['datedelivered'])){ $UpdateQuery .= ", DateDelivered = NULL"; }else{ $UpdateQuery .= ", DateDelivered = '{$_POST['datedelivered']}'"; } if(empty($_POST['dateaccepted'])){ $UpdateQuery .= ", DateAccepted = NULL"; }else{ $UpdateQuery .= ", DateAccepted = '{$_POST['dateaccepted']}'"; } $UpdateQuery .= " WHERE Project='{$_POST['hidden']}'"; mysqli_query($conn, $UpdateQuery);};$sql = "SELECT * FROM Projects";$result = $conn->query($sql);echo "<table><tr><th>Project</th><th>Client</th><th>Last Name</th><th>Date Received</th><th>Final Review Date</th><th>Date Delivered</th><th>Date Accepted</th></tr>";while($record = mysqli_fetch_array($result)){if ($result->num_rows > 0){echo "<form action='process.php' method='post'>";echo "<tr>"; echo "<td>" . "<input type='text' name='project' value='" . $record['Project'] . "' /></td>";echo "<td>" . "<input type='text' name='client' value='" . $record['Client'] . "'/></td>";echo "<td>" . "<input type='text' name='lastname' value='" . $record['LastName'] . "' /></td>";echo "<td>" . "<input type='text' name='datereceived' value='" . $record['DateReceived'] . "' /></td>";echo "<td>" . "<input type='text' name='finalreviewdate' value='" . $record['FinalReviewDate'] . "' /></td>";echo "<td>" . "<input type='text' name='datedelivered' value='" . $record['DateDelivered'] . "' /></td>";echo "<td>" . "<input type='text' name='dateaccepted' value='" . $record['DateAccepted'] . "' /></td>";echo "<td>" . "<input type='hidden' name='hidden' value='" . $record['Project'] . "' /></td>";echo "<td>" . "<input type='submit' name='update' value='update' /></td>";echo "<td>" . "<input type='submit' name='delete' value='delete' /></td>";echo "</tr>";echo "</form>";}}echo "</table>";?><?php $conn->close();?></body></html>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34048691', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1871056/']}
|
jdg_373462
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4461749
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to set the column width of CellTable in GWT?
Now provide the response and nothing else.
|
EDIT: As of GWT 2.2 table.setWidth and table.setColumnWidth are supported table.setWidth("100%", true);table.setColumnWidth(nameColumn, 35.0, Unit.PCT);table.setColumnWidth(addressColumn, 65.0, Unit.PCT); I was able to extend the CellTable with a method that sets the widths programmatically. It's a bit of a hack since all the real methods that should do this are private to CellTable and it seems like GWT should provide this method directly, but it seems to work. public void setColumnWidths(List<Integer> widths){ TableElement tel = TableElement.as(getElement()); NodeList<Element> colgroups = tel.getElementsByTagName("colgroup"); if (colgroups.getLength() == 1) { TableColElement cge = TableColElement.as(colgroups.getItem(0)); NodeList<Element> cols = cge.getElementsByTagName("col"); for (int j = 0; j < widths.size(); j++) { TableColElement column = null; if (cols.getLength() > j) { column = TableColElement.as(cols.getItem(j)); } else { column = cge.appendChild(Document.get().createColElement()); } column.setWidth(widths.get(j)+"px"); } }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4461749', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/542270/']}
|
jdg_373463
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
47723193
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What are you trying to accomplish? I am trying to parse data from a json api. Paste the part of the code that shows the problem. package mainimport ( "encoding/json" "fmt" "io/ioutil" "net/http")type Structure struct { stuff []interface{}}func main() { url := "https://api.coinmarketcap.com/v1/ticker/?start=0&limit=100" response, err := http.Get(url) if err != nil { panic(err) } body, err := ioutil.ReadAll(response.Body) if err != nil { panic(err) } decoded := &Structure{} fmt.Println(url) err = json.Unmarshal(body, decoded) if err != nil { panic(err) } fmt.Println(decoded)} What do you expect the result to be? I expected for the code to return a list of interface objects. What is the actual result you get? I got an error: panic: json: cannot unmarshal array into Go value of type main.Structure
Now provide the response and nothing else.
|
The application is unmarshalling a JSON array to a struct. Unmarshal to a slice: var data []interface{} err = json.Unmarshal(body, &data) Consider unmarshalling to a slice of structs specific to the response data: type Tick struct { ID string Name string Symbol string Rank string Price_USD string ... and so on} var data []Tick err = json.Unmarshal(body, &data)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47723193', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8761914/']}
|
jdg_373464
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1908754
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If one wants to find the probability that a continuous random variable will fall within a range of $a \leq X \leq b$, based on a mean value $\mu$, and a deviation of $\sigma$, he would integrate the normal distribution function: $$\int^b_a \frac{e^{-\frac{(x-\mu)^2}{2\sigma^2}}}{\sigma\sqrt{2\pi}}dx$$ Since this is for continuous probability, is there an alternative to normal distribution for discrete probability? Suppose $\mu = 100$, and $\sigma = 50$. For discrete probability, I would try to use bounds close together to achieve a similar, but still not the completely desired outcome. However, the probability is very low: $$\int^{99.95}_{100.05}p(x)dx = 0.0008$$ The probability seems too low for this to be true, which suggests that a different model for discrete probability should exist.
Now provide the response and nothing else.
|
Your ultimate goal is not clear. Perhaps I can flounder around andmake some useful comments. For appropriate choices of $n$ and $\theta,$ the distribution $Binom(n, \theta)$ is approximately normal, especially if $n$ is large and $\theta$ is not too far from 1/2. The mean is $\mu = n\theta$ and the variance is $\sigma^2 = n\theta(1-\theta).$ Also, for large enough $\lambda,$ the distribution $Pois(\lambda)$ is nearly normal. The mean and variance are $\mu = \lambda$ and $\sigma^2 = \lambda.$However, the Poisson model may have less flexibility in matching what you want. Of course, to find the probability that a random variable taking integervalues lies in an interval $(a, b]$ you will add probabilities for integervalues in that interval, rather than evaluating an integral. For example, if $X \sim Binom(n = 100, \theta = 1/2),$ you have $\mu = 50$and $\sigma = 5.$ Perhaps you want $$P(48 < X \le 52) = P(X = 49) + P(X = 50) + P(X = 51) + P(X = 52)\\ = P(X \le 52)-P(X \le 48) = F_X(52) - F_X(48) = 0.3091736,$$where $F_X(\cdot)$ is the CDF of $X.$ If there are many integers in the desired interval, computation by handcan be tedious. In R statistical software dbinom denotes a binomial PDFand pbinom a binomial CDF. The probability above could be evaluated in R as shown below. [The last value is a normal approximation (with continuitycorrection), which is often accurate to a couple of decimal places.] sum(dbinom(49:52, 100, .5)) # adding terms of the PDF ## 0.3091736 diff(pbinom(c(48,52), 100, .5)) # subtracting two CDF values ## 0.3091736 diff(pnorm(c(48.5,52.5), 50, 5)) # normal approximation ## 0.3093739 The figure below shows several values of the PDF of $Binom(100, .5),$emphasizes the four probabilities required (heights of thick blue bars), and shows the approximatingnormal density curve. The normal approximation is the area beneaththe curve between the vertical green lines.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1908754', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/350817/']}
|
jdg_373465
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
481308
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using the circuit below to provide constant current to th LEDs. I request your suggestion on how to calculate the tolerance of current (minimum and maximum variation of set current) due to temperature alone. How to consider changes in Vbe to calculate the current?
Now provide the response and nothing else.
|
A couple of notes may help clear the air. Early Effect One of the problems of BJTs is something called the Early Effect. This is where the collector current depends on the collector to emitter voltage magnitude. However, this isn't a problem for this circuit for the following reasons: The feedback BJT (as you call it) doesn't have the problem because it's collector-to-emitter voltage magnitude is fixed by the topology itself. Since it is fixed and doesn't change (much), the Early Effect is effectively nullified for the feedback BJT. The drive BJT (as you call it) doesn't have the problem even though its collector-to-emitter voltage can vary quite widely, because the drive BJT isn't doing to the measuring. That's being done by the feedback BJT. The Early Effect upon the drive BJT is being measured by the feedback BJT and taken into account. So the Early Effect in the drive BJT is nullified because there is a different BJT doing the current measurement and it controls the drive BJT. The upshot of the above is that the circuit isn't affected much by the Early Effect. And that's good thing. Temperature Effect on Drive BJT Changes in the \$V_{_\text{BE}}\$ due to temperature on the drive BJT are automatically compensated by the feedback BJT, which is measuring the collector current of the drive BJT as it passes through the resistor between the feedback BJT's base and emitter. So if the drive BJT heats up (which is likely because most of the power dissipation that takes place in the drive BJT) and this affects its base-emitter voltage magnitude, that doesn't matter. The feedback BJT is measuring the current and will adjust its collector voltage, as needed. So temperature impacts on the drive BJT are also nullified in this circuit. Temperature Effect on Feedback BJT This is the real problem in this circuit. This is where temperature will have an impact. (This is also a reason to keep the feedback BJT thermally separated/isolated from the drive BJT.) Roughly speaking, the base-emitter voltage will vary by somewhere between \$-1.8\:\frac{\text{mV}}{^\circ\text{C}}\$ to about \$-2.4\:\frac{\text{mV}}{^\circ\text{C}}\$ . There are two basic parts to the equation. One is due to the thermal voltage due to temperature, \$V_T=\frac{k\,T}{q}\$ -- the sign here is positive, in the sense that increasing temperature increases the thermal voltage. The other is due to the changes in the saturation current (which is due to the Boltzmann factor, which is a statement about the ratio or relative probabilities of different states) in the BJT -- the sign here is negative, so that increasing temperature increases the saturation current, but since the saturation current is in the denominator this means the effect is negative and not positive on the base-emitter voltage magnitude.) As it turns out in practice, the negative sign of the Boltzmann factor dominates and wipes out the positive sign of the thermal voltage, so that the net effect is as stated earlier -- between \$-1.8\:\frac{\text{mV}}{^\circ\text{C}}\$ to about \$-2.4\:\frac{\text{mV}}{^\circ\text{C}}\$ . Summary Now, we could do a lot of mathematics and develop the sensitivity equation I mentioned earlier. And if you really want that, I'll post it here. But take it from me, the large scale version of it is not a simple equation. It's quite a nasty formula, actually. I'd be happy to develop it for you (I enjoy the process of showing how to proceed from a starting point in mathematics to arriving at a conclusion.) But it involves starting with the combination of several complex equations and then taking their elaborate derivatives. If you don't really need that, then let's bypass it for now. So this leaves us with the small-scale approach. If we know the magnitude of the base-emitter voltage at some temperature and can guess that it won't change by more than \$-1.8\:\frac{\text{mV}}{^\circ\text{C}}\le \frac{\Delta V_{_\text{BE}}}{^\circ \text{C}}\le -2.4\:\frac{\text{mV}}{^\circ\text{C}}\$ , then we can make a simple statement: $$\Delta I_{_\text{LED}}=\frac{ \frac{\Delta V_{_\text{BE}}}{^\circ \text{C}}}{R_{_\text{SENSE}}}\cdot \Delta T$$ So, if \$\frac{\Delta V_{_\text{BE}}}{^\circ \text{C}}=-2.2\:\frac{\text{mV}}{^\circ\text{C}}\$ and \$R_{_\text{SENSE}}=33\:\Omega\$ and \$\Delta T=15\:\text{K}\$ , then \$\Delta I_{_\text{LED}}=-1\:\text{mA}\$ . Assuming \$V_{_\text{BE}}\approx 680\:\text{mV}\$ prior to the temperature change, \$I_{_\text{LED}}\approx 21\:\text{mA}\$ . So a rise of \$\Delta T=15\:\text{K}\$ of the feedback BJT temperature would then imply a change to \$I_{_\text{LED}}\approx 20\:\text{mA}\$ , in this case. This is likely to be quite acceptable. But if you are seeking the large-scale equation, which provides you with how things are over many decades of design currents, then you'll probably want the original expression I was suggesting -- the sensitivity equation, itself. This will tell you the percent change in \$I_{_\text{LED}}\$ for a percent change in temperature, at any starting set value for \$I_{_\text{LED}}\$ and \$T\$ . But this also requires the combination of several equations and the use of derivatives. If that's what you want, say so. Otherwise, the above small-signal local change equation is probably sufficient. Some Verification Let's revisit the conclusion I made above by doing a back-of-envelope calculation that actually analyzes the circuit. We should do this to see if the above estimate i provided holds up to slightly deeper scrutiny. We'll need a schematic so that I can identify parts in the equations: simulate this circuit – Schematic created using CircuitLab It follows: $$\begin{align*}I_{_\text{LED}}&=\frac{\beta_1}{\beta_1+1}\,I_{_{\text{E}_1}}=\frac{\beta_1}{\beta_1+1}\left(\frac{V_{_{\text{BE}_2}}}{R_{_\text{SENSE}}}+I_{_{\text{B}_2}}\right)\\\\&=\frac{\beta_1}{\beta_1+1}\left(\frac{V_{_{\text{BE}_2}}}{R_{_\text{SENSE}}}+\frac1{\beta_2}\left[\frac{V_{_\text{DRIVE}}-V_{_{\text{BE}_1}}-V_{_{\text{BE}_2}}}{R_{_\text{DRIVE}}}-\frac{I_{_\text{LED}}}{\beta_1}\right]\right)\\\\\text{solving for }I_{_\text{LED}},\\\\&=\left[\frac{\beta_1\,\beta_2}{\beta_1\,\beta_2+\beta_2+1}\right]\cdot\left[\frac{V_{_{\text{BE}_2}}}{R_{_\text{SENSE}}}+\frac{V_{_\text{DRIVE}}-V_{_{\text{BE}_1}}-V_{_{\text{BE}_2}}}{R_{_\text{DRIVE}}}\right]\end{align*}$$ Even with temperature variations on \$\beta\$ , the value of the first factor above will be very close to 1 (slightly less.) So we can remove it from consideration. \$V_{_\text{DRIVE}}\$ is reasonably assumed to be temperature-independent for analysis purposes. So this leaves us with: $$\Delta I_{_\text{LED}}=\frac{\frac{\Delta V_{_{\text{BE}_2}}}{^\circ \text{C}}}{R_{_\text{SENSE}}}\cdot \Delta T-\frac{\frac{\Delta V_{_{\text{BE}_1}}}{^\circ \text{C}}+\frac{\Delta V_{_{\text{BE}_2}}}{^\circ \text{C}}}{R_{_\text{DRIVE}}}\cdot \Delta T$$ So there's an adjustment term that I'd not included in the original case. However, because for all intents and purposes it will be the case that \$R_{_\text{DRIVE}}\gg R_{_\text{SENSE}}\$ and that term will not matter much. We can replace the \$\frac{\Delta V_{_{\text{BE}_i}}}{^\circ \text{C}}\$ variables in the above equation with the Shockley expansion that also includes the full temperature-dependent equations for \$I_{_\text{SAT}}\$ . A closed solution will involve the use of the product-log function and take a lot of room below. But it can be done. For now, I think it is enough to see that a basic circuit analysis does confirm the original equation as "close enough" when using reasonable estimates for the variation of \$V_{_\text{BE}}\$ with temperature. Analysis and Design I'm going to use the D44H11 BJT for \$Q_1\$ and the 2N2222A BJT for \$Q_2\$ . (Both are OnSemi datasheets.) I'm also going to arrange the circuit to deliver \$\approx 20\:\text{mA}\$ at \$Q_1\$ 's collector (nothing critical here, so I'm going to ignore nuances in order to keep the math easy to follow.) The D44H11 is much, much more capable than the current sink I'm designing. You could easily handle 100 times as much current through it. But this would require 100 times as much base current, as well, and I'd need to write more if not design more. I want to focus on the basics and avoid needless added complications. Let's first look at the expected \$\beta_1\$ : Those are typical curves. From these, it looks as though I can be pretty sure that over a very wide range of temperatures, and so long as \$V_{_\text{CE}}\ge 1\:\text{V}\$ , that \$\beta_1\gt 100\$ . However, let's look at the table: This provides a worst-case reading. It's for \$I_{_\text{C}}=2\:\text{A}\$ , which is 100 times what I'm considering. But if you look again at the above curves, you'll see that the positions are about the same in either case. So let's design this for \$\beta_1=60\$ . We are rock-solid safe with that choice. This means \$I_{_{\text{B}_1}}\le 333\:\mu\text{A}\$ . Different D44H11 devices may vary, but we can be pretty sure the base current won't exceed this value range. Taking worst-case and best-typical as the extremes, \$100\:\mu\text{A} \le I_{_{\text{B}_1}}\le 333\:\mu\text{A}\$ . For \$Q_1\$ , I actually don't care too much right about about its operating \$V_{_{\text{BE}_1}}\$ because it's the job of \$Q_2\$ to make adjustments there. So I'm not going to think about it. The circuit will handle it. Let's move on to \$Q_2\$ . It's the device that is doing the measuring function and there is the following relationship between its all-important \$V_{_{\text{BE}_2}}\$ and its \$I_{_{\text{C}_2}}\$ (for this device, \$\eta=1\$ ): $$V_{_{\text{BE}_2}}=V_T\cdot\ln\left({\frac{I_{_{\text{C}_2}}}{I_{_{\text{SAT}_2}}}+1}\right)$$ This is crucial because \$V_{_{\text{BE}_2}}\$ essentially determines \$Q_1\$ 's collector current and therefore the LED/LOAD current. So setting the \$Q_2\$ collector current is important. Part and temperature variations in the D44H11, \$Q_1\$ , will cause variations in its base current and these variations will cause variations in the collector current of \$Q_2\$ and that will cause variations in \$V_{_{\text{BE}_2}}\$ , directly impacting the controlled current sink. To work this out, we need the sensitivity equation: $$\begin{align*}\frac{\%\, V_{_{\text{BE}_2}}}{\%\,I_{_{\text{C}_2}}}=\frac{\frac{\text{d}\, V_{_{\text{BE}_2}}}{V_{_{\text{BE}_2}}}}{\frac{\text{d}\,I_{_{\text{C}_2}}}{I_{_{\text{C}_2}}}}&=\frac{\text{d}\, V_{_{\text{BE}_2}}}{\text{d}\,I_{_{\text{C}_2}}}\cdot \frac{I_{_{\text{C}_2}}}{V_{_{\text{BE}_2}}}=\frac{V_T}{V_{_{\text{BE}_2}}}\\\\&\therefore\\\\\%\,I_{_{\text{C}_2}}&=\%\, V_{_{\text{BE}_2}}\cdot\frac{V_{_{\text{BE}_2}}}{V_T}\end{align*}$$ Let's say that we want to allow only \$\%\, V_{_{\text{BE}_2}}\approx 0.05\$ (or 5%.) This means for thermal and part variations, we want to keep \$19 \:\text{mA}\le I_{_{\text{C}_1}}\le 21\:\text{mA}\$ . We should use the largest \$V_T\$ that we are likely to encounter for \$Q_2\$ . (Since \$Q_2\$ will drift with ambient temperature and hopefully isn't coupled to \$Q_1\$ , this means that perhaps the highest temperature we consider is \$55^\circ\text{C}\$ , or \$V_T\le 28.3\:\text{mV}\$ .) Let's look at this curve for the 2N2222A: First, note that this is for \$V_{_\text{CE}}=1\:\text{V}\$ . Luckily, we'll be operating \$Q_2\$ at only a little more than this (two \$V_{_\text{BE}}\$ 's), so the chart is close enough for our use. Second, note that this is a typical chart. And that we do NOT have a way of working out the minimum and maximum between parts within a bag. We are looking to avoid changes due to temperature since that's the whole point of this exercise, but we do need to have an idea what to expect for device variations. The main factor determining \$V_{_\text{BE}}\$ is the saturation current for a device and as this depends on the exact area of contact between the emitter and the base, you can easily find devices varying between 50% to 200% of the nominal 100% figure in the same bag. Due to the log function involved, this works out to about \$\pm 20\:\text{mV}\$ . We don't yet know the collector current for \$Q_2\$ , but let's eyeball the \$25^\circ\text{C}\$ curve here and pick off a value of \$660\:\text{mV}\$ . We can now estimate that \$640\:\text{mV}\le V_{_{\text{BE}_2}}\le 680\:\text{mV}\$ for part variation alone. From here, we find that \$\%\,I_{_{\text{C}_2}}=0.05\cdot\frac{680\:\text{mV}}{28.3\:\text{mV}}\approx 1.2=120\,\%\$ and \$\%\,I_{_{\text{C}_2}}=0.05\cdot\frac{640\:\text{mV}}{28.3\:\text{mV}}\approx 1.13=113\,\%\$ . The (barely) tighter spec is this last one, so that's the one to meet. (Note that the sensitivity equation pretty much tells us that we can accept quite a lot of variation in \$Q_2\$ 's collector current, which allows us to set its collector current much closer to the needed base current of \$Q_1\$ .) Solving \$I_{_\text{DRIVE}}-100\:\mu\text{A}=\left(1+1.13\right)\cdot\left(I_{_\text{DRIVE}}-333\:\mu\text{A}\right)\$ provides \$I_{_\text{DRIVE}}=540\:\mu\text{A}\$ . Now we return to the fact that \$640\:\text{mV}\le V_{_{\text{BE}_2}}\le 680\:\text{mV}\$ . Let's use \$R_{_\text{SENSE}}=33\:\Omega\$ . This means that we expect \$19.4\:\text{mA}\le I_{_\text{SINK}} \le 21\:\text{mA}\$ , with an geometric mean (to center things so the plus/minus part is evenly distributed) \$I_{_\text{SINK}}=20.18\:\text{mA}\pm 4\,\%\$ . So, looking back we can see that we permitted 5% for allowed variations in collector current in \$Q_2\$ and that we have another 4% for allowed \$Q_2\$ part variations. This is a good time to re-think. If we want to keep things down to about 5%, then we need to cap the collector current variations to 1% and not the original 5% we allowed, earlier. So let's do that. We want a tighter spec of 5% and it looks like we may be able to hit it. Going back, we find the tighter spec is \$\%\,I_{_{\text{C}_2}}=0.01\cdot\frac{640\:\text{mV}}{28.3\:\text{mV}}\approx 0.226=22.6\,\%\$ . And then \$I_{_\text{DRIVE}}-100\:\mu\text{A}=\left(1+0.226\right)\cdot\left(I_{_\text{DRIVE}}-333\:\mu\text{A}\right)\$ provides \$I_{_\text{DRIVE}}\approx 1.4\:\text{mA}\$ . Note that we increased the collector current that \$Q_2\$ will have to handle by a fair bit in order to keep this variation down to a minimum. But now we are at an expectation of about 5% variation in the current sink due to variations in parts for the design. (Resistors are easily much, much more accurate. But a 1% resistor will, of course, add a little bit here. We could worry about this, as well. But for these purposes, I think we've gone far enough.) Let's assume that \$V_{_\text{CC}}=V_{_\text{DRIVE}}=30\:\text{V}\$ . This means \$R_{_\text{DRIVE}}=\frac{V_{_\text{CC}}-V_{_{\text{BE}_1}}-V_{_{\text{BE}_2}}}{I_{_\text{DRIVE}}}\approx 20.5\:\text{k}\Omega\$ . We can select either the next lower or next higher value and be "pretty good." Since I want to tighten up a little more to account for some of that resistor variation, I'll select \$R_{_\text{DRIVE}}=18\:\text{k}\Omega\$ . simulate this circuit Here's the result of a Spice simulation where the load resistance (simulating LEDs, for example) is varied over a factor of 10 and the saturation current of \$Q_2\$ is varied by a factor of 4: The blue line is for \$120\:\Omega\$ load and the red line is for \$1.2\:\text{k}\Omega\$ load. (The D44H11 has a relatively strong Early Effect, so the load variations test that aspect of the circuit, as well.) As you can see, it meets the specs. It's only run for a single temperature, though. But for part variations, the designed values meet the final requirements we set for it. The 2N2222A in this temperature range will have a variation towards the lower end, or about \$-1.8\:\frac{\text{mV}}{^\circ\text{C}}\$ . This means that over a \$15^\circ\text{C}\$ variation we'd expect to see about \$800\:\mu\text{A}\$ variation. Let's see: I think you can easily see that the prediction is met. I think that's enough for now. The point is that you can actually design these circuits in order to manage certain goals. It takes some effort to do it. You can't just slap them down. (Well, I do it all the time here. But the readers usually don't want to see all of the above work involved and just want to see something quick and simple and anywhere in some ballpark.) The datasheets could be better. They could provide statistical information about the parts you get in a package. (Sometimes, if you ask nicely, you can get that information. Often not.) But it's still possible to pick off enough information on a datasheet to actually achieve reasonable goals. And if you can't get enough information, or if that information varies too much, then you need to find other parts or come up with a different topology that can cope with the lack of information (usually with a huge dose of negative feedback and/or more parts, or both.) In Closing If tighter tolerances over ambient temperature are desired, emitter degeneration is an option that may be added to \$Q_2\$ . A resistor that is predicted to drop anything more than about \$150\:\text{mV}\$ should help. (More is better.) This comes at a price, though: It takes away from the voltage compliance range for the circuit, since more voltage overhead is now required. Variations in the collector current of \$Q_2\$ now cause an Ohmic voltage drop variation across the degeneration resistor. So a tighter focus on restricting variations of \$Q_2\$ 's collector current come into play. Base current variations in \$Q_1\$ from all sources of those variations must now have a smaller impact on \$Q_2\$ 's collector current (which sets most of its emitter current and affects the current measurement duties of \$Q_2\$ .) So the resulting circuit may be somewhat less efficient. The degeneration does also improve behavior over part variations. But emitter degeneration is more important for managing operating temperature variation, as significant improvement can be had with a small loss of voltage compliance range. The sacrifices needed to get much with respect to part variation are partly why it's less often used. There are other, better topologies to consider before embarking too far down this path. \$Q_1\$ (the drive transistor) can also be replaced with a MOSFET. In fact, the idea is often jumped-at. But doing may also mean considering the possibility of somewhat wider Early Effect variations for \$Q_2\$ , as the \$V_{_\text{TH}}\$ of discrete MOSFETs for \$Q_1\$ may be wider than the \$V_{_\text{BE}}\$ variation of discrete BJTs they replace there. Just a note to keep in mind if tempted to make comparisons.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/481308', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/193564/']}
|
jdg_373466
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1412884
|
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 equation is $$\sqrt{7-4\sqrt2 \sin x}=2\cos(x)-\sqrt2 \tan(x)$$ We get the system $$\begin{cases}7-4\sqrt 2 \sin(x)=4\cos^2(x)-2\sqrt2\cos(x)\tan(x)+2\tan^2(x) \\2\cos(x)-\sqrt2 \tan(x)\ge 0\end{cases}$$ I transformed the equation thus: $$7(\sin^2(x)+cos^2(x))-4\sqrt 2 \sin(x)=4\cos^2(x)-2\sqrt2\sin(x)+2\tan^2(x)$$$$7\sin^2(x)+3cos^2(x)-2\sqrt 2 \sin(x)-2\frac{\sin^2(x)}{1-sin^2(x)}=0$$ I multiply the whole equation by $(1-sin^2(x))$ and then substitute sin(x) with t : $$4t^4-2\sqrt2 t^3+t^2+2\sqrt2 t - 3 =0$$ And here I'm stuck. The polynomial is seemingly non-factorizable. A hint would be welcome. (0: P.S. The problem as it is presented in the texbook:
Now provide the response and nothing else.
|
Hint: The solutions of $$\sqrt{7-4\sqrt2 \sin x}=2\cos(x)-\sqrt2 \tan(x)$$are also solutions of \begin{align*}7-4\sqrt{2}\sin x&=4\cos^2 x-4\sqrt{2}\cos x\tan x+2\tan^2 x\\7-4\sqrt{2}\sin x&=4\cos^2 x-4\sqrt{2}\sin x+2\tan^2 x\end{align*}Last equation is equivalent to$$4\cos^2 x+2\tan^2 x -7=0...(1)$$Let $t=\cos^2 x$, so $(1)$ can be seen as$$4t+2\left(\frac{1}{t}-1\right)-7=0\iff 4t^2-9t+2=0$$which can be solved by the quadratic formula giving us $t\in\{2,\,\frac{1}{4}\}$. Since no real $x$ satisfies $\cos^2 x =2$ we take $\cos^2 x =\frac{1}{4}$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1412884', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/126401/']}
|
jdg_373467
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4582566
|
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:
As the title states, the goal is to verify that the quadratic equation: $abc^2x^2+c(3a^2+b^2)x+3a^2-ab+b^2=0$ has real roots. This problem comes from an interschool mathematics contest for High-schoolers, here's my (brute force) attempt: Since we need to verify that the roots are rational, we need to prove that the discriminant of this equation (which I'll denote with $D$ ) is greater than $0$ . In other words: $D=B^2-4AC>0$ where $B=c(3a^2+b^2)$ , $A=abc^2$ and $C=3a^2-ab+b^2$ Therefore: $D=[c(3a^2+b^2)]^2-4(abc^2)(3a^2-ab+b^2)$ $D=[c^2(9a^4+6a^2b^2+b^4)]+[c^2(-12a^3b+4a^2b^2-4ab^3)]$ $D=c^2(9a^4+10a^2b^2+b^4-12a^3b-4ab^3)$ I'm not quite sure where to proceed from here. And this certainly does not prove that the roots are real as this expression can be negative. Is there a way to proceed from here? Are there any better or alternative ways to answer this? Please share your approaches!
Now provide the response and nothing else.
|
$$p(x) = ab{c}^{2}{x}^{2}+c \left( 3\,{a}^{2}+{b}^{2} \right) x+3\,{a}^{2}-ab+{b}^{2} .$$ Let's try to factor this with the idea of finding a factor $Ax+B$ where $A$ is a divisor of $abc^2$ and $B$ is a divisor of $3a^2-ab+b^2$ . Since $3a^2-ab+b^2$ cannot be factored over the rationals, we try without factoring it. (If this doesn't work, we have to do something harder.) The possible factors of $p(x)$ are $Ax+B$ where $$A \in \big\{1, a, b, ab, c, ac, bc, abc, c^2, ac^2, bc^2, abc^2\big\} ,\\B \in \big\{1, -1, (3a^2-ab+b^2), -(3a^2-ab+b^2)\big\} .$$ Trying these four candidates for $B$ until one works, we arrive at: $$p(x)= \left( cx+1 \right) \left( abcx+(3\,{a}^{2}-ab+{b}^{2})\right)$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4582566', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1092912/']}
|
jdg_373468
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
125500
|
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I don't have much knowledge on LED lights and find the technology quite fascinating (yes, I know, it is not that new!) I have read that in order to create "white" light, LEDs actually need to emit light from all spectrums. My question(s): How do LED light bulbs (cool white or warm) generate white light? What would be the light spectrum for cool white LED light bulbs? What would be the light spectrum for warm white LED light bulbs? Thanks! P.S. This is my first question here. If it should be forwarded to another SE site, please let me know! P.P.S. I have done my research BEFORE asking but could not find a technically accurate answer.
Now provide the response and nothing else.
|
gbulmer puts you on the right track. For the most part, "White" LEDs are nothing more than a single color LED with a phosphor on them. The phosphor takes roughly half of the light from the LED and converts it to a second frequency of light. The two frequencies of light combine in our eyes and look to be some variation of white. A power LED I have emits yellow and purple to attain a "cool white". Warm white has more red in it. In short though, the color spectrum of White LEDs is generally horrible unless you get a really expensive one designed for full spectrum use. In general, white LEDs consist of two-ish spikes of color in the spectrum with everything else very low in comparison. The result of poor color spectrum is that some colors won't even be present even though it appears to us as white. You need 3 separate bands of color to be capable of producing all of the variations in between. With only two bands of color, you could be shining the light at something green and it'll come back looking dark grey.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/125500', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/51468/']}
|
jdg_373469
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
93876
|
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 am learning about network documentation for the first time and have come across the following statement : Undocumented networks might not be protected and can be used to support insider attacks. According to this website , network documentation is a way of representing the organisation of your network. Why then might an undocumented network be unprotected and more susceptible to insider attacks? I would have thought that, since a documented network represents the organisation of the network, it would be easier to attack a documented network. I would appreciate help understanding the statement above.
Now provide the response and nothing else.
|
If your network is undocumented, then you don't know what all the parts are, how they are set up, or how they interoperate. That in turn means you can't reliably do any of these crucial things: do a full risk assessment identify required controls implement those controls fully measure the controls to confirm they are working monitor the network so you can detect attacks Let's do an example. Opening ISO 27002:2013 at random, we find 12.4.3, "System administrator and operator activities should be logged and the logs protected and regularly reviewed". If you don't have the network documented, you may have appliances in operation that you don't know about. So you have no way of knowing if they have logs that need monitoring, you have no way of reviewing those logs, no way of auditing that you are reviewing the logs, etc. etc.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/93876', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/80454/']}
|
jdg_373470
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4262937
|
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 use the least square method to fit ellipses to data points that originate from a binary image. The least square fit minimizes the sum of squared algebraic distances between data points and the closest point to a non-centered, rotated ellipse. For the definition of algebraic distance, see $[1]$ and following snippet: In the article also $6$ lines of Matlab code are given that implements the least square method for an ellipse-only fit (never parabola or hyperbola are fitted "accidentially"). This code was used for the fit. Below we see $4$ versions of the same ellipse where from left to right the border thickness was increased inwards and outwards by the same amount. The least square fit works well for thin borders but with increasing border thickness the fit systematically worsens. This is visible by the naked eye for the most right figure (data points for this ellipse can be downloaded here ). The fitted ellipse is not in the center of the elliptical shaped data points.With increasing border thickness the large semi-axis decreases and the small semi-axis increases, the other fit parameter are in principle not affected. The same fits I get if I use another algorithm suggested in $[2]$ (using the Matlab code included in the paper). Using Mathematica with another code delivers an even worse fit: The inner and outer borders of the data points are approximately confined by ellipses (green, manually fitted). The ellipse that I would expect by a least square fit would lie centrally between the green ellipses and would be similiar to the manually drawn red ellipse. How to explain and alleviate this phenomen to get good fits? Maybe there is a short algorithm/code? A good fit should go approximately through the center of the data points. Further information there are no overlapping data points all data points have the same weight original data points lie on a grid and before fit Gaussian noise is added (standard deviation $\ll$ grid spacing) thinning thick borders in the original images is not the desired solution References $[1]$ Andrew Fitzgibbon, Maurizio Pilu, and Robert B. Fisher: Direct Least Square Fitting of Ellipses, Pattern Analysis and Machine Intelligence, 21, 476 (1999). PDF $[2]$ Radim Halir and Jan Flusser: Numerically Stable Direct Least Squares Fitting of Ellipses, Proc. Sixth Int. Conf. in Central Europe on Computer Graphics and Visualization, 1, 125 (1998) PDF
Now provide the response and nothing else.
|
Using the symmetry, after a convenient rotation. First we calculate the inertia matrix centered at the barycenter: Given a set of points $S = \{s_k\} = \{x_k,y_k\},\ \ k=1,\cdots,n$ we calculate the barycenter $g = \frac 1n\sum_{k=1}^n s_k$ . After that we calculate the inertia matrix $$I = \left(\begin{array}{cc} I_{xx} & -I_{xy} \\ -I_{xy} & I_{yy} \\\end{array}\right) = \left(\begin{array}{cc} 510964. & 157771. \\ 157771. & 174852. \\\end{array}\right)$$ with eigenvectors $v_1 = \{-0.929802,-0.36806\},\ \ v_2 = \{0.36806,-0.929802\}$ Then we rotate the centered data points $S-g$ by an angle given by $\alpha = -\arccos\left(v_1\cdot \vec e_y\right) = -1.94772$ giving $S_{\alpha}$ Now we define a distance to perform the fitting as: $$\delta(\rho_k,\theta_k,a,c) = \left|\rho_k - \frac{1}{\sqrt{\frac{\cos^2\theta}{a^2}+\frac{\sin^2\theta}{c^2}}}\right|$$ After transforming to polar form the rotated data $S_{\alpha}\to \{\rho_k,\theta_k\}$ we solve the minimization problem $$\min_{a,c}\sum_{k=1}^n \delta(\rho_k,\theta_k,a,c)$$ having the result $$E_{\alpha}=\frac{x^2}{33.959^2}+\frac{y^2}{12.0246^2}-1 = 0$$ and recovering the original reference frame $$E=0.0060966 x^2+0.00414015 x y-0.393051 x+0.00168657 y^2-0.204216 y+6.60746 = 0$$ NOTE Attached a MATHEMATICA script to implement the process. Clear["Global`*"]dr[r_, t_] := r - 1/Sqrt[Cos[t]^2/a^2 + Sin[t]^2/c^2]m0 = Import["/path_to_data/ellipse_data.txt", "Table"];n = Length[m0];g = Total[m0]/n;{X, Y} = m0 // Transpose;ixx = Sum[(Y[[k]] - g[[2]])^2, {k, 1, n}];iyy = Sum[(X[[k]] - g[[1]])^2, {k, 1, n}];ixy = -Sum[(X[[k]] - g[[1]]) (Y[[k]] - g[[2]]), {k, 1, n}];mI = {{ixx, ixy}, {ixy, iyy}};{Lambda, {v1, v2}} = Eigensystem[mI];ang = -ArcCos[v1.{0, 1}/Norm[v1]];m0r = Table[RotationMatrix[ang].(m0[[k]] - g), {k, 1, n}];polardata = Table[{Norm[m0r[[k]]], ArcTan[m0r[[k, 1]], m0r[[k, 2]]]}, {k, 1, n}];pobj = Sum[(dr[polardata[[k, 1]], polardata[[k, 2]]])^2, {k, 1, n}];restrs = {0 < c < 15, 15 < a < 40};psol = NMinimize[Join[{pobj}, restrs], {a, c}];pellipse = x^2/a^2 + y^2/c^2 - 1 /. psol[[2]];ellipser = pellipse /. {Thread[{x, y} -> RotationMatrix[ang].{XX - g[[1]], YY - g[[2]]}]} // N // Expandgrg = Graphics[{Red, PointSize[0.05], Point[g]}];gr00 = ListPlot[m0, AspectRatio -> 2, PlotStyle -> {Thick, Black}];gr3 = ContourPlot[ellipser == 0, {XX, 0, 45}, {YY, 0, 75},ContourStyle -> {Thick, Red}, PlotRange -> All];Show[gr00, gr3, grg]
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4262937', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/737314/']}
|
jdg_373471
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2186061
|
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:
Using L'Hopital Rule, evaluate $$ \lim_{x \to 0} {\left( \frac {1} {x^2}-\frac {\cot x} {x} \right)}$$ I find this question weired.If we just combine the two terms into one single fraction, we get$$\lim_{x \to 0} {\frac {1-x\cot x} {x^2}}=\frac10=\infty$$ If we follow L'Hopital Rule, this is $\infty-\infty$ form. We follow the following process to convert it into $\frac00$form.$$\infty_1 -\infty_2=\frac 1{\frac 1{\infty_1}}-\frac 1{\frac 1{\infty_2}}=\frac {\frac 1{\infty_2}-\frac 1{\infty_1}}{{\frac 1{\infty_1}}{\frac 1{\infty_2}}}$$ So we will get $$\lim_{x \to 0} {\left( \frac {1} {x^2}-\frac {\cot x} {x} \right)}=\lim_{x \to 0} {\frac {x\tan x-x^2}{x^3\tan x}}$$ If you keep differentiating using the rule you will get rid of the form of $\frac00$ in the third step of differentiation, which give you the answer $1 \over 3$. This method is very tedious. Trust me, you don't want to try. I am wondering is there a smarter way of solving this question?Thanks.
Now provide the response and nothing else.
|
A single application of L'Hospital is sufficient: $$\frac {1} {x^2}-\frac {\cot x} {x}=\frac{\sin x-x\cos x}{x^2\sin x}\xrightarrow{\text{L'Hospital}}\frac{x\sin x}{2x\sin x+x^2\cos x}=\frac{\dfrac{\sin x}x}{2\dfrac{\sin x}x+\cos x}\xrightarrow{\text{sinc}}\frac1{2+1}.$$
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2186061', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/418166/']}
|
jdg_373472
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
82658
|
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'm using here-documents in a bash script to automate installation and setup where a password is required many times. I enter the password once and the script passes it to the various commands. In most instances the here-document approach handles this fine. However, in one case I get this error: Enter VNC password: stty: standard input: Inappropriate ioctl for deviceVerify password: stty: standard input: Inappropriate ioctl for device Please notice that this error message is from x11vnc -storepassword (not from sudo .) My problem is related to x11vnc -storepasswd and here's my code: sudo x11vnc -storepasswd ~/.vnc/passwd << ENDDOCpasswordpasswordyENDDOC That obviously (from the error) does not work. I would appreciate a working example of how to implement sudo x11vnc -storepasswd ~/.vnc/passwd in a script. In case it helps, the prompts look like this: Enter VNC password: Verify password: Write password to /home/user/.vnc/passwd? [y]/n n Will using expect be a better solution? If so, how would I use it in this case? (I have never used expect before but I have looked at a lot of examples since posting this question and I cannot get expect to work on my own.)
Now provide the response and nothing else.
|
x11vnc expects its standard input to be a terminal, and it changes the terminal mode to avoid echoing the password as you're typing. When standard input isn't a terminal, the stty calls to turn echo off and back on fail, hence the warning that you see. Expect is indeed a solution. Try this script (untested): #!/usr/bin/expect -fspawn x11vnc -storepasswd ~/.vnc/passwdexpect "password:" {send "swordfish" "\r"}expect "password:" {send "swordfish" "\r"}expect "Write*\?" {send "y\r"} Alternatively, if you can, use an authentication method other than RFB ( -passwdfile , or an SSL client certificate).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/82658', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/15010/']}
|
jdg_373473
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18388368
|
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 Python script, I need to create a new file in a sub directory without changing directories, and I need to continually edit that file from the current directory. My code: os.mkdir(datetime+"-dst")for ip in open("list.txt"): with open(ip.strip()+".txt", "a") as ip_file: #this file needs to be created in the new directory for line in open("data.txt"): new_line = line.split(" ") if "blocked" in new_line: if "src="+ip.strip() in new_line: #write columns to new text file ip_file.write(", " + new_line[11]) ip_file.write(", " + new_line[12]) try: ip_file.write(", " + new_line[14] + "\n") except IndexError: pass Problems : The path for the directory and file will not always be the same, depending on what server I run the script from. Part of the directory name will be the datetime of when it was created ie time.strftime("%y%m%d%H%M%S") + "word" and I'm not sure how to call that directory if the time is constantly changing. I thought I could use shutil.move() to move the file after it was created, but the datetime stamp seems to pose a problem. I'm a beginner programmer and I honestly have no idea how to approach these problems. I was thinking of assigning variables to the directory and file, but the datetime is tripping me up. Question : How do you create a file within a sub directory if the names/paths of the file and sub directory aren't always the same?
Now provide the response and nothing else.
|
Store the created directory in a variable. os.mkdir throws if a directory exists by that name.Use os.path.join to join path components together (it knows about whether to use / or \ ). import os.pathsubdirectory = datetime + "-dst"try: os.mkdir(subdirectory)except Exception: passfor ip in open("list.txt"): with open(os.path.join(subdirectory, ip.strip() + ".txt"), "a") as ip_file: ...
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18388368', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2697549/']}
|
jdg_373474
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6005609
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's suppose I have the following regex: -(\d+)- and I want to replace, using C#, the Group 1 (\d+) with AA , to obtain: -AA- Now I'm replacing it using: var text = "example-123-example";var pattern = @"-(\d+)-";var replaced = Regex.Replace(text, pattern, "-AA-"); But I don't really like this, because if I change the pattern to match _(\d+)_ instead, I will have to change the replacement string by _AA_ too, and this is against the DRY principle. I'm looking for something like: Keep the matched text exactly how it is, but change Group 1 by this text and Group 2 by another text ... Edit: That was just an example. I'm just looking for a generic way of doing what I said above. It should work for: anything(\d+)more_text and any pattern you can imagine. All I want to do is replace only groups, and keep the rest of the match.
Now provide the response and nothing else.
|
A good idea could be to encapsulate everything inside groups, no matter if need to identify them or not. That way you can use them in your replacement string. For example: var pattern = @"(-)(\d+)(-)";var replaced = Regex.Replace(text, pattern, "$1AA$3"); or using a MatchEvaluator: var replaced = Regex.Replace(text, pattern, m => m.Groups[1].Value + "AA" + m.Groups[3].Value); Another way, slightly messy, could be using a lookbehind/lookahead: (?<=-)(\d+)(?=-)
|
{}
|
{'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/6005609', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/297114/']}
|
jdg_373475
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37624232
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was asked this question in a recent interview. You are given an array that has a million elements. All the elements are duplicates except one. My task is to find the unique element. var arr = [3, 4, 3, 2, 2, 6, 7, 2, 3........] My approach was to go through the entire array in a for loop, and then create a map with index as the number in the array and the value as the frequency of the number occurring in the array. Then loop through our map again and return the index that has value of 1. I said my approach would take O(n) time complexity. The interviewer told me to optimize it in less than O(n) complexity. I said that we cannot, as we have to go through the entire array with a million elements. Finally, he didn't seem satisfied and moved onto the next question. I understand going through million elements in the array is expensive, but how could we find a unique element without doing a linear scan of the entire array? PS: the array is not sorted.
Now provide the response and nothing else.
|
I'm certain that you can't solve this problem without going through the whole array, at least if you don't have any additional information (like the elements being sorted and restricted to certain values), so the problem has a minimum time complexity of O(n) . You can, however, reduce the memory complexity to O(1) with a XOR-based solution, if every element is in the array an even number of times, which seems to be the most common variant of the problem, if that's of any interest to you: int unique(int[] array){ int unpaired = array[0]; for(int i = 1; i < array.length; i++) unpaired = unpaired ^ array[i]; return unpaired;} Basically, every XORed element cancels out with the other one, so your result is the only element that didn't cancel out.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37624232', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1456751/']}
|
jdg_373476
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17912893
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
type A struct { B struct { Some string Len int }} Simple question. How to initialize this struct? I would like to do something like this: a := &A{B:{Some: "xxx", Len: 3}} Expectedly I'm getting an error: missing type in composite literal Sure, I can create a separated struct B and initialize it this way: type Btype struct { Some string Len int}type A struct { B Btype}a := &A{B:Btype{Some: "xxx", Len: 3}} But it not so useful than the first way. Is there a shortcut to initialize anonymous structure?
Now provide the response and nothing else.
|
The assignability rules are forgiving for anonymous types which leads to another possibility where you can retain the original definition of A while allowing short composite literals of that type to be written. If you really insist on an anonymous type for the B field, I would probably write something like: package mainimport "fmt"type ( A struct { B struct { Some string Len int } } b struct { Some string Len int })func main() { a := &A{b{"xxx", 3}} fmt.Printf("%#v\n", a)} Playground Output &main.A{B:struct { Some string; Len int }{Some:"xxx", Len:3}}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17912893', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1865966/']}
|
jdg_373477
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17198658
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I tried to parse an XML file to an R data frame. This link helped me a lot: How to create an R data frame from an xml file? But still I was not able to figure out my problem. Here is my code: data <- xmlParse("http://forecast.weather.gov/MapClick.php?lat=29.803&lon=-82.411&FcstType=digitalDWML")xmlToDataFrame(nodes=getNodeSet(data1,"//data"))[c("location","time-layout")]step1 <- xmlToDataFrame(nodes=getNodeSet(data1,"//location/point"))[c("latitude","longitude")]step2 <- xmlToDataFrame(nodes=getNodeSet(data1,"//time-layout/start-valid-time"))step3 <- xmlToDataFrame(nodes=getNodeSet(data1,"//parameters/temperature"))[c("type="hourly"")] The data frame I want to have is like this: latitude longitude start-valid-time hourly_temperature29.803 -82.411 2013-06-19T15:00:00-04:00 9129.803 -82.411 2013-06-19T16:00:00-04:00 90 I'm stuck at the xmlToDataFrame() , any help would be very much appreciated.
Now provide the response and nothing else.
|
Data in XML format are rarely organized in a way that would allow the xmlToDataFrame function to work. You're better off extracting everything in lists and then binding the lists together in a data frame: require(XML)data <- xmlParse("http://forecast.weather.gov/MapClick.php?lat=29.803&lon=-82.411&FcstType=digitalDWML")xml_data <- xmlToList(data) In the case of your example data, getting location and start time is fairly straightforward: location <- as.list(xml_data[["data"]][["location"]][["point"]])start_time <- unlist(xml_data[["data"]][["time-layout"]][ names(xml_data[["data"]][["time-layout"]]) == "start-valid-time"]) Temperature data is a bit more complicated. First you need to get to the node that contains the temperature lists. Then you need extract both the lists, look within each one, and pick the one that has "hourly" as one of its values. Then you need to select only that list but only keep the values that have the "value" label: temps <- xml_data[["data"]][["parameters"]]temps <- temps[names(temps) == "temperature"]temps <- temps[sapply(temps, function(x) any(unlist(x) == "hourly"))]temps <- unlist(temps[[1]][sapply(temps, names) == "value"])out <- data.frame( as.list(location), "start_valid_time" = start_time, "hourly_temperature" = temps)head(out) latitude longitude start_valid_time hourly_temperature1 29.81 -82.42 2013-06-19T16:00:00-04:00 912 29.81 -82.42 2013-06-19T17:00:00-04:00 903 29.81 -82.42 2013-06-19T18:00:00-04:00 894 29.81 -82.42 2013-06-19T19:00:00-04:00 855 29.81 -82.42 2013-06-19T20:00:00-04:00 836 29.81 -82.42 2013-06-19T21:00:00-04:00 80
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/17198658', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1559014/']}
|
jdg_373478
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2748965
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was given this interview question recently: Given a 12-hour analog clock, compute in degree the smaller angle between the hour and minute hands. Be as precise as you can. I'm wondering what's the simplest, most readable, most precise algorithm is. Solution in any language is welcome (but do explain it a bit if you think it's necessary).
Now provide the response and nothing else.
|
It turns out that Wikipedia does have the best answer: // h = 1..12, m = 0..59static double angle(int h, int m) { double hAngle = 0.5D * (h * 60 + m); double mAngle = 6 * m; double angle = Math.abs(hAngle - mAngle); angle = Math.min(angle, 360 - angle); return angle;} Basically: The hour hand moves at the rate of 0.5 degrees per minute The minute hand moves at the rate of of 6 degrees per minute Problem solved. And precision isn't a concern because the fractional part is either .0 or .5 , and in the range of 0..360 , all of these values are exactly representable in double .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2748965', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/276101/']}
|
jdg_373479
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1670265
|
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 to show that $(\sqrt 3 +i)^n + (\sqrt 3 -i)^n$ is REAL for any positive integer $n$. My initial thought was to use trial and error using values $1,2,3,\ldots,n$ but that does not seem like a thorough proof. Many thanks in advance!
Now provide the response and nothing else.
|
I think can rewrite $C=|r|e^{i\theta},C^*=|r|e^{-i\theta}$, and use $C^n+C^{*n}=|r|^n (e^{ni\theta}+e^{-ni\theta})$ and use $e^{ia}=\cos (a)+i\sin (a)$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1670265', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/317403/']}
|
jdg_373480
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
40054357
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have this HTTPS call in curl below; header1="projectName: zhikovapp"header2="Authorization: Bearer HZCdsf="bl_url="https://BlazerNpymh.com/api/documents?pdfDate=$today"curl -s -k -H "$header1" -H "$header2" "$bl_url" I would like to write an equivalent python call using requests module. header ={ "projectName": "zhikovapp", "Authorization": "Bearer HZCdsf=" }response = requests.get(bl_url, headers = header) However, the request was not valid. What is wrong? The contents of the returned response is like this; <Response [400]>_content = '{"Message":"The request is invalid."}'headers = {'Content-Length': '37', 'Access-Control-Allow-Headers': 'projectname, authorization, Content-Type', 'Expires': '-1', 'cacheControlHeader': 'max-age=604800', 'Connection': 'keep-alive', 'Pragma': 'no-cache', 'Cache-Control': 'no-cache', 'Date': 'Sat, 15 Oct 2016 02:41:13 GMT', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 'Content-Type': 'application/json; charset=utf-8'}reason = 'Bad Request' I am using python 2.7 EDIT: I corrected some syntex errors after Soviut pointed them out.
Now provide the response and nothing else.
|
In request.get() the headers argument should be defined as a dictionary, a set of key/value pairs. You've defined a set (a unique list) of strings instead. You should declare your headers like this: headers = { "projectName": "zhikovapp", "Authorization": "Bearer HZCdsf="}response = requests.get(bl_url, headers=headers) Note the "key": "value" format of each line inside the dictionary. Edit: Your Access-Control-Allow-Headers say they'll accept projectname and authorization in lower case. You've named your header projectName and Authorization with upper case letters in them. If they don't match, they'll be rejected.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40054357', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1709088/']}
|
jdg_373481
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1919
|
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Since August 24 2012 , it is possible to buy a licence to hardware-decode MPEG-2 videos. Here are my questions: Does it mean that, without this licence, the RPi cannot handle at all MPEG-2 video, or it will struggle to play it smoothly? In what form comes the licence? Is it a file to install in the ditribution? Or is it a hardware activation or something? Thank you.
Now provide the response and nothing else.
|
The license enables you to decode and encode (where applicable) the mentioned media types using the built in hardware encoders/decoders. H.264 Encode is enabled in the latest version (Included in Pi Price) which is great! For an extra £2.40 you can watch MPEG2 video, ie DVD's are encoded in MPEG2! For an extra £1.20 you can decode VC-1 video, ie Microsoft's Silverlight Video Hardware en/decoders are much faster and do not rely on the core CPU to process these files; rather the GPU is used to process the files. It talks directly to the Video Memory (decoding) or RAM (encoding) making it nice and smooth. You do not need this license and can use software versions. But it is really slow. The license will be a file you place somewhere or a key you define as a global variable for the system. The en/decoder libraries will request these and pass them into the hardware where they will be resolved on that chip; if the key matches the serial number and is valid you will be allowed to use the exposed API (I can see this getting hacked very quickly). Raspberry Pi did not include this to keep costs down. For us, a few quid is ok, but if they made a million units that is £3.6million extra they have to spend on something only a fraction of people will use.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://raspberrypi.stackexchange.com/questions/1919', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/797/']}
|
jdg_373482
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3144050
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
<html> <head> </head> <body> <div> <a href="http://www.google.com"> <span>title<br></span> <span>description<br></span> <span>some url</span> </a> </div> </body></html> I am pretty new to CSS, I have a simple case like the above. I would like to make the "title" and "some url" clickable but want to make description as non-clickable. Is there any way to do that by applying some CSS on the span so that whatever inside that span, it is not clickable.My constraint is that, I do not want to change the structure of the div, instead just applying css can we make a span which is inside an anchor tag, not clickable ?
Now provide the response and nothing else.
|
Actually, you can achieve this via CSS. There's an almost unknown css rule named pointer-events. The a element will still be clickable but your description span won't. a span.description { pointer-events: none;} there are other values like: all, stroke, painted, etc. ref: http://robertnyman.com/2010/03/22/css-pointer-events-to-allow-clicks-on-underlying-elements/ UPDATE: As of 2016, all browsers now accept it: http://caniuse.com/#search=pointer-events UPDATE: As of 2022, browsers behavior may have changed, another option can be: a { pointer-events: none;}a span:not(.description) { pointer-events: initial;}
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/3144050', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/61395/']}
|
jdg_373483
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6996776
|
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 doing a page where I show thumbnails for videos that, when you click, it popups a YouTube video. This thumbnails are simple images of 195x195 but the end client it will upload as it, and I would like to add via CSS a "play icon" over the image of the video (compatible with IE7+). I've no idea on how to handle this. Can anyone help me? Thank you in advance!
Now provide the response and nothing else.
|
you might want to do something like this: <div class="imageWrapper" style="position: relative; width: 195px; height: 195px;"> <img src="/path/to/image.jpg " alt=.. width=.. height=..style="position: relative; z-index: 1;" /> <img src="/path/to/play.jpg " alt=.. width=.. height=.. style="position: absolute;left:80px; top: 80px;z-index: 10;" /> </div> of course do not use style="" , but put styles into separate CSS files. Explanation: put two images into div. If you give position: relative; property to your wrapper div, then anything inside this div would be position relatively to it. It means, you can add position: absolute; to the play image and using left: XXpx; and top: XXpx; you can position it where you want. You might want to use z-index to define which picture should be on the top. The higher z-index the higher layer. Please note: z-index works only if position is set.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6996776', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/569908/']}
|
jdg_373484
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
6911289
|
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 today that std::vector::at() is significantly slower than accessing values with square brackets [] . According to the doc .at() is safer because it won't let me access values beyond the bounds of the array. However, even if I access out of bound values with at() , I'll obviously still have an error, so that's something I need to avoid no matter what. So is there any good reason why anyone would use at() instead of [] ?
Now provide the response and nothing else.
|
If you have reason to believe that the index is not in your control, or if the control flow is particularly complicated and you're tracing bugs, then you might want to use at() during the debug phase, but never inside loops or any situation where you know that the index is safe. Even in other situations you should either prevalidate the index (e.g. if it's user input), or if you are just getting the value from a complicated algorithm, use assert and fix the bug if there is one. [Edit.] Or perhaps if you are writing a very complicated algorithm and you aren't sure that all your indices are always valid, you could use at() inside that algorithm and put the call into a try block -- but even here it is preferable to be offensive and use with assertions.[/] Personally, I can't see any good reasons for at() to survive into release code. You could possibly contrive some examples where you want to use exception handling as a convenient way to direct your control flow, but any such use case would be very situational.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6911289', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/561309/']}
|
jdg_373485
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24992980
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I tried to uglify output of Browserify in Gulp, but it doesn't work. gulpfile.js var browserify = require('browserify');var gulp = require('gulp');var uglify = require('gulp-uglify');var source = require('vinyl-source-stream');gulp.task('browserify', function() { return browserify('./source/scripts/app.js') .bundle() .pipe(source('bundle.js')) .pipe(uglify()) // ??? .pipe(gulp.dest('./build/scripts'));}); As I understand I cannot make it in steps as below. Do I need to make in one pipe to preserve the sequence? gulp.task('browserify', function() { return browserify('./source/scripts/app.js') .bundle() .pipe(source('bundle.js')) .pipe(uglify()) // ??? .pipe(gulp.dest('./source/scripts'));});gulp.task('scripts', function() { return grunt.src('./source/scripts/budle.js') .pipe(uglify()) .pipe(gulp.dest('./build/scripts'));});gulp.task('default', function(){ gulp.start('browserify', 'scripts');});
Now provide the response and nothing else.
|
You actually got pretty close, except for one thing: you need to convert the streaming vinyl file object given by source() with vinyl-buffer because gulp-uglify (and most gulp plugins) works on buffered vinyl file objects So you'd have this instead var browserify = require('browserify');var gulp = require('gulp');var uglify = require('gulp-uglify');var source = require('vinyl-source-stream');var buffer = require('vinyl-buffer');gulp.task('browserify', function() { return browserify('./source/scripts/app.js') .bundle() .pipe(source('bundle.js')) // gives streaming vinyl file object .pipe(buffer()) // <----- convert from streaming to buffered vinyl file object .pipe(uglify()) // now gulp-uglify works .pipe(gulp.dest('./build/scripts'));}); Or, you can choose to use vinyl-transform instead which takes care of both streaming and buffered vinyl file objects for you, like so var gulp = require('gulp');var browserify = require('browserify');var transform = require('vinyl-transform');var uglify = require('gulp-uglify');gulp.task('build', function () { // use `vinyl-transform` to wrap the regular ReadableStream returned by `b.bundle();` with vinyl file object // so that we can use it down a vinyl pipeline // while taking care of both streaming and buffered vinyl file objects var browserified = transform(function(filename) { // filename = './source/scripts/app.js' in this case return browserify(filename) .bundle(); }); return gulp.src(['./source/scripts/app.js']) // you can also use glob patterns here to browserify->uglify multiple files .pipe(browserified) .pipe(uglify()) .pipe(gulp.dest('./build/scripts'));}); Both of the above recipes will achieve the same thing. Its just about how you want to manage your pipes (converting between regular NodeJS Streams and streaming vinyl file objects and buffered vinyl file objects) Edit:I've written a longer article regarding using gulp + browserify and different approaches at: https://medium.com/@sogko/gulp-browserify-the-gulp-y-way-bb359b3f9623
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/24992980', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2825402/']}
|
jdg_373486
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1287146
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am new to LINQ and am trying to create some data points from a table to graph. The three fields of importance in this table are the id, the time and the value. I am writing a query to get the average value over a set time for a chosen id. The LINQ I have written follows: var value = (from t in _table where t.Id == id && t.Time >= intervalStartTime && t.Time <= intervalEndTime select t.Value).Average(); However this crashes at runtime with: "The null value cannot be assigned to a member with type System.Decimal which is a non-nullable value type.." At certain intervals there is no data so the SQL LINQ generates returns null, which I would liked to be COALESCED to 0 but instead crashes the application. Is there a way to write this LINQ query to be able to handle this properly? The table definition to make things clearer: [Serializable][Table(Name = "ExampleTable")]public class ExampleTable{ [Column(Name = "Id")] public int Id { get; set; } [Column(Name = "Time")] public DateTime Time { get; set; } [Column(Name = "Value")] public int Value{ get; set; }}
Now provide the response and nothing else.
|
I think you want var value = (from t in _table where t.Id == id && t.Time >= intervalStartTime && t.Time <= intervalEndTime select (int?)t.Value).Average() This way, you get a double? back, whereas without the (int?) cast you need to get a double back, which cannot be null . This is because of the signatures double Enumerable.Average(IEnumerable<int> source)double? Enumerable.Average(IEnumerable<int?> source) Now, to get an average of 0 instead of null, you need to place the coalescing operator at the end var value = (from t in _table where t.Id == id && t.Time >= intervalStartTime && t.Time <= intervalEndTime select (int?)t.Value).Average() ?? 0.0; IMHO this is a pretty awful design of the Enumerable / Queryable class; why can't Average(IEnumerable<int>) return double? , why only for Average(IEnumerable<int?>) ?
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1287146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5170/']}
|
jdg_373487
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
46835481
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
First, sorry for my terrible English, it is not my native language... I am building a simple app in Firebase, using the Firestore database. In my app, users are members of small groups. They have access to other users' data.In order not to query too many documents (one per user, in a subcollection of the group's document), I have chosen to add the users' data in an array inside the group's document.Here is my group's document: { "name":"fefefefe", "days":[false,false,false,false,true], "members":[ {"email":"eee@ff.com","id":"aaaaaaaa","name":"Mavireck"}, {"email":"eee2@ff.com","id":"bbbbbbbb","name":"Mavireck2"}, ],} How can I check with the security rules if a user is in a group ?Should I use an object instead ?I'd really prefer not use a subcollection for users, because I would reach the free quota's limits too quickly... Thank you for your time ! EDIT:Thanks for the answer. I will change it to an object : "Members": { uid1 : {}, uid2 : {} }
Now provide the response and nothing else.
|
In general, you need to write a rule like the following: service cloud.firestore { match /databases/{database}/documents { match /collection/{documentId} { // works if `members` = [uid1, uid2, uid3] // no way to iterate over a collection and check members allow read: if request.auth.uid in resource.data.members; // you could also have `members` = {uid1: {}, uid2: {}} allow read: if resource.data.members[request.auth.uid] != null; } }} You could also use subcollections: service cloud.firestore { match /databases/{database}/documents { // Allow a user to read a message if the user is in the room match /rooms/{roomId} { match /documents/{documentId} { allow read: if exists(/databases/$(database)/documents/documents/$(documentId)/users/$(request.auth.uid)); } match /users/{userId} { // rules to allow users to operate on a document } } }}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/46835481', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8802549/']}
|
jdg_373488
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
39762
|
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:
Happy new year mathematica gurus of stack exchange! As I see it one of the major obstacles in getting decent at programming mathematica is that, not only do you need to learn how certain commands work, but rather that you mainly need to understand how to write your syntax. This is a typical such situation, I was hoping that someone might shine some light on how to do it. I run this piece of code: For[i = 1, i <= samples, i++, AppendTo[fList, f1[randomSeeds[[1 + (n - 1) (i - 1)]][[1]], randomSeeds[[1 + (n - 1) (i - 1)]][[2]], 0, 0, 0, 0, 0, 0]]; ]For[i = 1, i <= samples, i++, AppendTo[fList, f1[randomSeeds[[1 + (n - 1) (i - 1)]][[1]], randomSeeds[[1 + (n - 1) (i - 1)]][[2]], randomSeeds[[2 + (n - 1) (i - 1)]][[1]], randomSeeds[[2 + (n - 1) (i - 1)]][[2]], 0, 0, 0, 0]]; ]For[i = 1, i <= samples, i++, AppendTo[fList, f1[randomSeeds[[1 + (n - 1) (i - 1)]][[1]], randomSeeds[[1 + (n - 1) (i - 1)]][[2]], randomSeeds[[2 + (n - 1) (i - 1)]][[1]], randomSeeds[[2 + (n - 1) (i - 1)]][[2]], randomSeeds[[3 + (n - 1) (i - 1)]][[1]], randomSeeds[[3 + (n - 1) (i - 1)]][[2]], 0, 0]]; ]For[i = 1, i <= samples, i++, AppendTo[fList, f1[randomSeeds[[1 + (n - 1) (i - 1)]][[1]], randomSeeds[[1 + (n - 1) (i - 1)]][[2]], randomSeeds[[2 + (n - 1) (i - 1)]][[1]], randomSeeds[[2 + (n - 1) (i - 1)]][[2]], randomSeeds[[3 + (n - 1) (i - 1)]][[1]], randomSeeds[[3 + (n - 1) (i - 1)]][[2]], randomSeeds[[4 + (n - 1) (i - 1)]][[1]], randomSeeds[[4 + (n - 1) (i - 1)]][[2]]]]; ] As you can see most of the stuff is identical in the for loops, it's just the number of zeroes that varies in the end. In fact, I only wish to run one of these for loops at the time. Just above these for loops I specify the number of dimensions I'm working in (n in the code), for n=2 I want to run the first loop, for n=3 I want to run the second etc. At the moment I comment an uncomment the undesired parts of the code, but that seems like a very ugly solution to me. So my question is this: is there a simple way of reducing these for copies of code into one copy? It seems to me as though this is a quite ineffective way of doing things. Edit: Small clarification: Ideally I want something like this: I give the program "2" as input and it chooses the first for loop above etc. Cheers,David
Now provide the response and nothing else.
|
To begin with you should try to avoid explicit For loops in most cases. See Alternatives to procedural loops and iterating over lists in Mathematica . You will often also benefit from a functional rather than mutable style. Consider for example this function which does not rely on any global variables: loop[fn_, seeds_, n_, samples_, jmax_] := fn @@ PadRight[#, 8] & /@ Join @@@ Table[seeds[[j + (n - 1) (i - 1), k]], {i, samples}, {j, jmax}, {k, 2}] An example of use: SeedRandom[1];randomSeeds = RandomInteger[{-50, 50}, {99, 2}];loop[f1, randomSeeds, 5, 8, 3] {f1[30, -36, -50, 17, -47, 15, 0, 0], f1[47, 18, 24, -35, -26, -46, 0, 0], f1[33, 20, -49, -20, -2, -25, 0, 0], f1[19, 6, -3, -22, 18, -24, 0, 0], f1[36, 26, -7, -17, -6, 36, 0, 0], f1[-12, -21, 25, -20, -33, 4, 0, 0], f1[-44, -7, -48, 29, -33, -16, 0, 0], f1[1, -9, -35, -32, -5, -44, 0, 0]} This matches the output of your first For loop. For the second and third: loop[f1, randomSeeds, 5, 8, 3]loop[f1, randomSeeds, 5, 8, 4] I intentionally put all data upon which loop depends as arguments to avoid relying on global values. If you do not want to pass these explicitly you might rely upon Options . For example: ClearAll[loop]Options[loop] = {Function -> f1, "Seeds" :> randomSeeds};loop[n_, samples_, jmax_, OptionsPattern[]] := OptionValue[Function] @@ PadRight[#, 8] & /@ Join @@@ Table[OptionValue["Seeds"][[j + (n - 1) (i - 1), k]], {i, samples}, {j, jmax}, {k, 2}] This relies on the global value of randomSeeds but it is no longer hard-coded. Now the call is simpler: loop[5, 6, 3] {f1[30, -36, -50, 17, -47, 15, 0, 0], f1[47, 18, 24, -35, -26, -46, 0, 0], f1[33, 20, -49, -20, -2, -25, 0, 0], f1[19, 6, -3, -22, 18, -24, 0, 0], f1[36, 26, -7, -17, -6, 36, 0, 0], f1[-12, -21, 25, -20, -33, 4, 0, 0]} You change the Options at any time with SetOptions : SetOptions[loop, Function -> foo];loop[5, 3, 4] {foo[30, -36, -50, 17, -47, 15, 50, -27], foo[47, 18, 24, -35, -26, -46, 50, 40], foo[33, 20, -49, -20, -2, -25, -6, 23]}
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/39762', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/7449/']}
|
jdg_373489
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
626416
|
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 define all signals as a sum of sinusoidals by taking fourier transform of the signal. Thats OK. My question is, why sinusoidals.? Can there be an another transform like Fourier somewhere in the universe that can explain all signals as sum of rectangulars or triangulars(or any periodic shape)?
Now provide the response and nothing else.
|
This question has a very general answer given by the Stone–Weierstrass theorem . This says, in the situation to which Fourier series apply, Let $C[a,b]$ be the space of continuous functions on the interval $[a,b]$ and let $A \subset C[a,b]$ be a set, closed under addition, multiplication, and scaling, having the two properties: For every $x \in [a,b]$, there is some $f \in A$ such that $f(x) \neq 0$, and For every $x, y \in [a,b]$, there is some $f \in A$ such that $f(x) \neq f(y)$. Then every function in $C[a,b]$ is the uniform limit of elements of $A$. The connection with Fourier series is that we can take $A$ to be the set of functions generated by $\sin(x)$ and $\cos(x)$ on (in this case) $[-\pi, \pi]$ by addition, multiplication (including the $0$'th power), and scaling. Since you can check that $\sin(x)$, $\cos(x)$, and the constant function $1$ can never simultaneously either vanish or be equal, $A$ satisfies the conditions of the theorem, showing that every continuous function on $[-\pi, \pi]$ is the uniform limit of "trigonometric polynomials": literally, polynomials in $\sin(x)$ and $\cos(x)$, which using trig identities (or complex exponentials, which is the same but easier) you can show are the same as expressions of the form $$\sum_{n = 0}^N (a_n \cos(nx) + b_n \sin(nx)).$$ Using other basic functions, the theorem gives a simple criterion for checking whether their "polynomials" can be used to approximate other functions. The advantage of Fourier series here is that the approximating polynomials are partial sums of a single infinite series whose coefficients can be computed by an inner product (an integral). That is, for example, one can use polynomials such as the Bernstein polynomials to approximate continuous functions as well, but as the degree of the polynomials approximating any one function increase, the coefficients all change, not just the highest ones. This is simply because these polynomials do not form an orthonormal set with respect to an inner product. Other such "orthogonal polynomials" exist in plenty, such as Legendre polynomials , and they do not have this problem. In short, the scheme that allows Fourier series to work can be generalized partially by replacing the trigonometric functions with an arbitrary orthonormal basis for some inner product on $C[a,b]$, and generalized even farther by just using any subalgebra of $C[a,b]$ that "separates points and vanishes nowhere", but then the approximants are not as well-behaved individually.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/626416', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/118978/']}
|
jdg_373490
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2719469
|
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 curious, why did Sun decide to make the JVM stack-based and Google decide to make the DalvikVM register-based? I suppose the JVM can't really assume that a certain number of registers are available on the target platform, since it is supposed to be platform independent. Therefor it just postpones the register-allocation etc, to the JIT compiler. (Correct me if I'm wrong.) So the Android guys thought, "hey, that's inefficient, let's go for a register based vm right away..."? But wait, there are multiple different android devices, what number of registers did the Dalvik target? Are the Dalvik opcodes hardcoded for a certain number of registers? Do all current Android devices on the market have about the same number of registers? Or, is there a register re-allocation performed during dex-loading? How does all this fit together?
Now provide the response and nothing else.
|
There are a few attributes of a stack-based VM that fit in well with Java's design goals: A stack-based design makes very fewassumptions about the targethardware (registers, CPU features),so it's easy to implement a VM on awide variety of hardware. Since the operands for instructionsare largely implicit, the objectcode will tend to be smaller. Thisis important if you're going to bedownloading the code over a slownetwork link. Going with a register-based scheme probably means that Dalvik's code generator doesn't have to work as hard to produce performant code. Running on an extremely register-rich or register-poor architecture would probably handicap Dalvik, but that's not the usual target - ARM is a very middle-of-the-road architecture. I had also forgotten that the initial version of Dalvik didn't include a JIT at all. If you're going to interpret the instructions directly, then a register-based scheme is probably a winner for interpretation performance.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2719469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/276052/']}
|
jdg_373491
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35013
|
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
As I understand it, the exponentiated beta value from a logistic regression is the odds ratio of that variable for the dependent variable of interest. However, the value does not match the manually calculated odds ratio. My model is predicting stunting (a measure of malnutrition) using, amongst other indicators, insurance. // Odds ratio from LR, being done in statalogit stunting insurance age ... etc. or_insurance = exp(beta_value_insurance)// Odds ratio, manually calculatedodds_stunted_insured = num_stunted_ins/num_not_stunted_insodds_stunted_unins = num_stunted_unins/num_not_stunted_uninsodds_ratio = odds_stunted_ins/odds_stunted_unins What is the conceptual reason for these values being different? Controlling for other factors in the regression? Just want to be able to explain the discrepancy.
Now provide the response and nothing else.
|
If you're only putting that lone predictor into the model, then the odds ratio between the predictor and the response will be exactly equal to the exponentiated regression coefficient . I don't think a derivation of this result in present on the site, so I will take this opportunity to provide it. Consider a binary outcome $Y$ and single binary predictor $X$: $$ \begin{array}{c|cc}\phantom{} & Y = 1 & Y = 0 \\ \hlineX=1 & p_{11} & p_{10} \\ X=0 & p_{01} & p_{00} \\ \end{array}$$ Then, one way to calculate the odds ratio between $X_i$ and $Y_i$ is $$ {\rm OR} = \frac{ p_{11} p_{00} }{p_{01} p_{10}} $$ By definition of conditional probability, $p_{ij} = P(Y = i | X = j) \cdot P(X = j)$. In the ratio, he marginal probabilities involving the $X$ cancel out and you can rewrite the odds ratio in terms of the conditional probabilities of $Y|X$: $${\rm OR} = \frac{ P(Y = 1| X = 1) }{P(Y = 0 | X = 1)} \cdot \frac{ P(Y = 0 | X = 0) }{ P(Y = 1 | X = 0)} $$ In logistic regression, you model these probabilities directly: $$ \log \left( \frac{ P(Y_i = 1|X_i) }{ P(Y_i = 0|X_i) } \right) = \beta_0 + \beta_1 X_i $$ So we can calculate these conditional probabilities directly from the model. The first ratio in the expression for ${\rm OR}$ above is: $$\frac{ P(Y_i = 1| X_i = 1) }{P(Y_i = 0 | X_i = 1)}=\frac{ \left( \frac{1}{1 + e^{-(\beta_0+\beta_1)}} \right) }{\left( \frac{e^{-(\beta_0+\beta_1)}}{1 + e^{-(\beta_0+\beta_1)}}\right)}= \frac{1}{e^{-(\beta_0+\beta_1)}} = e^{(\beta_0+\beta_1)}$$ and the second is: $$ \frac{ P(Y_i = 0| X_i = 0) }{P(Y_i = 1 | X_i = 0)}=\frac{ \left( \frac{e^{-\beta_0}}{1 + e^{-\beta_0}} \right) }{ \left( \frac{1}{1 + e^{-\beta_0}} \right) } = e^{-\beta_0}$$ plugging this back into the formula, we have ${\rm OR} = e^{(\beta_0+\beta_1)} \cdot e^{-\beta_0} = e^{\beta_1}$, which is the result. Note: When you have other predictors, call them $Z_1, ..., Z_p$, in the model, the exponentiated regression coefficient (using a similar derivation) is actually $$ \frac{ P(Y = 1| X = 1, Z_1, ..., Z_p) }{P(Y = 0 | X = 1, Z_1, ..., Z_p)} \cdot \frac{ P(Y = 0 | X = 0, Z_1, ..., Z_p) }{ P(Y = 1 | X = 0, Z_1, ..., Z_p)} $$ so it is the odds ratio conditional on the values of the other predictors in the model and, in general, in not equal to $$ \frac{ P(Y = 1| X = 1) }{P(Y = 0 | X = 1)} \cdot \frac{ P(Y = 0 | X = 0) }{ P(Y = 1 | X = 0)}$$ So, it is no surprise that you're observing a discrepancy between the exponentiated coefficient and the observed odds ratio. Note 2: I derived a relationship between the true $\beta$ and the true odds ratio but note that the same relationship holds for the sample quantities since the fitted logistic regression with a single binary predictor will exactly reproduce the entries of a two-by-two table. That is, the fitted means exactly match the sample means, as with any GLM. So, all of the logic used above applies with the true values replaced by sample quantities.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/35013', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/13378/']}
|
jdg_373492
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
49746
|
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I used the following command to install Iceweasel. sudo apt-get install iceweasel However, instead of Iceweasel, I get Firefox. Not that I'm complaining much, I love Firefox. If you click on Menu > Internet , there are 2 Firefox logos. One says Firefox ESR, and the other says Iceweasel > Firefox ESR. But I have no idea why it's doing this. Has Iceweasel been discontinued and Firefox linked to the Iceweasel install?
Now provide the response and nothing else.
|
TL;DR: Iceweasel was rebranded back to Firefox in Feb '16. You can no longer install Iceweasel. Background Info Firefox is open source. This means that anyone can freely distribute and modify the source code. However, the laws surrounding the trademark 'Firefox' and the Firefox logo are slightly different. The trademark and logo may only be used with unmodified/official versions of the source code. (This is because Mozilla wants users to have a consistent experience when using 'Firefox') Debian (the Linux distro which Raspbian is based off) has a set of guidelines called the Debian Free Software Guidelines , which determines what software is allowed to be included in Debian. Because the restrictions placed on the logo and trademark were not compatible with the guidelines, the distribution of Firefox to be included in Debian had to be rebranded. After many debates etc, the name Iceweasel was born and Firefox was rebranded. However, in February 2016, Mozilla allowed Debian to use the Firefox trademark and logos in their distributions: Mozilla recognizes that patches applied to Iceweasel/Firefox don'timpact the quality of the product. [...] In case of derivatives of Debian, Firefox branding can be used as longas the patches applied are in the same category as described above. Hence, Iceweasel was 'un-rebranded' back to Firefox. So why can't I install Iceweasel? Because Iceweasel has been rebranded to Firefox, the Iceweasel package has been discontinued, and instead Firefox is automatically installed. You can no longer install Iceweasel. Further reading Wikipedia article on Firefox Trademark laws Wikipedia article on Mozilla software rebranded by Debian Bug report for renaming Iceweasel to Firefox
|
{}
|
{'log_upvote_score': 6, 'links': ['https://raspberrypi.stackexchange.com/questions/49746', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/46678/']}
|
jdg_373493
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
29214932
|
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 R, with file.path , you can convert a character vector into a full file path, automatically using the correct file separator for your platform : > file.path("home", "foo", "script.R")[1] "home/foo/script.R" I'd like to do exactly the reverse : split a file path into a character vector of components. So far I almost manage to do it with a recursive function, but I don't find it very elegant : split_path <- function(file) { if(!(file %in% c("/", "."))) { res <- c(basename(file), split_path(dirname(file))) return(res) } else return(NULL)} Which gives : > split_path("/home/foo/stats/index.html")[1] "index.html" "stats" "foo" "home" Do you know of any already existing function, or at least a better way to do such a thing ? Thanks ! EDIT : I think I'll finally stick to this slightly different recursive version, thanks to @James, which should handle drive letters and network shares under Windows : split_path <- function(path) { if (dirname(path) %in% c(".", path)) return(basename(path)) return(c(basename(path), split_path(dirname(path))))}
Now provide the response and nothing else.
|
You can do it with a simple recursive function, by terminating when the dirname doesn't change: split_path <- function(x) if (dirname(x)==x) x else c(basename(x),split_path(dirname(x)))split_path("/home/foo/stats/index.html")[1] "index.html" "stats" "foo" "home" "/" split_path("C:\\Windows\\System32")[1] "System32" "Windows" "C:/"split_path("~")[1] "James" "Users" "C:/"
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29214932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/249691/']}
|
jdg_373494
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
52937409
|
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 create a new Woocommerce product programmatically with PHP code and I have tried it with the Woocommerce 3 CRUD methods: //Woocommerce CRUD$objProduct = new WC_Product_Simple();$objProduct->set_name('My Product 1'); //Set product name.$objProduct->set_status('publish'); //Set product status.//$objProduct->set_featured(FALSE); //Set if the product is featured. | bool$objProduct->set_catalog_visibility('visible'); //Set catalog visibility. | string $visibility Options: 'hidden', 'visible', 'search' and 'catalog'.$objProduct->set_description('My custom long description'); //Set product description.//$objProduct->set_short_description('My short description'); //Set product short description.//$objProduct->set_sku('U-123'); //Set SKU$objProduct->set_price(5.00); //Set the product's active price.//$objProduct->set_regular_price(5.00); //Set the product's regular price.//$objProduct->set_sale_price(); //Set the product's sale price.//$objProduct->set_date_on_sale_from(); //Set date on sale from. | string|integer|null $date UTC timestamp, or ISO 8601 DateTime. If the DateTime string has no timezone or offset, WordPress site timezone will be assumed. Null if their is no date.//$objProduct->set_date_on_sale_to();//Set date on sale to. | string|integer|null $date UTC timestamp, or ISO 8601 DateTime. If the DateTime string has no timezone or offset, WordPress site timezone will be assumed. Null if their is no date.//$objProduct->set_manage_stock(TRUE); //Set if product manage stock. | bool//$objProduct->set_stock_quantity(10); //Set number of items available for sale.//$objProduct->set_stock_status('instock'); //Set stock status. | string $status 'instock', 'outofstock' and 'onbackorder'//$objProduct->set_backorders('no'); //Set backorders. | string $backorders Options: 'yes', 'no' or 'notify'.//$objProduct->set_sold_individually(FALSE); //Set if should be sold individually. | bool//$objProduct->set_weight(); //Set the product's weight.//$objProduct->set_length(); //Set the product length.//$objProduct->set_width(); //Set the product width.//$objProduct->set_height(); //Set the product height.//$objProduct->set_upsell_ids($upsell_ids); //Set upsell IDs. | array $upsell_ids IDs from the up-sell products.//$objProduct->set_cross_sell_ids($cross_sell_ids); //Set crosssell IDs. | array $cross_sell_ids IDs from the cross-sell products.$objProduct->set_reviews_allowed(TRUE); //Set if reviews is allowed. | bool//$objProduct->set_purchase_note($purchase_note); //Set purchase note. | string $purchase_note Purchase note.$attribute = new WC_Product_Attribute();$attribute->set_id(wc_attribute_taxonomy_id_by_name('pa_color')); //if passing the attribute name to get the ID$attribute->set_name('pa_color'); //attribute name$attribute->set_options('red'); // attribute value$attribute->set_position(1); //attribute display order$attribute->set_visible(1); //attribute visiblity$attribute->set_variation(0);//to use this attribute as varint or not$raw_attributes[] = $attribute; //<--- storing the attribute in an array$attribute = new WC_Product_Attribute();$attribute->set_id(25);$attribute->set_name('pa_size');$attribute->set_options('XL');$attribute->set_position(2);$attribute->set_visible(1);$attribute->set_variation(0);$raw_attributes[] = $attribute; //<--- storing the attribute in an array$objProduct->set_attributes($raw_attributes); //Set product attributes. | array $raw_attributes Array of WC_Product_Attribute objects.//$objProduct->set_category_ids($term_ids); //Set the product categories. | array $term_ids List of terms IDs.//$objProduct->set_tag_ids($term_ids); //Set the product tags. | array $term_ids List of terms IDs.//$objProduct->set_image_id(); //Set main image ID. | int|string $image_id Product image id.//$objProduct->set_gallery_image_ids(); //Set gallery attachment ids. | array $image_ids List of image ids.$new_product_id = $objProduct->save(); //Saving the data to create new product, it will return product ID.return;} But I get this error: 22-Oct-2018 20:25:19 UTC] PHP Fatal error: Uncaught Error: Class 'WC_Product_Simple' not found in /home/u1771p590/domains/famyfuerza.com/public_html/store/wp-content/plugins/ff-dropship-data-scraper/ff-dropship-data-scraper.php:165 Stack trace: - #0 /home/u1771p590/domains/famyfuerza.com/public_html/store/wp-content/plugins/ff-dropship-data-scraper/ff-dropship-data-scraper.php(233): curl_download(' https://www.ban ...') - #1 /home/u1771p590/domains/famyfuerza.com/public_html/store/wp-settings.php(305): include_once('/home/u1771p590...') - #2 /home/u1771p590/domains/famyfuerza.com/public_html/store/wp-config.php(112): require_once('/home/u1771p590...') - #3 /home/u1771p590/domains/famyfuerza.com/public_html/store/wp-load.php(37): require_once('/home/u1771p590...') - #4 /home/u1771p590/domains/famyfuerza.com/public_html/store/wp-admin/admin.php(31): require_once('/home/u1771p590...') - #5 /home/u1771p590/domains/famyfuerza.com/public_html/store/wp-admin/index.php(10): require_once('/home/u1771p590...') - #6 {main} thrown in /home/u1771p590/domains/famyfuerza.com/public_html/store/wp-content/plugins/ff-dropship-data-scraper/ff-dropship-data-scraper.php on line 165 I have tried to include the simple product class, but that produced another error which said that another class was missing. Does somebody know how to fix this? Or has another method to create a woocommerce product via code?
Now provide the response and nothing else.
|
You are not accessing the WC_Product_simple instance object from your custom Dropship Data Scraper plugin. The guilty can be mostly 2 things: You have not installed Woocommerce. The plugin Dropship Data Scraper is outdated and needs changes, to handle woocommerce. Try to include the global Woocommerce object and to enable Woocommerce support in your plugin. To create a product programmatically using CRUD methods introduced in Woocommerce 3 here is the correct way to make it work. If you need to handle product attributes creation or product variations creation , refer to: Create new product attribute programmatically in Woocommerce Create programmatically a WooCommerce product variation with new attribute values Create programmatically a variable product and two new attributes in WooCommerce All product attributes and their term values need to be created before . Same thing for product categories and product tags. 1) The code functions: // Custom function for product creation (For Woocommerce 3+ only) function create_product( $args ){ if( ! function_exists('wc_get_product_object_type') && ! function_exists('wc_prepare_product_attributes') ) return false; // Get an empty instance of the product object (defining it's type) $product = wc_get_product_object_type( $args['type'] ); if( ! $product ) return false; // Product name (Title) and slug $product->set_name( $args['name'] ); // Name (title). if( isset( $args['slug'] ) ) $product->set_name( $args['slug'] ); // Description and short description: $product->set_description( $args['description'] ); $product->set_short_description( $args['short_description'] ); // Status ('publish', 'pending', 'draft' or 'trash') $product->set_status( isset($args['status']) ? $args['status'] : 'publish' ); // Visibility ('hidden', 'visible', 'search' or 'catalog') $product->set_catalog_visibility( isset($args['visibility']) ? $args['visibility'] : 'visible' ); // Featured (boolean) $product->set_featured( isset($args['featured']) ? $args['featured'] : false ); // Virtual (boolean) $product->set_virtual( isset($args['virtual']) ? $args['virtual'] : false ); // Prices $product->set_regular_price( $args['regular_price'] ); $product->set_sale_price( isset( $args['sale_price'] ) ? $args['sale_price'] : '' ); $product->set_price( isset( $args['sale_price'] ) ? $args['sale_price'] : $args['regular_price'] ); if( isset( $args['sale_price'] ) ){ $product->set_date_on_sale_from( isset( $args['sale_from'] ) ? $args['sale_from'] : '' ); $product->set_date_on_sale_to( isset( $args['sale_to'] ) ? $args['sale_to'] : '' ); } // Downloadable (boolean) $product->set_downloadable( isset($args['downloadable']) ? $args['downloadable'] : false ); if( isset($args['downloadable']) && $args['downloadable'] ) { $product->set_downloads( isset($args['downloads']) ? $args['downloads'] : array() ); $product->set_download_limit( isset($args['download_limit']) ? $args['download_limit'] : '-1' ); $product->set_download_expiry( isset($args['download_expiry']) ? $args['download_expiry'] : '-1' ); } // Taxes if ( get_option( 'woocommerce_calc_taxes' ) === 'yes' ) { $product->set_tax_status( isset($args['tax_status']) ? $args['tax_status'] : 'taxable' ); $product->set_tax_class( isset($args['tax_class']) ? $args['tax_class'] : '' ); } // SKU and Stock (Not a virtual product) if( isset($args['virtual']) && ! $args['virtual'] ) { $product->set_sku( isset( $args['sku'] ) ? $args['sku'] : '' ); $product->set_manage_stock( isset( $args['manage_stock'] ) ? $args['manage_stock'] : false ); $product->set_stock_status( isset( $args['stock_status'] ) ? $args['stock_status'] : 'instock' ); if( isset( $args['manage_stock'] ) && $args['manage_stock'] ) { $product->set_stock_status( $args['stock_qty'] ); $product->set_backorders( isset( $args['backorders'] ) ? $args['backorders'] : 'no' ); // 'yes', 'no' or 'notify' } } // Sold Individually $product->set_sold_individually( isset( $args['sold_individually'] ) ? $args['sold_individually'] : false ); // Weight, dimensions and shipping class $product->set_weight( isset( $args['weight'] ) ? $args['weight'] : '' ); $product->set_length( isset( $args['length'] ) ? $args['length'] : '' ); $product->set_width( isset( $args['width'] ) ? $args['width'] : '' ); $product->set_height( isset( $args['height'] ) ? $args['height'] : '' ); if( isset( $args['shipping_class_id'] ) ) $product->set_shipping_class_id( $args['shipping_class_id'] ); // Upsell and Cross sell (IDs) $product->set_upsell_ids( isset( $args['upsells'] ) ? $args['upsells'] : '' ); $product->set_cross_sell_ids( isset( $args['cross_sells'] ) ? $args['upsells'] : '' ); // Attributes et default attributes if( isset( $args['attributes'] ) ) $product->set_attributes( wc_prepare_product_attributes($args['attributes']) ); if( isset( $args['default_attributes'] ) ) $product->set_default_attributes( $args['default_attributes'] ); // Needs a special formatting // Reviews, purchase note and menu order $product->set_reviews_allowed( isset( $args['reviews'] ) ? $args['reviews'] : false ); $product->set_purchase_note( isset( $args['note'] ) ? $args['note'] : '' ); if( isset( $args['menu_order'] ) ) $product->set_menu_order( $args['menu_order'] ); // Product categories and Tags if( isset( $args['category_ids'] ) ) $product->set_category_ids( $args['category_ids'] ); if( isset( $args['tag_ids'] ) ) $product->set_tag_ids( $args['tag_ids'] ); // Images and Gallery $product->set_image_id( isset( $args['image_id'] ) ? $args['image_id'] : "" ); $product->set_gallery_image_ids( isset( $args['gallery_ids'] ) ? $args['gallery_ids'] : array() ); ## --- SAVE PRODUCT --- ## $product_id = $product->save(); return $product_id; } // Utility function that returns the correct product object instance function wc_get_product_object_type( $type = 'simple' ) { // Get an instance of the WC_Product object (depending on his type) if( $type === 'variable' ){ $product = new WC_Product_Variable(); } elseif( $type === 'grouped' ){ $product = new WC_Product_Grouped(); } elseif( $type === 'external' ){ $product = new WC_Product_External(); } else { $product = new WC_Product_Simple(); // "simple" By default } if( ! is_a( $product, 'WC_Product' ) ) return false; else return $product; } // Utility function that prepare product attributes before saving function wc_prepare_product_attributes( $attributes ){ global $woocommerce; $data = array(); $position = 0; foreach( $attributes as $taxonomy => $values ){ if( ! taxonomy_exists( $taxonomy ) ) continue; // Get an instance of the WC_Product_Attribute Object $attribute = new WC_Product_Attribute(); $term_ids = array(); // Loop through the term names foreach( $values['term_names'] as $term_name ){ if( term_exists( $term_name, $taxonomy ) ) // Get and set the term ID in the array from the term name $term_ids[] = get_term_by( 'name', $term_name, $taxonomy )->term_id; else continue; } $taxonomy_id = wc_attribute_taxonomy_id_by_name( $taxonomy ); // Get taxonomy ID $attribute->set_id( $taxonomy_id ); $attribute->set_name( $taxonomy ); $attribute->set_options( $term_ids ); $attribute->set_position( $position ); $attribute->set_visible( $values['is_visible'] ); $attribute->set_variation( $values['for_variation'] ); $data[$taxonomy] = $attribute; // Set in an array $position++; // Increase position } return $data; } 2) USAGE: - Example for a simple product creation with 2 product attributes "Color" and "Size": $product_id = create_product( array( 'type' => '', // Simple product by default 'name' => __("The product title", "woocommerce"), 'description' => __("The product description…", "woocommerce"), 'short_description' => __("The product short description…", "woocommerce"), // 'sku' => '', 'regular_price' => '5.00', // product price // 'sale_price' => '', 'reviews_allowed' => true, 'attributes' => array( // Taxonomy and term name values 'pa_color' => array( 'term_names' => array('Red', 'Blue'), 'is_visible' => true, 'for_variation' => false, ), 'pa_size' => array( 'term_names' => array('X Large'), 'is_visible' => true, 'for_variation' => false, ), ), ) ); // Displaying the created product IDecho $product_id; Tested and works using only Woocommerce 3 CRUD methods.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52937409', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9718461/']}
|
jdg_373495
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18952479
|
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 the error SLF4J: Class path contains multiple SLF4J bindings.SLF4J: Found binding in [jar:file:/C:/Users/george/.gradle/caches/artifacts-26/filestore/org.apache.logging.log4j/log4j-slf4j-impl/2.0-beta8/jar/15984318e95b9b0394e979e413a4a14f322401c1/log4j-slf4j-impl-2.0-beta8.jar!/org/slf4j/impl/StaticLoggerBinder.class]SLF4J: Found binding in [jar:file:/C:/Users/george/.gradle/caches/artifacts-26/filestore/org.slf4j/slf4j-log4j12/1.5.0/jar/aad1074d37a63f19fafedd272dc7830f0f41a977/slf4j-log4j12-1.5.0.jar!/org/slf4j/impl/StaticLoggerBinder.class]SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation. In my build.gradle file I have the following line to include the jar log4j-slf4j-impl-2.0-beta8.jar (which I want to bind to LOG4J2) compile 'org.apache.logging.log4j:log4j-slf4j-impl:2.0-beta8' In another build.gradle file in a dependent project I have multiple lines similar to the following: compile 'dcm4che:dcm4che-core:2.0.23' Now dcm4che includes a dependency on log4j version 1 (slf4j-log4j12) and this is therefore being included in the overall project. Here is a snippet from the Gradle dependency tree: | +--- dcm4che:dcm4che-core:2.0.23| | \--- org.slf4j:slf4j-log4j12:1.5.0| | +--- org.slf4j:slf4j-api:1.5.0 -> 1.7.5| | \--- log4j:log4j:1.2.13 -> 1.2.14 I have read the link suggested in the warning but I cannnot figure out how to make my app bind to log4j2 using the jar that I want.The Gradle documentation on dependency management has not really made it any clearer.
Now provide the response and nothing else.
|
The solution is to add the following in the build.gradle. configurations.all { resolutionStrategy.eachDependency { DependencyResolveDetails details -> if (details.requested.name == 'log4j') { details.useTarget "org.slf4j:log4j-over-slf4j:1.7.5" }} The result is that anything that normally requires log4j will use log4j-over-slf4j instead. I also added: if (details.requested.name == 'commons-logging') { details.useTarget "org.slf4j:jcl-over-slf4j:1.7.5"} for completeness to cover commons logging.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18952479', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/986820/']}
|
jdg_373496
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4365738
|
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 access PHP session variables from jQuery function in a .js file?In this code, I want to get "value" from a session variable $(function() { $("#progressbar").progressbar({ value: 37 });});
Now provide the response and nothing else.
|
You can produce the javascript file via PHP. Nothing says a javascript file must have a .js extention. For example in your HTML: <script src='javascript.php'></script> Then your script file: <?php header("Content-type: application/javascript"); ?>$(function() { $( "#progressbar" ).progressbar({ value: <?php echo $_SESSION['value'] ?> }); // ... more javascript ... If this particular method isn't an option, you could put an AJAX request in your javascript file, and have the data returned as JSON from the server side script.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4365738', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/132640/']}
|
jdg_373497
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20107414
|
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 matplotlib to render some figure in a web app. I've used fig.savefig() before when I'm just running scripts. However, I need a function to return an actual ".png" image so that I can call it with my HTML. Some more (possibly unnecessary) info: I am using Python Flask. I figure I could use fig.savefig() and just stick the figure in my static folder and then call it from my HTML, but I'd rather not do that every time. It would be optimal if I could just create the figure, make an image out of it, return that image, and call it from my HTML, then it goes away. The code that creates the figure works. However, it returns a figure, which doesn't work with HTML I guess. Here's where I call the draw_polygon in the routing, draw_polygon is the method that returns the figure: @app.route('/images/<cropzonekey>')def images(cropzonekey): fig = draw_polygons(cropzonekey) return render_template("images.html", title=cropzonekey, figure = fig) And here is the HTML where I am trying to generate the image. <html> <head> <title>{{ title }} - image</title> </head> <body> <img src={{ figure }} alt="Image Placeholder" height="100"> </body></html> And, as you can probably guess, when I load the page, all I get is Image Placeholder . So, they didn't like the format I fed the figure in with. Anyone know what matplotlib methods/work-arounds turn a figure into an actual image? I am all over these docs but I can't find anything. Thanks! BTW: didn't think it was necessary to include the python code that makes the figure, but I can include it if You guys need to see it (just didn't want to clutter the question)
Now provide the response and nothing else.
|
You have to separate the HTML and the image into two different routes. Your /images/<cropzonekey> route will just serve the page, and in the HTML content of that page there will be a reference to the second route, the one that serves the image. The image is served in its own route from a memory file that you generate with savefig() . I obviously didn't test this, but I believe the following example will work as is or will get you pretty close to a working solution: @app.route('/images/<cropzonekey>')def images(cropzonekey): return render_template("images.html", title=cropzonekey)@app.route('/fig/<cropzonekey>')def fig(cropzonekey): fig = draw_polygons(cropzonekey) img = StringIO() fig.savefig(img) img.seek(0) return send_file(img, mimetype='image/png') Your images.html template the becomes: <html> <head> <title>{{ title }} - image</title> </head> <body> <img src="{{ url_for('fig', cropzonekey = title) }}" alt="Image Placeholder" height="100"> </body></html>
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20107414', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2497586/']}
|
jdg_373498
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
949685
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I don't remember well of my Linear Algebra classes, looking the rank of a matrix $A\in M(n\times m)$ how can we say the application associated to this matrix is surjective or injective? For a matrix $A \in M(n\times n)$ is easy, $A$ is surjective (injective) iff $\text{rank} A=n$ . Thanks
Now provide the response and nothing else.
|
The rank-nullity theorem is the key here. If your matrix $A$ is $n\times m$, with rank $k$, the theorem says that$$\dim \ker f=m-k$$where $f$ is the linear map with associated matrix $A$. Injectivity is equivalent to $\dim\ker f=0$ or, by the theorem, to $k=m$, while surjectivity is equivalent to $k=n$. Since the rank is at most $\min\{m,n\}$, we can distinguish some cases: if $n<m$, the map can be surjective (when $k=n$), but not injective if $n>m$, the map can be injective (when $k=m$), but not surjective if $n=m$, the map is injective if and only if it is surjective (but it can be neither)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/949685', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/42912/']}
|
jdg_373499
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41127
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Suppose $p_n$ is $n$-th prime, $g_n=p_{n+1}-p_n$ is the corresponding prime gap . What is the highest number $C$, such that $p_N>C$ can be proven for $N=\min\{n\mid g_n\geq 1.609\cdot 10^{18}\}$. Motivation: I've read about Goldbach's weak conjecture . The number $C$ above is obvious lower bound for the first odd number, which does not admit a representation as a sum of three primes, which follows from check of Goldbach's conjecture up to $1.609\cdot 10^{18}$, which is done already by computers. I just want to know, how big is it.
Now provide the response and nothing else.
|
From the Wikipedia page on Bertrand's postulate , Dusart (1998) showed that for all $x > 3275$, there exists a prime between $x$ and $x \left( 1 + \frac{1}{2 \ln^2 x} \right)$. You are looking for the largest $N$ such that $\frac{N}{2\ln^2 N} < 1.609 \cdot 10^{18}$. A quick computation yields about $8.193\cdot 10^{21}$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/41127', 'https://mathoverflow.net', 'https://mathoverflow.net/users/8134/']}
|
jdg_373500
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4081298
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose we randomly pick 2 points A, B within a circle centeredat point O. What is the probability that the triangle formed by ABO isan obtuse one? (Note that A and B are not exclusively on thecircumference). And what is the conclusion extended to A, B within a ball instead? Thanks! PS this is from a Quant interview. The following is what I have derived during the exam: (Edited, thank you for your corrections!)consider the joint probability of x, y coordinate for any point in a unit circle, then $f_{XY}(x, y) = \frac{1}{\pi}$ , uniformly distributed inside the circular region. The distance between the point and the center, has thus a distribution $f_Z(z) = 2z$ for $z$ in [0, 1] ( $z^2 = x^2 + y^2$ ).Randomly pick an A, rotate the circle so that A is right on top of the center O. Suppose now A has a distance $z = a$ $(a > 0)$ away from the origin, then B could only be chosen in the region of $y > a$ $y < 0$ within an inner circle whose diameter is $OA$ Therefore, given that the distance is $z = a$ , the probability of ABO being an obtuse triangle is given corresponds to area $\arccos(a) - a\sqrt{1-a^2} + \frac{a^2\pi}{4} + \frac{\pi}{2}$ (Upper, inner, and lower). By this conditional probability, we could derive the total probability, which is $$\int_0^1 \frac{1}{\pi}\left(\arccos(a) - a\sqrt{1-a^2} + \frac{a^2\pi}{4} + \frac{\pi}{2}\right) \cdot 2a \; da = \frac{3}{4}$$ But is there an easier way to solve this? This looks like a math competition style of question and I expect some tricks to be at play. Thanks!
Now provide the response and nothing else.
|
The probability that point $A$ is at a distance from the center in $[a,a+da]$ is $2\pi a\,da/\pi=2a\,da$ .The probability that, fixed $A$ as above, $\angle ABO>90°$ , is the same as the probability that $B$ lies inside a circle of diameter $OA$ , that is $\pi(a/2)^2/\pi=a^2/4$ .Hence the overall probability that $\angle ABO>90°$ is: $$p(\angle ABO>90°)=\int_0^1 {a^2\over4}\cdot 2a\,da={1\over8}.$$ The probability that triangle $ABO$ is obtuse is then: $$p(\angle ABO>90°)+p(\angle BAO>90°)+p(\angle AOB>90°)={1\over8}+{1\over8}+{1\over2}={3\over4}.$$ EDIT. For a 3D sphere one can repeat the same argument, obtaining: $$p(\angle ABO>90°)=\int_0^1 {a^3\over8}\cdot 3a^2\,da={1\over16}.$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4081298', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/831119/']}
|
jdg_373501
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
264109
|
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 read a paper and met the concept Katetov extension. What is Katetov extension of the natural numbers? Reference on it are also welcome.
Now provide the response and nothing else.
|
In M. Katětov, Über H-abgeschlossene und bikompakte Räume , Cas. Mat. Fys., 69:39-49, 1940, Katětov proved that any Hausdorff space $X$ can be densely embedded in an $H$-closed space; he did it by constructing a specific $H$-closed extension, $\kappa X$, of $X$. (A space is $H$-closed if it is closed in every Hausdorff space in which it is embedded.) Definition. If $\langle X,\tau\rangle$ is a Hausdorff space, $\kappa X$, the Katětov extension of $X$, is the set $$X\cup\{p\subseteq\tau:p\text{ is a free open ultrafilter on }X\}$$ with the topology generated by $$\big\{\{p\}\cup U:U\in p\in\kappa X\setminus X\big\}\;.$$ The first paper here , by Mukherjee, Sengupta, and Ghosh, treats some cardinal functions on $\kappa D$ for discrete spaces $D$. Added: That link goes to a front page from which it’s not obvious how to reach the paper. Here is a direct link to the PDF. Katětov’s original paper is freely available here .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/264109', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/17980/']}
|
jdg_373502
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
53938125
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am new with Kafka Java API and I am working on consuming records from a particular Kafka topic. I understand that I can use method subscribe() to start polling records from the topic. Kafka also provides method assign() if I want to start polling records from selected partitions of the topics. I want to understand if this is the only difference between the two?
Now provide the response and nothing else.
|
Yes subscribe need group.id because each consumer in a group will dynamically assigned to partitions for list of topics provided in subscribe method and each partition can be consumed by one consumer thread in that group. This is achieved by balancing the partitions between all members in the consumer group so that each partition is assigned to exactly one consumer in the group assign will manually assign a list of partitions to this consumer. and this method does not use the consumer's group management functionality (where no need of group.id ) The main difference is assign(Collection) will loose the controller over dynamic partition assignment and consumer group coordination It is also possible for the consumer to manually assign specific partitions (similar to the older "simple" consumer) using assign(Collection). In this case, dynamic partition assignment and consumer group coordination will be disabled. subscribe public void subscribe(java.util.Collection<java.lang.String> topics) The subscribe method Subscribe to the given list of topics to get dynamically assigned partitions. and if the given list of topics is empty, it is treated the same as unsubscribe(). As part of group management, the consumer will keep track of the list of consumers that belong to a particular group and will trigger a rebalance operation if one of the following events trigger - Number of partitions change for any of the subscribed list of topicsTopic is created or deletedAn existing member of the consumer group diesA new member is added to an existing consumer group via the join API assign public void assign(java.util.Collection<TopicPartition> partitions) The assign method manually assign a list of partitions to this consumer. And if the given list of topic partitions is empty, it is treated the same as unsubscribe(). Manual topic assignment through this method does not use the consumer's group management functionality. As such, there will be no rebalance operation triggered when group membership or cluster and topic metadata change.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53938125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4958332/']}
|
jdg_373503
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16731065
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I created a simple JSF login page, and I'm trying to integrate it with spring security. Here is the form element from login.xhtml <h:form> <h:outputLabel value="User Id:" for="userId"/> <h:inputText id="j_username" label="User Id" required="true" value="#{loginBean.name}" > </h:inputText> <h:outputLabel value="Password: " for ="password"/> <h:inputSecret id="j_password" value="#{loginBean.password}" /> <h:commandButton value="Submit" action="#{j_spring_security_check}" /> </h:form> But the rendered html page has something like the below. Take a look at the form action and the input tag's names The form element <form id="j_idt6" name="j_idt6" method="post" action="/jsfproject2/faces/login.xhtml" enctype="application/x-www-form-urlencoded"> And the input tags User Id:</label><input id="j_idt6:j_username" type="text" name="j_idt6:j_username" /> Now I want form action to be /j_spring_security_check and input boxes to be 'j_username' and j_password How can we achieve this ?
Now provide the response and nothing else.
|
There are two options for Spring Security to work. Use prependId="false" on a JSF form As <h:form> is a naming container, it prepends id of its children with the specified id , or the autogenerated id, so as Spring Security expects ids to remain unchainged, just don't prepend the ids: <h:form prependId="false"> <h:outputLabel value="User Id: " for="userId" /> <h:inputText id="j_username" label="User Id" required="true" value="#{loginBean.name}" /> <h:outputLabel value="Password: " for ="password" /> <h:inputSecret id="j_password" value="#{loginBean.password}" /> <h:commandButton value="Submit" action="#{loginBean.login}" /></h:form> Note that #{j_spring_security_check} is a wrong action method: it needs to be #{loginBean.login} with the following contents: public String login() { //do any job with the associated values that you've got from the user, like persisting attempted login, etc. FacesContext facesContext = FacesContext.getCurrentInstance(); ExternalContext extenalContext = facesContext.getExternalContext(); RequestDispatcher dispatcher = ((ServletRequest)extenalContext.getRequest()).getRequestDispatcher("/j_spring_security_check"); dispatcher.forward((ServletRequest)extenalContext.getRequest(), (ServletResponse)extenalContext.getResponse()); facesContext.responseComplete(); return null;} Basically, all you need to do is dispatch to /j_spring_security_check and have j_username and j_password as request parameters. Use plain HTML form Basically, there's no particular need to mess with JSF form on this issue, in case you don't need to do some extra things apart from authentication, and plain HTML form is sufficient for Spring Security to do its job. <form action="/j_spring_security_check" method="POST"> <label for="j_username">User Id: </label> <input id="j_username" name="j_username" type="text" /> <label for="j_password">Password: </label> <input id="j_password" name="j_password" type="password"/> <input type="submit" value="Submit"/></form>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16731065', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/865188/']}
|
jdg_373504
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1514761
|
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:
$$\lim_{x\to\infty} x \sin\left(\frac{1}{x}\right) = ?$$ Not a long ago I saw this function, and I was curious, what limit it has, when $x$ approaches $\infty$? Some of my friends said fast that it must approach $\infty$, since $\sin$ is a bounded function, and $x$ goes to infinity, therefore infinity * bounded must be infinity. Some others said that $\sin(\frac{1}{x})$ is $0$, since $\frac{1}{x}$ is $0$, when $x \rightarrow \infty$. So, the first possible solution should be $\infty$, but here is an other one. Let $y=\frac{1}{x}$. If $x \rightarrow \infty$, then $y \rightarrow 0$. Using that: $$\lim_{x\to\infty} x \sin\left(\frac{1}{x}\right) = \lim_{y\to 0} \frac {1}{y} \sin(y) = \lim_{y\to 0} \frac{\sin(y)}{y} = 1$$ Here is a proof that, $\lim_{y\to 0} \frac{\sin(y)}{y} = 1$: Proof So here we have $2$ completely different solutions for the same task, which both seem "logical". Is any of them correct, or if not, what should be the solution? Is this convergent, or divergent? Any help appreciated!
Now provide the response and nothing else.
|
The first line of reasoning is clearly incorrect: let $f(x) = x$, $g(x) = (x^2 + 1)^{-1}$. Then $$\lim_{x \to \infty} f(x) = \infty$$ and $g(x) \in (0,1]$ is clearly bounded on $\mathbb R$. But $$\lim_{x \to \infty} f(x) g(x) = \lim_{x \to \infty} \frac{1}{x+1/x} = 0.$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1514761', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/215617/']}
|
jdg_373505
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35602939
|
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 when I try to insert '2011/03/13 02:53:50.000000000' into a timestamp column. If I change the 13 to a 15, 14, 12 or 11 it works no problem. I've also tried changing the /'s to -'s and still no-go. I've looked through some of the other threads related to this error but none seem to apply. I'm running version 5.7.9.
Now provide the response and nothing else.
|
It took me a while to figure this out... The problem is that '2011-03-13 02:53:50' is illegal because of daylight saving time switch between 2 and 3 AM, so all time values between 2 and 3 am on any DST introduction day are invalid. Same for '2016-03-13 02:32:21', etc. Change the system timezone to the one that does not use DST and you should be fine.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/35602939', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3586878/']}
|
jdg_373506
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1504451
|
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 I want something like Dictionary<Tkey1, TKey2, TValue>, but not (as I've seen here in other question) with the keys in AND, but in OR. To better explain: I want to be able to find an element in the dictionary providing just one of the keys, not both. I also think we should consider thread-safety and the ability to easily scale to a Dictionary<Tkey1, TKey2, TKeyN, TValue> solution...
Now provide the response and nothing else.
|
I would implement a data structure with these two dictionaries Dictionary<TKey1, KeyValuePair<TKey2, TValue>> dict1;Dictionary<TKey2, KeyValuePair<TKey1, TValue>> dict2; That way if you are given 1 key you have both the value and the other key as well for easy deletes and updates.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1504451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/182547/']}
|
jdg_373507
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
241139
|
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:
Everyone knows of the common cybersecurity tips to be careful when you open links in an email. But every day we look for something on the Internet, clicking links which the search engine shows us, and we do not have the same fear. Why are the links in email considered more dangerous than links from web search results? Maybe it is related to the fact that links in an email may contain a more personal attack malicious to you or your company?
Now provide the response and nothing else.
|
The results of a search engine are based on previously collected data, i.e. the engine does not starts to scanning the whole internet when doing a search but it looks through an index of seen and stored sites. The results are also ordered, i.e. the sites which fit the query best and which also have the highest reputation for good answers in general are at the top. Thus, as long as fairly common search terms are used the top hits come from sites with a high reputation. There are attempts to pollute search engines by returning different results to the search engines web bot than to the normal user. This is not new, so search engines partially try to detect such pollution by simulating normal users. They also include historic reputation information, i.e. sites which behaved shady in the past are considered shady for some time in the future too. New sites also have less reputation than established sites etc. This together makes search engines results fairly good (but not perfect) curated data. Links in mails are the opposite of this: No up-front checks and curation are done to these links and it is all to the end user (or some security software in the path) to decide if this link is safe or not. That's why these links are far more dangerous.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://security.stackexchange.com/questions/241139', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/214750/']}
|
jdg_373508
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
232974
|
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a 660297728 byte HDD image with MD5 hash f5a9d398e974617108d26c1654fe7bcb : root@T42# ls -l image-rw-rw-r-- 1 noc noc 660297728 Sep 29 19:00 imageroot@T42# md5sum imagef5a9d398e974617108d26c1654fe7bcb image Now if I dd this image file to /dev/sdb disk and check the MD5 hash of the disk, then it is different from MD5 hash of the image file: root@T42# dd if=image of=/dev/sdb bs=5121289644+0 records in1289644+0 records out660297728 bytes (660 MB) copied, 1006.38 s, 656 kB/sroot@T42# md5sum /dev/sdbf6152942a228a21a48c731f143600999 /dev/sdb What might cause such behavior?
Now provide the response and nothing else.
|
Is /dev/sdb exactly 660297728 bytes large? ( blockdev --getsize64 /dev/sdb ). If not, the checksum would naturally be different. Use cmp image /dev/sdb to find out where the differences are in detail. If it says EOF on image , it's identical.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/232974', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/33060/']}
|
jdg_373509
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
43772
|
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:
It is clear that cars with automatic transmissions cannot be towed with any drive wheels on the ground, engine off, in neutral, because the torque converter powers the lubrication pump for the transmission. Why is it considered safe for a manual transmission? Doesn't the transmission need to be lubricated and cooled, just like an automatic? What about the differential or all the other parts of the car that move while being towed? Don't they need to be properly lubricated too? What is the technical reason behind this? Edit #1 I thought that for a manual transmission in neutral, the output shaft does not spin the layshaft, which in turn does not spin the crankshaft, otherwise the entire powertrain would be 'closed' or 'connected', so how is it possible that splash lubrication is occurring at the bottom of the sump? Why was the method for supplying lubrication to an automatic transmission engineered differently compared to a manual transmission?
Now provide the response and nothing else.
|
Manual transmissions (most, but not all) lubricate not through a pump, but through the action of the gears and secondarily through the level of the transmission fluid itself. In some transmissions, the lower gears in the transmission, which touch the pool of fluid at the bottom of the transmission, transfers fluid through contact to the upper gears. In this situation, since the output to the drive axles is still attached to the gears, even when the transmission is in neutral, the fluid still flows. EDIT: Checking through many different transmission layouts, it also become apparent the level of the fluid is high enough to be right at the level of the main shaft in the transmission. In some transmissions where the lay shaft (as @Narcotixs pointed out) doesn't have gears actually turning, the amount of transmission fluid in the gear box allows for the lubrication of any moving parts. This representative image (sorry, best I could find on Google) shows the location of the fill plug in relationship to the main shaft. Most manual transmissions will have this same relationship between the fill plug and the main shaft. /EDIT The differential is much the same as the ring gear sits in the gear oil and the oil flows through differential. The differential doesn't care so long as the tires are moving. It will behave the same either way, whether there is power applied from the engine, or the tires are just rolling along. That being said, putting a car up onto a tow dolly or trailer is a much "safer" way to transport a vehicle. It will be much more secure, especially if you're looking to transport the vehicle for any longer length of time.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mechanics.stackexchange.com/questions/43772', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/25720/']}
|
jdg_373510
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11483863
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I get the indices of intersection points between two numpy arrays? I can get intersecting values with intersect1d : import numpy as npa = np.array(xrange(11))b = np.array([2, 7, 10])inter = np.intersect1d(a, b)# inter == array([ 2, 7, 10]) But how can I get the indices into a of the values in inter ?
Now provide the response and nothing else.
|
You could use the boolean array produced by in1d to index an arange . Reversing a so that the indices are different from the values: >>> a[::-1]array([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0])>>> a = a[::-1] intersect1d still returns the same values... >>> numpy.intersect1d(a, b)array([ 2, 7, 10]) But in1d returns a boolean array: >>> numpy.in1d(a, b)array([ True, False, False, True, False, False, False, False, True, False, False], dtype=bool) Which can be used to index a range: >>> numpy.arange(a.shape[0])[numpy.in1d(a, b)]array([0, 3, 8])>>> indices = numpy.arange(a.shape[0])[numpy.in1d(a, b)]>>> a[indices]array([10, 7, 2]) To simplify the above, though, you could use nonzero -- this is probably the most correct approach, because it returns a tuple of uniform lists of X , Y ... coordinates: >>> numpy.nonzero(numpy.in1d(a, b))(array([0, 3, 8]),) Or, equivalently: >>> numpy.in1d(a, b).nonzero()(array([0, 3, 8]),) The result can be used as an index to arrays of the same shape as a with no problems. >>> a[numpy.nonzero(numpy.in1d(a, b))]array([10, 7, 2]) But note that under many circumstances, it makes sense just to use the boolean array itself, rather than converting it into a set of non-boolean indices. Finally, you can also pass the boolean array to argwhere , which produces a slightly differently-shaped result that's not as suitable for indexing, but might be useful for other purposes. >>> numpy.argwhere(numpy.in1d(a, b))array([[0], [3], [8]])
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11483863', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1523360/']}
|
jdg_373511
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
70532
|
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've read a half-dozen threads here about the pros and cons of hosting in-house, but our situation is a little different than most, so I figured I'd just open a new question. In short, we're a small software company in the northeast U.S. ( not Boston or N.Y., a bit in the hills), with an existing product line. For various reasons related to future development work, we need to have servers in-house one way or the other -- right now, we have a couple of 1U Suns (very nice X2100's that are holding up like rocks BTW) in a quarter-height rack. We've been hosting our sites elsewhere for years, but now that we've got a pile of hardware in-house that won't be going anywhere, I'm thinking it might be worthwhile to just do all our public-facing hosting in house as well. My reasoning, in short: the hardware is essentially a sunk cost anyway we're already doing whatever admin work is necessary (though, in my experience, you need to pay through the nose for truly managed hosting, as opposed to just having access to a box, which seems to be what passes for 'managed' in the biz) our problems will be our own, or moreso compared to any hosting situation (i.e. I've experienced way more downtime because some fool kicked over a router or whatever at a hosting provider than I have due to random admin-level issues) we push a lot of large files around, and not having to wait for an upload to our hosted servers sounds very appealing Obvious cons include: Power. We've got appropriate UPS, but no redundancy. Bandwidth. Right now we have 16d/2u through Comcast. If we move our main site over, we'll need to at least double that, which might require bonding 2+ cable lines. A/C. I don't think this a real issue -- I don't expect that we'll ever have more than 10 servers in here (if we get larger than that, then the economics of this decision change a lot). Thoughts? Thanks! Update : After vacilating some, we've decided to keep hosting offsite. Coincidentially, there was a power outage on our block today, which sorta tipped the scales psychologically (hardly a rigorous process, but wasting about 3 hours was enough for me to take the cue that the universe was trying to tell me something ;-). Not sure what vendor we'll use going forward, but I appreciated the tip-off to the rackspace cloud as an alternative to ec2, etc.
Now provide the response and nothing else.
|
I just got done moving our public facing servers to Rackspace Cloud Servers. About a year ago I did what you're thinking about doing because I wanted complete control over my servers, and am a little bit sour on leasing cheap servers (the typical $100 / month "server" that's just a PC). I finally gave up on the in-house hosting gig because: Local bandwidth is either very expensive or not high quality or both. Good quality routers are also very expensive. So those times when a customer was downloading some huge file at the same time Google and Yahoo etc were crawling were not real nice. Having hardware in-house means that I have to babysit it. I've already got our local servers to worry about; adding more didn't help me out much. Power outages, some jerkwad with a shovel digging in the wrong spot, etc are suddenly a problem. Having local servers go offline is something we always have to worry about, but why should our public servers go offline with them? There have been times when we've had our lines go down for >24 hours. For in-house workers this is manageable, but having our public sites go away for that long can be bad news. Disaster recovery planning is more complicated. What do you do if the server goes up in smoke? Do you have another one? How fast can you bring it or some other machine online? If your connection goes down and your phone/cable company says it'll be up "in a day or two", can you wait it out or can you throw your sites up online somewhere quickly? How do you get them there if all of your connections are down? I know these sorts of issues have to be addressed no matter what, but what kind of resources do you have available locally? The one thing I did like, as you also mentioned, was being able to shoot files up to the web servers very quickly (we do a lot of WebDAV). But the way I figure it...better us having to wait for uploads than our customers having to wait for downloads. Anyhow, the Rackspace Cloud Server solution addressed just about all of the concerns I've always had with leasing dedicated machines or signing up with a VPS provider (including cost). It offers a lot of those little tricks that real virtualization promises. Anyhow, I won't advertise for them. An alternative might be Amazon EC2. Long story longer, I sleep better knowing that I'm not going to get a call because our webserver is on fire or that the power company dug up the DSL lines again. I'll let some other chump be responsible for that... in a place where they've actually got the resources at hand to handle these things. So my suggestion is to keep your public stuff in a good datacenter of some sort. Use those extra servers for in-house tasks. There's usually something you can use them for... testing, special projects, backup, etc.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/70532', 'https://serverfault.com', 'https://serverfault.com/users/21758/']}
|
jdg_373512
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5535992
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here is a simplification of my code: void Foo(params object[] args){ Bar(string.Format("Some {0} text {1} here {2}", /* I want to send args */);} string.Format requires the arguments sent as params . Is there some way I can convert the args collection into parameters for the string.Format method?
Now provide the response and nothing else.
|
The params keyword is only syntactic sugar that allows you to call such a method with any number of arguments. However, those arguments are always passed to the method as an array. This means that Foo(123, "hello", DateTime.Now) is equivalent to Foo(new object[] { 123, "hello", DateTime.Now }) . You can therefore pass the arguments from Foo directly to string.Format like this: void Foo(params object[] args){ Bar(string.Format("Some {0} text {1} here {2}", args));} However, in this particular case, you demand three arguments (because you have {0}, {1} and {2} in your format). Therefore you should change your code to: void Foo(object arg0, object arg1, object arg2){ Bar(string.Format("Some {0} text {1} here {2}", arg0, arg1, arg2));} ...or do as Marcelo suggested.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5535992', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/326370/']}
|
jdg_373513
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8099833
|
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 writting a generalized method to use it in a special task at a T4 template. The method should allow me to use specialized types from a general interface. I thought about the following signatures: interface IGreatInterface { Object aMethodAlpha<U>(U parameter) where U : IAnInterface; Object aMethodBeta(IAnInterface parameter)}public class AnInterestingClass : IAnInterface{} When I try to implement IGreatInterface the compiler flags an error for aMethodBeta() because I've made my T4 to write that method using a subtype of IAnInterface (i.e. I want to implement that method like this: Object aMethodBeta(AnInterestingClass parameter) ). Method aMethodAlpha<U>() can be used but is not as clean as I want because my T4 has to generate some extra code. I (perhaps wrongly) propose that an implementation of that method, which has to be done by a T4, could be Object aMethodAlpha<AnInterestingClass>(AnInterestingClass parameter) . I'm thinking that generic methods do not support contravariant types but I'm not sure; I suppose that It's the way the compiler prevents the coder to use a specific type having a method not defined in the general type... Does a generic method have to use the exact type when being implemented? Is there any trick to change this behavior?
Now provide the response and nothing else.
|
This question is quite confusing. Let me see if I can clarify it. When I try to implement IGreatInterface the compiler flags an error for aMethodBeta() because I've made that method using a subtype of IAnInterface I want to implement that method like this: Object aMethodBeta(AnInterestingClass parameter) . That's not legal. Simplifying somewhat: class Food {}class Fruit : Food {}class Meat : Food {}interface IEater{ void Eat(Food food);}class Vegetarian : IEater{ public void Eat(Fruit fruit);} Class Vegetarian does not fulfill the contract of IEater . You should be able to pass any Food to Eat, but a Vegetarian only accepts Fruit. C# does not support virtual method formal parameter covariance because that is not typesafe. Now, you might then say, how about this: interface IFruitEater{ void Eat(Fruit fruit);}class Omnivore : IFruitEater{ public void Eat(Food food);} Now we have got type safety; Omnivore can be used as an IFruitEater because an Omnivore can eat fruit, as well as any other food. Unfortunately, C# does not support virtual method formal parameter type contravariance even though doing so is in theory typesafe. Few languages do support this. Similarly, C# does not support virtual method return type variance either. I'm not sure if that actually answered your question or not. Can you clarify the question? UPDATE: What about: interface IEater{ void Eat<T>(T t) where T : Food;}class Vegetarian : IEater{ // I only want to eat fruit! public void Eat<Fruit>(Fruit food) { }} Nope, that's not legal either. The contract of IEater is that you will provide a method Eat<T> that can take any T that is a Food . You cannot partially implement the contract, any more than you could do this: interface IAdder{ int Add(int x, int y);}class Adder : IAdder{ // I only know how to add two! public int Add(2, int y){ ... }} However, you can do this: interface IEater<T> where T : Food{ void Eat(T t);}class Vegetarian : IEater<Fruit>{ public void Eat(Fruit fruit) { }} That is perfectly legal. However, you cannot do: interface IEater<T> where T : Food{ void Eat(T t);}class Omnivore : IEater<Fruit>{ public void Eat(Food food) { }} Because again, C# does not support virtual method formal parameter contravariance or covariance. Note that C# does support parametric polymorphism covariance when doing so is known to be typesafe. For example, this is legal: IEnumerable<Fruit> fruit = whatever;IEnumerable<Food> food = fruit; A sequence of fruit may be used as a sequence of food. Or, IComparable<Fruit> fruitComparer = whatever;IComparable<Apples> appleComparer = fruitComparer; If you have something that can compare any two fruits then it can compare any two apples. However, this kind of covariance and contravariance is only legal when all of the following are true: (1) the variance is provably typesafe, (2) the author of the type added variance annotations indicating the desired co- and contra-variances, (3) the varying type arguments involved are all reference types, (4) the generic type is either a delegate or an interface.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8099833', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/199419/']}
|
jdg_373514
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24971526
|
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 uploadify. when i try to open the page with uploadify script the page is crashed. I using this for a long time. but now only I am getting the error. Its happening only in chrome. Its working perfectly in firefox, safari, and IE. I searched through the google and find a solution like disable cache in the browser(working). But its not the best way to do this in the client browser. Is there any way to disable cache for the specific page using htaccess? I tried the following in the htaccess. but no use. <Files jquery.uploadify.js> ExpiresDefault "access plus 0 seconds"</Files> Please suggest me to solve this problem.
Now provide the response and nothing else.
|
Finally i solved it by adding an extra parameter(changing the URL or versioning the file) ?ver=<?php echo rand(0,9999);?> to the .js file like below. <script src="js/jquery.uploadify.min.js?ver=<?php echo rand(0,9999);?>" type="text/javascript"></script> For more information check this UPDATE(27-01-2015): The above solution is not working now. Found another solution. Add timeout around the uploadify function like below will prevent the chrome to crash. Its not the correct solution but it will prevent now. The forum of uploadify also locked. So, I cant able to post a question regard this. setTimeout(function () { $("#uploadify_id").uploadify({})...},0); Thanks for everyone.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24971526', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3049065/']}
|
jdg_373515
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13490684
|
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 can't seem to find what the difference is between Git and Nexus . Are the two comparable?
Now provide the response and nothing else.
|
There are both referential: one ( Git ) is a source referential for version control (with features like merging, branching, tags) the other ( Nexus ) is an artifact referential for any delivery (binaries or not) The referential database differs also: Git has its own internal repository storage mechanism Nexus is simply a collection of shared directories with a naming convention ( group.artifact.version ). As described in " What is a repository ": a collection of binary software artifacts and metadata stored in a defined directory structure. The idea is that, for large deliveries that can be produced quite often, it is much easier to store them in Nexus ( you can clean them easily enough: cd + rm ), as opposed to version them ( which makes a DVCS repo like Git way too big way too fast to be cloned easily ). So their goals are different, as I explain in: " How do different version control systems handle binary files? " " Best practice to store .jar files in VCS (SVN, Git, …) " " Using source controlled libraries in source controlled projects " You manage what you code in Git, and what you build in Nexus.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13490684', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/669331/']}
|
jdg_373516
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
13922
|
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I saw on Discovery channel that the source of Earth's magnetic field is the molten iron and metals in the earth's core. The spinning of these liquid metals produces the same effect as electric current in a coil which produces a magnetic field. The scientist in the program proved the concept by conducting an experiment where a big metal sphere where winded by a metallic tube in which molten Sodium was pumped so it circulate around the sphere in a similar way that happens inside earth. The experiment showed that a magnetic field was successfully produced. My question is : How could a circulating neutrally charged particles produce a magnetic field? It is like having two electric currents one due to the negative charges (electrons) and the other is due to positive charges (nucleus) with same value and in opposite direction so there should not be a magnetic field. so how does this happen?
Now provide the response and nothing else.
|
Circulating neutral particles will not by themselves create a magnetic field. However, if the neutral particles are moving through an existing magnetic field, and the neutral medium is conducting, then the magnetic field will induce a current via the Lorentz force. That induced current will in turn create it's own magnetic field, which may enhance the existing magnetic field. If things work out right you have a self-reinforcing dynamo where motion thru the magnetic fields drives currents and those currents in turn support the magnetic field. However, there had to be some sort of "seed" field to get the thing started in the beginning.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/13922', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/3241/']}
|
jdg_373517
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2862702
|
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:
Peter draws a ball from the bag, and then Angelina draws a ball. What is the probability that Angelina got a green ball? So far I have this: Scenario A: 1st ball is not green, 2nd green: 7/12 * 5/11 = 35/132 Scenario B: 1st ball is green, 2nd green: 5/12 * 4/11 = 20/132 --> $$\frac{55}{132} = \frac{5}{12}$$
Now provide the response and nothing else.
|
Your approach is fine, but it's worth realizing that unless you know something about the ball Peter has chosen, he may as well not have chosen at all, in which case Angelina simply has a $5/12$ chance of choosing a green ball. Where this point really becomes worth understanding is if, for example, not only Peter, but also Olivia, Ned, Melissa, and Larry choose balls before Angelina. The tree of possibilities is tedious and messy, but the answer is still $5/12$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2862702', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/579536/']}
|
jdg_373518
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
96178
|
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:
If I encrypt all my files can I get "attacked" by ransom attacks? Because my files are already encrypted, they cannot access them, so I should be safe or am I wrong? Also, if someone could tell me how this encryption works, I would be really thankful. I already read some articles on Wikipedia and it states there that the encryption does not work while booting (in the English article it's called Cold-Boot-Attack), so would it be possible to get access to the files somehow when booting? Not that I need it now, but you never know.
Now provide the response and nothing else.
|
TLDR: Any file encryption does not protect you against Ransom Attack. We can consider two scenarios: You encrypt your files with some tools (e.g. encrypted zip), You have encrypted whole partition (Truecrypt, dm-crypt etc.). In the first case, even if you have encrypted your files they can be encrypted again by ransomware. And then you won't be able to decrypt them. Bad situation. In the second case, ransomware lives in the computer's runtime (while you're using it), therefore it has an access to decrypted files on your computer. The disk partition is decrypted on boot up and encrypted again when you shutdown your machine. Again, bad situation. A file encryption does not protect you against ransomware. The Cold boot attack is a bit different story and you shouldn't consider it here to not confuse yourself. I've tried to explain it in the easy way, I hope I helped somehow :) To protect against ransomware you can (should!) do at least these three things: Do not visit malicious sites. Backup important stuff (on a separate, unplugged drive) :) You can also install some antivirus, EMET etc. The likelihood of being successfully ransom-attacked will for sure decrease.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/96178', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/82859/']}
|
jdg_373519
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
65553800
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Evaluating the following code, I would expect a single printing of Hello World . Instead, it causes an infinite loop. Can someone explain why? let array = ["what"]for text: String? in array { print("Hello World")} (Removing the optional ? obviously makes it print only once)
Now provide the response and nothing else.
|
This is an unexpected result, but it is happening because of the way Swift for in loops work under the hood. for in takes a variable and a Sequence . Swift calls makeIterator() on the Sequence to get an IteratorProtocol which returns successive items when next() is called on the iterator. next() returns an Optional so that it can return nil when all of the items have been exhausted. In a normal case, you receive the non-optional values and Swift continues giving them out until nil is received in which case the loop ends. This is the equivalent of your code when you don't use an optional : let array = ["what"]var iter = array.makeIterator()while let text = iter.next() { print("Hello World")} The optional binding ( while let ) fails when iter.next() returns nil and the loop ends. In your case, you have said that you will explicitly receive nil values (by declaring your loop variable as an optional ), so when next() is called on the iterator and it is out of values, it hands you a nil which you graciously receive and the loop continues. The iterator continues to hand out nil and you continue to take them, and you have an infinite loop. This is the equivalent of your code when you use an optional : let array = ["what"]var iter = array.makeIterator()while let text: String? = iter.next() { print("Hello World")} In this case, the optional binding always works because text can receive the nil . This blog gives a nice detailed explanation of what is happening under the hood with Swift for in loops.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/65553800', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3749617/']}
|
jdg_373520
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31679352
|
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 use jQuery to capture the value of two cells from a table. My table looks like this: <table id="searchByLocationResults" class="table table-hover table-striped" cellspacing="0" style="border-collapse:collapse;"> <tbody> <tr> <th scope="col">View Detail</th> <th scope="col">Quantity</th> <th scope="col" style="display:none;">Location ID</th> <th scope="col" style="display:none;">Item Type ID</th> </tr> @For Each item In Model Dim currentItem = item @<tr> <td><a class="btn btn-default btn-sm" onclick="viewDetails(this)">View Detail</a></td> <td> @Html.DisplayFor(Function(modelItem) currentItem.COUNT) </td> <td style="display:none;" class="locationID"> @Html.DisplayFor(Function(modelItem) currentItem.Unique_Location_ID) </td> <td style="display:none;" class="itemType"> @Html.DisplayFor(Function(modelItem) currentItem.Item_Type_Identifier) </td> </tr> Next </tbody> </table> As you can see there is a 'view details' button on each row. What I need to do is capture the display:none values in the cells with class=locationID and class=itemType when the button is clicked, only for the row that the button is clicked on. I have seen multiple solutions on stack over flow here , here and quite a few others. Most of these are dealing with capturing an entire row of values. I have tried a few different scripts: function viewDetails(clickedRow) { var locationID = $(this).find(".selected td:.locationID").val(); alert(locationID); and: function viewDetails(clickedRow) { var locationID = tr.find(".locationID").val(); alert(locationID); as well as a few others. How do you capture the values of the cells locationID and itemType for the row that 'View Details' is clicked on?
Now provide the response and nothing else.
|
Since we are speaking about maximizing throughput of IP address parsing, I suggest using a vectorized solution. Here is x86-specific fast solution (needs SSE4.1, or at least SSSE3 for poor): __m128i shuffleTable[65536]; //can be reduced 256x times, see @IwillnotexistIdonotexistUINT32 MyGetIP(const char *str) { __m128i input = _mm_lddqu_si128((const __m128i*)str); //"192.167.1.3" input = _mm_sub_epi8(input, _mm_set1_epi8('0')); //1 9 2 254 1 6 7 254 1 254 3 208 245 0 8 40 __m128i cmp = input; //...X...X.X.XX... (signs) UINT32 mask = _mm_movemask_epi8(cmp); //6792 - magic index __m128i shuf = shuffleTable[mask]; //10 -1 -1 -1 8 -1 -1 -1 6 5 4 -1 2 1 0 -1 __m128i arr = _mm_shuffle_epi8(input, shuf); //3 0 0 0 | 1 0 0 0 | 7 6 1 0 | 2 9 1 0 __m128i coeffs = _mm_set_epi8(0, 100, 10, 1, 0, 100, 10, 1, 0, 100, 10, 1, 0, 100, 10, 1); __m128i prod = _mm_maddubs_epi16(coeffs, arr); //3 0 | 1 0 | 67 100 | 92 100 prod = _mm_hadd_epi16(prod, prod); //3 | 1 | 167 | 192 | ? | ? | ? | ? __m128i imm = _mm_set_epi8(-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 6, 4, 2, 0); prod = _mm_shuffle_epi8(prod, imm); //3 1 167 192 0 0 0 0 0 0 0 0 0 0 0 0 return _mm_extract_epi32(prod, 0);// return (UINT32(_mm_extract_epi16(prod, 1)) << 16) + UINT32(_mm_extract_epi16(prod, 0)); //no SSE 4.1} And here is the required precalculation for shuffleTable : void MyInit() { memset(shuffleTable, -1, sizeof(shuffleTable)); int len[4]; for (len[0] = 1; len[0] <= 3; len[0]++) for (len[1] = 1; len[1] <= 3; len[1]++) for (len[2] = 1; len[2] <= 3; len[2]++) for (len[3] = 1; len[3] <= 3; len[3]++) { int slen = len[0] + len[1] + len[2] + len[3] + 4; int rem = 16 - slen; for (int rmask = 0; rmask < 1<<rem; rmask++) {// { int rmask = (1<<rem)-1; //note: only maximal rmask is possible if strings are zero-padded int mask = 0; char shuf[16] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}; int pos = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < len[i]; j++) { shuf[(3-i) * 4 + (len[i]-1-j)] = pos; pos++; } mask ^= (1<<pos); pos++; } mask ^= (rmask<<slen); _mm_store_si128(&shuffleTable[mask], _mm_loadu_si128((__m128i*)shuf)); } }} Full code with testing is avaliable here . On Ivy Bridge processor it prints: C0A70103Time = 0.406 (1556701184)Time = 3.133 (1556701184) It means that the suggested solution is 7.8 times faster in terms of throughput than the code by OP. It processes 336 millions of addresses per second (single core of 3.4 Ghz). Now I'll try to explain how it works. Note that on each line of the listing you can see contents of the value just computed. All the arrays are printed in little-endian order (though set intrinsics use big-endian). First of all, we load 16 bytes from unaligned address by lddqu instruction. Note that in 64-bit mode memory is allocated by 16-byte chunks, so this works well automatically. On 32-bit it may theoretically cause issues with out of range access. Though I do not believe that it really can. The subsequent code would work properly regardless of the values in the after-the-end bytes. Anyway, you'd better ensure that each IP address takes at least 16 bytes of storage. Then we subtract '0' from all the chars. After that '.' turns into -2, and zero turns into -48, all the digits remain nonnegative. Now we take bitmask of signs of all the bytes with _mm_movemask_epi8 . Depending on the value of this mask, we fetch a nontrivial 16-byte shuffling mask from lookup table shuffleTable . The table is quite large: 1Mb total. And it takes quite some time to precompute. However, it does not take precious space in CPU cache, because only 81 elements from this table are really used. That is because each part of IP address can be either one, two, three digits long => hence 81 variants in total.Note that random trashy bytes after the end of the string may in principle cause increased memory footprint in the lookup table. EDIT : you can find a version modified by @IwillnotexistIdonotexist in comments, which uses lookup table of only 4Kb size (it is a bit slower, though). The ingenious _mm_shuffle_epi8 intrinsic allows us to reorder the bytes with our shuffle mask. As a result XMM register contains four 4-byte blocks, each block contains digits in little-endian order. We convert each block into a 16-bit number by _mm_maddubs_epi16 followed by _mm_hadd_epi16 . Then we reorder bytes of the register, so that the whole IP address occupies the lower 4 bytes. Finally, we extract the lower 4 bytes from the XMM register to GP register. It is done with SSE4.1 intrinsic ( _mm_extract_epi32 ). If you don't have it, replace it with other line using _mm_extract_epi16 , but it will run a bit slower. Finally, here is the generated assembly (MSVC2013), so that you can check that your compiler does not generate anything suspicious: lddqu xmm1, XMMWORD PTR [rcx]psubb xmm1, xmm6pmovmskb ecx, xmm1mov ecx, ecx //useless, see @PeterCordes and @IwillnotexistIdonotexistadd rcx, rcx //can be removed, see @EvgenyKluevpshufb xmm1, XMMWORD PTR [r13+rcx*8]movdqa xmm0, xmm8pmaddubsw xmm0, xmm1phaddw xmm0, xmm0pshufb xmm0, xmm7pextrd eax, xmm0, 0 P.S. If you are still reading it, be sure to check out comments =)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31679352', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4103496/']}
|
jdg_373521
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24142437
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following in my __init__.py file. config = Configurator(settings=settings)config.include('pyramid_jinja2')config.include('pathshala.routes.all_routes')config.add_static_view('static', 'static', cache_max_age=3600)config.scan() I have defined all routes in routes.py which has: def all_routes(config): config.add_route('sis_add_student', '/sis/add') All views are defined in the views.py file (in the same package) which has: @view_config(route_name='sis_add_student')def add_student_view(request): return Response("Hey there!") However, when I try opening the path /sis/add , I get a 404 error. The Debug Toolbar suggests that the correct route has been identified but no view has been associated with that route. Interestingly, if I move the view declaration to __init__.py , it works fine. What am I doing wrong? I feel like my config.scan() is to blame because it fails to associate a view only when the declaration is in another file but I'm not sure about that and don't know how to fix that.
Now provide the response and nothing else.
|
Colons have nothing to do with the error you get. And yes, it can be achieved using ConvertFrom-StringData but, as already mentioned, you're feeding it an array instead of a string. Moreover, you need paths with double backslashes in your file because single backslashes are interpreted as escape characters. Here's how to fix your code: # Reading file as a single string:$sRawString = Get-Content "F:\dir\etc\props.properties" | Out-String# The following line of code makes no sense at first glance # but it's only because the first '\\' is a regex pattern and the second isn't. )$sStringToConvert = $sRawString -replace '\\', '\\'# And now conversion works.$htProperties = ConvertFrom-StringData $sStringToConvert$the_dir = $htProperties.'some_dir'Write-Host $the_dir
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24142437', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1446510/']}
|
jdg_373522
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
685794
|
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 though that the syntax for printf statements is printf format, item1, item2, ... as described e.g. here However, in this question printf is used like this: printf NR "%s ", $0 and it works! Why? Is it expected?
Now provide the response and nothing else.
|
There are two features at work here: printf , and AWK string concatenation . NR "%s " produces the concatenation of the value of NR and the string %s ; that is then given to printf as its first argument. A clearer way of writing this would be printf "%d%s ", NR, $0
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/685794', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/459270/']}
|
jdg_373523
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21691525
|
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 deserialize nested objects correctly in spray-json? import spray.json._ case class Person(name: String) case class Color(n: String, r: Int, g: Int, b: Int, p: Person) object MyJsonProtocol extends DefaultJsonProtocol { implicit object ColorJsonFormat extends RootJsonFormat[Color] { def write(c: Color) = JsObject( "color-name" -> JsString(c.n), "Green" -> JsNumber(c.g), "Red" -> JsNumber(c.r), "Blue" -> JsNumber(c.b), "person-field" -> JsObject("p-name" -> JsString(c.p.name)) ) def read(value: JsValue) = { value.asJsObject.getFields("color-name", "Red", "Green", "Blue", "person-field") match { case Seq(JsString(name), JsNumber(red), JsNumber(green), JsNumber(blue), JsObject(person)) => Color(name, red.toInt, green.toInt, blue.toInt, null) //gotta replace null with correct deserializer case _ => throw new DeserializationException("Color expected") } } } } import MyJsonProtocol._ val jsValue = Color("CadetBlue", 95, 158, 160, Person("guest")).toJson jsValue.prettyPrint val color = jsValue.convertTo[Color] //person is missing of course On a side-note, how to spray-json help serializing to a map of fields (with nested map for nested objects)?
Now provide the response and nothing else.
|
The example below demonstrates JSON -> Abstract Syntax Tree -> Scala Case Classes and back with custom field names and support for optional case class members. The example is derived from the spray-json documentation at https://github.com/spray/spray-json for version 1.2.5. package randoimport spray.json._case class Color(name: String, red: Int, green: Int, blue: Int)case class Team(name: String, color: Option[Color])object MyJsonProtocol extends DefaultJsonProtocol { implicit val colorFormat = jsonFormat(Color, "name", "r", "g", "b") implicit val teamFormat = jsonFormat(Team, "name", "jersey")}import MyJsonProtocol._object GoSox extends App { val obj = Team("Red Sox", Some(Color("Red", 255, 0, 0))) val ast = obj.toJson println(obj) println(ast.prettyPrint) println(ast.convertTo[Team]) println("""{ "name": "Red Sox", "jersey": null }""".asJson.convertTo[Team]) println("""{ "name": "Red Sox" }""".asJson.convertTo[Team])} The example outputs the following when executed: Team(Red Sox,Some(Color(Red,255,0,0))){ "name": "Red Sox", "jersey": { "name": "Red", "r": 255, "g": 0, "b": 0 }}Team(Red Sox,Some(Color(Red,255,0,0)))Team(Red Sox,None)Team(Red Sox,None)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21691525', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3103600/']}
|
jdg_373524
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8027148
|
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 retrieve the data to the right of ':' or use ':' as a starting point to get the data after. Looking for the right parsing items for this. var test = 'type:input'; charAt gives me the location of ':', but how do I then retrieve the 'input' from var test?
Now provide the response and nothing else.
|
You can use split : var testAfter = test.split(':')[1]; or substr with indexOf var testAfter = test.substr(test.indexOf(':')+1); or slice var testAfter = test.slice(test.indexOf(':')+1); or match var testAfter = test.match(/(:)(.+$)/).pop(); or replace var testAfter = test.replace(/^.+:/,''); if you want to be free to use whatever delimiter, this String extension may do the work: String.prototype.dataAfter = String.prototype.dataAfter || function(delim){ return this.split(delim)[1]; };//usagevar testAfter = test.dataAfter(':');var test2 = 'type#input';var testAfter = test2.dataAfter('#');
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8027148', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1009749/']}
|
jdg_373525
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
228558
|
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 having difficulties to deal with following problems; Assume $ \displaystyle\int_{[0,1]} x^n d \mu =0$ for all $n$, then is it true that $\mu=0$ on [0,1]? I think it is definitely true.. but I don't know how to proceed.. Can anybody help me?
Now provide the response and nothing else.
|
Let $T_n$ be the set of nodes on level $n$ of a complete binary tree of height $\omega$: $T_0$ is just the root, so it has $2^0=1$ node, $T_1$ has $2^1$ nodes, and in general $T_n$ has $2^n$ nodes. If the tree isn’t complete, the levels may be smaller, but the point is that they are all finite . Their union is the set of all nodes of the tree, and the union of countably many finite sets is countable. Now suppose that each node has countably infinitely many children. Label the root of the tree with the empty sequence, $\langle\rangle$. Label the nodes on level $1$, the children of the root, with $1$-tuples of natural numbers: $\langle 0\rangle,\langle 1\rangle,\langle 2\rangle,\dots~$. Label their children with $2$-tuples; for instance, the first three children of $\langle1\rangle$ are $\langle 1,0\rangle,\langle1,1\rangle$, and $\langle1,2\rangle$. On level $4$ you’ll find nodes with labels like $\langle 3,0,5,3\rangle$: this node is the child of $\langle 3,0,5\rangle$, which is the child of $\langle 3,0\rangle$, the child of $\langle 3\rangle$, the child of $\langle\rangle$, the root. In this way you can assign every node in the tree a unique label that is a finite sequence of natural numbers, and every such finite sequence will be attached to a node of the tree. Thus, there are exactly as many nodes as there are labels. There is only one empty label, and there are obviously $\aleph_0$ (countably infinitely many) labels on level $1$, one for each natural number. The labels on level $n$ are just the elements of the set $\Bbb N^n$, and it’s a basic fact of infinite cardinalities that $\Bbb N^n$ is countably infinite for each $n\in\Bbb Z^+$. Thus, each level of the tree has countably many nodes, and the union of countably many countable sets is still countable, so this tree also has only countably many nodes, not continuum-many.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/228558', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/43376/']}
|
jdg_373526
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
364590
|
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've the following endpoint: a/{id}/b and want to create a b with sending POST request to it. If a with given {id} is not found should I response with 404 NOT_FOUND or maybe with 409 CONFLICT ? It is to handle plain a/{id} , the trick is that here a subresource is used.
Now provide the response and nothing else.
|
404 NOT FOUND seems to be an appropriate response, because the resource with this ID does not exist. It's very clear to understand and you are expecting the same response if a/{id} is called. 409 CONFLICT does not seem to be the better choice, because in your example you will return a 409 when the parent resource was not found :). But remember that the most important thing is be consistent in your API.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/364590', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/288138/']}
|
jdg_373527
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
610530
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to create a personal home page for myself to learn more about web design (JavaScript, using Photo Shop, etc). I plan on having a graphical menu on the left, a banner across the top and also a "Photos" section where I can display photos of various pictures I have taken. However, when I look at other sites that do anything similar, I see some using GIFs, and some use JPGs and some even use PNGs. Is there any difference between these? Should I use a GIF for graphical images used on the site and JPGs for my photos? Should I make everything PNGs? Exact Duplicate: PNG vs. GIF vs. JPEG vs. SVG - When best to use? Website Image Formats: Choosing the right format for the right task. Which format for small website images? GIF or PNG?
Now provide the response and nothing else.
|
PNG should be used when: You need transparency (either 1-bit or alpha transparency) Lossless compression will work well (such as for a chart or logo, or computer generated image) JPEG should be used when: Lossless compression will not work well (such as a photograph) GIF should be when: PNG is not available, such as on very old software or browsers Animation is necessary Despite myths to the contrary, PNG outperforms GIF in most aspects. PNG is capable of every image mode of GIF apart from animation, and when using the same image mode, PNG will have better compression due to its superior DEFLATE algorithm compared to LZW. PNG is also capable of additional modes that GIF cannot do, such as 24 bit color, and alpha transparency, but this is where you need to be careful: if you forget to convert to palette mode your PNG image may be saved in 24 bit color which will take more space. PNG modes include (this is just a small subset) Palette colour of 2 to 256 colors (like GIF) Palette colour of 2 to 256 colors, with transparent color (like GIF) True color (24 bit color) True color with alpha channel (24 bit color + 8 bit alpha transparency) For best compression in PNG for the web, use a palette mode. If you find PNG files are larger than the equivalent GIF files, then you're saving the PNG in 24 bit color and the GIF in palette mode (because a GIF is always in palette mode). Try converting to palette mode first. PNG also has other modes such as palette color with alpha transparency. Modes such as this cannot be created in Photoshop, but other applications can create them. Edit 2013: Removed a bunch of stuff about IE6 compatibility.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/610530', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/65230/']}
|
jdg_373528
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
118466
|
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 get the gist of it. It's like a middle ground between brute force attack and lookup table, it stores the starting plaintext and ending hash for each chain where a chain is made by reduction and hash. What I don't get is: It's said that rainbow tables solve collisions, but why are collisions such a big deal to begin with? It's said that rainbow tables solve collisions by using a different reduction function for each column in the chain, but how does this prevent collisions? Aren't reduction functions just random characters you take from the hash? So what difference does it make if you take the first 8 characters instead of the last 8?
Now provide the response and nothing else.
|
The current highest voted answer doesn't really seem to give a proper response to your question. I'll try to answer both your questions simultaneously. Same reduction function in every column Say, you use the same reduction function for every column and have a basic table with 2 rows and 3 columns. P1 --R--> P1' --R--> P1'' --R--> P1'''P2 --R--> P2' --R--> P1' --R--> P1'' Here, an --R--> represents a hashing followed by a reduction. And P1, P2, P1', ... represent passwords.As you can see, there was a collision in the second chain. The value P1' has already been encountered in the first chain. Notice what happens afterwards. Since the hashing followed by the reduction of P1' is exactly the same as in the first chain, we get a value that has already been computed. If we continue this even further, the part of the second chain starting from P1' becomes an exact copy of the part of the first chain starting from P1' . So in effect, this is why collisions are bad. The second chain merged into the first. We have duplicate results in our table, resulting in wasted storage space and computation time. Different reduction function in every column This time, let's see what happens if we use a different reduction for every column.A reduction is represented by --RX--> where X is the column number. P1 --R1--> P1' --R2--> P1'' --R3--> P1'''P2 --R1--> P2' --R2--> P1' --R3--> P2'' Again, P1' was encountered in both chains.However, since the reduction functions are different, the value calculated after P1' in the second chain won't result in P1'' , as it does in the first chain. This effectively solves the merge issue from the first example. Note that this doesn't solve every chain merge though. Watch what happens in the following example: P1 --R1--> P1' --R2--> P1'' --R3--> P1'''P2 --R1--> P1' --R2--> P1'' --R3--> P1''' This time a collision happens in the first column of both chains. Since it happens in the same column, every next reduction function will be the same and the chains are merged once again. The probability of this happening is lower though.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/118466', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/104163/']}
|
jdg_373529
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
39651981
|
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 content that i want to send <div id="preview">        </div> Element function: function _(obj) { return document.getElementById(obj);} Ajax: $.ajax({ type: 'POST', url: 'http://<?php echo $domain ?>/libraries/ajax/pdf.php', data: 'html=' + _("preview").innerHTML + '&nama=a', dataType: 'html', beforeSend: function() {}, success: function(response) { Materialize.toast((response), 4000); }}); How to send &nsbp as text instead of POST parameter?
Now provide the response and nothing else.
|
If you have a grep that can do Perl compatible regular expressions (PCRE): $ grep -Po '"id": *\K"[^"]*"' infile.json"4dCYd4W9i6gHQHvd" -P enables PCRE -o retains nothing but the match "id": * matches "id" and an arbitrary amount of spaces \K throws away everything to its left ("variable size positive look-behind") "[^"]*" matches two quotes and all the non-quotes between them If your grep can't do that, you an use $ grep -o '"id": *"[^"]*"' infile.json | grep -o '"[^"]*"$'"4dCYd4W9i6gHQHvd" This uses grep twice. The result of the first command is "id": "4dCYd4W9i6gHQHvd" ; the second command removes everything but a pair of quotes and the non-quotes between them, anchored at the end of the string ( $ ). But, as pointed out, you shouldn't use grep for this, but a tool that can parse JSON – for example jq : $ jq '.data.id' infile.json"4dCYd4W9i6gHQHvd" This is just a simple filter for the id key in the data object. To get rid of the double quotes, you can use the -r ("raw output") option: $ jq -r '.data.id' infile.json4dCYd4W9i6gHQHvd jq can also neatly pretty print your JSON: $ jq . infile.json{ "data": { "name": "test", "id": "4dCYd4W9i6gHQHvd", "domains": [ "www.test.domain.com", "test.domain.com" ], "serverid": "bbBdbbHF8PajW221", "ssl": null, "runtime": "php5.6", "sysuserid": "4gm4K3lUerbSPfxz", "datecreated": 1474597357 }, "actionid": "WXVAAHQDCSILMYTV"}
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/39651981', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6211753/']}
|
jdg_373530
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
62104199
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been working with VSCode + Docker in Windows for some years now, and managed to have a fully working dev environment without any issues. Recently i setup a new development environment with WSL2. Moved all my projects, libraries, CLIs, etc, into WSL, using Docker Windows with WSL2 containers and VSCode on Windows with remote connection to WSL. Everything is working very smoothly and i like the fact i can have everything separated. But recently i came across an issue that i'm unable to solve, i lost the ability to debug PHP files.I'm using VSCode Remote WSL extension to work on my projects inside WSL, but when i try to debug, nothing happens. I have tree debugging settings in my VSCode for each dev environment that i use (Windows, MacOS and WSL). All work except for the WSL. When i try to debug with WSL, literally nothing happens, no output erros, no debug console information, nothing... Here are my VSCode debug settings: { "version": "0.2.0", "configurations": [{ "name": "Listen for XDebug Win10", "type": "php", "request": "launch", "port": 9000, "log": true, "externalConsole": false, "pathMappings": { "/var/www/project-a/api": "\\\\wsl$\\Ubuntu\\home\\ubuntu\\PROJECTS\\project-a\\api", }, "ignore": [ "**/vendor/**/*.php" ] }, { "name": "Listen for XDebug MacOS", "type": "php", "request": "launch", "port": 9000, "log": true, "externalConsole": false, "pathMappings": { "/var/www/project-a/api": "/Users/ricky/PROJECTS/project-a/api", }, "ignore": [ "**/vendor/**/*.php" ] }, { "name": "Listen for XDebug WSL", "type": "php", "request": "launch", "port": 9000, "log": true, "externalConsole": false, "pathMappings": { "/var/www/project-a/api": "/home/ubuntu/PROJECTS/project-a/api", }, "ignore": [ "**/vendor/**/*.php" ] }, ]} What am i doing wrong? Any ideas on how to solve this issue? ### UPDATE: I've changed the original right answer to a new one. Although @romain-prevost's solution worked, I think @dark's approach is wayyy much simpler :)
Now provide the response and nothing else.
|
Forget about the other answers. They are working but too complicated in my opinion. The problem is, that you can't connect to xdebug. The solution is to tell xdebug to set remote_host to host.docker.internal . Everything from there is available to localhost. Now you only have to listen inside Visual Studio Code to localhost via hostname . Et voilà.Now you can debug things invoked by your browser, inside your phpunit tests or within your commandline scripts. Complete Example launch.json { "version": "0.2.0", "configurations": [ { "name": "Listen for XDebug", "type": "php", "request": "launch", "port": 9000, "pathMappings": { "/var/www/html/": "${workspaceRoot}" }, "hostname": "localhost" } ]} php.ini [XDebug]xdebug.remote_enable = 1xdebug.remote_autostart = 1xdebug.remote_host = host.docker.internalxdebug.remote_port = 9000 Update for XDebug 3 launch.json { "version": "0.2.0", "configurations": [ { "name": "Listen for XDebug", "type": "php", "request": "launch", "port": 9003, "pathMappings": { "/var/www/html/": "${workspaceRoot}" }, "hostname": "localhost" } ]} php.ini [XDebug]xdebug.mode = developxdebug.start_with_request = yesxdebug.client_host = host.docker.internalxdebug.client_port = 9003
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/62104199', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1880662/']}
|
jdg_373531
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41644
|
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 have a lot of MATLAB code that needs to get ported to C (execution speed is critical for this work) as part of a back-end process for a web application. When I attempt to outsource this code to a C developer, I assume (correct me if I'm wrong) few C developers also understand MATLAB code (things like indexing and memory management are different, etc.). I wonder if there are any C developers out there that can recommend a procedure for me to follow to best communicate what the code does? For example, should I provide the MATLAB code and explain what it's doing line by line? Or, should I just provide the math/algorithm, explain it in plain English, and let the C developer implement it with this understanding in his/her own way (e.g. can I assume the developer understands how to work with complex math (i.e. imaginary numbers), how to generate histograms, perform an FFT, etc.)? Or, is there a better method? I expect I'm not the first to need to do this, so I wonder if any C developers out there ran into this situation and can share any conventional wisdom how they'd like this task to be transferred? Thanks in advance for any comments.
Now provide the response and nothing else.
|
I am in a similar situation as you in that I also have people port my Matlab code to C++. A lot depends on the complexity of your code, as well as on level of skill of the C/C++ developer and on their understanding of what they're supposed to implement - the better they are and the better they understand your problem, the more independently they can work. Since direct translation of Matlab code to C/C++ may not be the most efficient way to handle a problem, I suggest that you communicate well what the input is, what the code should do, and what it is supposed to return as output. You should also provide ways to test the code to ensure that it works correctly - both as a help for debugging as well as providing a means for quality control. On top of that, you should provide and explain the Matlab code as a rough guideline of how the result can be achieved. You should be able to assume that the developer knows how to structure a program and how to do use debugging tools. However, you may not necessarily be able to assume that the developer knows how to have specific knowledge in, say statistics, or (mathematical) optimization. Thus, debugging these parts will be much faster with your input. It may help to schedule regular meetings with the developer, so that "little things" that may feel a bit weird to the developer, but that will signal important issues to you can be communicated before they escalate into big issues.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/41644', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/17323/']}
|
jdg_373532
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
55139386
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can the useEffect hook (or any other hook for that matter) be used to replicate componentWillUnmount ? In a traditional class component I would do something like this: class Effect extends React.PureComponent { componentDidMount() { console.log("MOUNT", this.props); } componentWillUnmount() { console.log("UNMOUNT", this.props); } render() { return null; }} With the useEffect hook: function Effect(props) { React.useEffect(() => { console.log("MOUNT", props); return () => console.log("UNMOUNT", props) }, []); return null;} (Full example: https://codesandbox.io/s/2oo7zqzx1n ) This does not work, since the "cleanup" function returned in useEffect captures the props as they were during mount and not state of the props during unmount. How could I get the latest version of the props in useEffect clean up without running the function body (or cleanup) on every prop change? A similar question does not address the part of having access to the latest props. The react docs state: If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. In this case however I depend on the props... but only for the cleanup part...
Now provide the response and nothing else.
|
You can make use of useRef and store the props to be used within a closure such as render useEffect return callback method function Home(props) { const val = React.useRef(); React.useEffect( () => { val.current = props; }, [props] ); React.useEffect(() => { return () => { console.log(props, val.current); }; }, []); return <div>Home</div>;} DEMO However a better way is to pass on the second argument to useEffect so that the cleanup and initialisation happens on any change of desired props React.useEffect(() => { return () => { console.log(props.current); };}, [props.current]);
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/55139386', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3941291/']}
|
jdg_373533
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
14658469
|
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 somebody explain this to me please : Intent intent = new Intent(Context, AlarmReceiver.class); I never understood and I seriously think I never will if somebody doesn't try to explain this to me in depth. This whole context thing is so confusing to me. Sometimes it works like this : Intent intent = new Intent(getBaseContext(), AlarmReceiver.class); Sometimes it wont work like that but it accepts only : Intent intent = new Intent(context, AlarmReceiver.class); Sometimes its : Intent intent = new Intent(this, AlarmReceiver.class); etc. etc. and many other. I understand basics of context but how many are there? And why does eclipse throw me an error once and another time its fine? Why do we need to declare context sometimes? : Context context; I'm unable to find the right context for all situations how do I know what is the right one in every situation?
Now provide the response and nothing else.
|
First of all, let me explain what the context is a bit better, then let's go on to how it can be used and received. Essentially, context is a reference to linking your resources to your program. Each object is given its own context, which contains the resources required to set that object up. It is required for many objects to be created, and to get program identifying information, among other purposes. This makes it invaluable to set up new views and activities, but it can also be used for other purposes. See also this answer for more information. The context for an item can come from a variety of places. Sometimes it is stored and has to be retrieved, sometimes it is inherited. Basically, this is object oriented programming. Just to give you a few examples: Activity inherits context. Thus, if you are in an activity, you only need to pass itself to use the context. It also contains a pointer to getBaseContext() . You might occasionally need to reference that, if you need the entire application context, but most likely you won't for a while. View does not inherit context. However, it does have a method getContext() . If you need to get a context from a view, this is the way to get it. This context will not be complete, but will only have the context for the contents of the View. Fragments also do not inherit context. They contain a method getActivity() , which if the Fragment is active, will return the activity, which is the context for the Fragment. BroadcastReceivers do not inherit context either. In fact, they do not contain context at all, but simply receive the current context when an event is received (Such as onReceive(Context context, Intent intent) )
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14658469', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1880779/']}
|
jdg_373534
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8749929
|
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 replicate the functionality of the cat command in Unix. I would like to avoid solutions where I explicitly read both files into variables, concatenate the variables together, and then write out the concatenated variable.
Now provide the response and nothing else.
|
Simply use the Get-Content and Set-Content cmdlets: Get-Content inputFile1.txt, inputFile2.txt | Set-Content joinedFile.txt You can concatenate more than two files with this style, too. If the source files are named similarly, you can use wildcards: Get-Content inputFile*.txt | Set-Content joinedFile.txt Note 1: PowerShell 5 and older versions allowed this to be done more concisely using the aliases cat and sc for Get-Content and Set-Content respectively. However, these aliases are problematic because cat is a system command in *nix systems, and sc is a system command in Windows systems - therefore using them is not recommended, and in fact sc is no longer even defined as of PowerShell Core (v7). The PowerShell team recommends against using aliases in general . Note 2 : Be careful with wildcards - if you try to output to inputFiles.txt (or similar that matches the pattern), PowerShell will get into an infinite loop! (I just tested this.) Note 3 : Outputting to a file with > does not preserve character encoding! This is why using Set-Content is recommended.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/8749929', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/391161/']}
|
jdg_373535
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8104268
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to do something like this in a head tag, of master page, which has runatserver: <link rel="Stylesheet" type="text/css" href='<%=Config.ResourcesDomain %>/images/style.css' /> This is not working, as it produces this kind of html: <link rel="Stylesheet" type="text/css" href="<%=Config.ResourcesDomain %>/images/style.css" />
Now provide the response and nothing else.
|
The reason the output is being rendered like so: href="<%=Config.ResourcesDomain %>/images/style.css" Is because ASP.NET is treating the link as an HtmlLink control, and rendering the contents of the href attribute as a literal. This is a strange quirk of marking the head section as a server control, where certain elements are treated as server controls (even without being marked explicitly with the runat="server" attribute). Removing the quotations around the href attribute resolves the issue: href=<%= Config.ResourcesDomain %>/images/style.css Doing so stops the link element being treated as a server control, thus executing the code block and rendering the correct URL. However, the above writes the href value out without quotes. Using the following, will add the quotes to the link tag: href=<%= String.Format("'{0}'", Config.ResourcesDomain) %>/images/style.css Hope this helps. Edit Strangely, if you use double quotes for the href attribute, and include double quotes within the code block this also resolves the issue: href="<%= "" + Config.ResourcesDomain %>/images/style.css" However, none of the above are particularly elegant solutions, and setting the URL from the code behind is probably the way to go.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8104268', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/830285/']}
|
jdg_373536
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
95929
|
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:
Suppose the target of a Denial of Service attack is a PC on LAN with IP 192.168.1.10. Then, I can continue to ping the target by running the ping command in an infinite loop in CMD, that is, by executing the command ping 192.168.1.10 -t . How long would such a ping flood take to successfully crash the target PC, assuming it to be an average home PC?
Now provide the response and nothing else.
|
To put some hard numbers on it: it'll take forever. ping -t means "send one 'ICMP echo request' packet of 60 total bytes every second". Counting the 60-byte response, this works out to a bandwidth usage of 960 bits per second. You'll be able to DoS someone using a 1200 bps modem. You'll have a noticeable impact on anything less than a 9600 bps modem. Against a modern DSL or cable modem, or a gigabit ethernet connection, your "attack" will consume less bandwidth than the routine housekeeping traffic.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/95929', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/82418/']}
|
jdg_373537
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
12494515
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
$path = '/home/to//my///site'; I am trying to remove unnecessary forward slashes / from the path above I am trying to get this results /home/to/my/site I've failed with str_replace , since i don't know the number of slashes.
Now provide the response and nothing else.
|
Elegant solution With preg_replace you can obtain this with a single line of code: preg_replace('#/+#','/',$str); The pattern /+ will match the forwardslash / one or more times, and will replace it with a single / . Not-so Elegant solution There are of course other ways to achieve this, for example using a while loop. while( strpos($path, '//') !== false ) { $path = str_replace('//','/',$path);} This will call str_replace until all occurrences of // are replaced. You can also write that loop in a single line of code if you want to sacrifice readability (not suggested). while( strpos( ($path=str_replace('//','/',$path)), '//' ) !== false );
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12494515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1161888/']}
|
jdg_373538
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
37107570
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When i clicked the edit button the values from dataTable should display in form. But somehow it doesn't work. Below are my codes for reference. Call DataTable: $("#tranTable").on("click", "#edit", function(){ var row = $(this).closest("tr"); $("#Own-Account").removeClass("hidden"); $("fieldset#addToListMethod").addClass("hidden"); $("fieldset#Own-Account #templateTrxId").val( row.find("[name$=templateTrxId]").val() ) $("fieldset#Own-Account #templateId") .val( row.find("[name$=templateId]").val() ) $("fieldset#newFT #fromAccNo") .val( row.find("[name$=fromAccNo]").val() ), $("fieldset#newFT #methodOfTransfer") .val( row.find("[name$=methodOfTransfer]").val() ), $("fieldset#Own-Account #toAccNo") .val( row.find("[name$=toAccNo]").val() ), $("fieldset#Own-Account #paymentRef") .val( row.find("[name$=paymentRef]").val() ), $("fieldset#Own-Account #amount") .val( row.find("[name$=amount]").val() ), //hidden $("fieldset#Own-Account #otherPaymentDetail").val( row.find("[name$=otherPaymentDetail]").val() ), $("fieldset#Own-Account #email1").val( row.find("[name$=email1]").val() ), $("fieldset#Own-Account #email2").val( row.find("[name$=email2]").val() ), $("fieldset#Own-Account #sms1").val( row.find("[name$=sms1]").val() ), $("fieldset#Own-Account #sms2").val( row.find("[name$=sms2]").val() ), $("fieldset#Own-Account #purpose").val( row.find("[name$=purpose]").val() ) $("fieldset#Own-Account #isEdit").val(1); $("fieldset#Own-Account #dataTableRowId").val(row.data("row-id"));});
Now provide the response and nothing else.
|
From the exception, your problem likely occurs because the @RequestMapping doesn't find the parameter being sent from previous the page. In this case, it is likely like this: @RequestMapping(value = "/check")public String getID(@RequestParam(value = "params") String params){//your logic code here} From here, the exception occurs when the @RequestMapping doesn't find "params" : @RequestParam(value = "params") String params This happens because, by default, @RequestParam tries to get the value. It then returns an exception when the value is not found. So you have two ways to resolve this, You can supply the URL /check with a params variable or, You can change the @RequestParam requirement to false like this: @RequestParam(value = "params", required = false) String params Take note that this is an example to reflect your scenario and problem. Gud luk.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37107570', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5638110/']}
|
jdg_373539
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2589179
|
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:
Could one write a polynomial that produces an integer output only for prime number inputs? I know that if a polynomial of degree $n$ takes integer values at $n+1$ consecutive integer arguments, then it takes integer values at all integer arguments. However, since the prime number inputs aren't consecutive, then how would one go about proving it would be possible to write?
Now provide the response and nothing else.
|
No. Suppose there is such a polynomial $f(x)$ of degree $k$, say. First off, this polynomial has to have rational coefficients (by Lagrange interpolation, say). Let $N$ be the least common denominator of the coefficients. Then $g(x)=Nf(x)$ is a polynomial with integer coefficients and $g(2)$ is divisible by $N$. But $g(2-N)\equiv g(2)\equiv 0\pmod N$, so $g(2-N)$ is divisible by $N$, hence $f(2-N)$ is an integer. But clearly $2-N$ is not a prime, so we get a contradiction. Edit: for the sake of clarifying, here is how I have interpreted the question: is there a polynomial $f$ such that, for $n\in\mathbb Z$, $f(n)$ is an integer iff $n$ is prime? I show that there is no such polynomial. Edit 2: (in reply to Yves Daoust) Suppose that $f$ is a polynomial of degree $k$ which takes integer value at every prime. Pick any primes $p_1,\dots,p_{k+1}$. Consider polynomial $L(x)$ defined here for $x_i=p_i,y_i=f(p_i)$. Since every $\ell_i$ is a polynomial with rational coefficients of degree at most $k$, the same holds for $L$. Now note $f-L$ is a polynomial of degree at most $k$ which is zero at at least $k+1$ points $p_1,\dots,p_{k+1}$, hence it must be a zero polynomial. Thus $f=L$ has rational coefficients.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2589179', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/518051/']}
|
jdg_373540
|
Subsets and Splits
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves samples with 'mathoverflow.net' in the prompt, providing a basic subset for inspection but with limited analytical value.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves 10 samples where the prompt mentions Mathematica Stack Exchange, offering basic filtering to locate specific content.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves a limited number of rows where the prompt contains a specific URL, providing basic filtering that offers minimal insight into the broader dataset patterns.
SQL Console for PrimeIntellect/stackexchange-question-answering
This query retrieves 10 samples from the dataset where the prompt contains 'dsp.stackexchange.com', offering a basic filtering of data points related to that specific domain.
SQL Console for PrimeIntellect/stackexchange-question-answering
Retrieves a sample of rows where the prompt contains 'cs.stackexchange.com', providing a basic filter without extensive insight.
Electronics Q&A Subset
Retrieves a limited number of samples that contain a specific URL, providing only raw data filtered by that URL.
StackExchange Stats Questions
Retrieves 100 entries containing 'stats.stackexchange.com' in the prompt, which is useful for finding specific content but lacks broader analytical value.
Math StackExchange Questions
Retrieves 100 records from the train dataset where the prompt contains 'math.stackexchange.com', providing a basic filtered overview of specific entries.
Physics SE Questions
Retrieves 100 samples containing the word 'physics.stackexchange.com' in the prompt, offering basic filtering without deep analysis.