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
|
62072
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $a,b,n$ be integers such that $\gcd(a,n)=\gcd(b,n)=1$ . How to show that $\gcd(ab,n)=1$ ? In other words, how to show that if two integers $a$ and $b$ each have no non-trivial common divisor with and integer $n$ , then their product does no have a non-trivial common divisor with $n$ either. This is a problem that is an exercise in my course. Intuitively it seems plausible and it is easy to check in specific cases but how to give an actual proof is not obvious.
Now provide the response and nothing else.
|
Hint $\rm\ \ (n,ab)\ =\ (n,nb,ab)\ =\ (n,\overbrace{(n,a)}^{\large 1}\:b)\ =\ (n,b)\ =\ 1\ $ using prior said GCD laws. Such exercises are easy on applying the basic GCD laws that I mentioned in your prior questions, viz. the gcd associative , commutative, distributive and modular law $\rm\:(a,b+c\:a) = (a,b).\,$ In fact, to make such proofs more intuitive we can write $\rm\:gcd(a,b)\:$ as $\rm\:a\dot+ b\:$ and then use familiar arithmetic laws, e.g. see this proof of the GCD Freshman's Dream $\rm\:(a\:\dot+\: b)^n =\: a^n\: \dot+\: b^n\:.$ Said conceptually : invertibles ("units") $\!\bmod n,\,$ are closed under multiplication , clear by $$\begin{align}\rm a_k^{-1}\cdots a_1^{-1}&\rm\:\!\times\:\! (a_1\cdots a_k) =1\\[.2em]\rm\Rightarrow\ \ a_k^{-1}\cdots a_1^{-1} &\rm = (a_1\cdots a_k)^{-1}\end{align}\qquad$$ More generally: $ $ if $\rm\,(a,k)=(b,n)=1\,$ then $\rm\,(ab,kn)=(a,n)(b,k)$ . Remark $ $ Also worth emphasis is that not only are proofs using GCD laws more general, they are also more efficient notationally , hence more easily comprehensible. As an example, below is a proof using the GCD laws, followed by a proof using the Bezout identity (from Gerry's answer). $\begin{eqnarray}\qquad 1&=& &\rm(a\:,\ \ n)\ &\rm (b\:,\ \ n)&=&\rm\:(ab,\ &\rm n\:(a\:,\ &\rm b\:,\ &\rm n))\ \ =\ \ (ab,n) \\[.2em]1&=&\rm &\rm (a\color{#c00}r\!\!+\!\!n\color{#c00}s)\:&\rm(b\color{#c00}t\!\!+\!\!n\color{#c00}u)&=&\rm\ \ ab\:(\color{#c00}{rt})\!\!+\!\!&\rm n\:(a\color{#c00}{ru}\!\!+\!\!&\rm b\color{#c00}{st}\!\!+\!\!&\rm n\color{#c00}{su})\ \ so\ \ (ab,n)=1\end{eqnarray}$ Notice how the first proof using GCD laws avoids all the extraneous Bezout variables $\rm\:\color{#c00}{r,s,t,u}\:,\:$ which play no conceptual role but, rather, only serve to obfuscate the true essence of the matter. Further, without such noise obscuring our view, we can immediately see a natural generalization of the GCD-law based proof, namely $$\rm\ (a,\ b,\ n)\ =\ 1\ \ \Rightarrow\ \ (ab,\:n)\ =\ (a,\ n)\:(b,\ n) $$ This quickly leads to various refinement-based views of unique factorizations, e.g. the Euclid-Euler Four Number Theorem (Vierzahlensatz) or, more generally, Schreier refinement and Riesz interpolation. See also Paul Cohn's excellent 1973 Monthly survey Unique Factorization Domains.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/62072', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
|
jdg_378341
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
611685
|
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 want to find all directories and subdirectories in my current folder, excluding those that are hidden (or belonging to those that are hidden). The following do not work: find . -type d -name "[!.]*" because I think it only avoids empty hidden folders. Something like this is matched ./.cache/totem
Now provide the response and nothing else.
|
I'm assuming you're classing directories that start with a dot as "hidden". To avoid descending into such directories you should use -prune . find . -mindepth 1 -type d \( -name '.*' -prune -o -print \) This starts in the current directory (we could have specified * here but that presupposes your wildcard is not set to include dot files/directories - for example bash 's dotglob ). It then matches only on directories, but not considering . itself. The section in brackets tells find that if the name matches .* then it's to be pruned, so that neither it nor its descendants are to be considered further; otherwise print its name. If you don't have the (non-POSIX) -mindepth option you could use this alternative. Arguably this is better than the original solution I've suggested but I'm going to leave both in the answer find . -type d \( -name '.?*' -prune -o -print \)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/611685', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/416168/']}
|
jdg_378342
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
27832
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a DirectShow graph to render MPEG2/4 movies from a network stream. When I assemble the graph by connecting the pins manually it doesn't render. But when I call Render on the GraphBuilder it renders fine. Obviously there is some setup step that I'm not performing on some filter in the graph that GraphBuilder is performing. Is there any way to see debug output from GraphBuilder when it assembles a graph? Is there a way to dump a working graph to see how it was put together? Any other ideas for unraveling the mystery that lives in the DirectShow box? Thanks!-Z
Now provide the response and nothing else.
|
You can watch the graph you created using GraphEdit, a tool from the DirectShow SDK. In GraphEdit, select File->Connect to remote Graph... In order to find your graph in the list, you have to register it in the running object table: void AddToRot( IUnknown *pUnkGraph, DWORD *pdwRegister ) { IMoniker* pMoniker; IRunningObjectTable* pROT; GetRunningObjectTable( 0, &pROT ); WCHAR wsz[256]; swprintf_s( wsz, L"FilterGraph %08p pid %08x", (DWORD_PTR)pUnkGraph, GetCurrentProcessId() ); CreateItemMoniker( L"!", wsz, &pMoniker ); pROT->Register( 0, pUnkGraph, pMoniker, pdwRegister ); // Clean up any COM stuff here ...} After destroying your graph, you should remove it from the ROT by calling IRunningObjectTable::Revoke
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/27832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2587612/']}
|
jdg_378343
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3671237
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Somehow my execute statement says the object has no member "execute". What is wrong? class EdlSqliteDb{const SQLITE_DRIVER = "sqlite:";var $dbh;var $qIndex = Array();//function EdlSqliteDb($dsn) { try { $this->dbh = new PDO(self::SQLITE_DRIVER . $dsn); } catch (PDOException $e) { echo "Error connecting: " . $e->getMessage() . ' ' . self::SQLITE_DRIVER . $dsn; die(); } return;}//function addQ($index,$q){ $this->qIndex[$index] = $q;}//function PrepareQ($index){ try { $stmt = $this->dbh->prepare($this->qIndex[$index]); } catch (PDOException $e) { echo "Db Prepare Error: " . $e->getMessage(); die(); } return $stmt;}//function DbExecutePrepared($index, $arrParameters){ $stmt = $this->PrepareQ($index); if ($stmt->execute($arrParameters)) { $row = $stmt->fetch(); return $row; } else { print "<p>dbquery(): database table update execute error</p>\n"; die(); }} }
Now provide the response and nothing else.
|
This is most likely due to a failed preparation. Depending on error handling, PDO, instead of raising an exception, may just return false . If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling). Not entirely sure where this behaviour is defined, to be honest.... Update: here it is . The default behaviour is to fail silently. You need to set PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION for exceptions to be risen at all times . $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3671237', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/121626/']}
|
jdg_378344
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1209779
|
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:
Problem: How might I convert the base-10 fraction $\frac{7}{27}$ into it base-3 and base-12 decimal expansions? My work: Is $\frac{7}{27}$ precisely equal to $0.314$ in base-12? First I converted both nominator and denominator into base $B$, and then I performed division operations on that base $B$ too. But I am stick. Any ideas?
Now provide the response and nothing else.
|
Start with $x_1=0$ and then just let $x_{n+1}=1$ whenever $f(n)/n\leq p$ and $x_{n+1}=0$ whenever $f(n)/n> p$. It's easy to prove by induction that we will always have $\left|\frac{f(n)}n-p\right|\leq\frac 1n$ and so $f(n)/n\rightarrow p$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1209779', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/227004/']}
|
jdg_378345
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
231594
|
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 don't understand results of ar() function in R. I made up a very simple case, Fibonacci sequence: x <- c(1,1,2,3,5,8,13,21,34,55)ar(x) result is Coefficients: 1 0.5531 I would expect result of 1,1 - for the model x(n) = 1* x(n-1) + 1 * x(n-2) Can anyone explain me please why I don't get expected result?
Now provide the response and nothing else.
|
Since an ounce of algebra is equal to a ton of words, let me writesome formulas. Notation Denote $k( \cdot, \cdot )$ some covariance function,assume we have $m$ observations $(\mathbf x_i, y_i )_{i=1}^m$. Denote $$\Sigma =\begin{bmatrix}k( \mathbf x_1 , \mathbf x_1 ) & \dots & k( \mathbf x_1 , \mathbf x_m ) \\k( \mathbf x_2 , \mathbf x_1 ) & \dots & k( \mathbf x_2, \mathbf x_m ) \\\vdots & & \vdots \\k( \mathbf x_m , \mathbf x_1 ) & \dots & k( \mathbf x_m , \mathbf x_m )\\\end{bmatrix} \in \mathbb{R}^{m \times m },\k(\mathbf x) = \begin{bmatrix}k(\mathbf x, \mathbf x_1 ) \\ \vdots \\ k(\mathbf x, \mathbf x_m )\end{bmatrix} \in \mathbb{R}^m,\\mathbf y =\begin{bmatrix}y_1 \\\vdots \\y_m\end{bmatrix} \in \mathbb{R}^m$$ and $$ X =\begin{bmatrix}------ & \mathbf x_1^t & ------ \\ & \vdots & \\------ & \mathbf x_m^t & ------\end{bmatrix}.$$ Gaussian Process Regression Gaussian Process Regression (GPR) gives the poserior for $\mathbf x$as$$y \sim \mathcal{N} (k^t(\mathbf x) \Sigma^{-1} \mathbf y, k(\mathbf x,\mathbf x)- k^t(\mathbf x) \Sigma^{-1} k(\mathbf x ) ).$$ This arises by assuming $(\mathbf y, y )$ are all jointly Gaussianwith zero mean and a covariance structure specified by$k( \cdot, \cdot )$. That's the main idea and the rest is calculationsusing Schur complements. You would (probably) want to make aprediction based on either the posterior mean or the posteriormode. Luckily, in this case they are the same. You would predict,for a given $\mathbf x$:$$y^{\star} = k^t(\mathbf x ) \Sigma^{-1} \mathbf y.$$ General Linear Model A General Linear Model (GLM) arises when you try to find the bestlinear model to describe observations with a given covariancestructure (specified by $\Sigma$). You assume$$\mathbf y = X \beta+ \epsilon, \epsilon \sim \mathcal{N}(0,\Sigma).$$ Then the log-likelihood is $$\log p(\mathbf y|X,\beta x) = -\frac{1}{2} (X \beta - \mathbf y )^t\Sigma^{-1}(X\beta - \mathbf y),$$ up to an additive constant. Then the following $\beta^{\star}$ is aMaximum Likelihood Estimator for $\beta$: $$\beta^{\star} := \arg \min_{\beta} \| \Sigma^{-1/2} (X\beta - \mathbf y) \|_2^2 \\= ( (\Sigma^{-1/2} X)^t (\Sigma^{-1/2} X) )^{-1} (\Sigma^{-1/2} X)^t \Sigma^{-1/2}\mathbf y \\= (X^t \Sigma^{-1} X)^{-1} X^t \Sigma^{-1} \mathbf y.$$ Now, a prediction is made using this linear model as follows: $$y^{\star} = \mathbf x^t \beta^{\star} = \mathbf x^t (X^t \Sigma^{-1} X)^{-1} X^t \Sigma^{-1} \mathbf y.$$ Conclusion The formulas for the posterior mean for GPR and the GLMpredictor are clearly different, so this answers your question. A Few Comments One key difference is that a GLM does not take into account thecovariance between $\mathbf x$ and $\mathbf x_i$, for any $i$. In theGPR model, this information on $\mathbf x$ enters via the vector$k(\mathbf x)$. Expanding on this point you can think of either one of these models asa weigting scheme used to get from $\mathbf y$ to $y$. In the GLMcase, your weights are a linear function of $\mathbf x$ itself. In theGPR case, these weights are a still linear, but now in $k(\mathbfx, \cdot )$! More on this is the book, chapter 2. http://www.gaussianprocess.org/gpml/ The Gaussian Process model is Bayesian. It gives you a posteriordistribution (of which you take the mean for prediction). The GLMis frequentist - no posterior distribution, just point estimates(for $\beta^{\star}$ and for $y^{\star}$).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/231594', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/112476/']}
|
jdg_378346
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3590307
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've just started learning about ZFC set theory, and I'm looking into how relations over sets are defined in this context. The definition I found is that a relation $R$ over two sets $E$ and $F$ can either be implemented as: 1) A subset of $E \times F$ , or 2) As the triplet $(E,F,G)$ where $G$ is a subset of $E \times F$ . I was thinking about relations over sets of relations, and was wondering wether such a relation $R$ could compare itself. (i.e. could $R \space R \space S$ or $S \space R \space R$ (infix notation), where $S$ is another relation, be a valid statement?) My reasoning was that, if it were possible, there would necessarily be a cyclic membership chain like $R \in \dotsb \in R$ if we're going with definition 1), or $R \in \dotsb \in G \in \dotsb \in R$ with definition 2). And since the axiom of foundation prohibits it, it is not possible for a relation to compare itself with another. But while it is pretty simple to proove that this is correct if ordered pairs are implemented as $(a,b)=\{\{a\},\{a,b\}\}$ and n-tuples as nested ordered pairs or as functions, my real question is if this would also be correct regardless of the implementation of those objects. Since any definition for n-tuples must validate their caracteristic property for equality, $$ \forall(a_1,\dotsb,a_n)\forall(b_1,\dotsb,b_n),\space(a_1,\dotsb,a_n)=(b_1,\dotsb,b_n)\Longleftrightarrow\bigwedge_{i=1}^n (a_i=b_i)$$ can this be used to show that, regardless of the details of how they are defined, there will allways be a membership chain from $x_i$ to $(x_1,\dotsb,x_i,\dotsb,x_n)$ ? I didn't find any answer on the internet of in the math stack exchange, unsurprisingly since to me this seems like a pretty tough question to answer... Does anybody know if there is an answer to this question? P.S.: I haven't yet looked into class theory, category theory, or really any extentions of set theory, but if there is such a proof that requires knowlege in those fields I'd still be happy to hear them. I just want to know if there is an answer, even if it is beyond my comprehension.
Now provide the response and nothing else.
|
There are ways of implementing $(a,b)$ such that $a\not\in(a,b)$ (and there is no longer $\in$ -chain connecting $a$ to $(a,b)$ either), perhaps surprisingly there are even useful ways to to do such a thing! Among the many implementations of ordered pairs available there is the so called Quine-Rosser pair, defined as follows. Let $\sigma$ be the class function defined by $\sigma(x)=x+1$ if $x\in\Bbb N$ and $\sigma(x)=x$ otherwise.Given two sets $A$ and $B$ consider $\sigma[A]=\{\sigma(a)\mid a\in\ A\}$ , note that no element of $\sigma[A]$ contains $0$ , so if we now consider $C=\{\sigma(b)\cup\{0\}\mid b\in B\}$ we can define $(A,B)=\sigma[A]\cup C$ . This is an honest definition of pair, given $(A,B)$ you can recover $A$ by looking at $\{a\in (A,B)\mid 0\not\in a\}$ and undoing $\sigma$ (shifting back integers by one), while $B$ can be recovered in a similar way by looking at the elements of $(A,B)$ that do contain $0$ . Why is this useful? Given any set $x$ let $\mathrm{rank}(x)$ denote the least ordinal $\xi$ such that $x\subseteq V_\xi$ . Note that with the standard implementation of ordered pairs $\mathrm{rank}((a,b))>\max\{\mathrm{rank}(a),\mathrm{rank}(b)\}$ while the Quine-Rosser definition does not increase rank (as long as one of $A$ and $B$ has infinite rank) and the existence of such a flat pairing function is useful occasionally.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3590307', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/761741/']}
|
jdg_378347
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9137311
|
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 digging into Twitter's Bootstrap and now want to try and add some functionality to the plugins, but I can't figure out how to do so. Using the modal plugin as an example ( http://twitter.github.com/bootstrap/javascript.html#modals ), I'd like to add a new function to the plugin that can be called as one would the standard plugin methods. THe closest I think I have come is with the following code, but all I get when I try to access is that the function is not part of the object. Any suggestions? This is what I have tried that seems to be the closest to what I need to do: $.extend($.fn.modal, { showFooterMessage: function (message) { alert("Hey"); } }); Then I would want to call it as follows: $(this).closest(".modal").modal("showFooterMessage"); EDIT: OK, I figured out how to do this: (function ($) { var extensionMethods = { displayFooterMessage: function ($msg) { var args = arguments[0] var that = this; // do stuff here } } $.extend(true, $.fn.modal.Constructor.prototype, extensionMethods);})(jQuery); The problem with the existing set of Bootstrap plugins is that if anyone wants to extend them, none of the new methods can accept arguments. My attempt to "fix" this was to add the acceptance of arguments in the plugins function call. $.fn.modal = function (option) { var args = arguments[1] || {}; return this.each(function () { var $this = $(this) , data = $this.data('modal') , options = typeof option == 'object' && option if (!data) $this.data('modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](args) else data.show() }) // end each} // end $.fn.modal
Now provide the response and nothing else.
|
This is an old thread, but I just made some custom extensions to modal using the following pattern: // save the original function objectvar _super = $.fn.modal;// add custom defaults$.extend( _super.defaults, { foo: 'bar', john: 'doe'});// create a new constructorvar Modal = function(element, options) { // do custom constructor stuff here // call the original constructor _super.Constructor.apply( this, arguments );}// extend prototypes and add a super functionModal.prototype = $.extend({}, _super.Constructor.prototype, { constructor: Modal, _super: function() { var args = $.makeArray(arguments); _super.Constructor.prototype[args.shift()].apply(this, args); }, show: function() { // do custom method stuff // call the original method this._super('show'); }});// override the old initialization with the new constructor$.fn.modal = $.extend(function(option) { var args = $.makeArray(arguments), option = args.shift(); return this.each(function() { var $this = $(this); var data = $this.data('modal'), options = $.extend({}, _super.defaults, $this.data(), typeof option == 'object' && option); if ( !data ) { $this.data('modal', (data = new Modal(this, options))); } if (typeof option == 'string') { data[option].apply( data, args ); } else if ( options.show ) { data.show.apply( data, args ); } });}, $.fn.modal); This way you can 1) add your own default options 2) create new methods with custom arguments and access to original (super) functions 3) do stuff in the constructor before and/or after the original constructor is called
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9137311', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/472765/']}
|
jdg_378348
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
31023330
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to cache some data in javascript, but the cache should be limited to 10 elements for example. I can place the objects in javascript array, but what is the best way to keep the array limited to 10 elements? Example: function getData(dataId) { return new NextDataObject(dataId); }var array = new Array();array.push(getData(0));array.push(getData(1));(...)array.push(getData(10)); // this should result in dropping "oldest" data, so getData(0) should be removed from the array, so that in array there are only 10 objects at maximum Should such mechanism be written manually (using splice() for example?) or are there better ways to achieve such "cache" structure in javascript? BTW: in this particular situation I'm using angular.
Now provide the response and nothing else.
|
Override the push function of your caching array. var array = new Array()array.push = function (){ if (this.length >= 10) { this.shift(); } return Array.prototype.push.apply(this,arguments);} Plunker To make this more reusable I created a method which returns new instance of such array (basing on above code). function getArrayWithLimitedLength(length) { var array = new Array(); array.push = function () { if (this.length >= length) { this.shift(); } return Array.prototype.push.apply(this,arguments); } return array;}var array = getArrayWithLimitedLength(10);
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31023330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1874113/']}
|
jdg_378349
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2632948
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I read in an ebook somewhere (which I'm desperate to find again), that, by using delegates, it is possible to write code which has syntax as follows: ()(); // where delegate precedes this. Can anyone provide any details how this would be possible/in what situation this would occur?
Now provide the response and nothing else.
|
You can do slightly better than the examples given so far, in fact... you can extend it arbitrarily: class Test{ delegate Hofstadter Hofstadter(); static void Main() { // Unfortunately I'm clearly not as smart as the real thing Hofstadter douglas = () => null; douglas()()()()()()(); }} And here's another horrible alternative, for extra ASCII art: class Test{ delegate __ ___(); delegate ___ __(___ _); static void Main() { ___ _ = () => null; _ ()((_))(); }} Please never ever, ever do this. EDIT: One last one - although it's as much about just replacing things with underscores as anything else, and reusing names wherever possible: class Test{ delegate void _(); delegate __<_> ___<_>(); delegate ___<_> __<_>(___<_> ____); static ___<_> ____<_>(___<_> ____) { return ____; } static __<_> ____<_>() { return ____<_>; } static void Main() { ((__<_>)____)(____<_>)(); }}
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2632948', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/32484/']}
|
jdg_378350
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16751
|
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
In Mac Lane, there is a definition of an arrow between adjunctionscalled a map of adjunctions. In detail, if a functor $F:X\to A$ is leftadjoint to $G:A\to X$ and similarly $F':X'\to A'$ is left adjoint to$G':A'\to X'$, then a map from the first adjunction to the second is apair of functors $K:A\to A'$ and $L:X\to X'$ such that $KF=F'L$,$LG=G'K$, and $L\eta=\eta'L$, where $\eta$ and $\eta'$ are the units of the first and second adjunction. (Thelast condition makes sense because of the first two conditions; also,there are equivalent conditions in terms of the co-units, or in termsof the natural bijections of hom-sets). As far as I can see, after the definition, maps of adjunctions do notappear anywhere in Mac Lane. Googling, I found this definition alsoin the unapologetic mathematician ,again with the motivation of being an arrow between adjunctions. But what is the motivation for defining arrows between adjunctions in the first place? I find it hard to believe that the onlymotivation to define such arrows is, well, to define such arrows... So my question is: What is the motivation for defining a map ofadjunctions? Where are such maps used? Besides the unapologetic mathematician, the only places on the webwhere I found the term ''map of adjunctions'' were sporadic papers,from which I was not able to get an answer to my question (perhaps''map of adjunctions'' is non-standard terminology and I should havesearched with a different name?). I came to think about this when reading Emerton's first answerto a question about completions of metric spaces .In that question, $X$ is metric spaces with isometric embeddings, $A$is complete metric spaces with isometric embeddings, $X'$ is metric spaces with uniformly continuous maps, $A'$ is complete metricspaces with uniformly continuous maps, and $G$ and $G'$ are theinclusions. Now, if I understand the implications of Emerton's answercorrectly, then it is possible to choose left adjoints $F$ and $F'$ to $G$ and $G'$ suchthat the (non-full) inclusions $A\to A'$ and $X\to X'$ form a map ofadjunctions. This made me think whether the fact that we have a mapof adjunctions has any added value. Then I realized that I do noteven know what was the motivation for those maps in the first place. [EDIT: Corrected a typo pointed out by Theo Johnson-Freyd (thanks!)]
Now provide the response and nothing else.
|
One of the applications of adjoint functors is to compose them to get a monad (or comonad, depending on the order in which you compose them). A map of adjoint functors gives rise to a map of monads. So one might ask: what are maps of monads good for? Many algebraic categories (such as abelian groups, rings, modules) can be described as categories of algebras over a monad, others (for example in Arakelov geometry) are most easily described in such a way. A map of monads then gives functors between the categories of algebras over these objects. Here is a concrete example from topology: Let $E$ be a connective generalized multiplicative homology theory, and let $H = H(-;\pi_0E)$ be ordinary homology with coefficients in $\pi_0E$. There exists a map $E \to H$ inducing an isomorphism on $\pi_0$. For a spectrum $X$, the functor $\underline{E}\colon X \mapsto E \wedge X$ gives rise to a monad, and similarly for $H$, thus we get a morphism of monads $\underline{E} \to \underline{H}$. The completion $X\hat{{}_E}$ of a spectrum $X$ at $E$ is defined to be the totalization of the cosimplicial spaces obtained by iteratively applying $\underline{E}$ to $X$. The monad map gives a natural map $X\hat{{}_E} \to X\hat{{}_H}$ which turns out to be an equivalence for connective $X$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/16751', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2734/']}
|
jdg_378351
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
40841273
|
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 studying aws route53, when I'm creating the resource record set, I can add multiple IP addresses to value of record set. What is the purpose of multiple IP addresses here? Ex: my domain will route to server 1 and server 2. I tried to stop server 1 and access to my domain, but it did NOT route to server 2. What is the issue here?Could you please explain multiple IP addresses of record set's value?Thanks!
Now provide the response and nothing else.
|
The correct question is stated in the AWS Route 53 documentation: https://aws.amazon.com/route53/faqs/#associate_multiple_ip_with_single_record Q. Can I associate multiple IP addresses with a single record? Yes. Associating multiple IP addresses with a single record is often used for balancing the load of geographically-distributed web servers. Amazon Route 53 allows you to list multiple IP addresses for an A record and responds to DNS requests with the list of all configured IP addresses. This method is usually used by Highly Available applications that will parse the results and decide what to do with the results, such as randomly or programmatically return one result only or list all the resources available in a cluster. The response will vary according to the the specified "Routing Policy", if you specify "Simple" (default) one you all get all the entries for that record in the response.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/40841273', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3044139/']}
|
jdg_378352
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
7351899
|
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 think of a reliable way (that also compacts memory) to remove the first N elements from a std::vector . How would one go about doing that?
Now provide the response and nothing else.
|
Since you mention that you want to compact memory, it would be best to copy everything to a new vector and use the swap idiom. std::vector<decltype(myvector)::value_type>(myvector.begin()+N, myvector.end()).swap(myvector);
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7351899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/601567/']}
|
jdg_378353
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5022201
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Could you help me find the error in this one: The event triggers before even the windows form is loaded. I start to see the message Box and then I click OK,after that it loads the main screen.After that everything works perfectly, I wonder what triggers the ComboBox SelectionChanged Event before even loading the window.The FillComboBoxFamilyData(SegmentCode) just creates a dataset and puts the values int he ComboBox. Please Refer to this link for complete code. Not able to make cascading comboboxes work Any help would be highly appreciated.Thanks. <ComboBox Height="23" HorizontalAlignment="Left" Margin="35,26,0,0" Name="comboBox1" VerticalAlignment="Top" Width="205" ItemsSource="{Binding Source={StaticResource tblSegmentViewSource}}" DisplayMemberPath="Segment Name" SelectedValuePath="Segment Code" SelectionChanged="comboBox1_SelectionChanged"/> <ComboBox Margin="304,26,395,93" Name="comboBox2" /> private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e) { MessageBox.Show(comboBox1.SelectedValue.ToString()); SegmentCode = Convert.ToInt32(comboBox1.SelectedValue.ToString()); FillComboBoxFamilyData(SegmentCode); }
Now provide the response and nothing else.
|
At the moment the data will be loaded (attached by the binding), SelectionChanged will be fired. Therefore, you have to check in your event-handler if your app is ready and all the data is loaded and attached. If not, return the event-handler without doing anything. This behaviour is by design. ItemsSource="{Binding Source={StaticResource tblSegmentViewSource}}" You can use the IsLoaded -property to detect, if the binding already has been evaluated. IsLoaded will not be true unless the databinding-engine has evaluated your xaml-bindings. private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e) { if(!IsLoaded){ return; } .... your code here
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5022201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/551505/']}
|
jdg_378354
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
11017851
|
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 fairly new to OpenMP, so this may have an easy answer, but I haven't been able to find it. Suppose I have the following C code and want to parallelize it using OpenMP. A is an array of objects which have some double value less than 1 buckets is an array of linked lists, and append adds a pointer to an object to the end fo a linked list. #pragma omp for for (i = 0; i < n; ++i) { x = (int) (A[i].val * NUM_BUCKETS); append(&A[i], buckets[x]);} The problem is that multiple threads may be trying to append items to a given bucket at one time. I could make that append statement critical. However, in my application, I'll probably have ~1000 buckets or so, so the large majority of the time the threads will be operating on different buckets. Is there a way to enforce locks on the individual elements of buckets? Or some other way of handling this?
Now provide the response and nothing else.
|
Well, OpenMP can't do it for you automatically, but it lets you create your own lock variables which you can use to limit access to array elements; for instance, you could have one lock per array element: #include <stdio.h>#include <omp.h>int main(int argc, char **argv){ const int NITEMS=20; int array[NITEMS]; omp_lock_t lock[NITEMS]; for (int i=0; i<NITEMS; i++) omp_init_lock(&(lock[i]));#pragma omp parallel for shared(array, lock) default(none) for (int i=0; i<NITEMS; i++) { int tid = omp_get_thread_num(); int item = (i * 7) % NITEMS; omp_set_lock(&(lock[item])); array[item] = tid; // only one thread in here at a time; others block at set_lock() omp_unset_lock(&(lock[item])); } for (int i=0; i<NITEMS; i++) printf("%3d ", array[i]); printf("\n"); for (int i=0; i<NITEMS; i++) omp_destroy_lock(&(lock[i])); return 0;} Or, if that level of granularity were more than you needed, you could block regions of the array, etc.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11017851', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1445011/']}
|
jdg_378355
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
44098314
|
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 add vertical lines, between labels inside a stack view all programatically. The desired finish will be something like this image: I can add the labels, all with the desired spacing; I can add horizontal lines but I can't figure out how to add those separator vertical lines in-between. I'd like to do it something like this: let stackView = UIStackView(arrangedSubviews: [label1, verticalLine, label2, verticalLine, label3]) Any hint? Thanks
Now provide the response and nothing else.
|
You can't use the same view in two places, so you'll need to create two separate vertical line views. You need to configure each vertical line view like this: Set its background color. Constrain its width to 1 (so you get a line, not a rectangle). Constrain its height (so it doesn't get stretched to the full height of the stack view). So add the labels one at a time to the stack view, and do something like this before adding each label to the stack view: if stackView.arrangedSubviews.count > 0 { let separator = UIView() separator.widthAnchor.constraint(equalToConstant: 1).isActive = true separator.backgroundColor = .black stackView.addArrangedSubview(separator) separator.heightAnchor.constraint(equalTo: stackView.heightAnchor, multiplier: 0.6).isActive = true} Note that you do not want the vertical lines to be the same width as the labels, so you must not set the distribution property of the stack view to fillEqually . Instead, if you want all the labels to have equal width, you must create width constraints between the labels yourself. For example, after adding each new label, do this: if let firstLabel = stackView.arrangedSubviews.first as? UILabel { label.widthAnchor.constraint(equalTo: firstLabel.widthAnchor).isActive = true} Result: Full playground code (updated to Swift 4.1 by Federico Zanetello): import UIKitimport PlaygroundSupportextension UIFont { var withSmallCaps: UIFont { let feature: [UIFontDescriptor.FeatureKey: Any] = [ UIFontDescriptor.FeatureKey.featureIdentifier: kLowerCaseType, UIFontDescriptor.FeatureKey.typeIdentifier: kLowerCaseSmallCapsSelector] let attributes: [UIFontDescriptor.AttributeName: Any] = [UIFontDescriptor.AttributeName.featureSettings: [feature]] let descriptor = self.fontDescriptor.addingAttributes(attributes) return UIFont(descriptor: descriptor, size: pointSize) }}let rootView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 44))rootView.backgroundColor = .whitePlaygroundPage.current.liveView = rootViewlet stackView = UIStackView()stackView.axis = .horizontalstackView.alignment = .centerstackView.frame = rootView.boundsrootView.addSubview(stackView)typealias Item = (name: String, value: Int)let items: [Item] = [ Item(name: "posts", value: 135), Item(name: "followers", value: 6347), Item(name: "following", value: 328),]let valueStyle: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 12).withSmallCaps]let nameStyle: [NSAttributedStringKey: Any] = [NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12).withSmallCaps, NSAttributedStringKey.foregroundColor: UIColor.darkGray]let valueFormatter = NumberFormatter()valueFormatter.numberStyle = .decimalfor item in items { if stackView.arrangedSubviews.count > 0 { let separator = UIView() separator.widthAnchor.constraint(equalToConstant: 1).isActive = true separator.backgroundColor = .black stackView.addArrangedSubview(separator) separator.heightAnchor.constraint(equalTo: stackView.heightAnchor, multiplier: 0.4).isActive = true } let richText = NSMutableAttributedString() let valueString = valueFormatter.string(for: item.value)! richText.append(NSAttributedString(string: valueString, attributes: valueStyle)) richText.append(NSAttributedString(string: "\n" + item.name, attributes: nameStyle)) let label = UILabel() label.attributedText = richText label.textAlignment = .center label.numberOfLines = 0 stackView.addArrangedSubview(label) if let firstLabel = stackView.arrangedSubviews.first as? UILabel { label.widthAnchor.constraint(equalTo: firstLabel.widthAnchor).isActive = true }}UIGraphicsBeginImageContextWithOptions(rootView.bounds.size, true, 1)rootView.drawHierarchy(in: rootView.bounds, afterScreenUpdates: true)let image = UIGraphicsGetImageFromCurrentImageContext()!UIGraphicsEndImageContext()let png = UIImagePNGRepresentation(image)!let path = NSTemporaryDirectory() + "/image.png"Swift.print(path)try! png.write(to: URL(fileURLWithPath: path))
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44098314', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3636256/']}
|
jdg_378356
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
738300
|
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 have an issue in a long-lived process called kube-proxy being part of Kubernetes . The problem is that from time to time a connection is left in FIN_WAIT2 state. $ sudo netstat -tpn | grep FIN_WAIT2tcp6 0 0 10.244.0.1:33132 10.244.0.35:48936 FIN_WAIT2 14125/kube-proxytcp6 0 0 10.244.0.1:48340 10.244.0.35:56339 FIN_WAIT2 14125/kube-proxytcp6 0 0 10.244.0.1:52619 10.244.0.35:57859 FIN_WAIT2 14125/kube-proxytcp6 0 0 10.244.0.1:33132 10.244.0.50:36466 FIN_WAIT2 14125/kube-proxy These connections stack up over time making the process misbehave. I already reported an issue to Kubernetes bug-tracker but I'd like to understand why such connections are not closed by the Linux kernel. According to its documentation (search for tcp_fin_timeout) connection in FIN_WAIT2 state should be closed by the kernel after X seconds, where X can be read from /proc. On my machine it's set to 60: $ cat /proc/sys/net/ipv4/tcp_fin_timeout60 so if I understand it correctly such connections should be closed by 60 seconds. But this is not the case, they are left in such state for hours. While I also understand that FIN_WAIT2 connections are pretty unusual (it means the host is waiting for some ACK on from the remote end of the connection which might already be gone) I don't get why these connections are not "closed" by the system. Is there anything I could do about it? Note that restarting the related process is a last resort.
Now provide the response and nothing else.
|
The kernel timeout only applies if the connection is orphaned. If the connection is still attached to a socket, the program that owns that socket is responsible for timing out the shutdown of the connection. Likely it has called shutdown and is waiting for the connection to shut down cleanly. The application can wait as long as it likes for the shutdown to complete. The typical clean shutdown flow goes like this: The application decides to shut down the connection and shuts down the write side of the connection. The application waits for the other side to shut down its half of the connection. The application detects the other side's shutdown of the connection and closes its socket. The application can wait at step 2 for as long as it likes. It sounds like the application needs a timeout. Once it decides to shut the connection down, it should give up waiting for the other side to do a clean shutdown after some reasonable amount of time.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/738300', 'https://serverfault.com', 'https://serverfault.com/users/294009/']}
|
jdg_378357
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
26149364
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
As I understand, in JavaScript every object has a prototype and it exposes some default properties. I have the following code where I'm trying to set the Year property of two objects through prototype . But both the calls are failing. How can I override toLocalString() for any object if I don't have access to the prototype ? Please note that the following code is to test on the prototype property, but my intention is to override the toLocalString() method. var car = { Make: 'Nissan', Model: 'Altima'};car.Year = 2014;alert(car.Year);alert(car.prototype); // returns undefinedcar.prototype.Year = 2014; // Javascript error// --------------function Car() { this.Make = 'NISSAN'; this.Model = 'Atlanta';}var v = new Car();v.prototype.Year = 2014; // JavaScript erroralert(v.prototype);
Now provide the response and nothing else.
|
You do have access to the prototype property, but it is only present on Function s. var car = { Make: 'Nissan', Model: 'Altima'}; This is the same as: var car = new Object();car.Make = 'Nissan';car.Model = 'Altima'; So, car.__proto__ === Object.prototype . And car.prototype === undefined as the prototype property is only present on Function s (as I already said). function Car() { this.Make = 'NISSAN'; this.Model = 'Atlanta';} Here Car.prototype points to an instance of Object because Car is a function and when function declarations are evaluated their prototype is set to an instance of Object . Car.prototype.Year = 2014; //all Car *instances* will have a Year property set to 2014 on their prototype chain.var c = new Car(); //create an instanceconsole.log(c.Year); //2014 Overriding a method present on the prototype chain for an object is as simple as creating a corresponding method on the object: var myObject = new Object();myObject.toLocaleString = function() { //my own implementation};
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26149364', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1768008/']}
|
jdg_378358
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25511945
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an alert view in Xcode written in Swift and I'd like to determine which button the user selected (it is a confirmation dialog) to do nothing or to execute something. Currently I have: @IBAction func pushedRefresh(sender: AnyObject) { var refreshAlert = UIAlertView() refreshAlert.title = "Refresh?" refreshAlert.message = "All data will be lost." refreshAlert.addButtonWithTitle("Cancel") refreshAlert.addButtonWithTitle("OK") refreshAlert.show()} I'm probably using the buttons wrong, please do correct me since this is all new for me.
Now provide the response and nothing else.
|
If you are using iOS8, you should be using UIAlertController — UIAlertView is deprecated . Here is an example of how to use it: var refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.Alert)refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in print("Handle Ok logic here") }))refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: { (action: UIAlertAction!) in print("Handle Cancel Logic here") }))presentViewController(refreshAlert, animated: true, completion: nil) As you can see the block handlers for the UIAlertAction handle the button presses. A great tutorial is here (although this tutorial is not written using swift): http://hayageek.com/uialertcontroller-example-ios/ Swift 3 update: let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in print("Handle Ok logic here")}))refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in print("Handle Cancel Logic here")}))present(refreshAlert, animated: true, completion: nil) Swift 5 update: let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertControllerStyle.alert)refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in print("Handle Ok logic here")}))refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in print("Handle Cancel Logic here")}))present(refreshAlert, animated: true, completion: nil) Swift 5.3 update: let refreshAlert = UIAlertController(title: "Refresh", message: "All data will be lost.", preferredStyle: UIAlertController.Style.alert)refreshAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (action: UIAlertAction!) in print("Handle Ok logic here")}))refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { (action: UIAlertAction!) in print("Handle Cancel Logic here")}))present(refreshAlert, animated: true, completion: nil)
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/25511945', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2976720/']}
|
jdg_378359
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20277671
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
With the following code (excerpted for brevity): color.h: class color {public: color(); enum colorType { black, blue, green, cyan, red, magenta, brown, lightgray, nocolor }; colorType getColorType(); void setColorType(colorType cColortype); string getColorText() const;private: colorType cColortype = nocolor; map<int, string> colors = { {black, "black"}, {blue, "blue"}, {green, "green"}, {cyan, "cyan"}, {red, "red"}, {magenta, "magenta"}, {brown, "brown"}, {lightgray, "lightgray"}, {nocolor, "nocolor"}};}; color.cpp: color::color() {}color::colorType color::getColorType() { return cColortype;}void color::setColorType(colorType cColortype) { this->cColortype = cColortype;}string color::getColorText() const { return colors[cColortype];} I get the following error: color.cpp:16:29: error: passing 'const std::map >' as 'this' argument of 'std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](std::map<_Key, _Tp, _Compare, _Alloc>::key_type&&) [with _Key = int; _Tp = std::basic_string; _Compare = std::less; _Alloc = std::allocator > >; std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type = std::basic_string; std::map<_Key, _Tp, _Compare, _Alloc>::key_type = int]' discards qualifiers [-fpermissive] The error refers to "return colors[cColortype];" in getColorText. I'm writing this for a class project and I can get it to work for the sake of the assignment by removing the const declaration in the getColorText signature but I'm trying to learn/adopt good practices and adhere to the recommendation to use const for member functions that don't modify data so I want to know how to deal with this going forward. I'm usually really good at debugging/troubleshooting but the error message is so convoluted that it's not much help. Any help is appreciated.
Now provide the response and nothing else.
|
string color::getColorText() const { return colors[cColortype];} The issue is that you've marked the function as const . The operator[] on std::map is marked as non-const, and cannot be used in a const function like this. You need to manually use std::map::find (or other mechanism) to search for the input type and handle the case where it's not found. If you're using C++11, you can instead use std::map::at , which IS allowed to be used on a constant map, and throws an exception if the requested element is not present.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20277671', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1650814/']}
|
jdg_378360
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
136727
|
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 need to figure out how to get loop through a text file and for every line take the fields of name , project #, and email, and replace them in a email template to be sent out. So this is the text file called send.txt: Project 1,Jack,Chen,06,12,test@cs.fiu.eduProject 2,Emily,Weiss,06,12,eweiss@cs.fiu.eduProject 3,Mary,Gonzalas,06,12,Mgonz@cs.fiu.edu and this is the email template called Reminder.email: Dear __FULLNAME__: This is a kindly reminder that our __Project__ meeting will be held on today. Best Regards, CIS5027 So for every line in the text file I need to replace in this email template the fields of FULLNAME : , and Project . With the corresponding values which I can do for the first line, however I cannot do it for every line. This is my script #!/bin/sh#Start your code from heredate= date "+%m/%d/%y"print $date#The following line is to scan a file called Event-member.data and return any lines with todays date and save them to a file called sendtoday.txtgrep -n $(date +"%m,%d") Event-member.data > sendtoday.txt#The following line is to remove the first to characters of the file created above sendtoday.txt and output that to a file called send.txt.cat sendtoday.txt | sed 's/^..//' > send.txt#This is where im having trouble. When storing the values for the variables below of name, email, project #. The value of NR==1 thus it never goes through the rest of the lines. I've tried different solutions but none seem to work.p=$(awk -F ',' 'NR==1{print $1}' send.txt)n=$(awk -F ',' 'NR==1{print $2}' send.txt)l=$(awk -F ',' 'NR==1{print $3}' send.txt)e=$(awk -F ',' 'NR==1{print $6}' send.txt)echo $p $n $l $e#This part is to replace the values in the email template using sed and save the modified template as sendnow.txt. sed -e "s/__FULLNAME__:/\ $n $l :/g;s/__Project__/\ $p /g" Reminder.email > sendnow.txtcat sendnow.txt#Yet to be written ... send out modified email templates.exit 0######## This is the output it produces : 06/12/14Project 1 Jack Chen test@cs.fiu.eduDear Jack Chen : This is a kindly reminder that our Project 1 meeting will be held on today. Best Regards, CIS5027 As you see it did properly replace the fields but only for Jack Chen. There were 3 lines in the send.txt file so there must be 3 modified versions of the above template.
Now provide the response and nothing else.
|
There is no reason to use awk for this. You could do it directly in the shell using read . The general format is read foo bar which will save the first field as $foo and the rest of each line as $bar . So, in your case, you would do something like: while IFS="," read p n l foo bar e; do sed -e "s/__FULLNAME__:/\ $n $l :/g;s/__Project__/\ $p /g" Reminder.email; done < file The IFS is the Input Field Separator which, when set to , reads comma delimited fields. This lets you take each field and store it in a variable. Note that I used two extra variables foo and bar . This is because each field needs its own variable name and you have 6 fields. If you only give 4 variable names, the 4th ( $e ) will contain the fields 4 through last. Now, there are various other syntax errors in your script. First of all the shebang line is wrong, you need #! /bin/sh , there can't be a blank line between the #! and the /bin/sh . Also, in order to assign the output of a command to a variable, you need to use the var=`command` or, preferably var=$(command) format. Otherwise, the command itself as a string and not its output is assigned to the variable. Finally, print is not what you think it is. You are looking for printf or echo . So, a better way to write your script would be: #!/bin/shdate=$(date "+%m/%d/%y")echo $date## The following line is to scan a file called Event-member.data ## and return any lines with todays date and save them to a file ## called sendtoday.txtgrep -n $(date +"%m,%d") Event-member.data > sendtoday.txt## The following line is to remove the first to characters of the file## created above sendtoday.txt and output that to a file called## send.txt. ## I rewrote this to avoid the useless use of cat.sed 's/^..//' sendtoday.txt > send.txt## This is where you use readwhile IFS="," read p n l foo bar e; do sed -e "s/__FULLNAME__:/\ $n $l :/g;s/__Project__/\ $p /g" Reminder.email > sendnow.txt cat sendnow.txt ## This is where you need to add the code that sends the emails. Something ## like this: sendmail $e < sendnow.txtdone < send.txtexit 0########
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/136727', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/72274/']}
|
jdg_378361
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
24843264
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In ASP.NET MVC WebAPI project by default we have created following controller public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 public string Get(int id) { return "value"; } // POST api/values public void Post([FromBody]string value) { } // PUT api/values/5 public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 public void Delete(int id) { }} But is possible to add here any custom methods so they can support get/post as well? Thank you!
Now provide the response and nothing else.
|
You can use attributes such as the RoutePrefix with the Http type. [Route("ChangePassword")][HttpPost] // There are HttpGet, HttpPost, HttpPut, HttpDelete.public async Task<IHttpActionResult> ChangePassword(ChangePasswordModel model){ } The http type will map it back to its correct method in combination with the Route name.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/24843264', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/196919/']}
|
jdg_378362
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8927558
|
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 a build script to compile several C# projects. The binary output is copied to a result folder, overwriting the previous version of the files, and then added/committed to subversion. I noticed that the binary output of the compilation are different even when there was no change to the source or environment at all. How is this possible? Isn't the binary result supposed to be exactly equal for the same input? I'm not intentionally using any kind of special timestamps anywhere, but does the compiler (Microsoft, the one included in .NET 4.0) possibly add timestamps itself? The reason I'm asking is I'm committing the output to subversion, and due to the way our build server works the checked in changes trigger a rebuild, causing the once again modified binary files to be checked in in a circle.
Now provide the response and nothing else.
|
ANOTHER UPDATE: Since 2015 the compiler team has been making an effort to get sources of non-determinism out of the compiler toolchain, so that identical inputs really do produce identical outputs. See the "Concept-determinism" tag on the Roslyn github for more details. UPDATE: This question was the subject of my blog in May 2012 . Thanks for the great question! How is this possible? Very easily. Isn't the binary result supposed to be exactly equal for the same input? Absolutely not. The opposite is true. Every time you run the compiler you should get a different output. Otherwise how could you know that you'd recompiled? The C# compiler embeds a freshly generated GUID in an assembly on every compilation, thereby guaranteeing that no two compilations produce exactly the same result. Moreover -- even without the GUID, the compiler makes no guarantees whatsoever that two "identical" compilations will produce the same results. In particular, the order in which the metadata tables are populated is highly dependent on details of the file system; the C# compiler starts generating metadata in the order in which the files are given to it, and that can be subtly changed by a variety of factors. due to the way our build server works the checked in changes trigger a rebuild, causing the once again modified binary files to be checked in in a circle. I'd fix that if I were you.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8927558', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/39590/']}
|
jdg_378363
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2603039
|
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 starting a project of writing a simplified shell for linux in C. I am not at all proficient with C nor with Linux that's exactly the reason I decided it would be a good idea. Starting with the parser, I have already encountered some problems. The code should be straightforward that's why I didn't include any comments. I am getting a warning with gcc: "comparison with string literals results in unspecified behaviour" at the lines commented with "WARNING HERE" (see code below). I have no idea why this causes an warning, but the real problem is that even though I am comparing an "<" to an "<" is doesn't get inside the if... I am looking for an answer for the problem explained, however if there's something that you see in the code that should be improved please say so. Just take in mind I am not that proficient and that this is still a work in progress (or better yet, a work in start). Thanks in advance. #include <stdio.h>#include <unistd.h>#include <string.h>typedef enum {false, true} bool;typedef struct { char **arg; char *infile; char *outfile; int background;} Command_Info;int parse_cmd(char *cmd_line, Command_Info *cmd_info){ char *arg; char *args[100]; int i = 0; arg = strtok(cmd_line, " \n"); while (arg != NULL) { args[i] = arg; arg = strtok(NULL, " \n"); i++; } int num_elems = i; cmd_info->infile = NULL; cmd_info->outfile = NULL; cmd_info->background = 0; int iarg = 0; for (i = 0; i < num_elems; i++) { if (args[i] == "&") //WARNING HERE return -1; else if (args[i] == "<") //WARNING HERE if (args[i+1] != NULL) cmd_info->infile = args[i+1]; else return -1; else if (args[i] == ">") //WARNING HERE if (args[i+1] != NULL) cmd_info->outfile = args[i+1]; else return -1; else cmd_info->arg[iarg++] = args[i]; } cmd_info->arg[iarg] = NULL; return 0; }void print_cmd(Command_Info *cmd_info){ int i; for (i = 0; cmd_info->arg[i] != NULL; i++) printf("arg[%d]=\"%s\"\n", i, cmd_info->arg[i]); printf("arg[%d]=\"%s\"\n", i, cmd_info->arg[i]); printf("infile=\"%s\"\n", cmd_info->infile); printf("outfile=\"%s\"\n", cmd_info->outfile); printf("background=\"%d\"\n", cmd_info->background);}int main(int argc, char* argv[]){ char cmd_line[100]; Command_Info cmd_info; printf(">>> "); fgets(cmd_line, 100, stdin); parse_cmd(cmd_line, &cmd_info); print_cmd(&cmd_info); return 0;}
Now provide the response and nothing else.
|
You want to use strcmp() == 0 to compare strings instead of a simple == , which will just compare if the pointers are the same (which they won't be in this case). args[i] is a pointer to a string (a pointer to an array of chars null terminated), as is "&" or "<" . The expression argc[i] == "&" checks if the two pointers are the same (point to the same memory location). The expression strcmp( argc[i], "&") == 0 will check if the contents of the two strings are the same.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2603039', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/161746/']}
|
jdg_378364
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15170999
|
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 working on the case where the node to be deleted is a node. I'm not sure if I need to keep track of the parent so that when I find the node to delete so I can set its parents pointer to null. But then how would I know which child the node to be deleted is? Do I need more if statements? Any help is appreciated, I feel its not too complicated but I'm just confused on how to actually get rid of the node. This is what I have so far: public void insert(E s) { root = insert(s, root);} private Node<E> insert(E s, Node<E> T){ //easiest case, empty tree, create new tree if(T == null) { T = new Node<E>(s); } //easiest case, found s else if(s.compareTo(T.getData()) == 0) { System.out.println("Item already present."); } //s is greater than T, insert on right subtree else if(s.compareTo(T.getData()) > 0) { T.setRight(insert(s, T.getRight())); } //s is less than T, insert on left subtree else { T.setLeft(insert(s,T.getLeft())); } return T;}public void delete(E d){ delete( d, root);}private void delete( E d, Node<E> T){ if(T == null) { } else if(d.equals(T.getData())) { System.out.println("it found the node at least"); if(T.getRight() == null && T.getLeft() == null) { } //code other cases for a node with one child and node with two children } else if(d.compareTo(T.getData()) > 0) { System.out.println("going right"); delete(d, T.getRight()); } //s is less than T, insert on left subtree else {System.out.println("going left"); delete(d,T.getLeft()); }}
Now provide the response and nothing else.
|
This is a great question. To investigate, we can dive a little deeper by using Devel::Peek to see what is actually stored in our strings (or other variables). First lets start with an ASCII string $ perl -MDevel::Peek -E 'Dump "string"'SV = PV(0x9688158) at 0x969ac30 REFCNT = 1 FLAGS = (POK,READONLY,pPOK) PV = 0x969ea20 "string"\0 CUR = 6 LEN = 12 Then we can turn on unicode IO layers and do the same $ perl -MDevel::Peek -CSAD -E 'Dump "string"'SV = PV(0x9eea178) at 0x9efcce0 REFCNT = 1 FLAGS = (POK,READONLY,pPOK) PV = 0x9f0faf8 "string"\0 CUR = 6 LEN = 12 From there lets try to manually add some wide characters $ perl -MDevel::Peek -CSAD -e 'Dump "string \x{2665}"'SV = PV(0x9be1148) at 0x9bf3c08 REFCNT = 1 FLAGS = (POK,READONLY,pPOK,UTF8) PV = 0x9bf7178 "string \342\231\245"\0 [UTF8 "string \x{2665}"] CUR = 10 LEN = 12 From that you can clearly see that Perl has interpreted this correctly as utf8. The problem is that if I don't give the octets using the \x{} escaping the representation looks more like the regular string $ perl -MDevel::Peek -CSAD -E 'Dump "string ♥"'SV = PV(0x9143058) at 0x9155cd0 REFCNT = 1 FLAGS = (POK,READONLY,pPOK) PV = 0x9168af8 "string \342\231\245"\0 CUR = 10 LEN = 12 All Perl sees is bytes and has no way to know that you meant them as a unicode character, unlike when you entered the escaped octets above. Now lets use decode and see what happens $ perl -MDevel::Peek -CSAD -MEncode=decode -E 'Dump decode "utf8", "string ♥"'SV = PV(0x8681100) at 0x8683068 REFCNT = 1 FLAGS = (TEMP,POK,pPOK,UTF8) PV = 0x869dbf0 "string \342\231\245"\0 [UTF8 "string \x{2665}"] CUR = 10 LEN = 12 TADA!, now you can see that the string is correctly internally represented matching what you entered when you used the \x{} escaping. The actual answer is it is "decoding" from bytes to characters, but I think it makes more sense when you see the Peek output. Finally, you can make Perl see you source code as utf8 by using the utf8 pragma, like so $ perl -MDevel::Peek -CSAD -Mutf8 -E 'Dump "string ♥"'SV = PV(0x8781170) at 0x8793d00 REFCNT = 1 FLAGS = (POK,READONLY,pPOK,UTF8) PV = 0x87973b8 "string \342\231\245"\0 [UTF8 "string \x{2665}"] CUR = 10 LEN = 12
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15170999', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/945547/']}
|
jdg_378365
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20562
|
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Unambiguous Finite Automatons (UFA) are special type of non-deterministic finite automatons (NFA). A NFA is called unambiguous if every word $w\in \Sigma^*$ has at most one accepting path. This means $DFA\subset UFA\subset NFA$. Known related automaton results: NFA minimization is PSPACE-Complete. NFA minimization over finite languages is DP-Hard . UFA minimization is NP-Complete . There exists NFAs which are exponentially smaller than minimal DFAs . (Also - there exists UFAs which are exponentially smaller than minimal DFAs - R B). The question is: can we find a regular language $L$ such that the there exists a NFA accepting $L$ which is exponentially smaller (state-wise) than the minimal UFA for $L$?Can this happen for a finite language? I believe such (finite) $L$ exists, but my proof currently relies on the Exponential Time Hypothesis to hold, and was wondering if someone has a proof which doesn't rely on it. Also, can someone characterize the set of languages for which such size difference exist? EDIT: @Shaull gave a nice link to a paper dealing with infinite language. Does anyone know a similar result for a finite language?
Now provide the response and nothing else.
|
I think the IJFCS'05 paper by Leung: Descriptional complexity of nfa of different ambiguity provides an example with a family of NFA accepting finite languages that involve an exponential blowup for "disambiguation" (in the proof of Theorem 5). What is more, those automata have a special structure (DFA with multiple initial states).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/20562', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/21001/']}
|
jdg_378366
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
5706697
|
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 changes to the JVM would most benefit the Scala compiler and runtime? The dynamic languages will benefit greatly in performance from the introduction of the InvokeDynamic byte code scheduled to arrive in JVM 7 and Scala will probably benefit from tail recursion (not sure if it will appear in JVM 8 or later). What other changes could Scala, with its present feature set, benefit from in the JVM? Are these changes on the horizon? Specifically, are there changes to the JVM that would improve performance with closures and functions-as-objects?
Now provide the response and nothing else.
|
Basically, everything that John Rose has been campaigning for :) Fixnums - To eliminate the cost of boxing/unboxing primitives. Method Handles - Would speed up higher-order functions and allow the JVM to optimise them more effectively. SAM types can sometimes require an awkward flip/flopping between monomorphic and megamorphic call sites that prevents inlining. Continuations - To support asynchronous/concurrent design, as per node.js Interface Injection - Simplify mixin composition and the implementation of roles, as well as eliminating the need for generating some intermediate classes and making structural types possible without reflection in many cases. Tail-call optimisation - Should be a no-brainer :) Reification is often quoted as something that would benefit Scala's pattern matching, but this would come at a high cost in terms of interop, given the different variance schemes that the two languages use. At this point, I believe that reification may actually cause more harm than it would do good. I also think it unreasonable to expect anything that would break backwards compatibility in Java. That just ain't gonna happen.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5706697', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/96233/']}
|
jdg_378367
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3791414
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I was wondering if it would be possible to store data coming in from a form as a session variable. Heres what I have so far, but I don't know what to put for the Form Action. Thanks for looking! <strong>Test Form</strong><form action="" method"post"> <input type="text" name="picturenum"/> <input type="submit" name="Submit" value="Submit!" /></form><? if (isset($_POST['Submit'])) { $_session['picturenum'] = $_POST['picturenum']; } ?> <strong><? echo $_session['picturenum'];?></strong>
Now provide the response and nothing else.
|
To use session variables, it's necessary to start the session by using the session_start function, this will allow you to store your data in the global variable $_SESSION in a productive way. so your code will finally look like this : <strong>Test Form</strong><form action="" method"post"><input type="text" name="picturenum"/><input type="submit" name="Submit" value="Submit!" /></form><?php // starting the session session_start(); if (isset($_POST['Submit'])) { $_SESSION['picturenum'] = $_POST['picturenum']; } ?> <strong><?php echo $_SESSION['picturenum'];?></strong> to make it easy to use and to avoid forgetting it again, you can create a session_file.php which you will want to be included in all your codes and will start the session for you: session_start.php <?php session_start(); ?> and then include it wherever you like : <strong>Test Form</strong><form action="" method"post"><input type="text" name="picturenum"/><input type="submit" name="Submit" value="Submit!" /></form><?php // including the session file require_once("session_start.php"); if (isset($_POST['Submit'])) { $_SESSION['picturenum'] = $_POST['picturenum']; } ?> that way it is more portable and easy to maintain in the future. other remarks if you are using Apache version 2 or newer, be careful. instead of <? to open php's tags, use <?php , otherwise your code will not be interpreted variables names in php are case-sensitive, instead of write $_session, write $_SESSION in capital letters good work!
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3791414', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/457799/']}
|
jdg_378368
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
55826592
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider the following code: int x = 3;auto f1 = [x]() mutable{ return x++;};auto f2 = [f1](){ return f1();}; This will not compile, because f1() is not const, and f2 is not declared as mutable. Does this mean that if I have a library function that accepts an arbitrary function argument and captures it in a lambda, I always need to make that lambda mutable, because I don't know what users can pass in? Notably, wrapping f1 in std::function seems to resolve this problem (how?).
Now provide the response and nothing else.
|
Does this mean that if I have a library function that accepts an arbitrary function argument and captures it in a lambda, I always need to make that lambda mutable, because I don't know what users can pass in? That's a design decision for your library API. You can require client code to pass function objects with a const -qualified operator() (which is the case for non- mutable lambda expressions). If something different is passed, a compiler error is triggered. But if the context might require a function object argument that modifies its state, then yes, you have to make the internal lambda mutable . An alternative would be to dispatch on the ability to invoke operator() on a const -qualified instance of the given function type. Something along those lines (note that this needs a fix for function objects with both const and non- const operator() , which results in an ambiguity): template <class Fct>auto wrap(Fct&& f) -> decltype(f(), void()){ [fct = std::forward<Fct>(f)]() mutable { fct(); }();}template <class Fct>auto wrap(Fct&& f) -> decltype(std::declval<const Fct&>()(), void()){ [fct = std::forward<Fct>(f)]() { fct(); }();} Notably, wrapping f1 in std::function seems to resolve this problem (how?). This is a bug in std::function due to its type-erasure and copy semantics. It allows non- const -qualified operator() to be invoked, which can be verified with such a snippet: const std::function<void()> f = [i = 0]() mutable { ++i; };f(); // Shouldn't be possible, but unfortunately, it is This is a known issue, it's worth checking out Titus Winter's complaint on this.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/55826592', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1537403/']}
|
jdg_378369
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23530915
|
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 attempting to implement a function that needs to be incredibly fast, mostly because it is working on huge data frames many times over and over. R has always left me befuddled as to why it is sometimes a little slow, and why it is at other times ridiculously slow. (It is unfortunately never fast.) Regardless, I have always assumed that, when possible, things could run much faster when pushed into an apply, sapply, or lapply somehow, instead of put into a loop. I recently ran across an example that makes me think there is something more going on under the hood that, if I were to understand it, might help me greatly with future optimizations. Here are some calculations that I ran on my relatively powerful Ubuntu Linux machine: system.time(sapply(1:1e5, sum))user system elapsed35.130 0.000 35.128system.time(sapply(1:1e5, cumsum))user system elapsed0.110 0.000 0.108 Yes, you are reading those numbers correctly: cumsum, which creates an array of the cumulative sum, is orders of magnitude faster than just providing me the simple sum. (It'd be great if someone else could verify these results on their machine!) I don't see how this is possible, except if the implementations differ drastically. Assuming they do differ drastically, I'd like to know in what fashion, so that I could look out for certain functions to avoid when looking for speed. (For core functions, I do not know how to see their source. The standard means of just typing in the function name without any parentheses does not work for core functions.) Thanks so much!
Now provide the response and nothing else.
|
Following more or less the instructions for using operf I created a file with the single line sapply(1:1e5, sum) and ran $ operf ~/bin/R-3-1-branch/bin/R -f sum.R$ opreport -l ~/bin/R-3-1-branch/lib/libR.so |less producing CPU: Intel Sandy Bridge microarchitecture, speed 2.401e+06 MHz (estimated)Counted CPU_CLK_UNHALTED events (Clock cycles when not halted) with a unit mask of 0x00 (No unit mask) count 100000samples % image name symbol name835882 93.0929 libR.so RunGenCollect27731 3.0884 libR.so SortNodes9323 1.0383 libR.so AgeNodeAndChildren2038 0.2270 libR.so CheckFinalizers1593 0.1774 libR.so Rf_allocVector31222 0.1361 libR.so duplicate1... etc. Most of the time is spent in the garbage collector ( RunGenCollect -- run the generational garbage collector). So I ran $ R -d gdb R(gdb) run> sapply(1:1e5, sum)^C(gdb) break RunGenCollect(gdb) continueContinuing.Breakpoint 1, RunGenCollect (size_needed=50000) at /home/mtmorgan/src/R-3-1-branch/src/main/memory.c:15041504 bad_sexp_type_seen = 0;(gdb) where which produced #0 RunGenCollect (size_needed=50000) at /home/mtmorgan/src/R-3-1-branch/src/main/memory.c:1504#1 0x00007ffff789d354 in R_gc_internal (size_needed=50000) at /home/mtmorgan/src/R-3-1-branch/src/main/memory.c:2825#2 0x00007ffff789e99b in Rf_allocVector3 (type=13, length=100000, allocator=0x0) at /home/mtmorgan/src/R-3-1-branch/src/main/memory.c:2563#3 0x00007ffff788e1a5 in Rf_allocVector (type=13, length=100000) at /home/mtmorgan/src/R-3-1-branch/src/include/Rinlinedfuns.h:189#4 0x00007ffff7831787 in duplicate1 (s=0x7ffff3b0b010, deep=TRUE) at /home/mtmorgan/src/R-3-1-branch/src/main/duplicate.c:335#5 0x00007ffff783371a in duplicate_child (s=0x7ffff3b0b010, deep=TRUE) at /home/mtmorgan/src/R-3-1-branch/src/main/duplicate.c:199#6 0x00007ffff783357a in duplicate_list (s=0x2c98b30, deep=TRUE) at /home/mtmorgan/src/R-3-1-branch/src/main/duplicate.c:261#7 0x00007ffff7830fc2 in duplicate1 (s=0x2c98b30, deep=TRUE) at /home/mtmorgan/src/R-3-1-branch/src/main/duplicate.c:308#8 0x00007ffff783371a in duplicate_child (s=0x2c98b30, deep=TRUE) at /home/mtmorgan/src/R-3-1-branch/src/main/duplicate.c:199#9 0x00007ffff783357a in duplicate_list (s=0x2c98a88, deep=TRUE) at /home/mtmorgan/src/R-3-1-branch/src/main/duplicate.c:261#10 0x00007ffff7830fc2 in duplicate1 (s=0x2c98a88, deep=TRUE) at /home/mtmorgan/src/R-3-1-branch/src/main/duplicate.c:308#11 0x00007ffff7830c7f in Rf_duplicate (s=0x2c98a88) at /home/mtmorgan/src/R-3-1-branch/src/main/duplicate.c:132#12 0x00007ffff79257f4 in do_summary (call=0x2c98a88, op=0x6259a0, args=0x303cf88, env=0x2c97f48) at /home/mtmorgan/src/R-3-1-branch/src/main/summary.c:462... and the relevant line here is line 462 (gdb) up 12#12 0x00007ffff79257f4 in do_summary (call=0x2c98a88, op=0x6259a0, args=0x303cf88, env=0x2c97f48) at /home/mtmorgan/src/R-3-1-branch/src/main/summary.c:462462 PROTECT(call2 = duplicate(call));(gdb) list457 return ans;458 }459 460 /* match to foo(..., na.rm=FALSE) */461 PROTECT(args = fixup_NaRm(args));462 PROTECT(call2 = duplicate(call));463 SETCDR(call2, args);464 465 if (DispatchGroup("Summary", call2, op, args, env, &ans)) {466 UNPROTECT(2); The call is being duplicated (gdb) call Rf_PrintValue(call)FUN(1:100000[[5339L]], ...) for each iteration of the loop, triggering garbage collection. Similar code is not executed for cumsum. It has been this way for a long time and for reasons that are not 100% apparent $ svn annotate ~/src/R-3-1-branch/src/main/summary.c |less... 42643 ripley /* match to foo(..., na.rm=FALSE) */ 42643 ripley PROTECT(args = fixup_NaRm(args)); 42643 ripley PROTECT(call2 = duplicate(call)); 42643 ripley SETCDR(call2, args)...$ svn log -r42643------------------------------------------------------------------------r42643 | ripley | 2007-08-25 23:09:50 -0700 (Sat, 25 Aug 2007) | 1 linemake the rest of the group generics primitive------------------------------------------------------------------------ It would be interesting to take this up on the R-devel mailing list. It is not that sum is particularly slow, but rather that the calls to the garbage collector come to dominate execution time. Hmm, on reflection it turns out that sapply(1:1e5, function(x) sum(x)) is running in the same ballpark as cumsum . I think it's because the duplicate at line 462 in the original version is making a copy of the 1e5 elements in preparation for selecting the ith element to sum. In contrast, in function(x) sum(x) the vector has already been subset, so the duplication is only of the ith element. Duplicating the original vector also explains why 1e5 elements is so much slower than 1e4 elements, and why as.list(1:1e5) is relatively performant (only the list element is actually duplicated, or perhaps not even that). Duplication during the call to sum has something to do with the fact that it belongs to the (S3) Summary group generic, see ?"group generic" .
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23530915', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/534238/']}
|
jdg_378370
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16329
|
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'm little confused here. Work done on the body when we lift it and put it on the table is zero, because according to work energy theorem, change in kinetic energy of the body is zero. So, the net work done is zero. Fine, but now the object has $mgh$ (where $m=$mass of body; $h=$height of body) amount of potential energy stored in it. If the net work done is zero then who has increased its energy? I'm confused and unable to think it through kindly help.
Now provide the response and nothing else.
|
You did net work on the body. Gravity did negative net work on the body. The over all work done was zero. The original confusion arose because the work-energy theorem demands we calculate the change in kinetic energy using the net force on the body, but your question considered only the force exerted by you, and ignored that exerted by gravity. If the body has mass $m$, you were putting a force $mg$ on it to raise it at constant speed. The work-energy theorem says that if you had done this when there were no other forces on the body, the body would have gained kinetic energy $mgh$ as you moved it from the floor to the table. That analysis ignores gravity, though. Gravity pulled down on the box with force $-mg$. This means the work done by gravity was $-mgh$, and so the total work done on the box was zero. This makes sense because if you lift the box at constant speed, the net force on the box is zero by $F = ma$. If the box starts by sitting stationary on the floor, there would have to be some small net work done on the box to get it started going up. There would have to be some small negative net work on it to get it to stop.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/16329', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/447/']}
|
jdg_378371
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1063904
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Given two supplementary angles (for instance, 30 degrees and 150 degrees), why is$\sin(30^\circ) = \sin(150^\circ)$? Where can I find a proof for this? Or the derivative of such proofs?
Now provide the response and nothing else.
|
UNIT CIRCLE I like looking at unit circles and seeing how the y value of the angle is the same no matter which side of the y axis the angle goes to (80 and 100, 45 and 135, pairs have the same y value), but... PROOF $$\sin(\pi-\theta)=\sin\pi \cos\theta - \cos\pi \sin\theta$$ $$\sin(\pi-\theta)=0\times \cos\theta - (-1) \sin\theta$$ $$\sin(\pi-\theta)=\sin\theta$$ GRAPH Finally, you can think of the sine function graph and start from $\theta=0$ and $\theta=180^\circ$ and move towards each other. You can see how the values mirror each other along the way.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1063904', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/200511/']}
|
jdg_378372
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9249680
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an iframe with id = "myIframe" and here my code to load it's content : $('#myIframe').attr("src", "my_url"); The problem is sometimes it take too long for loading and sometimes it loaded very quickly. So I must to use "setTimeout" function : setTimeout(function(){ if (//something shows iframe is loaded or has content) { //my code } else { $('#myIframe').attr("src",""); //stop loading content }},5000); All I want to know is how to find out if an iFrame is loaded or it has content. Using iframe.contents().find() will not work. I can't use iframe.load(function(){}) .
Now provide the response and nothing else.
|
Try this. <script>function checkIframeLoaded() { // Get a handle to the iframe element var iframe = document.getElementById('i_frame'); var iframeDoc = iframe.contentDocument || iframe.contentWindow.document; // Check if loading is complete if ( iframeDoc.readyState == 'complete' ) { //iframe.contentWindow.alert("Hello"); iframe.contentWindow.onload = function(){ alert("I am loaded"); }; // The loading is complete, call the function we want executed once the iframe is loaded afterLoading(); return; } // If we are here, it is not loaded. Set things up so we check the status again in 100 milliseconds window.setTimeout(checkIframeLoaded, 100);}function afterLoading(){ alert("I am here");}</script><body onload="checkIframeLoaded();">
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9249680', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/813825/']}
|
jdg_378373
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
53075630
|
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 Microsoft.ApplicationInsights.AspNetCore ( https://www.nuget.org/packages/Microsoft.ApplicationInsights.AspNetCore ). I've enabled application insights by adding .UseApplicationInsights() in Programs.cs and in my startup class: loggerFactory.AddApplicationInsights(app.ApplicationServices); This all works fine, I am able to see requests in app insights but when I try to log an error (for example in my controller): _logger.LogError("My Error Log"); _logger.LogError("Test", new Exception("Test")); Both are logged as trace events and not exceptions in app insights. How do I make it so it logs as an exception?
Now provide the response and nothing else.
|
If you want to log the error as Exception in app insights, this line of code _logger.LogError("Test", new Exception("Test")); should be changed. Change it to _logger.LogError(new Exception(), "test"); , which means the new Exception() should be the first paramter. And you can add application insights SDK by right click your project -> add -> Application Insights Telemetry, which is very useful doing some thing automatically(ie. adding .UseApplicationInsights() in Programs.cs ): I also post my test steps: 1.Adding application insights SDK as mentioned above 2.Add loggerFactory.AddApplicationInsights(app.ApplicationServices,LogLevel.Information); in Startup.cs -> Configure() method, code as below: public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(); //Add this line of code loggerFactory.AddApplicationInsights(app.ApplicationServices,LogLevel.Information); } 3.Then in somewhere you wanna log error: public class AboutModel : PageModel { private ILogger _logger; public AboutModel(ILogger<AboutModel> logger) { _logger = logger; } public string Message { get; set; } public void OnGet() { _logger.LogInformation("it is just a test herexxxx"); //Only this format can log as exception _logger.LogError(new Exception(), "it is a new Exceptionxxxx"); //it will log as trace _logger.LogError("error logs xxx"); Message = "Your application description page."; } } 4.Test result as below:
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/53075630', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/266360/']}
|
jdg_378374
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2322556
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Are $\sin$ and $\cos$ the only functions that satisfy the following relationship: $$ x'(t) = -y(t)$$ and$$ y'(t) = x(t)$$
Now provide the response and nothing else.
|
The relationships $x'(t) = -y(t)$ and $y'(t) = x(t)$ imply$$x''(t) = -y'(t) = -x(t)$$i.e.$$x''(t) = -x(t)$$which only has solutions $x(t) = A \cos t + B \sin t$ for some constants $A$, $B$. For a given choice of the constants we then get $y(t) = -x'(t) = A \sin t - B \cos t$.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/2322556', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/454303/']}
|
jdg_378375
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
28609565
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a spring-boot application on the same host as the Maria DB and both are running fine for some time. But between 12 hours and 2 days it seems that the spring boot application looses the connection to the database (stacktrace) and does not recover from that. When I restart the spring application all is fine again for some time. The application is not under load and when it looses the connection the application is still working but the db connection does not recover. The DB did not restart in the meantime (uptime 4 weeks). Only the monitoring service pings the application which pings the DB once a minute. (spring boot health) Other Java applications that are connected to the same DB are running fine and do not have any issues. My Question is: Why does spring not recover from that error and try to reconnect to the DB again? How can I set up spring to reconnect to the DB? 2015-02-19 15:25:48.392 INFO 4931 [qtp92662861-19] --- o.s.b.f.xml.XmlBeanDefinitionReader : Loading XML bean definitions from class path resource [org/springframework/jdbc/support/sql-error-codes.xml]2015-02-19 15:25:48.580 INFO 4931 [qtp92662861-19] --- o.s.jdbc.support.SQLErrorCodesFactory : SQLErrorCodes loaded: [DB2, Derby, H2, HSQL, Informix, MS-SQL, MySQL, Oracle, PostgreSQL, Sybase]2015-02-19 15:25:48.616 WARN 4931 [qtp92662861-19] --- o.s.jdbc.support.SQLErrorCodesFactory : Error while extracting database product name - falling back to empty error codesorg.springframework.jdbc.support.MetaDataAccessException: Error while extracting DatabaseMetaData; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed. at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:296) at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:320) at org.springframework.jdbc.support.SQLErrorCodesFactory.getErrorCodes(SQLErrorCodesFactory.java:214) at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.setDataSource(SQLErrorCodeSQLExceptionTranslator.java:134) at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.<init>(SQLErrorCodeSQLExceptionTranslator.java:97) at org.springframework.jdbc.support.JdbcAccessor.getExceptionTranslator(JdbcAccessor.java:99) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:413) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:468) at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:478) at org.springframework.boot.actuate.health.DataSourceHealthIndicator.doDataSourceHealthCheck(DataSourceHealthIndicator.java:98) at org.springframework.boot.actuate.health.DataSourceHealthIndicator.doHealthCheck(DataSourceHealthIndicator.java:87) at org.springframework.boot.actuate.health.AbstractHealthIndicator.health(AbstractHealthIndicator.java:38) at org.springframework.boot.actuate.endpoint.HealthEndpoint.invoke(HealthEndpoint.java:67) at org.springframework.boot.actuate.endpoint.HealthEndpoint.invoke(HealthEndpoint.java:34) at org.springframework.boot.actuate.endpoint.mvc.HealthMvcEndpoint.invoke(HealthMvcEndpoint.java:102) at sun.reflect.GeneratedMethodAccessor78.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852) at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837) at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:769) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1667) at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilterInternal(WebRequestTraceFilter.java:110) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650) at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ApplicationContextHeaderFilter.doFilterInternal(EndpointWebMvcAutoConfiguration.java:280) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:186) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650) at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650) at onlinevalidation.CorsFilter.doFilter(CorsFilter.java:20) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650) at org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration$MetricsFilter.doFilterInternal(MetricFilterAutoConfiguration.java:90) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:583) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143) at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577) at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1125) at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515) at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185) at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1059) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97) at org.eclipse.jetty.server.Server.handle(Server.java:497) at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311) at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:248) at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540) at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:610) at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:539) at java.lang.Thread.run(Thread.java:745)Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed. at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:408) at com.mysql.jdbc.Util.handleNewInstance(Util.java:377) at com.mysql.jdbc.Util.getInstance(Util.java:360) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:935) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:924) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:870) at com.mysql.jdbc.ConnectionImpl.throwConnectionClosedException(ConnectionImpl.java:1232) at com.mysql.jdbc.ConnectionImpl.checkClosed(ConnectionImpl.java:1225) at com.mysql.jdbc.ConnectionImpl.getMetaData(ConnectionImpl.java:2932) at com.mysql.jdbc.ConnectionImpl.getMetaData(ConnectionImpl.java:2927) at sun.reflect.GeneratedMethodAccessor76.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:483) at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:126) at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:109) at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:80) at com.sun.proxy.$Proxy68.getMetaData(Unknown Source) at org.springframework.jdbc.support.JdbcUtils.extractDatabaseMetaData(JdbcUtils.java:285) ... 66 common frames omittedCaused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failureThe last packet successfully received from the server was 758,805 milliseconds ago. The last packet sent successfully to the server was 37 milliseconds ago. at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:408) at com.mysql.jdbc.Util.handleNewInstance(Util.java:377) at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1036) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3427) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3327) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2435) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2582) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2526) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2484) at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1446) at org.springframework.jdbc.core.JdbcTemplate$1QueryStatementCallback.doInStatement(JdbcTemplate.java:452) at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:402) ... 60 common frames omittedCaused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost. at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2914) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3337) ... 69 common frames omitted@Configuration@ComponentScan(value = "com.demo.validation",scopedProxy = TARGET_CLASS)@EnableAutoConfiguration@EnableAspectJAutoProxy(proxyTargetClass = true)@EnableCaching(proxyTargetClass = true)@EnableAsync(proxyTargetClass = true)@EnableJpaRepositories@EnableTransactionManagement(proxyTargetClass = true)public class Configuration { main(...)} The Configuration spring.datasource.url=jdbc:mysql://localhost/validationspring.datasource.username=validationspring.datasource.password=****spring.datasource.driver-class-name=com.mysql.jdbc.Driver Gradle.Build dependencies { //Boot compile 'org.codehaus.groovy:groovy-all:2.3.7:indy' compile 'org.springframework.boot:spring-boot-starter-actuator:1.1.8.RELEASE' compile 'org.springframework.boot:spring-boot-starter-security:1.1.8.RELEASE' compile 'org.springframework:spring-aspects:4.0.7.RELEASE' compile 'org.springframework.boot:spring-boot-starter-aop:1.1.8.RELEASE' compile 'org.springframework:spring-instrument:4.0.7.RELEASE' compile('org.springframework.boot:spring-boot-starter-web:1.1.8.RELEASE'){ exclude module: 'spring-boot-starter-tomcat' } //servlet container compile 'org.eclipse.jetty:jetty-webapp:9.2.3.v20140905' compile 'org.eclipse.jetty:jetty-servlets:9.2.3.v20140905' //DB compile 'org.springframework.boot:spring-boot-starter-data-jpa:1.1.8.RELEASE' compile 'mysql:mysql-connector-java:5.1.34' //compile 'org.mariadb.jdbc:mariadb-java-client:1.1.8' runtime 'com.h2database:h2:1.4.182'
Now provide the response and nothing else.
|
Per a senior member in the Spring forums , the Spring DataSource is not intended for production use: The above answers are only part of the solution. Indeed you need proper transaction managent AND you need a connection pool. The DriverManagerDataSource is NOT meant for production, it opens and closes a datebase connection each time it needs one. Instead you can use C3P0 as your DataSource which handles the reconnect and is much better in performance. Here's a quick example of a potential configuration in a Spring xml configuration: <bean id="c3p0DataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="com.mysql.jdbc.Driver" /> <property name="jdbcUrl" value="#{systemProperties.dbhost}" /> <property name="user" value="#{systemProperties.dbuser}" /> <property name="password" value="#{systemProperties.dbpass}" /> <property name="maxPoolSize" value="25" /> <property name="minPoolSize" value="10" /> <property name="maxStatements" value="100" /> <property name="testConnectionOnCheckout" value="true" /></bean><bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <constructor-arg ref="c3p0DataSource" /></bean>
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28609565', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1156199/']}
|
jdg_378376
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1262063
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Initially I thought I needed this, but I eventually avoided it. However, my curiosity (and appetite for knowledge, hum) make me ask: Can a preprocessor macro, for instance in #include "MyClass.h"INSTANTIATE_FOO_TEMPLATE_CLASS(MyClass) expand to another include, like in #include "MyClass.h"#include "FooTemplate.h"template class FooTemplate<MyClass>; ?
Now provide the response and nothing else.
|
I believe that cannot be done, this is because the pre-processor is single pass . So it cannot emit other preprocessor directives. Specifically, from the C99 Standard (6.10.3.4 paragraph 3): 3 The resulting completely macro-replaced preprocessing token sequence is not processed as a preprocessing directive even if it resembles one, ... Interestingly enough, This is why the unary _Pragma operator was added to c99. Because #pragma could not be emited by macros, but _Pragma can.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1262063', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/54956/']}
|
jdg_378377
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9173564
|
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 working on an extension that will receive CatalogEvent information from Magento (Enterprise) when saved and do custom processing on the information. Here's the code I use to listen to the event: <?xml version="1.0"?><config> <global> <models> <mage4ucustomredirect> <class>Mage4u_Customredirect</class> </mage4ucustomredirect> </models> <events> <enterprise_catalogevent_event> <observers> <abc> <type>singleton</type> <class>Mage4u_Customredirect_Model_Observer</class> <method>on_enterprise_catalogevent_event</method> </abc> </observers> </enterprise_catalogevent_event> </events> </global></config> and this is the observer: class Mage4u_Customredirect_Model_Observer{ public function on_enterprise_catalogevent_event(Varien_Event_Observer $observer) { Mage::log( "on_enterprise_catalogevent_event" ); }}?> When I save the CatalogEvent, I do not receive the call. Can you spot any problems with my code?
Now provide the response and nothing else.
|
The reason is that the string sorts alphabetically (instead of numerically like you would want it) and 1 sorts before 9 .You could solve it like this: SELECT * FROM employeesORDER BY substring(em_code, 3)::int DESC; It would be more efficient to drop the redundant 'EM' from your em_code - if you can - and save an integer number to begin with. Answer to question in comment To strip any and all non-digits from a string: SELECT regexp_replace(em_code, E'\\D','','g')FROM employees; \D is the regular expression class-shorthand for "non-digits". 'g' as 4th parameter is the "globally" switch to apply the replacement to every occurrence in the string, not just the first. After replacing every non-digit with the empty string, only digits remain.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9173564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1004859/']}
|
jdg_378378
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35261153
|
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 find that I need to type ../ a lot to require() files. My directory structure includes these: js/ components/ ... actions/ ... From the components folder, I need to do import foo from '../actions/fooAction' . Is it possible to make the root directory the root of the project? I.e. I want to do import foo from '/actions/fooAction' instead. I tried setting Webpack's resolve.root option, but it didn't seem to do anything.
Now provide the response and nothing else.
|
The resolve.root option does not modifiy how file modules are resolved. A required module prefixed with '/' is an absolute path to the file. For example, require('/home/marco/foo.js') will load the file at /home/marco/foo.js. The / resolves to the root of your file system. Maybe what you want is to resolve your js folder as a modules directory . webpack.config.js resolve: { root: path.resolve('./js')} With this configuration added to your config file will tell webpack to resolve any import or require relative to your js folder. Then, instead of using import foo from '../actions/fooAction' you will be able to: import foo from 'actions/fooAction` Mind the lack of / at the beginning.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/35261153', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/599184/']}
|
jdg_378379
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
41940
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
For example, the square can be described with the equation $|x| + |y| = 1$. So is there a general equation that can describe a regular polygon (in the 2D Cartesian plane?), given the number of sides required? Using the Wolfram Alpha site, this input gave an almost-square: PolarPlot(0.75 + ArcSin(Sin(2x+Pi/2))/(Sin(2x+Pi/2)*(Pi/4))) (x from 0 to 2Pi) This input gave an almost-octagon: PolarPlot(0.75 + ArcSin(Sin(4x+Pi/2))/(Sin(4x+Pi/2)*Pi^2)) (x from 0 to 2Pi) The idea is that as the number of sides in a regular polygon goes to infinity, the regular polygon approaches a circle. Since a circle can be described by an equation, can a regular polygon be described by one too? For our purposes, this is a regular convex polygon (triangle, square, pentagon, hexagon and so on). It can be assumed that the centre of the regular polygon is at the origin $(0,0)$, and the radius is $1$ unit. If there's no such equation, can the non-existence be proven? If there are equations, but only for certain polygons (for example, only for $n < 7$ or something), can those equations be provided?
Now provide the response and nothing else.
|
Any polygon (regular or not) can be described by an equation involving only absolute values and polynomials. Here is a small explanation of how to do that. Let's say that a curve $C$ is given by the equation $f$ if we have $C = \{(x,y) \in \mathbb{R}^2, \, f(x,y) = 0\}$. If $C_1$ and $C_2$ are given by $f_1$ and $f_2$ respectively, then $C_1 \cup C_2$ is given by $f_1 . f_2$ and $C_1 \cap C_2$ is given by $f_1^2 + f_2^2$ (or $|f_1| + |f_2|$). So if $C_1$ and $C_2$ can be described by an equation involving absolute values and polynomials, then so do $C_1 \cup C_2$ and $C_1 \cap C_2$. If $C = \{(x,y) \in \mathbb{R}^2, \, f(x,y) \ge 0\}$, then $C$ is given by the equation $|f|-f$. Now, any segment $S$ can be described as $S = \{(x,y) \in \mathbb{R}^2, \, a x + b y = c, \, x_0 \le x \le x_1, \, y_0 \le y \le y_1\}$, which is given by a single equation by the above principles. And since union of segments also are given by an equation, you get the result. EDIT : For the specific case of the octagon of radius $r$, if you denote $s = \sin(\pi/8)$, $c = \cos(\pi/8)$, then one segment is given by $|y| \le rs$ and $x = rc$, for which an equation is $$f(x, y) = \left||rs - |y|| - (rs - |y|)\right| + |x-rc| = 0$$ So I think the octagon is given by $$f(|x|,|y|) \ f(|y|,|x|) \ f\left(\frac{|x|+|y|}{\sqrt{2}}, \frac{|x|-|y|}{\sqrt{2}}\right) = 0$$ To get a general formula for a regular polygon of radius $r$ with $n$ sides, denote $c_n = \cos(\pi/n)$, $s_n = \sin(\pi/n)$ and $$f_n(x+iy) = \left||rs_n - |y|| - (rs_n - |y|)\right| + |x-rc_n|$$ then your polygon is given by $$\prod_{k = 0}^{n-1} f_n\left(e^{-\frac{2 i k \pi}{n}} (x+iy)\right) = 0$$ Depending on $n$, you can use symmetries to lower the degree a bit (as was done with $n = 8$).
|
{}
|
{'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/41940', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11493/']}
|
jdg_378380
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
117888
|
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:
A friend of mine showed me this example: Plot[BesselJ[9/2, x], {x, 0, 1}, PlotLabel -> Style["The integrand seems to be simple", 14]] Integrate[BesselJ[9/2, x], {x, 0, 1}] // N(* 0.000148473 <- This is the correct result *)NIntegrate[BesselJ[9/2, x], {x, 0, 1}](*-1.26625*10^170 *) It's not hard to fix the code: (* Solution 1 *)NIntegrate[BesselJ[9/2, x], {x, 0, 1}, WorkingPrecision -> 16](* 0.0001484729674125616 *)(* Solution 2 *)Clear@ff[x_?NumericQ] := BesselJ[9/2, x]NIntegrate[f@x, {x, 0, 1}](* 0.000148473 *) But I wonder why NIntegrate fails in such a wild way by default? Seeing the Solution 2 above, it's natural to guess that NIntegrate has done some improper symbolic processing, but this seems not to be true: NIntegrate[BesselJ[9/2, x], {x, 0, 1}, Method -> {Automatic, "SymbolicProcessing" -> 0}](* -1.26625*10^170 *)
Now provide the response and nothing else.
|
Because NIntegrate evaluates the integrands before starting the actual integration, in some cases (like this one) it is better to define the integrand function F with the signature F[x_?NumericQ] . BF[n_?NumericQ, x_?NumericQ] := BesselJ[n, x]NIntegrate[BF[9/2, x], {x, 0, 1}](* 0.000148473 *)Integrate[BesselJ[9/2, x], {x, 0, 1}]%% // N(* Sqrt[2/\[Pi]] (30 Cos[1] + Sqrt[2 \[Pi]] FresnelS[Sqrt[2/\[Pi]]] - 20 Sin[1]) *)(* 0.000148473 *) When expanded BesselJ[9/2, x] // Expand(* -((105 Sqrt[2/\[Pi]] Cos[x])/x^(7/2)) + ( 10 Sqrt[2/\[Pi]] Cos[x])/x^(3/2) + (105 Sqrt[2/\[Pi]] Sin[x])/x^( 9/2) - (45 Sqrt[2/\[Pi]] Sin[x])/x^(5/2) + ( Sqrt[2/\[Pi]] Sin[x])/Sqrt[x] *) the oscillatory nature of the integrand terms near zero confuses NIntegrate 's algorithms. (I have answered very similar questions in different forums over the years.) A similar discussion/answer is J.M.'s answer of "NIntegrate and Integrate of a Spherical Bessel function" . And as J.M. noted in a comment : "SymbolicProcessing" -> 0 does absolutely nothing because BesselJ[] is already auto-expanded in the half-integer case, and the resulting expression is numerically iffy. (We mention this because of the attempt to remedy the situation with "SymbolicProcessing" in the question.)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/117888', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1871/']}
|
jdg_378381
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1310939
|
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:
$$2<\frac{x}{x-1}\leq 3$$ Is the only way is to multiple both sides by $(x-1)^2$? so we get $2x^2-4x+2<x^2-x $ and $x^2-x<3x^2-6x+3$ which is $-x^2+3x-2$ and $-2x^2+5x-3<0$ so the sloutions are: $1<x\leq \frac{3}{2}$ and $1<x\leq 2$ so overall it is $1<x\leq\frac{3}{2}$
Now provide the response and nothing else.
|
The simplest, as we have a homographic function, is to write it in canonical form:\begin{align*}2<\frac{x}{x-1}\leq 3&\iff 2 < 1+\frac1{x-1}\leq 3 \iff 1< \frac1{x-1}\leq 2\\&\iff \frac12\le x-1 <1 \iff \frac32 \le x <2\end{align*}The third equivalence is valid because all numbers at the end of the first line have the same sign.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1310939', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/103441/']}
|
jdg_378382
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
62473925
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a NodeJS/Electron application, as a listener server. An IP ANPR camera sends a POST request with alarm information to said server, then I want said server to process the return XML. However as there is a text and various other blobs returned in the chunk, I'm at a point where I am unsure what I need to do to clean it up. I'll attach a copy of the request body, and my http.createServer function. All I require is the XML portion so I can parse and proceed with it. HTTP server function: var port = 7200;http.createServer((request, response) => { const { headers, method, url } = request; let body = []; request.on('error', (err) => { console.error(err); }).on('data', (chunk) => { body.push(chunk); }).on('end', () => { body = Buffer.concat(body).toString(); response.on('error', (err) => { console.error(err); }); console.log(body); response.statusCode = 200; response.end(); // END OF NEW STUFF });}).listen(port);console.log(`Server listening on port ${port}`); This works fine, the requests are coming in. This is the portion of the body I would like to parse just the XML from: ---------------------------7e13971310878\r\nContent-Disposition: form-data; name=\"anpr.xml\";filename=\"anpr.xml\";\r\nContent-Type: text/xml\r\nContent-Length: 2827\r\n\r\n<EventNotificationAlert version=\"2.0\" xmlns=\"http://www.isapi.org/ver20/XMLSchema\">\r\n <ipAddress>192.168.5.43</ipAddress>\r\n <ipv6Address>::</ipv6Address>\r\n <portNo>7200</portNo>\r\n <protocol>HTTP</protocol>\r\n <macAddress>98:df:82:37:1d:5e</macAddress>\r\n <channelID>1</channelID>\r\n <dateTime>2020-06-19T15:10:13+00:00</dateTime>\r\n <activePostCount>2</activePostCount>\r\n <eventType>ANPR</eventType>\r\n <eventState>active</eventState>\r\n <eventDescription>ANPR</eventDescription>\r\n <channelName>ANPR Exit</channelName>\r\n <ANPR>\r\n <licensePlate>01MH8551</licensePlate>\r\n <line>1</line>\r\n <direction>forward</direction>\r\n <confidenceLevel>99</confidenceLevel>\r\n <plateType>unknown</plateType>\r\n <plateColor>other</plateColor>\r\n <licenseBright>112</licenseBright>\r\n <pilotsafebelt>unknown</pilotsafebelt>\r\n <vicepilotsafebelt>unknown</vicepilotsafebelt>\r\n <pilotsunvisor>unknown</pilotsunvisor>\r\n <vicepilotsunvisor>unknown</vicepilotsunvisor>\r\n <envprosign>unknown</envprosign>\r\n <dangmark>unknown</dangmark>\r\n <uphone>unknown</uphone>\r\n <pendant>unknown</pendant>\r\n <tissueBox>unknown</tissueBox>\r\n <label>unknown</label>\r\n <decoration>unknown</decoration>\r\n <plateCharBelieve>100,100,100,100,100,100,100,100</plateCharBelieve>\r\n <speedLimit>0</speedLimit>\r\n <illegalInfo>\r\n <illegalCode>0</illegalCode>\r\n </illegalInfo>\r\n <vehicleType>truck</vehicleType>\r\n <featurePicFileName>1</featurePicFileName>\r\n <detectDir>0</detectDir>\r\n <detectType>3</detectType>\r\n <barrierGateCtrlType>0</barrierGateCtrlType>\r\n <alarmDataType>0</alarmDataType>\r\n <dwIllegalTime>0</dwIllegalTime>\r\n <vehicleInfo>\r\n <index>2</index>\r\n <vehicleType>2</vehicleType>\r\n <colorDepth>2</colorDepth>\r\n <color>unknown</color>\r\n <speed>0</speed>\r\n <length>0</length>\r\n <vehicleLogoRecog>0</vehicleLogoRecog>\r\n <vehileSubLogoRecog>0</vehileSubLogoRecog>\r\n <vehileModel>0</vehileModel>\r\n </vehicleInfo>\r\n <pictureInfoList>\r\n <pictureInfo>\r\n <fileName>licensePlatePicture.jpg</fileName>\r\n <type>licensePlatePicture</type>\r\n <dataType>0</dataType>\r\n </pictureInfo>\r\n <pictureInfo>\r\n <fileName>detectionPicture_1.jpg</fileName>\r\n <type>licensePlatePicture</type>\r\n <dataType>0</dataType>\r\n <vehicleHead>back</vehicleHead>\r\n <redLightTime>0</redLightTime>\r\n <absTime>20200619151013606</absTime>\r\n <plateRect>\r\n <X>29697</X>\r\n <Y>59648</Y>\r\n <width>17664</width>\r\n <height>6400</height>\r\n </plateRect>\r\n </pictureInfo>\r\n <pictureInfo>\r\n <fileName>detectionPicture_2.jpg</fileName>\r\n <type>licensePlatePicture</type>\r\n <dataType>0</dataType>\r\n <vehicleHead>back</vehicleHead>\r\n <redLightTime>0</redLightTime>\r\n <absTime>20200619151013608</absTime>\r\n <plateRect>\r\n <X>29697</X>\r\n <Y>59648</Y>\r\n <width>17664</width>\r\n <height>6400</height>\r\n </plateRect>\r\n </pictureInfo>\r\n </pictureInfoList>\r\n </ANPR>\r\n <UUID>fa41feec-1dd1-11b2-9e33-944acfe73596</UUID>\r\n <picNum>3</picNum>\r\n <monitoringSiteID></monitoringSiteID>\r\n <deviceID>88</deviceID>\r\n</EventNotificationAlert>---------------------------7e13971310878\r\nContent-Disposition: form-data;name=\"licensePlatePicture.jpg\";filename=\"licensePlatePicture.jpg\";\r\nContent-Type:
Now provide the response and nothing else.
|
I had the exact same issue. Turned out that Webpack would mess around with Material UI's rules of JSS precedence. You need to manually override the injection order using the index option. In your makeStyles() or withStyles() , add {index: 1} : //Hookconst useStyles = makeStyles({ // your styles here}, {index: 1})// HOC MyComponent = withStyles({ // your styles here}, {index: 1})(MyComponent)
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/62473925', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10069684/']}
|
jdg_378383
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2076409
|
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 guess that this is a very absurd/basic question, but still: class m{public: void f(int ***); /***/}void m::f(int ***a = NULL){ /***/} The call to f (as well as any function which has default values for all the arguments) doesn't accept 0 arguments. Why? How should I format the declaration then?
Now provide the response and nothing else.
|
That works fine if the function definition is in the header file. The rule is that whoever is calling the function has to 'see' the default value. So, I'm guessing you have the function definition in a separate source file. Assuming that's the case, just put the default in the function declaration (in the class): class m{public: void f(int *** = 0); /***/}; You'll also need to remove the default value from the function definition as you can only define the default in a single place (even if the value itself is the same).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2076409', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/250069/']}
|
jdg_378384
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3207728
|
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 version control my web server as described in Version control for my web server , by creating a git repo out of my /var/www directory . My hope was that I would then be able to push web content from our dev server to github, pull it to our production server, and spend the rest of the day at the pool. Apparently a kink in my plan is that Git won't respect file permissions (I haven't tried it, only reading about it now.) I guess this makes sense in that different boxes are liable to have different user/group setups. But if I wanted to force permissions to propagate, knowing my servers are configured the same, do I have any options? Or is there an easier way to approach what I'm trying to do?
Now provide the response and nothing else.
|
The git-cache-meta mentioned in SO question " git - how to recover the file permissions git thinks the file should be? " (and the git FAQ ) is the more staightforward approach. The idea is to store in a .git_cache_meta file the permissions of the files and directories. It is a separate file not versioned directly in the Git repo. That is why the usage for it is: $ git bundle create mybundle.bdl master; git-cache-meta --store$ scp mybundle.bdl .git_cache_meta machine2: #then on machine2:$ git init; git pull mybundle.bdl master; git-cache-meta --apply So you: bundle your repo and save the associated file permissions. copy those two files on the remote server restore the repo there, and apply the permission
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/3207728', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/165673/']}
|
jdg_378385
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
155701
|
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:
Let $X_1,..,X_n$ a random sample of $X$~$U[-\theta,\theta]$, $\theta>0$. Find the confidence interval for $\theta$. I'm trying to find a pivotal quantity with the maximum and minimum, but I can not find any, can anyone give me a tip? EDIT: I can take $Q(X;\theta)=\frac{max|X_i|}{\theta}$ as pivotal quantity?
Now provide the response and nothing else.
|
First you need to find the distribution of the sufficient statistic $T=\max |X_i|$. You've already seen that $|X_i|=U\sim\mathrm{U}(0,\theta)$. To find the distribution of the maximum of $n$ observations, $T=U_{(n)}$, it's easiest to consider the cumulative distribution function: $$\begin{align}F_T(t) &= \Pr (U_{(n)} < t) = \Pr(U_1 <t, U_2 <t, \ldots, U_n <t)\\&=F_U(t)^n= \left(\frac{t}{\theta}\right)^n\end{align}$$ Differentiating with respect to $t$ gives the density $$f_T(t)= \frac{nt^{n-1}}{\theta^n}$$ You can now calculate the density function of your proposed pivot $Q = \frac{T}{\theta}$ to confirm it's free of $\theta$: $$f_Q(q)=f_T(\theta q)\cdot\left|\frac{\mathrm{d}t}{\mathrm{d}q}\right|=\frac{n(\theta q)^{n-1}}{\theta^n}\cdot\theta=nq^{n-1}$$
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/155701', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/-1/']}
|
jdg_378386
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17590182
|
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 the below code to get the value of a particular node, but while loading the xml this exception is thrown: Exception: Data at the root level is invalid. Line 1, position 1. XML <?xml version="1.0"?><Data xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Date>11-07-2013</Date> <Start_Time>PM 01:37:11</Start_Time> <End_Time>PM 01:37:14</End_Time> <Total_Time>00:00:03</Total_Time> <Interval_Time/> <Worked_Time>00:00:03</Worked_Time> <Short_Fall>08:29:57</Short_Fall> <Gain_Time>00:00:00</Gain_Time> </Data> C#: XmlDocument xml = new XmlDocument();filePath = @"D:\Work_Time_Calculator\10-07-2013.xml";xml.LoadXml(filePath); // Exception occurs here XmlNode node = xml.SelectSingleNode("/Data[@*]/Short_Fall");string id = node["Short_Fall"].InnerText; Modified Code C#: XmlDocument xml = new XmlDocument();filePath = @"D:\Work_Time_Calculator\10-07-2013.xml";xml.Load(filePath); XmlNode node = xml.SelectSingleNode("/Data[@*]/Short_Fall");string id = node["Short_Fall"].InnerText; // Exception occurs here ("Object reference not set to an instance of an object.")
Now provide the response and nothing else.
|
The problem in your code is xml.LoadXml(filePath); LoadXml method take parameter as xml data not the xml file path Try this code string xmlFile = File.ReadAllText(@"D:\Work_Time_Calculator\10-07-2013.xml"); XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(xmlFile); XmlNodeList nodeList = xmldoc.GetElementsByTagName("Short_Fall"); string Short_Fall=string.Empty; foreach (XmlNode node in nodeList) { Short_Fall = node.InnerText; } Edit Seeing the last edit of your question i found the solution, Just replace the below 2 lines XmlNode node = xml.SelectSingleNode("/Data[@*]/Short_Fall");string id = node["Short_Fall"].InnerText; // Exception occurs here ("Object reference not set to an instance of an object.") with string id = xml.SelectSingleNode("Data/Short_Fall").InnerText; It should solve your problem or you can use the solution i provided earlier.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17590182', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1594506/']}
|
jdg_378387
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
9874960
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have some generic code that works with flags specified using C++11 enum class types. At one step, I'd like to know if any of the bits in the flag are set. Currently, I'm using the code: if (flags != static_cast<E>(0)) // Works, but ugly. I could also force users to specify a particular name for an all-zero field, which is more readable but imposes my naming conventions on anyone using it: if (flags != E::none) // Works, if you manually define none = 0. But neither of these reads as nicely as the traditional: if (flags) // Doesn't work with class enums. Is it possible to specify a custom function to evaluate a class enum in a boolean context?
Now provide the response and nothing else.
|
Is it possible to specify a custom function to evaluate a class enum in a boolean context? Yes, but not automatically. Manually calling a function is still more elegant than the other alternatives presented. Simply pick a nice function name, such as any , and implement it. Overload resolution will make sure your function plays well with all others. bool any( E arg ) { return arg != E::none; }...if ( any( flags ) ) { ... Looks nice enough to me. Update: if you want this to apply to several enumeration types, it can be templated: template< typename enum_type > // Declare traits typestruct enum_traits {}; // Don't need to declare all possible traitstemplate<>struct enum_traits< E > { // Specify traits for "E" static constexpr bool has_any = true; // Only need to specify true traits};template< typename enum_type > // SFINAE makes function contingent on traittypename std::enable_if< enum_traits< enum_type >::has_any, bool >::typeany( enum_type e ) { return e != enum_type::none; } I've been using this sort of mechanism for other things and never encountered any side effects or issues :v) . You could skip the trait and set the SFINAE condition to something like enum_type::none == enum_type::none , to merely check for the presence of none and the equality operator, but that would be less explicit and safe.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9874960', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_378388
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8641355
|
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 play a mp3 audio file in HTML. I don't want to display the whole player with controls like Volume etc.I just need a play/pause button, Designed by me, not the core design of some player, like yahoo player, or google one. For example the audio will be autoplay. When a button (probably an image) is clicked it will pause, and when that image is clicked again, the audio will play again. There are quite few examples here : http://www.w3schools.com/html/html_sounds.asp Can I control any of them to play/stop from JS code ?
Now provide the response and nothing else.
|
You can use the html5 audio tag . You can specify your own controls for playback. <audio preload="auto" autobuffer> <source src="elvis.mp3" /> <source src="elvis.wav" /> <!-- fallback if no mp3 support in browser --></audio> This is a jQuery solution. http://jsfiddle.net/QPW27/109/ This is what your non-jQuery solution would look like. var foo = document.getElementById('player');foo.pause(); //just bind play/pause to some onclick events on your pagefoo.play(); Different browsers support different audio formats. You can specify fallback audio versions though. This website has a nice chart of browser support as of July 2011.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8641355', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/585748/']}
|
jdg_378389
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
945063
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My SQL Server CPU has been at around 90% for the most part of today. I am not in a position to be able to restart it due to it being in constant use. Is it possible to find out what within SQL is causing such a CPU overload? I have run SQL Profiler but so much is going on it's difficult to tell if anything in particular is causing it. I have run sp_who2 but am not sure what everything means exactly and if it is possible to identify possible problems in here. To pre-empt any "it's probably just being used a lot" responses, this has only kicked in today from perfectly normal activitly levels. I'm after any way of finding what is causing CPU grief within SQL.
Now provide the response and nothing else.
|
This query uses DMV's to identify the most costly queries by CPU SELECT TOP 20 qs.sql_handle, qs.execution_count, qs.total_worker_time AS Total_CPU, total_CPU_inSeconds = --Converted from microseconds qs.total_worker_time/1000000, average_CPU_inSeconds = --Converted from microseconds (qs.total_worker_time/1000000) / qs.execution_count, qs.total_elapsed_time, total_elapsed_time_inSeconds = --Converted from microseconds qs.total_elapsed_time/1000000, st.text, qp.query_planFROM sys.dm_exec_query_stats AS qsCROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS stCROSS APPLY sys.dm_exec_query_plan (qs.plan_handle) AS qpORDER BY qs.total_worker_time DESC For a complete explanation see: How to identify the most costly SQL Server queries by CPU
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/945063', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/64519/']}
|
jdg_378390
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1877417
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the proper way to set a timer in android in order to kick off a task (a function that I create which does not change the UI)? Use this the Java way: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Timer.html Or there is a better way in android (android's handler)?
Now provide the response and nothing else.
|
Standard Java way to use timers via java.util.Timer and java.util.TimerTask works fine in Android, but you should be aware that this method creates a new thread. You may consider using the very convenient Handler class (android.os.Handler) and send messages to the handler via sendMessageAtTime(android.os.Message, long) or sendMessageDelayed(android.os.Message, long) . Once you receive a message, you can run desired tasks. Second option would be to create a Runnable object and schedule it via Handler's functions postAtTime(java.lang.Runnable, long) or postDelayed(java.lang.Runnable, long) .
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1877417', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/125440/']}
|
jdg_378391
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
272868
|
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 $d \geq 2$ be an integer and $\xi=\exp(\frac{2\pi i}{d})$. I am trying to compute the determinant of the matrix$$(\xi^{ij}-1)_{1 \leq i, j \leq d-1}.$$ Let me call it $\Delta(d)$. For small values of $d$ I get: $\Delta(2)=-2$ $\Delta(3)=-3\sqrt{3}i$ $\Delta(4)=-16i$ But I can't seem to find a general formula. How can I do this?
Now provide the response and nothing else.
|
Using the earlier responses and comments, I confirm the formula suggested by Neil Strickland:$$\Delta(d)=d^{d/2}i^{m(d)}\qquad\text{with}\qquad m(d): = 1 + d(7-d)/2\in\mathbb{Z}.$$Consider the $d\times d$ Vandermonde matrix$$\Phi(d):=(\xi^{ij})_{0\leq i,j \leq d-1}.$$Subtracting the first column from each other column, we get a matrix with first row equal to $(1,0,\dots,0)$ and lower right $(d-1)\times(d-1)$ block equal to the OP's matrix. Therefore,$$\Delta(d)=\det\Phi(d).$$It is straightforward to check that $\Phi(d)^\ast\cdot\Phi(d)$ equals $d$ times the identity matrix, therefore$$ |\det\Phi(d)|^2=d^d.$$In other words, $|\det\Phi(d)|=d^{d/2}$, and we are left with determining$$\frac{\det\Phi(d)}{|\det\Phi(d)|}=\prod_{0\leq i<j\leq d-1}\frac{\xi^j-\xi^i}{|\xi^j-\xi^i|}.$$Let me use the notation $e(t):=e^{2\pi it}$, familiar from analytic number theory. Then we see that$$\xi^j-\xi^i=e\left(\frac{j}{d}\right)-e\left(\frac{i}{d}\right)=e\left(\frac{i+j}{2d}\right)\left(e\left(\frac{j-i}{2d}\right)-e\left(\frac{i-j}{2d}\right)\right).$$On the right hand side, $0<\frac{j-i}{2d}<\frac{1}{2}$, hence $e\left(\frac{j-i}{2d}\right)$ lies in the upper half-plane. As a result,$$\frac{\xi^j-\xi^i}{|\xi^j-\xi^i|}=e\left(\frac{i+j}{2d}\right)i.$$We need to calculate the product of the right hand side over the $\binom{d}{2}$ pairs $0\leq i<j\leq d-1$. By symmetry (or by brute-force calculation), the average of $i+j$ equals $d-1$, whence$$\prod_{0\leq i<j\leq d-1}\frac{\xi^j-\xi^i}{|\xi^j-\xi^i|}=\left(e\left(\frac{d-1}{2d}\right)i\right)^{\binom{d}{2}}=e\left(\left(\frac{d-1}{2d}+\frac{1}{4}\right)\binom{d}{2}\right).$$We calculate$$\left(\frac{d-1}{2d}+\frac{1}{4}\right)\binom{d}{2}=\frac{(3d-2)(d-1)}{8},$$therefore in the end$$\Delta(d)=d^{d/2}i^{n(d)}\qquad\text{with}\qquad n(d):=(3d-2)(d-1)/2\in\mathbb{Z}.$$This agrees with Neil Strickland's formula, upon noting that $m(d)\equiv n(d)\pmod{4}$, i.e.,$$2+d(7-d)\equiv (3d-2)(d-1)\pmod{8}.$$ Added 1. As Alexey Ustinov remarked, $\Phi(d)$ is known as a Schur matrix. As Carlitz wrote in his 1959 paper , "this matrix is familiar in connection with Schur's derivation of the value of Gauss's sum". In fact, on page 295 of this paper, Carlitz uses the known value of Gauss's sum to find the eigenvalues of this matrix (which are all of the form $\pm\sqrt{d}$ and $\pm i\sqrt{d}$, hence one only needs to find the 4 multiplicities). This can be regarded as a refinement and an alternate proof of the above result, since the product of the eigenvalues is the determinant. Added 2. Carlitz referred to Landau's Vorlesungen, whose relevant part appeared in English as Landau: Elementary Number Theory (Chelsea, 1958). So I looked up this translation, and to my surprise on pages 211-212 I found essentially the same calculation as above. In fact all this is in Schur's 1921 paper , thanks to Alexey Ustinov for locating it for me (alternative link here ). As Landau explains (following Schur), the determinant calculation leads to an evaluation of Gauss's sum, at least for odd $d$. The point is that one can figure out the 4 eigenvalue multiplicities from the determinant, and hence one obtains the formula for the trace of $\Phi(d)$ as well. However, this trace is nothing but Gauss's sum! Added 3. For a more recent treatment of Schur's evaluation of the Gauss sum, see Section 6.3 in Rose: A course in number theory (2nd ed., Oxford University Press, 1994).
|
{}
|
{'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/272868', 'https://mathoverflow.net', 'https://mathoverflow.net/users/111500/']}
|
jdg_378392
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2126714
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a class and I want to find all of its public fields (not methods). How can I do this?
Now provide the response and nothing else.
|
Field[] fields = YourClassName.class.getFields(); returns an array of all public variables of the class. getFields() return the fields in the whole class-heirarcy. If you want to have the fields defined only in the class in question, and not its superclasses, use getDeclaredFields() , and filter the public ones with the following Modifier approach: Modifier.isPublic(field.getModifiers()); The YourClassName.class literal actually represents an object of type java.lang.Class . Check its docs for more interesting reflection methods. The Field class above is java.lang.reflect.Field . You may take a look at the whole java.lang.reflect package.
|
{}
|
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2126714', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/80932/']}
|
jdg_378393
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
523771
|
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:
When two black holes merge, they will produce the so-called ringdown before forming a new black hole, even the newly created black hole produces some sort of tones due to the force of the impact, but it is barely audible for LIGO and other instruments to pick up. Anyway, I want to know how is the loud but short-lived overtone produced and why can it be used to validate that black holes do not have other properties beside mass, angular momentum and charge.
Now provide the response and nothing else.
|
The ringdown is simply the black hole formed in the merger settling down to a final stationary form. According to the no-hair theorem, this stationary form has to be described by the Kerr family of metrics described by the mass and angular momentum of the final black hole (since the intitial system is assumed to be electrically neutral). The characteristic spectrum of this ringdown can be calculated in general relativity and is determined only by the mass and angular momentum of the final Kerr black hole. Consequently, if one measures the characteristic frequency and decay time of the dominant mode, one can uniquely determine the mass and angular momentum of the final black hole, leading to a prediction for the frequencies of all other modes present in the ringdown. If one would observe other modes in the ringdown that do not belong to this spectrum, then this falsifies this prediction, and means that the final black hole and its ringdown are not described by the Kerr metric and general relativity. This is often presented as a would be failure of the no hair theorem, which tells us that the final black hole has to be Kerr. (However, it could equally be interpretted as a failure of GR itself.)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/523771', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/75502/']}
|
jdg_378394
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
17321391
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Directly from this java tutorial: For static generic methods, the type parameter section must appear before the method's return type. Is it not true for NON-static generic method? If not what's the NON-static generic method syntax? Thanks in advance.
Now provide the response and nothing else.
|
The syntax for declaring non-static generic methods is the same as for static methods, just without the static keyword: generic type parameters are placed before the return type. class Example { public <E> void method(E param) { }} Non-static methods may also use the generic type parameter of the enclosing class, like below. These are not considered generic methods; a generic method is one that declares type parameters . class Example<T> { // Not a generic method! public void method(T param) { }}
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17321391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2017866/']}
|
jdg_378395
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1230453
|
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 really know a lot about this subject but I was wondering if the product of a transcendental number by an integer is transcendental?
Now provide the response and nothing else.
|
The product of a transcendental number by a nonzero algebraic number is necessarily transcendental (as the ratio of two algebraic numbers is algebraic). To prove the case that an algebraic number divided by a nonzero integer is algebraic (as in the revised question), if $x$ satisfies $\alpha_kx^k + \ldots + a_0 = 0$, then $y = x/n$ satisfies $n^k\alpha_k y^k + n^{k-1}\alpha_{k-1}y^{k-1} + \ldots + n\alpha_1 y + \alpha_0 = 0$. The product of two transcendental numbers can easily be algebraic, however. As suggested by zarathustra in the comments, $e \times 1/e= 1$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1230453', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
|
jdg_378396
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18293875
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there an easy way to rename a project? I tried to rename the folder, but it didn't work.
Now provide the response and nothing else.
|
Renaming the project is actually easier than renaming an app. This question explains how to rename an app. To rename the project, you need to change the project name wherever it appears. grep -nir oldname . can help you find where it appears. In my case, I had to change the following places: Rename the oldprojectname directory to newprojectname manage.py : Change os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'oldprojectname.settings') newprojectname/wsgi.py : Change os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'oldprojectname.settings') newprojectname/settings.py : Change ROOT_URLCONF = 'oldprojectname.urls' and change WSGI_APPLICATION = 'oldprojectname.wsgi.application' newprojectname/urls.py : Change oldprojectname in a line I had added
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18293875', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1730594/']}
|
jdg_378397
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
16363621
|
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 produce an Excel workbook that will contain proprietary formulas and other intellectual property. I will most likely produce this workbook in Visual Studio 2010 with C#. How protected is the code within these projects? Do the same problems with reflection in C# still apply to these workbook projects? If so, are there obfuscation tools specifically for these types of workbooks? To add to this question - what about good 'ole VBA? Is there a way to protect that code too if we were to go the VBA route?
Now provide the response and nothing else.
|
As other answers have suggested, VBA security in Excel 2003 (.xls) is flawed; a password is only a little annoyance, most often than not for the developper himself. IMHO you're absolutely better off with VSTO, even if VBA security in Excel 2007+ (.xlsx) is much better, not to mention the VBA IDE which hasn't seen improvements in centuries (although no so true with the right VBE add-in... ). A solution could be to write the sensible code in a separate library which your VSTO project calls; instead of intricate formulas you could expose functions which would appear as "black boxes" (i.e. an abstraction of the formula's functionality); how it's implemented is just not available to anyone without the source code), and without the dll the workbook couldn't be calculated (would be #NAME? all over the place). For example, instead of =some proprietary formula returning a Smurf , users would see =Smurf(SomeTableColumnName, SomeRangeName, SomeRangeReference, SomeCellReference) . Of course this comes at a performance cost, so I would only do this for stuff that's really important to protect. I think a user that manages to extract the proprietary formulas from such an on-the-side library, deserves to leave with them - between that and Alt+F11, there's quite a step; the proprietary code is as "protected" as any other .net assembly is. UPDATE Still without using any 3rd-party libraries, if the proprietary code does not need Excel interoperability, a perhaps better solution could be to create the function in VBA (i.e. leave the Excel interop part within Excel) and only pass primitive types (VBA Integer => .net Int16 ; VBA Long => .net Int32 , strings, etc.) to a COM-visible library which doesn't even need to use Excel interop; it will be COM interop instead of Excel interop and the performance hit would be significantly reduced, though still present (it remains .net managed code "talking" to unmanaged COM). The VBA code's responsibility would be to read and write to/from the worksheets, and the COM-visible library's role would be to implement the calculations to be made out of the values passed by the VBA code; of course the VBA code would be easily accessible to the user (Alt+F11), but again they couldn't access the actual calculation implementation. And then the VBA code could be password-protected, and the calculation results without the DLL would be either 0 's or #VALUE! , depending on how the VBA code is implemented. The key is to leave Excel-specifics in Excel and have the .net library pick up where it can without referencing Excel interop assemblies - for example, the VBA function would take a cell reference, grab its value (perhaps validate it) and pass it to the .net assembly, which would return another primitive type that VBA would return to Excel. Another plus is that the library code with the proprietary calculations could be reused, if you ever were to "convert" the Excel workbook into, say, a Web application.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16363621', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/208127/']}
|
jdg_378398
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
55755561
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I have a data set that looks like this: state.x77[1,] Population Income Illiteracy Life Exp Murder HS Grad Frost 3615.00 3624.00 2.10 69.05 15.10 41.30 20.00 Area 50708.00 as.numeric(state.x77[1,]) [1] 3615.00 3624.00 2.10 69.05 15.10 41.30 20.00 50708.00 I want something that looks like this:`[1] "Arizona" "Washington" Thanks!
Now provide the response and nothing else.
|
There is no try catch statement in Rust. The closest approach is the ? operator. However, you do not have to create a function and a match statement to resolve it in the end. You can define a closure in your scope and use ? operator inside the closure. Then throws are held in the closure return value and you can catch this wherever you want like following: fn main() { let do_steps = || -> Result<(), MyError> { do_step_1()?; do_step_2()?; do_step_3()?; Ok(()) }; if let Err(_err) = do_steps() { println!("Failed to perform necessary steps"); }} Playground Is it possible to handle multiple different errors at once instead of individually in Rust without using additional functions? There is a anyhow crate for the error management in Rust mostly recommended nowadays. As an alternative, There is a failure crate for the error management in Rust. Using Failure , you can chain, convert, concatenate the errors. After converting the error types to one common type, you can catch (handle) it easily.
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/55755561', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
|
jdg_378399
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1594047
|
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:
Prove that if c ϵ C and $x = \frac{(c+\sqrt{c^2+4})}{2}$ so $x-\frac{1}{x} $ ϵ C. I have no idea how do this. Please help me.
Now provide the response and nothing else.
|
We have $x-\frac{1}{x}$ = $\frac{x^2 - 1}{x}$ = $\frac{(x-1)(x+1)}{x}$ x-1 = $\frac{c + \sqrt{ c ^ {2}+4 }}{2}$ -1 = $\frac{c + \sqrt{ c ^ {2}+4 }-2}{2}$ x+1 = $\frac{c + \sqrt{ c ^ {2}+4 }+2}{2}$ So : $x-\frac{1}{x}$ = $\frac{\frac{c + \sqrt{ c ^ {2}+4 }-2}{2}*\frac{c + \sqrt{ c ^ {2}+4 }+2}2}{\frac{c + \sqrt{ c ^ {2}+4 }}{2}}$ = $\frac{(c + \sqrt{ c ^ {2}+4 })^2 - 4 }{4}$*$\frac{2}{c + \sqrt{ c ^ {2}+4 }}$ = $\frac{2c^2 + 2c \sqrt{ c ^ {2}+4 }}{2(c + \sqrt{ c ^ {2}+4} )}$=c We have proved $x-\frac{1}{x}$ ϵ C
|
{}
|
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1594047', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/301698/']}
|
jdg_378400
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4337820
|
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 know that during projection 3D space points $(x, y, z)$ projects to projection plane which has 2D points $(x, y).$ But during matrix calculation we use homogenous coordinates is of the form $(x, y, 1).$ And we know that projective plane is of the form $(x, y, 1).$ My question is that homogenous coordinates and projective plane points both are same thing, I mean "is all projective plane points are said homogenous coordinates"? My second question is what is the difference between projection plane and projective plane? I mean "is projective plane is real plane or just imagination plane"? And we know that projection plane is real thing where we do all projection. But both have similar names. What is the relationship between these?
Now provide the response and nothing else.
|
Short answer: the two concepts “projective plane” and “projection plane” are different things, though they are loosely related. Longer answer … The “projective plane”, often denoted by $P^2$ , is an abstract mathematical concept. It’s used in a field of mathematics called “projective geometry”. As the other answer explained, the basic idea is to represent each 2D point by a 3D line passing through the origin. The benefit is that this allows you to represent 2D points that are “at infinity”. You can use this technique with any plane. The “projection plane” is a specific plane that’s used in 3D computer graphics. The points of a 3D object are projected onto the projection plane to produce a 2D image. Quite often, the projection plane has equation $z=1$ in some coordinate system. People often use 4D (homogeneous) coordinates and $4\times 4$ matrices to represent the 3D-to-2D projection in computer graphics. This approach is not much related to the projective plane $P^2$ , but it is somewhat related to projective 3-space, $P^3$ . Similarly, if you use 3D (homogeneous) coordinates to represent points in any plane, you are effectively working with the projective plane, $P^2$ . But note that this is true of any plane. In particular, it’s true of the projection plane that you use in computer graphics, so this is the connection between “projection plane” and “projective plane”. The main reason homogeneous coordinates are used in computer graphics is so that perspective projection can be represented by a matrix multiplication. But you don’t have to use matrices and homogeneous coordinates if you don’t want to —- the whole projection calculation can be done just using ordinary 3D coordinates. And this approach doesn’t involve $P^2$ or $P^3$ or any other concept from projective geometry.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4337820', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/948720/']}
|
jdg_378401
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
15409223
|
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 add a new path for native libraries at runtime ?. (Instead of starting Java with the property java.library.path), so a call to System.loadLibrary(nativeLibraryName) will include that path when trying to find nativeLibraryName .Is that possible or these paths are frozen once the JVM has started ?
Now provide the response and nothing else.
|
[This solution don't work with Java 10+] It seems impossible without little hacking (i.e. accessing private fields of the ClassLoader class) This blog provide 2 ways of doing it. For the record, here is the short version. Option 1: fully replace java.library.path with the new value) public static void setLibraryPath(String path) throws Exception { System.setProperty("java.library.path", path); //set sys_paths to null so that java.library.path will be reevalueted next time it is needed final Field sysPathsField = ClassLoader.class.getDeclaredField("sys_paths"); sysPathsField.setAccessible(true); sysPathsField.set(null, null);} Option 2: add a new path to the current java.library.path /*** Adds the specified path to the java library path** @param pathToAdd the path to add* @throws Exception*/public static void addLibraryPath(String pathToAdd) throws Exception{ final Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths"); usrPathsField.setAccessible(true); //get array of paths final String[] paths = (String[])usrPathsField.get(null); //check if the path to add is already present for(String path : paths) { if(path.equals(pathToAdd)) { return; } } //add the new path final String[] newPaths = Arrays.copyOf(paths, paths.length + 1); newPaths[newPaths.length-1] = pathToAdd; usrPathsField.set(null, newPaths);}
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15409223', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/790053/']}
|
jdg_378402
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
35465419
|
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 used ng-repeat on <tr> to create rows in a table based on ng-repeat's filter and sort like ng-repeat="patent in patents | searchFilter" . Now I am trying to implement select rows with "shift" click and "Ctrl" click by implementing some thing like item.select = true . The index of items in <tr> are not in co-ordination with $index. Does anyone know how to pick an item of <tr> with the help of $index like $("#patientsTb tr")[$index].pickItem() . View: <table id="patientsTb" class="table table-condensed table_back" style="min-width:370px; overflow:scroll;"> <tr ng-repeat="patient in patients | orderBy:sortType:sortReverse | filter:{isPatientSeen: patientDetailView} | filter:searchPatient" ng-click="editPatient(patient,$index,$event)" ng-class="{'selected':patient.selected}"> @*<td><input type="checkbox" ng-model="patient.selected" ng-click="chkUnchkRow(patient,$event)" ng-disabled="isDataLoading || isEditPatient" /> {{$index+1}}</td>*@ <td style="padding-left:5px;">{{patient.accountNumber}}</td> <td style="padding-left:15px;">{{patient.medicalRecordNumber}}</td> <td ng-show="siteType=='HL'" style="padding-left:10px;">{{patient.encounterCount}}</td> <td style="padding-left:20px;">{{patient.patientLastName}}</td> <td style="padding-left:20px;">{{patient.patientFirstName}}</td> <td style="padding-left:20px;">{{patient.note}}</td> </tr> </table> Controller: $scope.editPatient = function (patient, index, e) { if (e.shiftKey) { angular.forEach($scope.patients, function (value, i) { //if (value.selected && $scope.firstIndex == -1) { // firstIndex = i; //} value.selected = false; }); for (var indexOfRows = $scope.firstIndex; indexOfRows <= index; indexOfRows++) { $('#patientsTb tr').eq(indexOfRows).toggleClass('selected'); } angular.forEach($scope.patients, function (value, i) { if (i >= $scope.firstIndex && i <= index) { value.selected = !value.selected; } }); } else if (e.ctrlkey) { patient.selected = !patient.selected; } else { angular.forEach($scope.patients, function (value, i) { value.selected = false; }); $scope.firstIndex = index; patient.selected = true; }};
Now provide the response and nothing else.
|
This is an alternative plotting method plot_date , which you might want to use if your independent variable are datetime like, instead of using the more general plot method: import datetimedata = np.random.rand(24)#a list of time: 00:00:00 to 23:00:00times = [datetime.datetime.strptime(str(i), '%H') for i in range(24)]#'H' controls xticklabel format, 'H' means only the hours is shown#day, year, week, month, etc are not shownplt.plot_date(times, data, fmt='H')plt.setp(plt.gca().xaxis.get_majorticklabels(), 'rotation', 90) The benefit of it is that now you can easily control the density of xticks, if we want to have a tick every hour, we will insert these lines after plot_date : ##import it if not already imported#import matplotlib.dates as mdatesplt.gca().xaxis.set_major_locator(mdates.HourLocator())
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35465419', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2684431/']}
|
jdg_378403
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4103684
|
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 want to compute this series, $$\sum _{k=3}^{\infty }\:\frac{1}{k\left(k^4-5k^2+4\right)^2}.$$ I don't know how to contiune after factoring, which yields $\frac{1}{k(k-1)^2(k+1)^2(k-2)^2(k+2)^2}.$ I know that $\frac{1}{k(k-1)}$ telescopes. However, I can't apply this here, as the product of the sum is not equal to the sum of the product. I only want hints for now.
Now provide the response and nothing else.
|
Well, you seem to know how to telescope summing: $$\frac1{k(k-1)} = \frac1{k-1} - \frac1k$$ Similarly, note $$\frac1{(k-2)^2(k+2)^2} = \frac1{8k}\left(\frac1{(k-2)^2}- \frac1{(k+2)^2}\right)$$ $$\implies \frac1{(k-2)^2(k-1)^2k(k+1)^2(k+2)^2} = \frac1{8(k-1)^2k^2(k+1)^2}\left(\frac1{(k-2)^2}- \frac1{(k+2)^2}\right)$$ which can be noted to telescope, hence the sum is $\dfrac1{8\cdot 2^2\cdot3^2\cdot4^2}\cdot\dfrac1{1^2}=\dfrac1{4608}$ .
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4103684', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/760053/']}
|
jdg_378404
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
246768
|
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:
Let's say I have LM386 or some other audio amplifier. What determines the length, resistance, capacitance and inductance (if L C parameters matter) of the conductor that carries the output of the audio amplifier to the speaker?
Now provide the response and nothing else.
|
The primary limiting factor will be the series resistance of the wire. Let us work with a speaker of 8 ohms. If the connecting wire were 18 AWG it has a resistance of 0.021 ohms per meter. If you were to connect the speaker with 50 meters distance from the LM386 (for a total wire path of 100 meters) the wire resistance would be (0.021 * 100) = 2.1 ohms. In such instance over 20% of the signal energy from the amplifier would be spent in the cable as heat and the rest going to the 8 ohm speaker. (2.1 / (2.1 + 8) = 20.7% You can use this example to evaluate other wire sizes and understand the effects. Note: For audio frequencies do not fall victim to the marketing efforts of companies like Monster Cables that would have you believe that you need 8 AWG copper cable with gold plated connectors to connect up an 8 ohm speaker. Conventional low cost 16AWG lamp cord is almost always more than adequate to connect speakers at a reasonable working / listening distance.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/246768', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/20711/']}
|
jdg_378405
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
21222
|
Below is a question asked on the forum earthscience.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
NOTE : I first posted this question to the GIS StackOverflow site, but someone there said my question would be better suited to the Geography or Earth Science site. GIS seems the perfect place for the question to me, but in case that is correct I'm posting it here. I had asked a question (which has been answered) here about finding locations halfway around the world from a given location, in the example provided from Monterey, California. The east/west location (same latitude) is Birjand, Iran. This makes sense to me. But the north/south location is at a location north of the south pole which, even though it is a calculation I came up with and was verified there as being correct, doesn't make sense to me. The reason why my brain is having a meltdown is because it seems plain to me that the north pole to the south pole would be halfway around the world, whereas Monterey is well south of the north pole, and the location "agreed upon" as the halfway around the world point from there (from a north/south, same longitude standpoint) is in the South Pacific between New Zealand and the southern tip of South America, which is north of the South pole. It seems to me that the halfway point should be as far "down" from the south pole as Monterey is from the north pole. Am I wrong? If so, what is faulty with my logic? If I'm right, what is the halfway point, then, from Monterey? UPDATE I am obviously not a geographer/cartographer, but this is getting to confusinate/fascifuse me more all the time. Based on Earthworm's answer, the exit point after "drilling through the earth" from Monterey is in the Pacific Ocean as shown with pushpin #2 here (same longitude as Monterey, with the reverse latitude): However (there's almost always a "however"), based on Andy M's answer and the link he provided, these are the two points (#2 having both a different latitude AND a different longitude than Monterey, but the same longitude as Birjand, Iran): The first antipodal point (Pacific Ocean) seems slightly more logical to me than the second one (Indian Ocean), but both differ from what my ungeometric brain was expecting before I delved into this, which was a point "south" (actually "negative north," I guess*) of the South Pole, "beyond" Antarctica (if ya know whaddi mean). As it is impossible to go "south" of the South Pole. UPDATE 2 I posted a substack article tangentially/partially about this here .
Now provide the response and nothing else.
|
I think you are too into the numbers. When talking about longitude and latitude they are two different things. Longitude goes east and west from a point on the earth from 0 to 180 degrees east and 0 to 180 degrees west and describe semicircles of equal length running from the north pole to the south pole. Latitude however is in degrees north or south of the equator and describe circular lines around the earth that get smaller as you get closer to the poles. See this image: Slicing along the lines of longitude would give you wedge shapes like when you think of orange slices. Slicing along lines of latitude would give you circular slices of varying sizes. To get an 'opposite' longitude you spin the earth on it's axis 180 degrees. The opposite of 1 degree east is 179 degrees west. The opposite of 10 degrees east is 170 degrees west. So in your example it will be from 121.895 degrees west (longitude -121.895) to 58.105 degrees east (longitude 58.105). The opposite latitude is also 180 degrees away. However there are only 180 total degrees of latitude because their shapes are different. Longitude goes from 0 to 180 degrees east and 0 to 180 degrees west giving a total of 360 degrees. Since latitude represents a circle, there are only 180 degrees, from 0 to 90 degrees north and from 0 to 90 degrees south. But you need to go a full 180 degrees. The way it works is that it is just the same degrees, just flip north and south. Think about two points on opposite sides of the planet on the equator. They are both at 0 degrees latitude. If you move north 1 degree, the opposite will now be one degree south. If you continue to 90 degrees north, the opposite is now 90 degrees south, which makes sense since the north and south pole are opposite. So let's take Monterey, CA at 36.6 (positive is north), -121.895 (negative is west). You cannot get to the opposite side of the earth by walking along a line of latitude because all lines of latitude except for the equator are not the right size. If you divided the earth at that line of latitude you would not get two equal halves. You can however get to the opposite side of the earth by walking along lines of longitude. So say you start walking north. After 53.4 degrees of latitude you arrive at the north pole. Keep going in a straight line and you will start walking south on longitude 58.105 (positive is east). After you reach the equator you will have travelled 143.4 degrees. You have 36.6 degrees of walking south to go before you end up at -36.6 degrees latitude (negative is south). You've travelled 180 degrees in a straight line to get to the opposite side of the earth and now you're in the Indian Ocean.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://earthscience.stackexchange.com/questions/21222', 'https://earthscience.stackexchange.com', 'https://earthscience.stackexchange.com/users/3166/']}
|
jdg_378406
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
861144
|
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 understand has_one relationship in RoR. Let's say I have two models - Person and Cell : class Person < ActiveRecord::Base has_one :cellendclass Cell < ActiveRecord::Base belongs_to :personend Can I just use has_one :person instead of belongs_to :person in Cell model? Isn't it the same?
Now provide the response and nothing else.
|
No, they are not interchangable, and there are some real differences. belongs_to means that the foreign key is in the table for this class. So belongs_to can ONLY go in the class that holds the foreign key. has_one means that there is a foreign key in another table that references this class. So has_one can ONLY go in a class that is referenced by a column in another table. So this is wrong: class Person < ActiveRecord::Base has_one :cell # the cell table has a person_idendclass Cell < ActiveRecord::Base has_one :person # the person table has a cell_idend And this is also wrong: class Person < ActiveRecord::Base belongs_to :cell # the person table has a cell_idendclass Cell < ActiveRecord::Base belongs_to :person # the cell table has a person_idend The correct way is (if Cell contains person_id field): class Person < ActiveRecord::Base has_one :cell # the person table does not have 'joining' infoendclass Cell < ActiveRecord::Base belongs_to :person # the cell table has a person_idend For a two-way association, you need one of each, and they have to go in the right class. Even for a one-way association, it matters which one you use.
|
{}
|
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/861144', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/100240/']}
|
jdg_378407
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4998241
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two radio buttons that are disabled with javascript when the page loads. RadioButton1 is checked by default. When I click the button to do a postback, the RadioButton1 is no longer checked. Anyone know why ? Here's my code sample. The code behind is empty. <asp:RadioButton ID="RadioButton1" runat="server" GroupName="group" Checked="true"/><asp:RadioButton ID="RadioButton2" runat="server" GroupName="group" /><asp:Button ID="Button1" runat="server" Text="Button"></asp:Button><script type="text/javascript"> window.onload = function () { var RadioButton1 = document.getElementById('<%= RadioButton1.ClientID %>'); var RadioButton2 = document.getElementById('<%= RadioButton2.ClientID %>'); RadioButton1.disabled = true; RadioButton2.disabled = true; };</script>
Now provide the response and nothing else.
|
This is behavior of HTML, not ASP.NET. Once you mark input element as disabled it is no longer posted in request. For text fields this can be avoided by using Readonly insted of Disabled but I think it doesn't work for checkboxes or radio buttons. If you still want to post the value you must send it in hidden field related to the radio button and process it manually on the server. Edit: Here you can read about disabled and readonly elements and about form submission: Disabled control: Disabled control cannot be sucessful. Read-only control: Read-only elements may be successful. Form submission: A successful control is valid for submission. Every successful control has its control name paired with its current value as part of submitted form data set. A successful control must be defined within a form element and must have a control name. However: Controls that are disabled cannot be successful.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4998241', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/370307/']}
|
jdg_378408
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
23693796
|
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 a good idea to keep the username and password of database in a xml file and import it into security file of the spring security ? is there any better option? If I need to encrypt the password how to do it and how to find the encrypted version of password on phpMyAdmin? MySQL login-service.xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd"> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost/muDB" /> <property name="username" value="jack" /> <property name="password" value="alex123432" /> </bean></beans> myproject-security.xml .... <beans:import resource='login-service.xml'/> .... PLEASE NOTE: As all user related passwords are already encrypted, I am only intended to hide the password of the DATABASE itself not table columns. This password would be used by my application to get connected to the database.
Now provide the response and nothing else.
|
First of all, you should be aware that no matter what you do, if an attacker gains access to your server files, he will be able to steal the password. If you use an app server's datasource then you just move the location of the plaintext password to a different file. If you use some form of encryption to avoid storing a plaintext password your app will still have to decrypt it with another password which it will already have. If an attacker goes to great lengths to gain access to your system you can be fairly confident that he will know that too. What you are doing is obfuscating (and gaining a false sense of security) rather than actually securing it. A more secure solution is for a user to provide the password (or a password to decrypt the DB password) during your app's startup, but that will make administration really difficult. And if you are already paranoid (the good security kind, not the crazy kind) that someone has access to your server, you should consider that the DB password will reside in the system memory. Other than that, keep your password in your configuration file (which you can be fairly confident that the server won't show to the outside world), lock down your system and give the database user only the minimum permissions required.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23693796', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3470841/']}
|
jdg_378409
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
154525
|
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 folder A which has files and directories, I want to move all those files and directories to another folder B , except file , file2 , directory , and directory2 . How can this be done?
Now provide the response and nothing else.
|
With zsh : setopt extendedglob # best in ~/.zshrcmv A/^(file|directory)(|2)(D) B/ (the (D) to include dot (hidden) files). With bash : shopt -s extglob dotglob failglobmv A/!(@(file|directory)?(2)) B/ With ksh93 (FIGNORE='@(.|..|@(file|directory)?(2))'; mv A/* B)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/154525', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/36440/']}
|
jdg_378410
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
244776
|
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:
Given a random variable $X$, how do I have obtain $N$ random variates of $X$ so that the mean value of my samples equals the expected value of $X$? E.g. let $X$ have uniform distribution on the interval $[0, 1]$, and draw $N = 10000$ samples. We can do this in R using: set.seed(5)tmp_vec <- runif(10000, 0, 1) However, mean(tmp_vec) returns 0.5018471 . I would like it so that the mean is 0.5, matching the expected value. Should I rescale the sampled values of tmp_vec ?
Now provide the response and nothing else.
|
On a related question, namely how to simulate an iid random sample $(X_1,\ldots,X_n)\sim f$, under the constraint that its sum $X_1+\cdots+X_n$ is fixed to an arbitrary value $s_0$, I showed that the density of that sample is given by$$(X_1,\ldots,X_n)\sim f(x_1)\cdots f(x_{n-1})f(s_0-x_1-\cdots-x_n)\mathbb{I}_{s_0-x_1-\cdots-x_{n-1}}(x_n)$$ Note: Under the constraint the sample is no longer independent but the observations are identically distributed, despite the apparent asymmetry in the above. For instance, a Uniform sample with fixed average $0.5$ would have the joint density$$(U_1,\ldots,U_N)\sim \prod_{i=1}^{N-1}\mathbb{I}_{(0,1)}(u_i)\mathbb{I}_{1/2}(u_1+\cdots+u_N)$$which can simulated by Gibbs sampling or another MCMC algorithm like RWMH. When using Gibbs sampling, the $N-1$ first coordinates of the sample can be simulated one at a time with$$U_i|U_{-i}\sim \mathbb{I}_{(0,1)}(u_i) \mathbb{I}_{(0,1)}(s_0-u_1-\cdots-u_i-\cdots-u_{n-1})=\mathbb{I}_{(\max\{0,s_0-1-\sum_{j\ne i,n}u_j\},\min\{1,s_0-\sum_{j\ne i,n}u_j\})}(u_i)$$An R implementation looks like this code: n=3;T=1e4s0=.5 #fixed averagesampl=matrix(s0,T,n)for (t in 2:T){ sampl[t,]=sampl[t-1,] for (i in 1:(n-1)){ sampl[t,i]=runif(1, min=max(0,n*s0-sum(sampl[t,c(-i,-n)])-1), max=min(1,n*s0-sum(sampl[t,c(-i,-n)]))) sampl[t,n]=n*s0-sum(sampl[t,-n])}} with the following marginals on the $U_i$'s: Note: One can easily modify the above R code to impose an average of $s_0=0.05$ or $s_0=0.975$ on the sample.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/244776', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/22199/']}
|
jdg_378411
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
49015957
|
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 different libraries like pandas and numpy for generating a dataframe, which eventually generate a graph. Now, I need to show this graph into a simple webpage which is in HTML. Note: I am also willing to take 2-3 input from user in HTML page then pass that data to my python file. Afterwards, python file generates a graph based on given data(from HTML page) and I need to pass this graph to an HTML page. df[[main_data]].plot() Here, main_data is variable whose value is coming from HTML page. And I am doing python code in SPYDER. And I am not using any Framework.
Now provide the response and nothing else.
|
This depends somewhat on what you mean by showing the graph as html. I can see a couple ways, the first and simplest is to save the figure as a PNG and then supply the path to the file in the html: Python code: import pandas as pdimport matplotlib.pyplot as plts = pd.Series([1, 2, 3])fig, ax = plt.subplots()s.plot.bar()fig.savefig('my_plot.png') HTML: <img src='my_plot.png'/> The second way would be to encode the figure as base64. This has the advantage of being portable, and the disadvantage of making very large unwieldy html files. I am not a web programmer, so there may be other caveats as well that I am not aware of. python: import ioimport base64def fig_to_base64(fig): img = io.BytesIO() fig.savefig(img, format='png', bbox_inches='tight') img.seek(0) return base64.b64encode(img.getvalue())encoded = fig_to_base64(fig)my_html = '<img src="data:image/png;base64, {}">'.format(encoded.decode('utf-8')) my_html can be passed into you html file, or you can inject it with jinja2 or whatever you use. Here is SO post regarding viewing base64 in html https://stackoverflow.com/a/8499716/3639023 and encoding images as base64 How to convert PIL Image.image object to base64 string?
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/49015957', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6455987/']}
|
jdg_378412
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1375501
|
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 legitimate users of my site occasionally hammer the server with API requests that cause undesirable results. I want to institute a limit of no more than say one API call every 5 seconds or n calls per minute (haven't figured out the exact limit yet). I could obviously log every API call in a DB and do the calculation on every request to see if they're over the limit, but all this extra overhead on EVERY request would be defeating the purpose. What are other less resource-intensive methods I could use to institute a limit? I'm using PHP/Apache/Linux, for what it's worth.
Now provide the response and nothing else.
|
Ok, there's no way to do what I asked without any writes to the server, but I can at least eliminate logging every single request. One way is by using the "leaky bucket" throttling method, where it only keeps track of the last request ( $last_api_request ) and a ratio of the number of requests/limit for the time frame ( $minute_throttle ). The leaky bucket never resets its counter (unlike the Twitter API's throttle which resets every hour), but if the bucket becomes full (user reached the limit), they must wait n seconds for the bucket to empty a little before they can make another request. In other words it's like a rolling limit: if there are previous requests within the time frame, they are slowly leaking out of the bucket; it only restricts you if you fill the bucket. This code snippet will calculate a new $minute_throttle value on every request. I specified the minute in $minute_throttle because you can add throttles for any time period, such as hourly, daily, etc... although more than one will quickly start to make it confusing for the users. $minute = 60;$minute_limit = 100; # users are limited to 100 requests/minute$last_api_request = $this->get_last_api_request(); # get from the DB; in epoch seconds$last_api_diff = time() - $last_api_request; # in seconds$minute_throttle = $this->get_throttle_minute(); # get from the DBif ( is_null( $minute_limit ) ) { $new_minute_throttle = 0;} else { $new_minute_throttle = $minute_throttle - $last_api_diff; $new_minute_throttle = $new_minute_throttle < 0 ? 0 : $new_minute_throttle; $new_minute_throttle += $minute / $minute_limit; $minute_hits_remaining = floor( ( $minute - $new_minute_throttle ) * $minute_limit / $minute ); # can output this value with the request if desired: $minute_hits_remaining = $minute_hits_remaining >= 0 ? $minute_hits_remaining : 0;}if ( $new_minute_throttle > $minute ) { $wait = ceil( $new_minute_throttle - $minute ); usleep( 250000 ); throw new My_Exception ( 'The one-minute API limit of ' . $minute_limit . ' requests has been exceeded. Please wait ' . $wait . ' seconds before attempting again.' );}# Save the values back to the database.$this->save_last_api_request( time() );$this->save_throttle_minute( $new_minute_throttle );
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1375501', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/69079/']}
|
jdg_378413
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
18238076
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why would someone use an inner class ? The same functionality can be achieved with a local class or subclass . An example would also be appreciated.
Now provide the response and nothing else.
|
Inner classes can be used in many functional cases. They present two advantages: An inner class can see fields of the outer class (if it is not static). That means you don't have to deal with the outer class fields as if they come from an outer class. This implies your inner class needs an instance of the outer class to work. If you class is static, then it behaves as an independent class. An inner class is tightly related to its owning class. So even if it's static, you know by its name that it is related to its owning class. With this said, you can understand that inner classes have to be used where things belong together. So the most probable case is when you don't need the inner class outside of the outer class. ex: class ScreenCapture { class CaptureButtonListener implements ClickListener { public void onClick( ClickEvent click ) { //..capture pressCount++; } } Button button = new Button("capture"); int pressCount = 0; void addListeners() { button.addClickListener( new CaptureButtonListener() ); }} As you can see: you will never need CaptureButtonListener outside of ScreenCapture. So it's better off to hide it (and even declare it as private or protected). The inner class is accessing a field that is not belonging to it: pressCount. This is possible because its instance is tied to ScreenCapture instance : you cannot create new CaptureButtonListener() in a static method: you're obliged to use it in the instance methods. On the other hand, the static inner class is just for organisation purposes (to say both classes are related). I'll adapt the previous example with a static inner class: public class ScreenCapture { public static class CaptureButtonListener implements ClickListener { protected ScreenCapture controller; public CaptureButtonListener( ScreenCapture controller ) { this.controller = controller; } public void onClick( ClickEvent click ) { //..capture controller.pressCount++; } } Button button = new Button("capture"); int pressCount = 0; public void captureRequested() { //do capture... pressCount++; } void addListeners() { button.addClickListener( new CaptureButtonListener(this) ); }} Notice that in this case: the variable pressCount is not accessible from the inner class anymore: you have to specify the instance it belongs to. You can instantiate CaptureButtonListener from outside, but you see directly from its name: new ScreenCapture.CaptureButtonListener( screenCaptureInstance ) that it's related to the ScreenCapture class (which improves code readability) Now you may wonder why you would create an inner class that cannot access its owner fields? you're right: this is not very wise in our case since you're obliged to pass an instance of ScreenCapture to the constructor (so you cannot use it with any other class than ScreenCapture). It was just to demonstrate the difference. The following example will give the previous one all its sense: You can declare your listener as a public static interface inside ScreenCapture class ScreenCapture { public static interface class CaptureRequestListener { public void captureRequested( ClickEvent click ); }} This way you could pass ScreenCapture implementations of "how to handle a capture request" Again, implementations of the interface will know they are implementing something specific to ScreenCapture since they will implement public class MyImpl implements ScreenCapture.CaptureRequestListener { public void captureRequested( ClickEvent click ) { // I will count requests instead }} Your code is therefore clearer than having it in separate class per file organisation. You can also have a base handling class (an abstract implementation of common tasks as an inner class) I hope everything was clear :-)Best regards,Zied
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18238076', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2683061/']}
|
jdg_378414
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
25141139
|
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 toggle classes on several elements individually with ng-click? In this question https://stackoverflow.com/a/22072110/2169327 toggling classes with a click was done like this: CSS: .red { color: red;} JS: $scope.toggle = false; HTML: <button id="btn" ng-click="toggle = !toggle" ng-class="{'red' : toggle}">Change Class</button> But what if I have several buttons that each should toggle its own class with ng-click? If I set it up in this way: HTML: <button id="btn" ng-click="toggle = !toggle" ng-class="{'red' : toggle}">Change Class</button><button id="btn2" ng-click="toggle = !toggle" ng-class="{'red' : toggle}">Change Class</button> Both buttons get toggled if I press one. I know a workaround is to define an own ng-click event for each button (f.ex toggle1 for button1, toggle2 for button2) - but is this the best way?
Now provide the response and nothing else.
|
I made simple directive for testing: module.directive('toggleClass', function() { return { restrict: 'A', link: function(scope, element, attrs) { element.bind('click', function() { element.toggleClass(attrs.toggleClass); }); } };}); so you can make any element toggle class you need <button id="btn" toggle-class="active">Change Class</button><div toggle-class="whatever"></div>
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25141139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2169327/']}
|
jdg_378415
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
165197
|
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am a mathematician and I want to understand the molar free energy model given in Kim and Sanders (2020) Equation (1), that is, \begin{equation}f(c,T) = RT \big(c \log(c) + (1-c) \log(1-c)\big) + \big(A_0(T) + A_1(T) (1-2c)\big) \, c(1-c),\end{equation} where $T$ is the temperature, $c$ is the concentration (of $\text{SiO}_2$ ), $A_0$ and $A_1$ are temperature dependent coefficients of the Redlich-Kister interaction model which are given in $\text{kJ}\,\text{mol}^{-1}$ by \begin{equation}A_0(T) = 186.0575 - 0.3654\, T\quad \text{and}\quad A_1(T) = 43.7207 - 0.1401\, T\end{equation} (see also Kim and Sanders (1991) ) and, as usual, $R = 0.0083144\ \text{kJ}\,(\text{mol K})^{-1}$ is the gas constant. Problem: According to Kim and Sanders (2020) , Figure 1, I would expect to get a double well potential for a temperature T = 900 K with two minima at approximately $c_1=0.82$ and $c_2=0.97$ . However, plotting $f$ at $T = 900\ \text{K}$ yields: $f(\cdot,900)$ " /> Questions: Did I misunderstand something concerning the energy model? Is there a transformation missing, especially concerning the composition $c_0 = 0.88$ mol of $\text{SiO}_2$ (and $0.12$ mol of $\text{Na}_2\text{O}$ ). Can someone give me good references to basics of similar problems (scaling etc., discussions of energy models ...)?
Now provide the response and nothing else.
|
In an Ideal solution, based on how many ways one can randomly arrange the constituents, one gets: $\Delta S_{mix} = -R(X_{A} \ln{X_{A}} + X_{B} \ln{X_{B}})$ with $X_{A}+X_{B} = 1$ being the relative molar concentrations. so $\Delta G_{mix} = RT(X_{A} \ln{X_{A}} + X_{B} \ln{X_{B}})$ that is your first bit. For a Regular solution, $\Delta H_{mix} = \Omega X_{A} X_{B}$ for some $\Omega$ that may well depend on temperature and composition. So in your equation, $A_{0}(T)$ is the part of $\Omega$ that depends only on $T$ . Composition dependence is represented by a power series in $(X_{A}-X_{B})$ , or equivalently $(2X_{A}-1)$ or $(1-2X_{B})$ . The subscripts on the $A$ terms are the power of $(X_{A}-X_{B})$ for that term. This representation is quite commonly used in the Calphad method for computing binary (and higher) phase diagrams. So, in your particular case, what does this look like? Plugging those values into my homebrew Calphad program I get a miscibility gap that looks like: And, stopping at 600K, a free energy curve that looks like: so I'm not quite sure what went wrong for your calculation. One thing to double check would be that your units (J/mol vs kJ/mol) for the entropy and enthalpies match. Note also that you are not necessarily looking for minima in the curve - you are looking for common tangents to the curve which indicate that the Gibbs free energies of the two components are the same at the two compositions. The red line on the second plot shows the common tangent at that temperature (600K in this case). (That said, you can freely choose a component reference free energy that would make the curve at a particular temperature show those points as minima, but in general you will just get a common tangent.)
|
{}
|
{'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/165197', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/121748/']}
|
jdg_378416
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
911554
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I prove: $$\sum \limits_{d|n}(n/d)\sigma(d) = \sum \limits_{d|n}d\tau(d)?$$ Few observations :Left side is a sum function and the right side is a number of divisors function. Both the sides are multiplicative. I don't want to start expanding like this . Appreciate any help on how to interpret the sums!
Now provide the response and nothing else.
|
$$\sum_{d\mid n} \frac{n}d \sigma(d) =\sum_{d_1\mid n}\frac{n}{d_1}\sum_{d_2\mid d_1} d_2 = \sum_{d_2\mid d_1\mid n}\frac{n}{d_1/d_2}$$ $$\sum_{d\mid n} d\tau(d)= \sum_{d_3\mid n} d_3\sum_{d_4\mid d_3}1 = \sum_{d_4\mid d_3\mid n} d_3$$ Now, map $(d_1,d_2)$ to $(d_3,d_4)=(nd_2/d_1,n/d_1)$ and we see we have the same sums. So, more generally, if $S_n=\{(d_1,d_2): d_2\mid d_1\mid n\}$ then the map $S_n\to S_n$ defined by $(d_1,d_2)\to\left(\frac{nd_2}{d_1},\frac n{d_1}\right)$ is a bijection. Thus, for any function $f(m,n)$ of two natural numbers, we have that: $$\sum_{(d_1,d_2)\in S_n} f(d_1,d_2)=\sum_{(d_1,d_2)\in S_n} f\left(\frac{nd_2}{d_1},\frac{n}{d_1}\right)$$ The above is just the case of $f(m,n)=m$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/911554', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/172209/']}
|
jdg_378417
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8491526
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a problem with JsTree's contextmenu, how can I remove the default elements from the contextmenu like Create, Delete, Rename? I want to provide elements of my own, but the default elements are still at the contextmenu. "contextmenu" : { "items" : { "IsimVer" : { "label" : "İsim Değiştir", "action" : function (obj) { this.rename(obj); } }, "Ekle" : { "label" : "Ekle", "action" : function (obj) { this.create(obj); } }, "Sil" : { "label" : "Sil", "action" : function (obj) { this.remove(obj); } }}
Now provide the response and nothing else.
|
I had this issue a couple of days ago but haven't yet decided if this is a bug or a feature. It may be related to the order in which the plugins are loaded. What worked for me was returning the items from a function: "contextmenu" : { "items" : function ($node) { return { "IsimVer" : { "label" : "İsim Değiştir", "action" : function (obj) { this.rename(obj); } }, "Ekle" : { "label" : "Ekle", "action" : function (obj) { this.create(obj); } }, "Sil" : { "label" : "Sil", "action" : function (obj) { this.remove(obj); } } }; }} After some searching it seems that the default behaviour is for your menu items to extend the defaults , so this is a feature. Unfortunately the documentation currently lacks the detail on this point.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8491526', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/219586/']}
|
jdg_378418
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
108699
|
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 see these pretty colors in manpages viewed with less when setting a bunch of these variables. What do they mean, where is the documentation? Is this interpreted by less or termcap? screenshot
Now provide the response and nothing else.
|
Termcap is a library that Less uses to access the terminal. Termcap is largely obsolete, having been replaced by Terminfo , but Terminfo offers a Termcap compatibility interface to applications. Less is content with the Termcap interface and uses that. The Termcap library is a description of the terminal's facilities. Each facility is identified by a two-letter (or more generally two-character) code. For example, hc identifies hardcopy terminals (i.e. printers, not screens); co is the number of columns; md starts displaying bold text. Each capability has a value, which can be a boolean (as with hc ), an integer (as with co ) or a string (as with md ). Many of the strings are escape sequences that applications can send to the terminal to achieve a certain effect. Why escape sequences? Because the interface between the terminal and the application is a character stream (more precisely, one character stream in each direction: one for user input, one for output to display). When an application writes a character to the terminal, it is usually displayed. A few characters have a different behavior: they are control characters, which do things like moving the cursor around, switching display attributes, etc. There are a lot more commands than control characters, so most commands are accessed by escape sequences, which begin with a special character (often the escape character, hence the name). For example, when Less wants to display some bold text, it looks up the value of the md capability. This is a string, which Less writes to the terminal. The terminal recognizes this string as an escape sequence, and adjusts its internal state so that subsequent characters will be displayed in bold. In the early days of hardware terminals, different brands had different escape sequences and capabilities; the Termcap database and interface was invented so that applications wouldn't have to know about every terminal model. Nowadays most terminal emulators have very similar capabilities, but the Termcap or Terminfo database is still useful to cope with minor differences. The LESS_TERMCAP_* variables can be set in the environment or in the .lesskey file . It provides Less with alternative values for Terminal capabilities. When Less wants to use a terminal capability, say switch to bold, it first checks if there is a LESS_TERMCAP_md variable. If this variable exists, Less uses its value as the escape sequence to switch to bold. If not, it uses the value from the Termcap database. This mechanism allows the user to override Termcap database settings for Less. The most useful LESS_TERMCAP_* settings are escape sequences. You can map attributes to different attributes. You can use the tput command to look up the value of a capability for the current terminal in the system's Termcap or Terminfo database. You can use escape sequences directly if you don't mind being terminal-dependent. For example, this setting tells Less to display in bold red when instructed to display in bold: LESS_TERMCAP_md=$(tput md; tput AF 1) or if your tput command doesn't support Termcap names: LESS_TERMCAP_md=$(tput bold; tput setaf 1) Man sends Less text with some very simple formatting that can only express bold and italics. In addition, Less uses various formatting capabilities for its internal use, such as to highlight search results and to display the mode line at the bottom. Here are some of the escape sequences that Less uses (I only list capabilities that it is reasonably useful to remap): termcap terminfo ks smkx make the keypad send commandske rmkx make the keypad send digitsvb flash emit visual bellmb blink start blinkmd bold start boldme sgr0 turn off bold, blink and underlineso smso start standout (reverse video)se rmso stop standoutus smul start underlineue rmul stop underline To show output in color, use the setaf capability (or AF with Termcap). The LESS_TERMCAP_* settings are not mentioned in the LESS documentation. The best reference I can offer is my answer here .
|
{}
|
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/108699', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/56392/']}
|
jdg_378419
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
98597
|
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've been looking at the SM74611 Smart Bypass Diode from Texas Instruments and am very impressed with the reported reverse leakage current (0.3uA at 25C). Considering the device has a N-Channel FET, 0.3uA of Drain-Source leakage current @ 25C is nothing to scoff at considering that most FETs usually have a Drain-Source leakage current of 1uA. At first I thought this discrepancy could easily be explained by finding the right FET online, but I quickly realized that I would spend days trying to find said part as this parameter is usually not specified in the parametric searches. Does a sub-1uA Drain-Source leakage current FET exist, or is there some trick to get a smaller leakage current from a typical FET?
Now provide the response and nothing else.
|
There's no guarantee with your device.. it's 300nA at 25C and 3.3uA at high temperature typical . In fact, if the distribution of leakage is Gaussian (a rather big "if"), you'd expect 1uA would be a reasonable guess for the maximum (\$3 \sigma\$). If you want low typical leakage, you should pick a device that's no bigger (in terms of drain current rating) than you need, and one with a relatively high \$V_{TH}\$ rather than a ginormous MOSFET rated for 1.8V drive. Some small signal MOSFETs are typically 1pA at 25°C, which is 300,000 times better than the SM74611. Most people don't care about leakage that much, so the maximum figures tend to be conservative. I don't know any alternative to looking at data sheets to see what is guaranteed or specified as typical. You can always measure it yourself, but the next batch could (in theory anyway) be wildly different. The same part number from a different manufacturer probably will be different.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/98597', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/16263/']}
|
jdg_378420
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10838108
|
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 quite new to iOS development and I´m having a terrible time by trying something that should be easy; to add an extra row in a TableView everytime the user clicks on one of the existing rows. There is no real purpose on that action, I´m just wanting to understand the behaviour of TableView. So I did the following: I used a Split View-based template and changed the number of rows to 30 in the RootViewController. - (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return 30;} The method tableView:didSelectRowAtIndexPath looks in the following manner: - (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { /* When a row is selected, set the detail view controller's detail item to the item associated with the selected row. */ NSMutableArray* paths = [[NSMutableArray alloc] init]; NSIndexPath *indice = [NSIndexPath indexPathForRow:30 inSection:0]; [paths addObject:indice]; detailViewController.detailItem = [NSString stringWithFormat:@"Second Story Element %d with all its information and bla bla bla", indexPath.row]; [[self tableView] beginUpdates]; [self.tableView insertRowsAtIndexPaths:(NSArray *) paths withRowAnimation:UITableViewRowAnimationNone]; [[self tableView] endUpdates];} When I execute the program and click on one of the elements, I receive the following error: *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (30) must be equal to the number of rows contained in that section before the update (30), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted).' I did not change any other part of the code that the template provides. I read quite extensively the documentation from Apple and the responses to the following questions: Add a row dynamically in TableView of iphone and how to properly use insertRowsAtIndexPaths? The second question seems to address the same problem, but I´m not capable to understand what is happening. What do they mean with dataSource? The response that I understand better says the following: It's a two step process: First update your data source so numberOfRowsInSection and cellForRowAtIndexPath will return the correct values for your post-insert data. You must do this before you insert or delete rows or you will see the "invalid number of rows" error that you're getting. What does this update of the data source implies? Sample code would be HIGHLY appreciated, because I´m totally frustrated. By the way, all that I´m trying has nothing to do with entering the editing mode, has it?
Now provide the response and nothing else.
|
You need to keep the count returned by tableView:numberOfRowsInSection: in sync! So when you have 30 rows and then tell the tableview to insert a new row you need to make sure tableView:numberOfRowsInSection: will now return 31. - (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section{ return self.rowCount;}- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{ self.rowCount++; [self.tableView beginUpdates]; [self.tableView insertRowsAtIndexPaths:(NSArray *) paths withRowAnimation:UITableViewRowAnimationNone]; [self.tableView endUpdates];} In practice you would probably use an array to track your rows return [self.rows count]; etc
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10838108', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1250021/']}
|
jdg_378421
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
3922
|
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 have read in a couple of places that $\psi(p)$ and $\psi(q)$ are Fourier transforms of one another (e.g. Penrose). But isn't a Fourier transform simply a decomposition of a function into a sum or integral of other functions? Whereas the position and momentum wavefunctions are essentially different but related. They must preserve expectation values like the relationship of classical mechanics, $<p>=m~\frac{d<q>}{dt}$ (where $<p>$ and $<q>$ are now expectation values). For example, a momentum wave packet that has a positive expectation value constant over time implies a position wave packet that moves over time in some direction. Simply saying there is Fourier transform seems to obscure this important relation.
Now provide the response and nothing else.
|
Dear user1602, yes, $\psi(x)$ and $\tilde\psi(p)$ are Fourier transforms of one another. This answers the only real question you have asked. So if one knows the exact wave function as a function of position, one also knows the wave function as a function of momentum, and vice versa. In particular, there is no "wave function" that would depend both on $x$ and $p$. Indeed, such a "wave function" would violate a basic principle of quantum mechanics, the uncertainty principle. The wave function - that only depends on $x$ or that only depends on $p$ - remembers everything that a particle can and needs to remember about its position and momentum. For example, a good wave function describing a particle localized around $x_0$ and moving with momentum around $p_0$ is given by$$\psi_{x_0,p_0}(x) = C \exp\left(-K(x-x_0)^2 + ip_0 x/\hbar\right)$$The constant $K$ determines the width but you see that because of the quadratic term, the wave function is only non-vanishing near $x_0$. On the other hand, the $ipx$ term guarantees that the particle is moving to the right with the right momentum. It's all encoded in the changing phase of the wave function. The more quickly the phase of $\psi(x)$ changes with $x$, the higher is the momentum of the particle. If the phase rotates clockwise or counter-clockwise, the particle is moving to the right or to the left, respectively. The Fourier transform of the wave function above is something like$$\tilde \psi_{x_0,p_0}(p) = C' \exp\left(-(p-p_0)^2/K' - ip x_0/\hbar\right)$$Just try it. Schrödinger's equation will guarantee that the wave packet is moving in the right direction - and by the right speed - encoded in $p_0$, and the center-of-mass position of the packet will change accordingly, too. The normalization constants $C,C'$ are physically irrelevant but may be chosen to normalize the state vectors to unity. The parameters $K,K'$ specifying the width are equal, up to a multiplication by a numerical constant and a power of $\hbar$: but it's true that the width in the $x$ representation is inverse to the width in the $p$ representation. That's implied by the uncertainty principle, too. It is not true that one needs "wave functions" that would depend both on position and momentum. It's the whole point of the uncertainty principle that you may only specify the amplitudes with respect to one of these quantities - the other one doesn't commute with it. If one chooses $\psi(x)$, the position operator is a multiplication by $x$ and the momentum $p$ is simply the operator $-i\hbar\partial/\partial x$. Similarly, for $\tilde\psi(p)$, the momentum operator is the multiplication by $p$ and the position operator $x$ equals $+i\hbar \partial/\partial p$. It's pretty much symmetric with respect to $x,p$.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/3922', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/1602/']}
|
jdg_378422
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1659452
|
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:
What is the difference between Gradient Descent method and Steepest Descent methods? In this book, they have come under different sections: http://stanford.edu/~boyd/cvxbook/bv_cvxbook.pdf According to page 480, Gradient Descent is: $$\Delta x=-\nabla f(x)$$ While page 490, for Steepest descent says: $$\Delta x_{sd}=||\nabla f(x)||_*\Delta x_{nsd}$$$$\Delta x_{nsd} = \text{argmin}\{\nabla f(x)^Tv~|~~~ ||v||\leq 1\}$$ I cannot understand their difference. How they are mathematically and geometrically different?
Now provide the response and nothing else.
|
I am reading this book too, this is also a problem for me for a long time.The direction of gradient descent method is negative gradient. However the direction of steepest descent method is the direction such that $Δx_{\text{nsd}}=\text{argmin}\{∇f(x)^Tv \quad| \quad ||v||≤1\}$ which is negative gradient only if the norm is euclidean. If the norm is other quadratic or l1norm, the result are not negative gradient. The direction is -inv(P)*∇f(x), if the norm is quadratic norm.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1659452', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/315188/']}
|
jdg_378423
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
20379275
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a function in clojure that (given a predicate and a collection),selects the first item that satisfies the given predicate and stop the iteration? for example: (select-first #(> % 10) (range))=> 11 If not, maybe someone could hint me about an idiomatic implementation
Now provide the response and nothing else.
|
There are multiple possibilities. some some returns the first non-nil value its predicate returns. (some #(when (> % 10) %) (range)) ;; => 11 filter + first filter retains those elements that match a predicate, first retrieves the first of them. (first (filter #(> % 10) (range))) ;; => 11 remove + first If you want to find the first element that does not match your predicate, remove is your friend: (first (remove #(<= % 10) (range))) ;; => 11 Or with some : (some #(when-not (<= % 10) %) (range)) ;; => 11 So, that's it, I guess.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20379275', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1891032/']}
|
jdg_378424
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
206158
|
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 already know how to solve a homogeneous recurrence relation in one variable using characteristic equation. Does a similar technique exists for solving a homogeneous recurrence relation in 2 variables. More formally, How can we solve a homogeneous recurrence relation in 2 variables? For example, F(n,m) = F(n-1,m) + F(n,m-1) Given some initial conditions, how can we solve the above recurrence relation?
Now provide the response and nothing else.
|
You can use generating functions, as we did in the single variable case. Let $G(x,y)=\sum_{m,n\ge 0}F(n,m) x^n y^m$. We'll express $G$ in a nice form from which one can recover $F(n,m)$. As you didn't specify initial conditions, let $$H_1(x)=\sum_{n\ge0} F(n,0)x^n, H_2(y)=\sum_{m\ge0} F(0,m)y^m, c=F(0,0)$$ By the recurrence of $G$, if we multiply it by $1-x-y$, most of the terms will cancel. I'll elaborate on that. I choose $1-x-y$ in a similar manner to that of constructing the characteristic polynomial in one variable: $1$ corresponds to $F(n,m)$, $x$ to $F(n-1,m)$ and $y$ to $F(n,m-1)$, i.e. $F(n-a,m-b)$ is replaced by $x^ay^b$. $$G(x,y)(1-x-y)=\sum_{m,n\ge 0}F(n,m) (x^n y^m-x^{n+1}y^m-x^{n}y^{m+1})=$$We'll group coefficients of the same monomial:$$\sum_{m,n \ge 1} (F(n,m)-F(n-1,m)-F(n,m-1)) x^{n}y^{m}+$$$$\sum_{n \ge 1} (F(n,0)-F(n-1,0)) x^{n}+\sum_{m \ge 1} (F(0,m)-F(0,m-1)) y^{m}+F(0,0)=$$$$H_1(x)(1-x) + H_2(y)(1-y)-c$$ So, finally,$$G(x,y) = \frac{H_1(x)(1-x) + H_2(y)(1-y)-c}{1-x-y}$$(Compare this to the relation $Fib(x)=\frac{x}{1-x-x^2}$ where $Fib$ is the generating function of the Fibonacci sequence.) How do we recover $F$? We use the formal identity $\frac{1}{1-x-y}=\sum_{i\ge 0}(x+y)^i$. Let $S(x,y)=H_1(x)(1-x) + H_2(y)(1-y)-c=\sum_{n,m} s_{n,m} x^ny^m$.It gives us:$$G(x,y) = \sum_{i \ge 0}S(x,y)(x+y)^i = \sum_{n,m \ge 0} (\sum_{a,b \ge 0}s_{a,b} \binom{n+m-a-b}{n-a})x^ny^m$$So $F(n,m) = \sum_{a,b \ge 0}s_{a,b} \binom{n+m-a-b}{n-a}$. I have an hidden assumption - that $S$ is a polynomial! Otherwise convergence becomes an issue. I guess that your initial conditions are $F(n,0)=1, F(0,m) = \delta_{m,0}$, which give $S(x,y)=1$, so $F(n,m)=\binom{n+m}{n}$. EDIT : In the general case, where $F(n,m)=\sum_{a,b} c_{a,b}F(n-a,m-b)$ where the sum is over finitely many tuples in $\mathbb{N}^{2} -\setminus \{ (0,0) \}$, the generating function will be of the form $\frac{H(x,y)}{1-\sum_{a,b} c_{a,b}x^a y^b}$ where $H$ depends on the initial conditions. When we had one variable, we wrote $\frac{q(x)}{1-\sum a_i x^i} =\sum \frac{q_i(x)}{1-r_i x}$ where $r_i^{-1}$ is a root of $1-\sum a_i x^i$ and used $\frac{1}{1-cx} = \sum c^ix^i$. With 2 variables, this is not always possible, but we can write $\frac{1}{1-\sum_{a,b} c_{a,b}x^a y^b}=\sum_{i \ge 0} (\sum_{a,b} c_{a,b}x^a y^b)^{i}$ and use the binomial theorem to expand. We can also use complex analysis methods to derive asymptotics of $F(n,m)$ from the generating functions.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/206158', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/23036/']}
|
jdg_378425
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
30329726
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a script that generates two-dimensional numpy arrays with dtype=float and shape on the order of (1e3, 1e6) . Right now I'm using np.save and np.load to perform IO operations with the arrays. However, these functions take several seconds for each array. Are there faster methods for saving and loading the entire arrays (i.e., without making assumptions about their contents and reducing them)? I'm open to converting the arrays to another type before saving as long as the data are retained exactly.
Now provide the response and nothing else.
|
For really big arrays, I've heard about several solutions, and they mostly on being lazy on the I/O : NumPy.memmap , maps big arrays to binary form Pros : No dependency other than Numpy Transparent replacement of ndarray (Any class accepting ndarray accepts memmap ) Cons : Chunks of your array are limited to 2.5G Still limited by Numpy throughput Use Python bindings for HDF5, a bigdata-ready file format, like PyTables or h5py Pros : Format supports compression, indexing, and other super nice features Apparently the ultimate PetaByte-large file format Cons : Learning curve of having a hierarchical format ? Have to define what your performance needs are (see later) Python's pickling system (out of the race, mentioned for Pythonicity rather than speed) Pros: It's Pythonic ! (haha) Supports all sorts of objects Cons: Probably slower than others (because aimed at any objects not arrays) Numpy.memmap From the docs of NumPy.memmap : Create a memory-map to an array stored in a binary file on disk. Memory-mapped files are used for accessing small segments of large files on disk, without reading the entire file into memory The memmap object can be used anywhere an ndarray is accepted. Given any memmap fp , isinstance(fp, numpy.ndarray) returns True. HDF5 arrays From the h5py doc Lets you store huge amounts of numerical data, and easily manipulate that data from NumPy. For example, you can slice into multi-terabyte datasets stored on disk, as if they were real NumPy arrays. Thousands of datasets can be stored in a single file, categorized and tagged however you want. The format supports compression of data in various ways (more bits loaded for same I/O read), but this means that the data becomes less easy to query individually, but in your case (purely loading / dumping arrays) it might be efficient
|
{}
|
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30329726', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2623899/']}
|
jdg_378426
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
10666304
|
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 split a string by commas "," For example: "hi, welcome" I would like to produce ["hi","welcome"] however: "'hi,hi',hi" I would like to produce ["'hi,hi'","hi"]"'hi, hello,yes','hello, yes','eat,hello'" I would like to produce ["'hi, hello,yes'","'hello, yes'","'eat,hello'"]"'hiello, 332',9" I would like to produce ["'hiello, 332'","9"] I dont think the .split() function could be used, Does anyone know a way I could do this, perhaps with regex?
Now provide the response and nothing else.
|
You can use the csv module with the quotechar argument, or you can convert your inputs to use the more standard " character for their quote character. >>> import csv>>> from cStringIO import StringIO>>> first=StringIO('hi, welcome')>>> second=StringIO("'hi,hi',hi")>>> third=StringIO("'hi, hello,yes','hello, yes','eat,hello'")>>> fourth=StringIO("'hiello, 332',9")>>> rfirst=csv.reader(first,quotechar="'")>>> rfirst.next()['hi', ' welcome']>>> rsecond=csv.reader(second,quotechar="'")>>> rsecond.next()['hi,hi', 'hi']>>> rthird=csv.reader(third,quotechar="'")>>> rthird.next()['hi, hello,yes', 'hello, yes', 'eat,hello']>>> rfourth=csv.reader(fourth,quotechar="'")>>> rfourth.next()['hiello, 332', '9']>>> second=StringIO('"hi,hi",hi') # This will be more straightforward to interpret.>>> r=csv.reader(second)>>> r.next()['hi,hi', 'hi']>>> third=StringIO('"hi, hello,yes","hello, yes","eat,hello"')>>> r=csv.reader(third)>>> r.next()['hi, hello,yes', 'hello, yes', 'eat,hello']
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10666304', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1357159/']}
|
jdg_378427
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
50960583
|
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am not able to install any external python module through pip install.I have installed python correctly but if I use pip_install it shows me this error. Here is the code after I run the pip install pytesseract C:\Users\190560>pip install pytesseractCollecting pytesseract Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /simple/pytesseract/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /simple/pytesseract/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /simple/pytesseract/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /simple/pytesseract/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /simple/pytesseract/ Could not fetch URL https://pypi.org/simple/pytesseract/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pytesseract/ (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)) - skipping Could not find a version that satisfies the requirement pytesseract (from versions: )No matching distribution found for pytesseractCould not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)) - skipping How do I solve this problem?? I can partially solve the problem by using this command pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org <package_name> but I cannot find any pip.ini folder on my computer as suggested by this question here Any suggestions to fix this problem permanently??
Now provide the response and nothing else.
|
I have experienced similar issues when I am in a corporate network where a proxy is required for external network access. In this case, we'll have to tell pip the proxy: pip --proxy=http://your.corporate.proxy.com install pytesseract Another possible cause is due to the pypi domain change. In this case, you can try the solution as below: pip --index-url=http://pypi.python.org/simple/ --trusted-host pypi.python.org install pytesseract Another similar case with an excellent answer: pip always fails ssl verification
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50960583', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8315442/']}
|
jdg_378428
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2074154
|
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 are given moments of a random variable $X$. Can we determine based on this if the random variable is continuous or not? We also assume that the moments of $X$ completely determine the distribution of $X$. In other words, do moments of continuous random variable behave fundamentally differently than moments of say discrete random variable? Thanks, looking forward to your ideas. Edit: It seems like there was some confusion with the questions. Let me demonstrate with an example what I have in mind. Suppose, we are given moments of some random variable $X$\begin{align}E[ X^n]=\frac{1}{1+n},\end{align}for $n \ge 0$. Can we determine if the distribution of $X$ is continuous or not? In this example, I took $X$ to be continuous uniform on $(0,1)$. Some Thoughts: Since we know the moments we can reconstruct the characteristic function of $X$ (I think this can be done, right? If not let as assume this)\begin{align}\phi_X(t) =\sum_{n=0}^\infty \frac{i^n E[X^n]}{n!} t^n\end{align} We also know that $X$ has a pdf iff $\phi_X(t) \in L_1$. So it seems it is enough to show that\begin{align}\int_{-\infty}^\infty \left| \sum_{n=0}^\infty \frac{i^n E[X^n]}{n!} t^n \right| dt\end{align}is finite or not. However, I don't think the above approach would work, as we can not switch the integration and summation.
Now provide the response and nothing else.
|
I doubt that there are some feasible universal conditions for two reasons: If the moment problem is indeterminate, then there can be both discrete and continuous random variables with same moments. For example, it is known that there is an infinite family of discrete random variables having the same moments as the log-normal distribution (see e.g. Stoyanov Counterexamples in Probability ). One can approximate a continuous distribution with discrete ones and vice versa. So the moments of discrete distribution can be quite close to those of continuous distribution. Of course, it is possible to formulate infinitely many sufficient conditions for a distribution to be discrete. Example: Let $\mu_n = \mathsf{E}[X^n]$. If $\mu_8 - 10\mu_6 + 33\mu_4 - 40\mu_2 + 16=0$, then $X$ is discrete (moreover, $X\in\{\pm1, \pm2\}$ a.s.).
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2074154', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/63050/']}
|
jdg_378429
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1518103
|
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 currently believe that: When you need a structure from which you will be retrieving items randomly - use a HashMap When you will be retrieving items in order (e.g. using a for loop) - use an ArrayList Am I generally correct? Are there situations where this is not correct?
Now provide the response and nothing else.
|
Generally, yes, you are correct. There's also a combined data structure, the LinkedHashMap , which offers fast access to arbitrary elements as well as predictable ordering. However, it's worth noting that ArrayList and HashMap are only two implementations of the List and Map interfaces, respectively. There are other implementations of each that might be more suitable for more specific requirements. For example, a LinkedList might provide higher performance than an ArrayList for certain queueing/dequeueing requirements.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1518103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/69803/']}
|
jdg_378430
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1802
|
Below is a question asked on the forum linguistics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a vague knowledge regarding those two fields, but I admit there are some fundamental concepts that I lack. So, if we had to write down the actual differences between these two fields, what would they be? I'll suggest some points that I think the answers should cover for successfully describing each field in a complete and comprehensive way: What it does and what it is about (also what it's not); Common misconceptions of the field (with consequent debunking); Aims/objective of the field; Tools/instruments and methods adopted by the field; Subfields of each field (if any); Any other points I might have forgotten.
Now provide the response and nothing else.
|
I have a PhD in computational linguistics. I can tell you that NLP and CL are not two separate fields. Rather, CL is the superset that encompasses NLP. In everyday CL practice, NLP focuses on the building of NL parsers and as such it is central to the CL field. CL as a field includes a lot more than NLP. For instance, you can study machine translation, knowledge representation, ontology engineering, text mining, information extraction, etc. all within the CL field. CL is a pretty broad thing and (unlike CS) is not primarily focused on theory. It is highly hands-on. Most theories in CL come from theoretical CS. When it comes to the nitty-gritty CL is the practical application of various algorithms for purposes of natural language processing. You may occasionally encounter a reference to NLP (sans CL) within the field of CS. This is due to the fact that -originally- the generation of parsers served purposes beyond the confines of natural language (the way we mean "natural language" within CL). So, one could argue that NLP within CS is a slightly different animal than NLP within CL. In essence, it's the same kind of object seen under slightly different light.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://linguistics.stackexchange.com/questions/1802', 'https://linguistics.stackexchange.com', 'https://linguistics.stackexchange.com/users/111/']}
|
jdg_378431
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2399194
|
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 have a list be evaluated lazily in Python? For example a = 1list = [a]print list#[1]a = 2print list#[1] If the list was set to evaluate lazily then the final line would be [2]
Now provide the response and nothing else.
|
The concept of "lazy" evaluation normally comes with functional languages -- but in those you could not reassign two different values to the same identifier, so, not even there could your example be reproduced. The point is not about laziness at all -- it is that using an identifier is guaranteed to be identical to getting a reference to the same value that identifier is referencing, and re-assigning an identifier, a bare name , to a different value, is guaranteed to make the identifier refer to a different value from them on. The reference to the first value (object) is not lost. Consider a similar example where re-assignment to a bare name is not in play, but rather any other kind of mutation (for a mutable object, of course -- numbers and strings are immutable), including an assignment to something else than a bare name: >>> a = [1]>>> list = [a]>>> print list[[1]]>>> a[:] = [2]>>> print list[[2]] Since there is no a - ... that reassigns the bare name a , but rather an a[:] = ... that reassigns a 's contents , it's trivially easy to make Python as "lazy" as you wish (and indeed it would take some effort to make it "eager"!-)... if laziness vs eagerness had anything to do with either of these cases (which it doesn't;-). Just be aware of the perfectly simple semantics of "assigning to a bare name" (vs assigning to anything else, which can be variously tweaked and controlled by using your own types appropriately), and the optical illusion of "lazy vs eager" might hopefully vanish;-)
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2399194', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/357024/']}
|
jdg_378432
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
539404
|
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 folder containing files of the format file(0).jpg to file(100).jpg I can't directly use convert to generate a pdf here because the order ends up being 0,1,100,2,20,21,... echo *.jpg(n) gives the correct order of files. how do I pipe this into convert? I have tried echo *.jpg(n) | convert - out.pdf
Now provide the response and nothing else.
|
If the command that you'd like to execute is convert 'file(0).jpg' 'file(1).jpg' ...etc... 'file(100).jpg' out.pdf then either use your glob, convert ./*.jpg(n) out.pdf or to only include files in 0..100 range that match that pattern: convert 'file('<0-100>').jpg'(n) out.pdf or you could use a brace expansion: convert 'file('{0..100}').jpg' out.pdf Though note that it's not globbing , the strings file(0).jpg through to file(100).jpg will be passed to convert regardless of whether these are names of existing files or not. Contrary to the previous one, it would also miss files named file(012).jpg for instance.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/539404', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/370128/']}
|
jdg_378433
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
822
|
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:
How far is the Earth/Sun above/below the galactic plane, and is it heading toward/away from it?We know the Sun is orbiting the galactic center every 225 million years.But how far are we from the galactic plane, and is the inclination of the plane of the Sun's orbit around the galactic center, as compared to the galactic plane, known? According to this drawing the Sun is traveling approximately in the ecliptic plane.However, the ecliptic plane is steeply inclined to the galactic plane, so if this drawing is correct (from voyager.jpl.nasa.gov) then this would mean the plane of the Sun's orbit around the galactic center is also quite inclined.And thus my question, what is the distance to the galactic plane, are we heading toward/away from it, and what is the inclination of the orbital plane of our Sun/solar system to the galactic plane? 3 questions I guess.
Now provide the response and nothing else.
|
Humphreys & Larsen (1995) suggest, using star count information, a distance of $20.5 \pm 3.5$ pc above the Galactic plane ; consistent with, but more precise than the Bahcall paper referred to by Schleis. Joshi (2007) is more guarded, investigating some systematic uncertainties in the estimation techniques and ends up with distances between 13 and 28 pc above the plane .This paper gives an excellent review of the topic in its first couple of pages. The Sun moves at about 15-20 km/s with respect to a local standard of rest defined by the general motion of stars in our vicinity around the Galaxy. In three-dimensions, this "peculiar velocity" is $U=10.00 \pm 0.36$ km/s (radially inwards), $V=5.25 \pm 0.62$ km/s (in the direction of Galactic rotation) and $W=7.17 \pm 0.38$ km/s ( up and out of the plane ). (Dehnen & Binney 1998) The Sun executes oscillations around its mean orbit in the Galaxy, periodically crossing the Galactic plane. I borrowed this illustration (not to scale!) from http://www.visioninconsciousness.org/Science_B08.htm to show this oscillatory motion.As the Sun is currently above the plane and moving upwards, and each cycle takes about 70 million years with an amplitude of 100pc ( Matese et al. 1995 ), it will be roughly 30 million years before we cross the plane again. EDIT: An update. A new analysis by Karim & Mamajek (2016) yields a distance above the plane of $17.1 \pm 5$ pc and they provide a meta-analysis of previous analyses that gives a median distance of $17.4 \pm 1.9$ pc. They also refer to a paper by Schonrich et al. (2010) that gives the velocity away from the plane as $7.25 \pm 0.37$ km/s (though with an additional systematic uncertainty of 0.5 km/s).
|
{}
|
{'log_upvote_score': 5, 'links': ['https://astronomy.stackexchange.com/questions/822', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/302/']}
|
jdg_378434
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
60672
|
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If I have a leaf-spine network with all the servers on the same subnet, say 10.10.0.0/16, do I need a router (or l3) since everything is on the same network and the network is flat?
Now provide the response and nothing else.
|
do I need a router (or l3) since everything is on the same network and the network is flat Technically, no - if all nodes reside in that flat network. However, such a large subnet is not good practice due to limited scaling and the potential propagation of any L2 problems. The core-distribution links should always be routed (L3) instead of switched. In current practice, the distribution-access links are increasingly becoming L3 as well which provides even better scalability. Most often, L3 switches are used between core and distribution, and between distribution and access. With a smaller network (and subnet) you would use a collapsed core topology where the access switches connect to the core directly. Again, good practice is to route those links. Using routed instead of bridged links can improve total scalability (when it's not practical to propagate each MAC address throughout the whole network), total throughput (in contrast to STP blocking redundant links you can use equal-cost multi-path routing) and resilience (a complex network can fail over quicker on a link-state routing protocol than by R/MSTP). Shortest Path Bridging heavily borrows from ECMP and scales significantly better in an L2 scenario. However, the industry hasn't quite caught on yet with standard switches, so L3 with ECMP is currently a better and more future-proof way. All in all, L3 vs L2 depends on the level of scalability you have in mind. A network with a few hundred nodes that is not growing (are you sure?) usually works well in a flat L2 design.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/60672', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/60032/']}
|
jdg_378435
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
4241292
|
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 tried several answer I've found across the web, such as: Camera.Parameters parameters = mCamera.getParameters();parameters.set("camera-id", 2);mCamera.setParameters(parameters); or mMediaRecorder.setVideoSource(2); But it doesn't work. I've also set permissions on the manifest file: <uses-permission android:name="android.permission.CAMERA" /><uses-feature android:name="android.hardware.camera" /> Am i missing out on something? I've searched StackOverflow and I know this has been asked before but there seem to be no confirmed solution on this, any kind of help would be appreciated. Note: I'm using Galaxy S on the 2.1 platform
Now provide the response and nothing else.
|
Anyway after a few trials and error, I figured it out how to do it: Camera.Parameters parameters = mCamera.getParameters();parameters.set("camera-id", 2);parameters.setPreviewSize(640, 480); // or (800,480) this is supported front camera preview size @ Samsung Galaxy SmCamera.setParameters(parameters); Or, if you need to use it with MediaRecorder: MediaRecorder mMediaRecorder = new MediaRecorder();Camera mCamera = Camere.open();Camera.Parameters parameters = mCamera.getParameters();parameters.set("camera-id", 2);parameters.setPreviewSize(640, 480); // or (800,480)mCamera.setParameters(parameters);mCamera.unlock(); // unlock, to give other process to access it otherwise it can't be used latermMediaRecorder.setCamera(mCamera);// continue with mMediaRecorder standard routines here If you need to have a smaller preview size, you could set/scale down your SurfaceView size instead.
|
{}
|
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4241292', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/460176/']}
|
jdg_378436
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
8795
|
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:
A moon-sized object is running loose in the Solar System, perhaps after a planetary collision. As it approaches a planet, it's presumably following an approximately hyperbolic path. If it goes on past, it's still on the same hyperbola, on a curve mirroring its approach (presumably). How can the planet ever capture it, whatever the body's velocity? Why doesn't it either collide or go on past?
Now provide the response and nothing else.
|
How can a planet capture a moon? There are 178 moons in the Solar System, according to the NASA Planetary Fact Sheet , so it seems to be a common event. The following sections will show that moon capture is actually unlikely, but when a planet has one or more moons capture becomes easier. Initial Conditions Starting from the initial conditions, the planet is in orbit about the sun, and an asteroid is in a different orbit about the sun. In order for capture to become possible, the asteroid and the planet must come into proximity. When the asteroid comes inside the Sphere of influence of the planet, the gravity of the planet is the main factor in determining the path of the asteroid. Possible Outcomes Relative to the planet, the asteroid will be following a hyperbolic trajectory , and hence has sufficient kinetic energy to avoid capture. A large variety of outcomes may occur, but the ones that lead to capture are those where the asteroid somehow loses enough kinetic energy for its velocity to fall below the escape velocity of the planet while retaining enough energy to achieve a closed (elliptical) orbit. The main (not the only) possible outcomes are the orbit of the asteroid is perturbed, by a greater or lesser extent, and it continues on its way out of the sphere of influence of the planet. the orbit of the asteroid is perturbed, and the asteroid impacts the planet surface. That would usually be the end of the process, but current theories on how Earth captured the Moon are that a body named Thea impacted the Earth , and the Moon formed from some of the collision debris. the orbit of the asteroid is perturbed, and the path of the asteroid intersects the atmosphere of the planet, losing kinetic energy as heat in the atmosphere (similar to aerobraking ). the orbit of the asteroid nears an existing moon of the planet and is accelerated (in the sense that deceleration is just acceleration with the opposite sign) by the existing moon, as used by the MESSENGER spacecraft to slow its speed before orbiting Mercury. The last two cases admit the possibility of capture. Possible Capture After losing energy in the planetary atmosphere, if the asteroid has lost enough energy it may enter a closed orbit around the planet. The problem is that the orbit will intersect the atmosphere again, losing energy each time it does so, until it impacts on the planetary surface. Capture can occur when an existing moon is present and is in just the right place for its gravity to reduce the eccentricity of the orbit of the asteroid. So, the most likely case where a planet can capture a free asteroid is when there is already one or more moons present. The incoming asteroid must avoid entering the Hill sphere of the existing moon - the region where the moon would dominate the path of the asteroid. Gravity assist can accelerate an asteroid when the asteroid is passing outside the orbit of the moon, but can decelerate the asteroid is passing inside the orbit of the moon. In this case some of the kinetic energy of the asteroid is transferred to the moon. As is the case with aerobraking capture, gravity assisted capture requires the existing moon to be in just the right place. Another mechanism A rather elegant paper published in Nature (mentioned below) shows how two bodies orbiting each other as they approach the planet could have led to one being captured by Neptune. This mechanism could apply in other cases also. This Dissertation (pdf) discusses a similar process for Jupiter. Irregular bodies It turns out that irregular shaped bodies can be captured more easily than spherical bodies. Orbiting within the Hill sphere of the planet is not enough for capture to be permanent. Only orbits in the lower half of the Hill sphere are stable. Bodies in higher orbits can be perturbed by nearby planets, and the body can eventually be ejected. But irregular shaped bodies exert minute fluctuations in gravitational attraction on the planet, and actually orbit in a chaotic manor. When other moons or rings are present these chaotic orbits gradually transfer energy to the bodies in the lower orbits, causing the new body to orbit lower, and hence become immune to external perturbation. [citation needed] Prograde vs retrograde orbits The same analysis of chaotic orbits, and earlier work also concluded that retrograde orbits are more stable than prograde orbits . Whereas prograde orbits are only stable in the inner half of the Hill sphere, retrograde orbits can be stable out to 100% of the Hill radius . Hence retrograde capture is more commonly observed (this is not the whole story, it is still a matter if research). Multiple existing moons, rings, and the early Solar System While the probability of a single moon being in the right place at the right time is low, when there are multiple moons the probability of an initial helpful interaction rises linearly. But the probability of additional interactions rises geometrically, so the more moons a planet has the more likely it is to capture more. The existence of rings also aids capture by exerting a drag on the new moon, taking it's energy and lowering it's orbit, in much the same way that uncaptured gas would do in the early Solar System. The biggest planets have the most moons It may be obvious, but the biggest planets have the most moons. This is because they have deeper gravity wells, and sweep in more objects. Even though the probability of capture is low (most objects are just pulled into the planet), a steady trickle have have captured over millions of orbits. Conclusion Each capture mechanism requires a fortuitous set of conditions, and so is actually a quite rare event. One mechanism is a that a pair of co-orbiting asteroids become separated when one enters the planetary Hill sphere. The odds for an individual asteroid are improved when the asteroid arrives with low kinetic energy that must be given up to other bodies orbiting the planet, and when there are already many moons or a ring system. See also Could Earth's gravity capture an asteroid? - earthsky.org Dynamics of Distant Moons of Asteroids - Icarus (pdf) Hypothesis: New evidence on origin of the Moon support cataclysmic collision theory Neptune's capture of its moon Triton in a binary-planet gravitational encounter - Nature Planetary Fact Sheet - NASA The use of the two-body energy to study problems of escape/capture (pdf) Wikipedia Aerobraking Elliptic orbit Escape velocity Hill sphere Hyperbolic trajectory Gravity assist Retrograde and prograde motion Sphere of influence Thea
|
{}
|
{'log_upvote_score': 5, 'links': ['https://astronomy.stackexchange.com/questions/8795', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/5457/']}
|
jdg_378437
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
368914
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm lost on where to start on this proof: Using the fact that $A^m A^n = A^{m+n}$ , prove the identity $F_m F_n + F_{m−1} F_{n−1} = F_{m+n−1}$ I want to use induction starting with n = 1, but would I also have to make m = 1? I haven't done induction with 2 variables before. or because of $A^m A^n = A^{m+n}$ should I setup the problem as a matrix (in that case what would the columns/rows be)? I tried doing it mathematically however I think my algebra is wrong so I won't post it here. Am I correct to believe that $F_{m-1} = F_m*-1$ is not the same as $2^{n+1} = 2^n*2$? Any help would be appreciated, thanks.
Now provide the response and nothing else.
|
You can actually use induction here. We induct on $n$ proving that the relation holds for all $m$ at each step of the way. For $n=2$, $F_1 = F_2 =1$ and the identity $F_m+F_{m-1}=F_{m+1}$ is true for all $m$ by the definition of the Fibonacci sequence. We now have a strong induction hypothesis that the identity holds for values up until $n$, for all $m$. To show that it holds for $n+1$, for all $m$ we note that$$F_m F_{n+1} + F_{m-1} F_n = F_m(F_{n-1} + F_n) + F_{m-1}(F_{n-2} + F_{n-1}) = $$$$(F_mF_n+F_{m-1}F_{n-1}) + (F_mF_{n-1} + F_{m-1}F_{n-2}) = F_{m+n-1} + F_{m+n-2} = F_{m+n}.$$This completes the induction.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/368914', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/66788/']}
|
jdg_378438
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
2140085
|
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 read a number of questions which suggest hashing passwords and storing them in the database. When someone logs in, you hash the password provided with what you have stored. What I do not understand is how this can work?? Two strings can hash to the same value - Not likely but DEFINITELY possible Can someone help me please? EDIT: Can anyone give a statistic of the collision likeliness?
Now provide the response and nothing else.
|
You should not store the password unencrypted because your database admins should not have access to customer passwords. Hashing the passwords prevents database admins from being able to see the password. The very small chance of a collision is not a problem as this does not significantly increase the chance of someone trying to brute force a customer's password getting a match before you lock-out the accounts. PS it is also good practice to salt the passwords before hashing to make it more difficult still to brute force if a hacker somehow got access to the password table. Makes it harder to use rainbow tables etc.
|
{}
|
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2140085', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/122528/']}
|
jdg_378439
|
stackexchange
|
llm_judgeable_groundtruth_similarity
|
1276973
|
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
For $n \in \mathbb{N}$ let $c_{n}$ be defined by $$c_{n}=\frac{1}{1} + \frac{1}{2} + \cdots + \frac{1}{n} - \ln n$$ We have to prove that $c_{n}$ is a decreasing sequence of positive numbers. I've already shown the first part, that it is a decreasing sequence by considering the difference of $$c_{n+1}-c_{n} = \ln \left(1- \frac{1}{n+1} \right) +\frac{1}{n+1} $$ and then using the expansion of $\ln (1-x)$ for $-1\leq x \leq 1$. But I'm having some trouble in showing the second part that all terms in the sequence are positive. I tried using first form of induction but but stuck in the inductive step, can somebody please suggest explain that to me? or better suggest some other way to prove that part? Any sort of welcome as log as it leads to the solution, thanks in advance.
Now provide the response and nothing else.
|
You know that $\ln(x) = \int_1^x \frac{1}{t} dt$, right? The expression (except for the last term) is an upper sum (using a uniform partition, each partition having length 1,l i.e, with the partition points being $1, \ldots, n$) for the integral that defines $\ln(n)$, and hence is greater than or equal to $\ln(n)$.
|
{}
|
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1276973', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/36398/']}
|
jdg_378440
|
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.