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 | 45122155 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
<title>TheSaaS - Responsive Bootstrap SaaS, Software & WebApp Template</title><script>if (top !== self) top.location.replace(self.location.href +'?utm_source=themeforest&utm_medium=preview&utm_campaign=thesaas');</script><!-- Styles --><link type="text/css" href="{{url_for('static',filename='assets/css/core.min.css')}}" rel="stylesheet"><link type="text/css" href="{{url_for('static',filename='assets/css/thesaas.min.css')}}" rel="stylesheet"><link type="text/css" href="{{url_for('static',filename='assets/css/style.css')}}" rel="stylesheet"><!-- Favicons --><link rel="apple-touch-icon" href="{{url_for('static',filename='assets/img/apple-touch-icon.png')}}"><link rel="icon" href="{{url_for('static',filename='assets/img/favicon.png')}}"><!-- Open Graph Tags --><meta property="og:title" content="TheSaaS"><meta property="og:description" content="A responsive, professional, and multipurpose SaaS, Software, Startup and WebApp landing template powered by Bootstrap 4."><meta property="og:image" content="http://thetheme.io/thesaas/assets/img/og-img.jpg"><meta property="og:url" content="http://thetheme.io/thesaas/"><meta name="twitter:card" content="summary_large_image"> <!-- Topbar --><nav class="topbar topbar-inverse topbar-expand-md topbar-sticky"> <div class="container"> <div class="topbar-left"> <button class="topbar-toggler">☰</button> <a class="topbar-brand" href="index.html"> <img class="logo-default" src="{{url_for('static',filename='assets/img/logo.png')}}" alt="logo"> <img class="logo-inverse" src="{{url_for('static',filename='assets/img/logo-light.png')}}" alt="logo"> </a> </div> </div></nav><!-- END Topbar --><!-- Header --><header class="header fadeout header-inverse pb-0 h-fullscreen" style="background-image: linear-gradient(to bottom, #243949 0%, #517fa4 100%);"> <canvas class="constellation"></canvas> <div class="container"> <div class="row h-full"> <div class="col-12 text-center align-self-center"> <h1 class="fs-50 fw-600 lh-15 hidden-sm-down">Built for <span class="text-primary" data-type="Authors, Startups, Entrepreneurs, SaaS, WebApps"></span></h1> <h1 class="fs-35 fw-600 lh-15 hidden-md-up">Built for<br><span class="text-primary" data-type="Authors, Startups, Entrepreneurs, SaaS, WebApps"></span></h1> <br> <p class="fs-20 hidden-sm-down"><strong>TheSaaS</strong> is an elegant, modern and fully customizable SaaS and WebApp template</p> <p class="fs-16 hidden-md-up"><strong>TheSaaS</strong> is an elegant, modern and fully customizable SaaS and WebApp template</p> <br> <hr class="w-60 hidden-sm-down"> <br> <a class="btn btn-xl btn-round btn-primary fs-20 fw-500 w-350 shadow-3 hidden-sm-down" href="https://themeforest.net/item/thesaas-responsive-bootstrap-saas-software-webapp-template/19778599?license=regular&open_purchase_for_item_id=19778599&purchasable=source&ref=thethemeio">Purchase Now - $19</a> <a class="btn btn-lg btn-round btn-primary w-250 shadow-3 hidden-md-up" href="https://themeforest.net/item/thesaas-responsive-bootstrap-saas-software-webapp-template/19778599?license=regular&open_purchase_for_item_id=19778599&purchasable=source&ref=thethemeio">Purchase Now - $19</a> <br> <p class="mt-2 mt-md-4"><a href="https://themeforest.net/item/thesaas-responsive-bootstrap-saas-software-webapp-template/19778599?license=extended&open_purchase_for_item_id=19778599&purchasable=source&ref=thethemeio"><small>or purchase an Extended License</small></a></p> </div> <div class="col-12 align-self-end text-center pb-70"> <a class="scroll-down-2 scroll-down-inverse" href="#" data-scrollto="section-demo"><span></span></a> </div> </div> </div></header><!-- END Header --><!-- Main container --><main class="main-content"> <!-- |ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | Sample Landing Pages |ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ !--> <section class="section overflow-hidden" id="section-demo"> <div class="container"> <header class="section-header"> <small>Demo</small> <h2>Sample Landing Pages</h2> <hr> <p class="lead">Apart from internal pages, we have designed several single sample pages to get start with.</p> </header> <div class="row gap-y text-center"> <div class="col-12 col-md-6 col-lg-4" data-aos="fade-up" data-aos-delay="0"> <p><a href="demo-helpato.html"><img class="shadow-2 hover-shadow-5" src="{{url_for('static',filename='assets/img/demo-helpato-sm.jpg')}}" alt="demo helpato landing"></a></p> <p><strong>Helpato</strong></p> </div> <div class="col-12 col-md-6 col-lg-4" data-aos="fade-up" data-aos-delay="150"> <p><a href="demo-trello.html"><img class="shadow-2 hover-shadow-5" src="{{url_for('static',filename='assets/img/demo-trello-sm.jpg')}}" alt="demo helpato landing"></a></p> <p><strong>Trello</strong></p> </div> <div class="col-12 col-md-6 col-lg-4" data-aos="fade-up" data-aos-delay="300"> <p><a href="demo-gmail.html"><img class="shadow-2 hover-shadow-5" src="{{url_for('static',filename='assets/img/demo-gmail-sm.jpg')}}" alt="demo helpato landing"></a></p> <p><strong>Gmail</strong></p> </div> <div class="col-12 col-md-6 col-lg-4" data-aos="fade-up" data-aos-delay="0"> <p><a href="demo-skype.html"><img class="shadow-2 hover-shadow-5" src="{{url_for('static',filename='assets/img/demo-skype-sm.jpg')}}" alt="demo helpato landing"></a></p> <p><strong>Skype</strong></p> </div> <div class="col-12 col-md-6 col-lg-4" data-aos="fade-up" data-aos-delay="150"> <p><a href="demo-github.html"><img class="shadow-2 hover-shadow-5" src="{{url_for('static',filename='assets/img/demo-github-sm.jpg')}}" alt="demo github landing"></a></p> <p><strong>GitHub</strong></p> </div> <div class="col-12 col-md-6 col-lg-4" data-aos="fade-up" data-aos-delay="300"> <p><a href="demo-app.html"><img class="shadow-2 hover-shadow-5" src="{{url_for('static',filename='assets/img/demo-app-sm.jpg')}}" alt="demo app landing"></a></p> <p><strong>Mobile App</strong></p> </div> <div class="col-12 col-md-6 col-lg-4" data-aos="fade-up" data-aos-delay="0"> <p><a href="demo-bootstrap.html"><img class="shadow-2 hover-shadow-5" src="{{url_for('static',filename='assets/img/demo-bootstrap-sm.jpg')}}" alt="demo bootstrap landing"></a></p> <p><strong>Bootstrap</strong></p> </div> <div class="col-12 col-md-6 col-lg-4 hidden-sm-down" data-aos="fade-up" data-aos-delay="150"> <p><a href="demo-slack.html"><img class="shadow-2 hover-shadow-5" src="{{url_for('static',filename='assets/img/demo-slack-sm.jpg')}}" alt="demo slack landing"></a></p> <p><strong>Slack</strong></p> </div> <div class="col-12 col-md-6 col-lg-4 hidden-sm-down" data-aos="fade-up" data-aos-delay="300"> <p><a href="demo-zendesk.html"><img class="shadow-2 hover-shadow-5" src="{{url_for('static',filename='assets/img/demo-zendesk-sm.jpg')}}" alt="demo zendesk landing"></a></p> <p><strong>Zendesk</strong></p> </div> </div> </div> </section></main><!-- END Main container --><!-- Footer --><footer class="site-footer"> <div class="container"> <div class="row gap-y align-items-center"> <div class="col-12 col-lg-3"> <p class="text-center text-lg-left"> <a href="index.html"><img src="{{url_for('static',filename='assets/img/logo.png')}}" alt="logo"></a> </p> </div> <div class="col-12 col-lg-6"> <ul class="nav nav-inline nav-primary nav-hero"> <li class="nav-item"> <a class="nav-link" href="index.html">Home</a> </li> <li class="nav-item"> <a class="nav-link" href="blog.html">Blog</a> </li> <li class="nav-item"> <a class="nav-link" href="page-feature.html">Features</a> </li> <li class="nav-item hidden-sm-down"> <a class="nav-link" href="page-pricing.html">Pricing</a> </li> <li class="nav-item hidden-sm-down"> <a class="nav-link" href="page-contact.html">Contact</a> </li> </ul> </div> <div class="col-12 col-lg-3"> <div class="social text-center text-lg-right"> <a class="social-facebook" href="https://www.facebook.com/thethemeio"><i class="fa fa-facebook"></i></a> <a class="social-twitter" href="https://twitter.com/thethemeio"><i class="fa fa-twitter"></i></a> <a class="social-instagram" href="https://www.instagram.com/thethemeio/"><i class="fa fa-instagram"></i></a> <a class="social-dribbble" href="https://dribbble.com/thethemeio"><i class="fa fa-dribbble"></i></a> </div> </div> </div> </div></footer><!-- END Footer --><!-- Scripts --><script src="{{url_for('static',filename='assets/js/core.min.js')}}"></script><script src="{{url_for('static',filename='assets/js/thesaas.min.js')}}"></script><script src="{{url_for('static',filename='assets/js/script.js')}}"></script> Hello,This is a template which I have modified .. outside flask when I am running this, this works fine ( without url_for ). But when I am trying to use within flask, the javascript files are not working .. please help me
Now provide the response and nothing else.
| You could make it a generator: def mygen(lst): for item in lst: yield item yield item + '_ind'>>> a = ['a','b','c']>>> list(mygen(a))['a', 'a_ind', 'b', 'b_ind', 'c', 'c_ind'] You could also do it with itertools.product , itertools.starmap or itertools.chain or nested comprehensions but in most cases I would prefer a simple to understand, custom generator-function. With python3.3, you can also use yield from βgenerator delegationβto make this elegant solution just a bit more concise: def mygen(lst): for item in lst: yield from (item, item + '_ind') | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45122155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8043394/']} | jdg_381141 |
stackexchange | llm_judgeable_groundtruth_similarity | 832692 |
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 embedding Google Maps into my web site. Once Google Maps is loaded, I need to kick off a few JavaScript processes. Is there a way to auto-detect when Google Maps has fully loaded, including tile downloads and all? A tilesloaded() method exists that is supposed to accomplish exactly this task but it does not work .
Now provide the response and nothing else.
| This was bothering me for a while with GMaps v3. I found a way to do it like this: google.maps.event.addListenerOnce(map, 'idle', function(){ // do something only the first time the map is loaded}); The "idle" event is triggered when the map goes to idle state - everything loaded (or failed to load). I found it to be more reliable then tilesloaded/bounds_changed and using addListenerOnce method the code in the closure is executed the first time "idle" is fired and then the event is detached. See also the events section in the Google Maps Reference. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/832692', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_381142 |
stackexchange | llm_judgeable_groundtruth_similarity | 183882 |
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:
Assume a particle in 3D euclidean space. Its kinetic energy:$$T = \frac{1}{2}m\left(\dot x^2 + \dot y^2 + \dot z^2\right)$$ I need to change to spherical coordinates and find its kinetic energy:$$T = \frac{1}{2}m\left(\dot r^2 + r^2\dot\theta^2 + r^2\sin^2\theta\dot\phi^2\right)$$ Its well known that:$$ x = r\sin\theta\cos\phi \\y = r\sin\theta\sin\phi \\z = r\cos\theta$$ A way of doing it is taking the time derivatives, arriving with $3+3+2=8$ different terms with some squares, then open it arriving at $6+6+3 = 12$ different terms majority of them with 4 sine or cossine multiplications. Then to cancel out some terms somehow to arrive in this neat $3$-term expression for kinetic energy in spherical coordinates. In short, a lot of work just to arrive in a simple expression. Here is my question: Is there a shorter way? Or even better: is there an effortless way?
Now provide the response and nothing else.
| There is an effortless way, if you accept geometrical reasoning. You know, that $T = \frac 1 2 m \vec v^2 = \frac 1 2 m \lvert \vec v \rvert^2$. Furthermore, spherical coordinates are orthogonal, therefore you can just write: $$\lvert \vec v \rvert = \sqrt{v_\phi^2 + v_\theta^2 + v_r^2}$$ Geometrically, one easily finds:$v_r = \dot r$, $v_\theta = r \dot \theta$ and $v_\phi = r \sin(\theta) \dot \phi$. And thus the result: $$\lvert\vec v\rvert = \sqrt{\dot r^2 + r^2 \dot \theta^2 + r^2 \sin^2(\theta) \dot \phi^2}.$$ | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/183882', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/57094/']} | jdg_381143 |
stackexchange | llm_judgeable_groundtruth_similarity | 32365884 |
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 knockoutjs you can output the ViewModel in a nice json format for debugging <pre data-bind="text: ko.toJSON($data, null, 2)"></pre> if there is a way to accomplish the same in Aurelia
Now provide the response and nothing else.
| You could create a custom element. Here's an example: https://gist.run?id=9eea8902521f4523ee2c app.html <template> <require from="./debug"></require> <input value.bind="firstName"> <input value.bind="lastName"> <debug></debug></template> app.js export class App { firstName = 'Donald'; lastName = 'Draper';} debug.html <template> <pre><code>${json}</code></pre></template> debug.js export class Debug { bindingContext = null; updateJson() { if (this.bindingContext === null) { this.json = 'null'; } else if (this.bindingContext === undefined) { this.json = 'undefined' } else { // todo: use a stringify function that can handle circular references. this.json = JSON.stringify(this.bindingContext, null, 2); } } bind(bindingContext) { this.bindingContext = bindingContext; this.updateJson(); this.interval = setInterval(::this.updateJson, 150); } unbind() { this.bindingContext = null; clearInterval(this.interval); }} Result | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32365884', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1592884/']} | jdg_381144 |
stackexchange | llm_judgeable_groundtruth_similarity | 31575784 |
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 replace all double quotes in a file (temp1.txt) with two double quotes using this PowerShell command, run from a bat file in Windows 7: powershell -Command "(gc c:\temp\temp1.txt) -replace '\"', '\"\"' | Out-File -encoding UTF8 c:\temp\temp2.txt" I keep getting the error: 'Out-File' is not recognized as an internal or external command. When I change the command to replace the letter "a" with the letter "b", it works fine like this: powershell -Command "(gc c:\temp\temp1.txt) -replace 'a', 'b' | Out-File -encoding UTF8 c:\temp\temp2.txt" I need to escape the double quote since the entire powershell -Command is within a double quoted string. How do you escape the double quote?
Now provide the response and nothing else.
| Hm, here you need to escape the " on the command line, inside a double quoted string. From my testing, the only thing that seems to work is quadruple double quotes """" inside the quoted parameter: powershell.exe -command "echo '""""X""""'" So then your command line should be: powershell -Command "(gc c:\temp\temp1.txt) -replace '""""', '""""""""' | Out-File -encoding UTF8 c:\temp\temp2.txt" There is another way to handle this with PowerShell, assuming you don't want to just put these commands in a file and call it that way: use -EncodedCommand . This lets you base64 encode your entire command or script and pass it as a single parameter on the command line. So here's your original command: (gc c:\temp\temp1.txt) -replace '"', '""' | Out-File -encoding UTF8 c:\temp\temp2.txt Here's a script to encode it: $c = @"(gc c:\temp\temp1.txt) -replace '"', '""' | Out-File -encoding UTF8 c:\temp\temp2.txt"@$b = [System.Text.Encoding]::Unicode.GetBytes($c)$e = [System.Convert]::ToBase64String($b) $e now contains: KABnAGMAIABjADoAXAB0AGUAbQBwAFwAdABlAG0AcAAxAC4AdAB4AHQAKQAgAC0AcgBlAHAAbABhAGMAZQAgACcAIgAnACwAIAAnACIAIgAnACAAfAAgAE8AdQB0AC0ARgBpAGwAZQAgAC0AZQBuAGMAbwBkAGkAbgBnACAAVQBUAEYAOAAgAGMAOgBcAHQAZQBtAHAAXAB0AGUAbQBwADIALgB0AHgAdAA= So your new command line can be: powershell.exe -encodedCommand KABnAGMAIABjADoAXAB0AGUAbQBwAFwAdABlAG0AcAAxAC4AdAB4AHQAKQAgAC0AcgBlAHAAbABhAGMAZQAgACcAIgAnACwAIAAnACIAIgAnACAAfAAgAE8AdQB0AC0ARgBpAGwAZQAgAC0AZQBuAGMAbwBkAGkAbgBnACAAVQBUAEYAOAAgAGMAOgBcAHQAZQBtAHAAXAB0AGUAbQBwADIALgB0AHgAdAA= There is no need to worry about escaping anything. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31575784', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2847853/']} | jdg_381145 |
stackexchange | llm_judgeable_groundtruth_similarity | 1671040 |
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 replace a bunch of characters in a MySQL field. I know the REPLACE function but that only replaces one string at a time. I can't see any appropriate functions in the manual . Can I replace or delete multiple strings at once? For example I need to replace spaces with dashes and remove other punctuation.
Now provide the response and nothing else.
| You can chain REPLACE functions: select replace(replace('hello world','world','earth'),'hello','hi') This will print hi earth . You can even use subqueries to replace multiple strings! select replace(london_english,'hello','hi') as warwickshire_englishfrom ( select replace('hello world','world','earth') as london_english) sub Or use a JOIN to replace them: select group_concat(newword separator ' ')from ( select 'hello' as oldword union all select 'world') originner join ( select 'hello' as oldword, 'hi' as newword union all select 'world', 'earth') trans on orig.oldword = trans.oldword I'll leave translation using common table expressions as an exercise for the reader ;) | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/1671040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/37947/']} | jdg_381146 |
stackexchange | llm_judgeable_groundtruth_similarity | 11700659 |
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 store a group of objects in a hashmap , where the key shall be a composite of two string values. is there a way to achieve this? i can simply concatenate the two strings , but im sure there is a better way to do this.
Now provide the response and nothing else.
| You could have a custom object containing the two strings: class StringKey { private String str1; private String str2;} Problem is, you need to determine the equality test and the hash code for two such objects. Equality could be the match on both strings and the hashcode could be the hashcode of the concatenated members (this is debatable): class StringKey { private String str1; private String str2; @Override public boolean equals(Object obj) { if(obj != null && obj instanceof StringKey) { StringKey s = (StringKey)obj; return str1.equals(s.str1) && str2.equals(s.str2); } return false; } @Override public int hashCode() { return (str1 + str2).hashCode(); }} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11700659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1203861/']} | jdg_381147 |
stackexchange | llm_judgeable_groundtruth_similarity | 28559 |
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In org-mode is it possible to generate a table, where there is a column which contains a value computed from values in the other columns and which contains the sum of these values? More specifically, at the moment I have a table with seven columns, where the last two columns contain values computed from values in the other columns using the following formula: #+TBLFM: $6=$4-$3;t::$7=$4-$3-$2;t I would like to include the sum of the last column. Is this possible? If yes, how can this be achieved? When I tried to do this I always got zero. Ideally I would like to have the sum somewhere outside of the table or in the last row (even if I add new rows).
Now provide the response and nothing else.
| You should use cell formulas (prefixed by := instead of = ) for your results. The example below gives the sum of the last column both at the first and the last rows. | | | 8 || Col1 | Col2 | Sum ||------+------+-----|| 1 | 3 | 4 || 2 | 8 | 10 || 3 | -9 | -6 ||------+------+-----|| | | 8 |#+TBLFM: $3=$1+$2::@1$3=vsum(@I..@II)::@6$3=vsum(@I..@II) vsum sums a vector of numbers; @I and @II refer to the first and second hlines. | {} | {'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/28559', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/10405/']} | jdg_381148 |
stackexchange | llm_judgeable_groundtruth_similarity | 3758023 |
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 use this square cursor (image below) in the text <input> tags?
Now provide the response and nothing else.
| Sample I've changed how it works , and it seems to solve a few issues :) Accepts any text a normal input can Backspace works Theoretically can support pasting text Usual caveats apply still, most notably the inability to visually see where the caret is. I'd think long and hard whether this solution is worth implementing, based on its drawbacks and usability issues. $(function() { var cursor; $('#cmd').click(function() { $('input').focus(); cursor = window.setInterval(function() { if ($('#cursor').css('visibility') === 'visible') { $('#cursor').css({ visibility: 'hidden' }); } else { $('#cursor').css({ visibility: 'visible' }); } }, 500); }); $('input').keyup(function() { $('#cmd span').text($(this).val()); }); $('input').blur(function() { clearInterval(cursor); $('#cursor').css({ visibility: 'visible' }); });}); #cmd { font-family: courier; font-size: 14px; background: black; color: #21f838; padding: 5px; overflow: hidden;}#cmd span { float: left; padding-left: 3px; white-space: pre;}#cursor { float: left; width: 5px; height: 14px; background: #21f838;}input { width: 0; height: 0; opacity: 0;} <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div id="cmd"> <span></span> <div id="cursor"></div></div><input type="text" name="command" value="" /> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3758023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/244413/']} | jdg_381149 |
stackexchange | llm_judgeable_groundtruth_similarity | 1934184 |
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 $\operatorname{Psym}_n$ be the cone of symmetric positive-definite matrices of size $n \times n$. How to prove the positive square root function $\sqrt{\cdot}:\operatorname{Psym}_n \to \operatorname{Psym}_n$ is uniformly continuous? I am quite sure this is true, since on any compact ball this clearly holds, and far enough from the origin, I think the rate of change should decrease (analogous to the one-dimensional case where $(\sqrt{x})'=\frac{1}{2\sqrt{x}}$ tends to zero when $x \to \infty$). A naive approach is to try to use the mean value inequality: For that we need to show the norm $\|d(\sqrt{\cdot})_A\|$ is bounded for $\|A\|$ large enough. We know the derivative satisfies: $$d(\sqrt{\cdot})_A(B) \cdot \sqrt{A} + \sqrt{A} \cdot (\sqrt{\cdot})_A(B)=B$$ for every $B \in \operatorname{sym}_n$. Thus, $$ \|B\| \le \| d(\sqrt{\cdot})_A(B) \cdot \sqrt{A}\| +\| \sqrt{A} \cdot (\sqrt{\cdot})_A(B) \|\le 2 \| \sqrt{A}\| \| d(\sqrt{\cdot})_A(B)\|,$$ so we only get a bound from below : $$\|d(\sqrt{\cdot})_A\|_{op} \ge \frac{1}{2\|\sqrt{A}\|}$$
Now provide the response and nothing else.
| The cheapest way is to write some representation of the square root in terms of functions whose continuity is obvious. Note that the square root is homogeneous of degree $1/2$, so it suffices to show that if $\|A-B\|\le 1$, then $\|A^{1/2}-B^{1/2}\|\le C$. Now consider the function $$f(x)=\int_0^1\left[1-\frac1{1+tx}\right]t^{-3/2}\,dt$$Making the obvious change of variable $tx=s$, we get $$f(x)=x^{1/2}\int_0^x\frac{s}{1+s}s^{-3/2}\,ds=Kx^{1/2}-x^{1/2}\int_x^\infty\frac{s}{1+s}s^{-3/2}\,ds=Kx^{1/2}+g(x)\,.$$Note that $|g(x)|\le 2$ for all $x>0$. Thus,$$\|KA^{1/2}-f(A)\|\le 2$$for an arbitrary positive definite self-adjoint $A$. Now it will suffice to show that $f$ is "operator Lipschitz", but that is obvious since $$f(A)-f(B)=\int_0^1(1+tA)^{-1}(B-A)(1+tB)^{-1}t^{-1/2}\,dt$$and $\|(1+tX)^{-1}\|\le 1$ for any positive definite self-adjoint $X$ and $t\ge 0$. (The resolvent identity $X^{-1}-Y^{-1}=X^{-1}(Y-X)Y^{-1}$ has been used here, of course). In fact, we can say much more: every $\alpha$-Holder continuous function $F$ is operator Holder continuous ($0<\alpha<1$) on the space of self-adjoint matrices. The Lipschitz case is more subtle, however, and is not fully resolved yet. I know neither how curious you are about all this stuff, nor how much you know already, so I'm stopping here. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1934184', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/104576/']} | jdg_381150 |
stackexchange | llm_judgeable_groundtruth_similarity | 18777396 |
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 following this PHP Google+ tutorial and I am trying to install composer in my WAMP directory C:\wamp\www\gplus-quickstart-php>curl -s https://getcomposer.org/installer | php but I'm getting this error 'php' is not recognized as an internal or external command operable program or batch file. How do I resolve this problem? I already have PHP installed (via WAMP Server). Do I have to install PHP in my computer as well?
Now provide the response and nothing else.
| Ok a couple of things you need to do here. First windows does not have a curl processor like unix so you need to use the other option for installing Composer php -r "eval('?>'.file_get_contents('https://getcomposer.org/installer'));" For this to work you need the php.exe processor to be on your path, so you have 2 options here. Either add the c:\wamp\bin\php\phpx.y.z folder to your PATH thats the bad option for WAMPServer as you can have more than one version of PHP installed and when you activate another version your PATH will still be pointing at the Old version. Or my prefered option write yourself a little .cmd file which will do it for you like this filename = addphp.cmd PATH=%PATH%;c:\wamp\bin\php\phpx.y.z Put this file in a folder already registered on your path so you can run it from anywhere in a command window. Now you will have to edit the \wamp\bin\php\phpx.y.z\php.ini file. This is similiar to the one used by php code run through the Apache web server but is only used by the PHP CLI (Command Line Interpreter) Make sure the extension php_curl is uncommented or the above line wont work i.e. remove the ; comment symbol extension=php_curl.dll So now run a command window, cd into the folder that you want composer installed into and run the command above, then follow the rest of the install instructions on Install instructions | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18777396', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/225998/']} | jdg_381151 |
stackexchange | llm_judgeable_groundtruth_similarity | 43687689 |
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 a portable project so do not have direct access to native code. I have an interface in my project that allows me to access native objects in the Android/iOS projects. We use this primarily for playing audio. Android, for example, has things like Window w = new Window();w.SetFlags(WindowManagerFlags.Fullscreen, WindowManagerFlags.KeepScreenOn); However the main issue would be accessing a Window object. I could pass a Xamarin.Forms.Page object to the native code, but there would be no way (I don't think) to cast it to a native Android Window object to access the flags. Is there a way to do this with a portable project?
Now provide the response and nothing else.
| You can't do this without platform specific services or renderers. A portable project will have to call platform specific code in order to achieve this. From that platform specific code, either as a DependencyService or Renderer , you can access the Window object through the Forms.Context . The Forms.Context is your Android Activity , through which you can reach the Window object. On Android it works like this: Android.Views.Window window = (Forms.Context as Activity).Window;window.SetFlags(WindowManagerFlags.KeepScreenOn); On iOS you can try this ( Apple docs ): UIApplication.SharedApplication.IdleTimerDisabled = true; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43687689', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6475372/']} | jdg_381152 |
stackexchange | llm_judgeable_groundtruth_similarity | 32701107 |
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 google this alot, but unfortunatilty found no working solution. I know its a bad technique, but I need to send user its password by email. I have manage to sent user Hash password, but i am unable to decrypt this password. The following is the procedure i am using. $results = DB::select("select * from dockl_users where email='" . Input::get('email') ."';"); foreach($results as $data){ $password= $data->password; $email= $data->email; } Mail::send('passwordRecovery', array('email' =>$password), function($message) { $message->to(Input::get('email') )->subject('Password Recovery'); }); The above code send Encrypted password to the user by email but when i try to decrypt, it gives me following error message. $decrypt= Crypt::decrypt($data->password); Invalid data. throw new DecryptException("Invalid data."); Kindly guide me how to achieve this..
Now provide the response and nothing else.
| Short answer is that you don't 'decrypt' the password (because it's not encrypted - it's hashed). The long answer is that you shouldn't send the user their password by email, or any other way. If the user has forgotten their password, you should send them a password reset email, and allow them to change their password on your website. Laravel has most of this functionality built in (see the Laravel documentation - I'm not going to replicate it all here. Also available for versions 4.2 and 5.0 of Laravel). For further reading, check out this 'blogoverflow' post: Why passwords should be hashed . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32701107', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4977669/']} | jdg_381153 |
stackexchange | llm_judgeable_groundtruth_similarity | 211436 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In my database, in one of the table I have a GUID column with allow nulls. I have a method with a Guid? parameter that inserts a new data row in the table. However when I say myNewRow.myGuidColumn = myGuid I get the following error: "Cannot implicitly convert type 'System.Guid?' to 'System.Guid'."
Now provide the response and nothing else.
| The ADO.NET API has some problems when it comes to handling nullable value types (i.e. it simply doesn't work correctly). We've had no end of issues with it, and so have arrived at the conclusion that it's best to manually set the value to null, e.g. myNewRow.myGuidColumn = myGuid == null ? (object)DBNull.Value : myGuid.Value It's painful extra work that ADO.NET should handle, but it doesn't seem to do so reliably (even in 3.5 SP1). This at least works correctly. We've also seen issues with passing nullable value types to SqlParameters where the generated SQL includes the keyword DEFAULT instead of NULL for the value so I'd recommend the same approach when building parameters. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/211436', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1360/']} | jdg_381154 |
stackexchange | llm_judgeable_groundtruth_similarity | 55484740 |
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 bundle markdown files without creating much overhead (i.e. not adding them manually to the asset bundles in Xcode and Android Studio, not using 3rd party dependencies). My idea was to allow require() to include them by adjusting the metro bundler settings in metro.config.js : /** * Metro configuration for React Native * https://github.com/facebook/react-native * * @format */module.exports = { transformer: { getTransformOptions: async () => ({ transform: { experimentalImportSupport: false, inlineRequires: false, }, }), }, resolver: { assetExts: [`md`] // < include md }}; Sadly metro bundler replaces the array of given defaults with what's set here. I don't want to explicitly repeat the default asset extension list which lists about 20+ file extensions, especially since I want to stick to the defaults otherwise. See: https://github.com/facebook/metro/blob/master/packages/metro-config/src/defaults/defaults.js . Appending to the array does not work, too. Using RN 0.59.3. Anything I'm missing?
Now provide the response and nothing else.
| Found the answer on how to include the defaults here: https://stackoverflow.com/a/55118654/844907 . /** * Metro configuration for React Native * https://github.com/facebook/react-native * * @format */// get defaults assetExts arrayconst defaultAssetExts = require("metro-config/src/defaults/defaults").assetExts;module.exports = { transformer: { getTransformOptions: async () => ({ transform: { experimentalImportSupport: false, inlineRequires: false, }, }), }, resolver: { assetExts: [ ...defaultAssetExts, // <- array spreading defaults 'md' ] }}; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55484740', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/844907/']} | jdg_381155 |
stackexchange | llm_judgeable_groundtruth_similarity | 4117565 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a question that is driving me crazy. I have a large number of buttons (10, more or less) on my screen, inside a TableRow. I need to access them, and I had planned to perform through a loop. Access to one, is very easy, adding this: boton7 = (Button) findViewById (R.id.Btn7) My question is, if you can dynamically set the id string (R.id.Btn7) to put in a can get the buttons for, and for example, change the color .... something like this: for (int i = 0; i <10; i + +) { Button eachBoton= (Button) findViewById (R.id.Btn + i); eachBoton. setBackgroundColor (Color.Red);} That, of course, does not work .... my question is if anyone knows how exactly the chain can be mounted R.id.Btn + i to work. Thanks a lot.
Now provide the response and nothing else.
| You can use Resources#getIdentifier() to get a resource identifier for the given resource name: int resourceId = getResources().getIdentifier( "Btn"+i, "id", this.getContext().getPackageName());Button button = (Button) findViewById(resourceId); Alternately you can prepare an array with all the ids you need and access elements of that array. This is more efficient: private final int[] btns = {R.id.btn1, R.id.btn2, R.id.btn3, R.id.btn4, ...}...Button button = (Button) findViewById(btns[i]); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4117565', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/499804/']} | jdg_381156 |
stackexchange | llm_judgeable_groundtruth_similarity | 50363220 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How do I model my mongoose schema to get these three buttons when I am on the other users profile? Add Friend Requested Friends My users schema const schema = new Mongoose.Schema({ firstName: { type: String, default: '', trim: true }, lastName: { type: String, default: '', trim: true },}, { timestamps: true }) I could not find the correct modelling for this... And also please suggest the aggregation after modelling...
Now provide the response and nothing else.
| So Finally I made it and I think it is probably the best way to do it with mongodb and mongoose 1. Create a model for users. var Schema = mongoose.Schema const usersSchema = new Schema({ firstName: { type: String, required: true }, lastName: { type: String, required: true }, friends: [{ type: Schema.Types.ObjectId, ref: 'Friends'}] }, {timestamps: true}) module.exports = mongoose.model('Users', usersSchema) 2. Create a model for friends having enums for accepted, rejected, pending and requested. const friendsSchema = new Schema({ requester: { type: Schema.Types.ObjectId, ref: 'Users'}, recipient: { type: Schema.Types.ObjectId, ref: 'Users'}, status: { type: Number, enums: [ 0, //'add friend', 1, //'requested', 2, //'pending', 3, //'friends' ] } }, {timestamps: true}) module.exports = mongoose.model('Friends', friendsSchema) 3. Now api calls --> Lets say we have two users UserA and UserB... So when UserA requestes UserB to be a friends at that time we make two documents so that UserA can see requested and UserB can see pending and at the same time we push the _id of these documents in user's friends const docA = await Friend.findOneAndUpdate( { requester: UserA, recipient: UserB }, { $set: { status: 1 }}, { upsert: true, new: true } ) const docB = await Friend.findOneAndUpdate( { recipient: UserA, requester: UserB }, { $set: { status: 2 }}, { upsert: true, new: true } ) const updateUserA = await User.findOneAndUpdate( { _id: UserA }, { $push: { friends: docA._id }} ) const updateUserB = await User.findOneAndUpdate( { _id: UserB }, { $push: { friends: docB._id }} ) 4. If UserB acceptes the request Friend.findOneAndUpdate( { requester: UserA, recipient: UserB }, { $set: { status: 3 }} ) Friend.findOneAndUpdate( { recipient: UserA requester: UserB }, { $set: { status: 3 }} ) 5. If UserB rejectes the request const docA = await Friend.findOneAndRemove( { requester: UserA, recipient: UserB } ) const docB = await Friend.findOneAndRemove( { recipient: UserA, requester: UserB } ) const updateUserA = await User.findOneAndUpdate( { _id: UserA }, { $pull: { friends: docA._id }} ) const updateUserB = await User.findOneAndUpdate( { _id: UserB }, { $pull: { friends: docB._id }} ) 6. Get all friends and check whether the logged in user is friend of that user or not User.aggregate([ { "$lookup": { "from": Friend.collection.name, "let": { "friends": "$friends" }, "pipeline": [ { "$match": { "recipient": mongoose.Types.ObjectId("5afaab572c4ec049aeb0bcba"), "$expr": { "$in": [ "$_id", "$$friends" ] } }}, { "$project": { "status": 1 } } ], "as": "friends" }}, { "$addFields": { "friendsStatus": { "$ifNull": [ { "$min": "$friends.status" }, 0 ] } }}]) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/50363220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7510657/']} | jdg_381157 |
stackexchange | llm_judgeable_groundtruth_similarity | 6351271 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a simple question about Backbone.js' get and set functions. 1) With the code below, how can I 'get' or 'set' obj1.myAttribute1 directly? Another question: 2) In the Model, aside from the defaults object, where can/should I declare my model's other attributes, such that they can be accessed via Backbone's get and set methods? var MyModel = Backbone.Model.extend({ defaults: { obj1 : { "myAttribute1" : false, "myAttribute2" : true, } }})var MyView = Backbone.View.extend({ myFunc: function(){ console.log(this.model.get("obj1")); //returns the obj1 object //but how do I get obj1.myAttribute1 directly so that it returns false? }}); I know I can do: this.model.get("obj1").myAttribute1; but is that good practice?
Now provide the response and nothing else.
| While this.model.get("obj1").myAttribute1 is fine, it's a bit problematic because then you might be tempted to do the same type of thing for set, i.e. this.model.get("obj1").myAttribute1 = true; But if you do this, you won't get the benefits of Backbone models for myAttribute1 , like change events or validation. A better solution would be to never nest POJSOs ("plain old JavaScript objects") in your models, and instead nest custom model classes. So it would look something like this: var Obj = Backbone.Model.extend({ defaults: { myAttribute1: false, myAttribute2: true }});var MyModel = Backbone.Model.extend({ initialize: function () { this.set("obj1", new Obj()); }}); Then the accessing code would be var x = this.model.get("obj1").get("myAttribute1"); but more importantly the setting code would be this.model.get("obj1").set({ myAttribute1: true }); which will fire appropriate change events and the like. Working example here: http://jsfiddle.net/g3U7j/ | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6351271', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/773694/']} | jdg_381158 |
stackexchange | llm_judgeable_groundtruth_similarity | 60006406 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was trying to make a little program where you can input a number and it would be displayed on the screen. The problem is, whenever I type in a number it gives me either a NumberFormatException or another Exception... and I don't know what to do, I tried doing it in a method with try{} and catch{} where I said int i = Integer.parseInt(String); and I also tried to do that directly but none of it worked. //in "Window" class public void actionPerformed(ActionEvent e) { else if(e.getSource() == submit) { Lines.drawPointLine(null); } } //in "Lines" class public static void drawPointLine(Graphics g) { if(pointPosX == 0) { int i; g.drawLine(30, 490, 60, convertPointPos(i = Integer.parseInt(window.enterpoint.getText()))); } } public static int convertPointPos(int point) { int s = (int) (point * 0.46); int retpoint = 490 - s; System.out.println(retpoint); return retpoint; } Here is the code where I tried to convert it directly but it still gives me an Exception and I don't know what to do...
Now provide the response and nothing else.
| Oh, it is not clear from docs, that 'this' refers to document only in document #deleteOne. So, the correct usage of 'deleteOne' hook is: In model: DocSchema.pre('deleteOne', { document: true }, function(next) { console.log(this) next()}) later in code (in controller, etc): const doc = await DocModel.findOne({ name: 'myDoc' })await doc.deleteOne() Now 'this' refers to the document | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60006406', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/12819936/']} | jdg_381159 |
stackexchange | llm_judgeable_groundtruth_similarity | 5741247 |
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 carefully read about rainbow tables and can't get one thing. In order to build a hash chain a reduction function is used. It's a function that somehow maps hashes onto passwords. This article says that reduction function isn't an inverse of hash, it's just some mapping . I don't get it - what's the use of a mapping that isn't even an inverse of the hash function? How should such mapping practically work and aid in deducing a password?
Now provide the response and nothing else.
| A rainbow table is "just" a smart compression method for a big table of precomputed hashes. The idea is that the table can "invert" a hash output if and only if a corresponding input was considered during the table construction. Each table line ("chain") is a sequence of hash function invocations. The trick is that each input is computed deterministically from the previous output in the chain, so that: by storing the starting and ending points of the chain, you "morally" store the complete chain, which you can rebuild at will (this is where a rainbow table can be viewed as a compression method); you can start the chain rebuilding from a hash function output. The reduction function is the glue which turns a hash function output into an appropriate input (for instance a character string which looks like a genuine password, consisting only of printable characters). Its role is mostly to be able to generate possible hash inputs with more or less uniform probability, given random data to work with (and the hash output will be acceptably random). The reduction function needs not have any specific structure, in particular with regards to how the hash function itself works; the reduction function must just allow keeping on building the chain without creating too many spurious collisions. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5741247', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/57428/']} | jdg_381160 |
stackexchange | llm_judgeable_groundtruth_similarity | 34367315 |
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 rendered the normal text with jquery date rule. The date rule working fine in chrome but not working in the Firefox and IE . please see my code block. <form id="myform"> <input id="datepick" type="text" name ="datepick"/> <input type="submit" id="ValidateDate" /></form> $("#myform").validate({ rules: { datepick:{ date:"MM/dd/yyyy" } }, messages: { datepick:{ date:"Give MM/dd/yyyy format" } } }); $('#datepick').keyup(function () { $("#ValidateDate").submit(); });</script> when i type 12/3err/3001 it throws error in all browser when i type 12/234/2333 it throws error chrome not in firefox and IE. Additionally i want to share one information. http://jqueryvalidation.org/date-method/ In the above link jQuery validation is not working properly in Mozilla , IE browser even for a normal textbox. please type the 22/233/2222 value in the above jquery link sample then you can find the below output variation In chrome : In Firefox: Please help me to resolve this..... Thanks, Gobalakrishnan
Now provide the response and nothing else.
| There are many ways to handle this situation, I do not recommend Jozemite Apps answer, because this will cause problems on apps with more than 1 view controller.(you want to present the alert on the current view controller, not the root) My preferred way of doing it is through delegation.What needs to be done is create a protocol to handle messaging: import Foundationprotocol ViewControllerDelegate{ func sendMessage(message:String);} In your view controller: class ViewController : UIViewController, ViewControllerDelegate{ ... func sendMessage(message:String) { //do alert view code here } //in the view controllers view did load event func viewDidLoad() { var view = self.view as! GameSceneView view.delegate = self } In your view code: var delegate : ViewControllerDelegate Finally in game scene where you want to present: self.view.delegate?.sendMessage(message) This way allows limited access to the VC, and can be modified with more options when needed. Another way is to set up a notification system, and use NSNotificationCenter to pass a message from the scene to the current VC and have it send a message; in ViewController func viewDidLoad(){ NSNotificationCenter.defaultCenter().addObserver(self,selector:"AlertMessage:",name:"AlertMessage",object:nil);}func AlertMessage(notification:NSNotification){ if(let userInfo = notification.userInfo) { let message = userInfo["message"] ....//do alert view call here }} In Game scene code: ...at the spot you want to send a messagelet userInfo = ["message":message];NSNotificationCenter.defaultCenter.postNotificationNamed("AlertMessage",object:nil,userInfo:userInfo) Another approach is to save the view controller pointer to game scene view: //in Game Scene View codevar viewController : UIViewController; //in the view controllers view did load eventfunc viewDidLoad(){ var view = self.view as! GameSceneView view.viewController = self}//finally in game scene where you want to presentlet myAlert: UIAlertController = UIAlertController(title: "Alert!", message: "Oh! Fancy", preferredStyle: .Alert)myAlert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))self.view.viewController.presentViewController(myAlert, animated: true, completion: nil) Yet another way is to make your view controller global. In view controller code: private var _instance : UIViewController class ViewController : UIViewController{ class var instance { get { return _instance; } } func viewDidLoad() { _instance = self; }} Then just call ViewController.instance!. whenever you need access to your view controller. Each of these methods have there strengths and weaknesses, so choose whatever way works best for you. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34367315', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3952615/']} | jdg_381161 |
stackexchange | llm_judgeable_groundtruth_similarity | 4149 |
Below is a question asked on the forum reverseengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to learn reverse engineering so I was starting to try compiling simple (to start with) C programs and then reading the disassembly. The following file int main(void) { return 0;} compiled with gcc then disassembled with objdump -d ends up creating 172 lines of output. I don't understand why there is so much output. What is the meaning of the different sections: 0000000000400370 <_init>:0000000000400390 <__libc_start_main@plt-0x10>:00000000004003a0 <__libc_start_main@plt>:00000000004003b0 <__gmon_start__@plt>:00000000004003c0 <_start>:00000000004003f0 <deregister_tm_clones>:0000000000400420 <register_tm_clones>:0000000000400460 <__do_global_dtors_aux>:0000000000400480 <frame_dummy>:00000000004004ad <main>:00000000004004c0 <__libc_csu_init>:0000000000400530 <__libc_csu_fini>:0000000000400534 <_fini>: Of course I have been reading about the calling convention and opcodes so I can see how the section corresponds to the C code.
Now provide the response and nothing else.
| I see you're mixing up sections with functions. What you have provided in your question are functions necessary to an ELF binary to execute. For example, the _start function is usually the entry point of a binary and it will probably call the main function at some point. You can get the address of the entry of a binary using readelf -h on the binary file you have. About the output, though your program is "empty" it was still compiled & linked successfully - for that it is not erroneous - into an executable ELF. This document provides everything you need to know about how an ELF binary is structured & how to manipulate it : ELF Format (PDF). Now if you want to retrieve section information in a binary file the readelf function can again help with that, you just have to call it with the -S and the target binary file ( readelf -S prog ). Since you're just starting to learn, I recommend you checking the binutils ( readelf , objdump , ...) and their related documentation and start playing with simple programs before moving to crackmes and more advanced or obfuscated binary files. | {} | {'log_upvote_score': 4, 'links': ['https://reverseengineering.stackexchange.com/questions/4149', 'https://reverseengineering.stackexchange.com', 'https://reverseengineering.stackexchange.com/users/4425/']} | jdg_381162 |
stackexchange | llm_judgeable_groundtruth_similarity | 264234 |
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:
Why are there no "even" harmonics in AC machines?In Chapman's book, he says it's because of symmetry of the flux density wave but I don't get it...
Now provide the response and nothing else.
| You know that a square wave with perfect symmetry has NO EVEN harmonics. (typo fixed) You can imagine if a magnetic material had a "hard saturation" limit instead of a "Landau"? curve with hysteresis, you would get a square wave current for a sine wave voltage. Thus all the current is fundamental & odd harmonics. But with a symmetrical soft saturation curve the harmonics are attenuated. The harmonics increase as the current enters the soft saturation region, yet still remain ODD multiples as long as the non-linear soft saturation curve is symmetrical . Thus the only time you would get even harmonics in a magnetic material is if there was remanence such as from DC bias. Then the voltage swing produces more asymmetrical current and no longer is a symmetrical soft square wave but asymmetrical even harmonic producing fourier components of the distorted waveform. Then the apparent inductance drops quickly and is usually rated for -10% at rated DC or ac current. Normally large transformers experience remenance from abrupt disconnects and flux leakage resistance balances the current after several seconds which is apparent by the hum of large MVA transformers during reconnect. This is why "smart reclosures" remember the phase of disconnect and reclose at exactly the same phase to minimize Remenance and saturation currents that produce many forces inside transformers and even harmonics. To visualize fourier components with a hand-drawn waveform or std. waveform try this java app. then choose boxes for mag/phase and log view and change the frequency spikes with mouse and see the effects on time domain signal. Note the absence of even harmonics in both a square wave and a triangle wave but the phase is different in each harmonic. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/264234', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/72683/']} | jdg_381163 |
stackexchange | llm_judgeable_groundtruth_similarity | 36274089 |
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 building an API in Yii2 and have added CORS and authentication. This works fine for all Create/Read/Update/Delete actions but not for custom actions. Has anyone experienced this before? URL manager: ['class' => 'yii\rest\UrlRule', 'controller' => 'api/v1/user', 'pluralize' => false], Controller behaviors: public function behaviors(){ return ArrayHelper::merge([ 'corsFilter' => [ 'class' => Cors::className(), ], [ 'class' => HttpBearerAuth::className(), 'except' => ['options', 'login', ], ], ], parent::behaviors() );} As mentioned, actions for CRUD are fine but a custom action such as http://domain.com/user/test will respond with a 401 Unauthorised response. Is it not possible to get CORS and auth to work together on custom actions? Edit: I should add that the issue (401) occurs only when a browser makes the OPTIONS request. Normal requests (curl,Postman) are not affected. The issue seems to occur with the RESTful,Cors,Auth combination.
Now provide the response and nothing else.
| try this: public function behaviors(){ $behaviors = parent::behaviors(); unset($behaviors['authenticator']); $behaviors['corsFilter'] = [ 'class' => Cors::className(), 'cors' => [ 'Origin' => ['*'], 'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'], 'Access-Control-Request-Headers' => ['*'], 'Access-Control-Allow-Credentials' => true, ], ]; $behaviors['authenticator'] = [ 'class' => HttpBearerAuth::className(), 'except' => ['options','login'], ]; return $behaviors;} It will unset the default authenticator implemented by the parent controller to be sure that cors is treated first. Then we force cors to allow credentials before implementing your own authenticator . The other thing that may raise that Unauthorized error is a not-found or wrong Options response as a browser request it first to get a list of allowed verbs. You may check that list in its headers response within your browser's network tab. The general rule is when you ask your browser to perform a sensible verb like PUT, DELETE or POST to any url it may first send an OPTIONS request to that same url ( check this ) to check if that verb is allowed before sending the real request. So Yii should be configured to respond to all those OPTIONS verbs by performing the correct redirections. The default CRUD actions implemented by ActiveController are using those default patterns : 'PUT,PATCH {id}' => 'update','DELETE {id}' => 'delete','GET,HEAD {id}' => 'view','POST' => 'create','GET,HEAD' => 'index','{id}' => 'options','' => 'options', So whatever configurations you did implement in urlManager['rules'] be sure to not override the last 2 of them and if you are using custom patterns always remember to include its equivalent options verbs like in this example: [ 'class' => 'yii\rest\UrlRule', 'controller' => ['account' => 'auth/account'], 'patterns' => [ 'POST,HEAD login' => 'login', 'POST,HEAD signup' => 'signup', 'POST req-reset-pass' => 'request-password-reset', 'POST reset-pass' => 'reset-password', // OPTTIONS VERBS 'OPTIONS login' => 'options', 'OPTIONS signup' => 'options', 'OPTIONS req-reset-pass' => 'options', 'OPTIONS reset-pass' => 'options', ]], The same applies when adding custom patterns within extraPatterns . The Options action is implemented by default in ActiveController . it's code can be seen here . In case you are extending a different controller than ActiveController like maybe \yii\rest\Controller be sure to manually include it: public function actions() { $actions = parent::actions(); $actions['options'] = [ 'class' => 'yii\rest\OptionsAction', // optional: 'collectionOptions' => ['GET', 'POST', 'HEAD', 'OPTIONS'], 'resourceOptions' => ['GET', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'], ]; return $actions;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36274089', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1647948/']} | jdg_381164 |
stackexchange | llm_judgeable_groundtruth_similarity | 50753477 |
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 following the PyTorch tutorial here .It says that x = torch.randn(3, requires_grad=True)y = x * 2while y.data.norm() < 1000: y = y * 2print(y)Out: tensor([-590.4467, 97.6760, 921.0221]) Could someone explain what data.norm() does here?When I change .randn to .ones its output is tensor([ 1024., 1024., 1024.]) .
Now provide the response and nothing else.
| It's simply the L2 norm (a.k.a Euclidean norm) of the tensor. Below is a reproducible illustration: In [15]: x = torch.randn(3, requires_grad=True)In [16]: y = x * 2In [17]: y.dataOut[17]: tensor([-1.2510, -0.6302, 1.2898])In [18]: y.data.norm()Out[18]: tensor(1.9041)# computing the norm using elementary operationsIn [19]: torch.sqrt(torch.sum(torch.pow(y, 2)))Out[19]: tensor(1.9041) Explanation : First, it takes a square of every element in the input tensor x , then it sums them together, and finally it takes a square root of the resulting sum. All in all, these operations compute the so-called L2 or Euclidean norm . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50753477', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6002424/']} | jdg_381165 |
stackexchange | llm_judgeable_groundtruth_similarity | 9509002 |
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 form that functions as a settings page. When form elements are modified, they are marked as unsaved and have a different border color. When the form is saved, they are marked as saved by having another border color. What I want is that when the form is saved, the border will gradually fade out. The order will go: <input type='text' class='unsaved' /> Not saved yet, border is yellow<input type='text' class='saved' /> Saved, so the border is green<input type='text' class='' /> Fade out if coming from class saved If I can get a CSS3 transition to fire when the class saved is removed, then it could fade out and everything would be hunky-dory. Currently, I have to manually animate it (using a plug-in, of course), but it looks choppy, and I would like to move the code to CSS3 so it will be smoother. I only need this to work in Chrome and Firefox 4+, though others would be nice. CSS: Here's the associated CSS: .unsaved { border: 3px solid #FFA500; padding: 0;}.saved { border: 3px solid #0F0; padding: 0;} I would like to work in the following transition (or something like it): border-color: rgba(0,0,0,0);-webkit-transition: border-color .25s ease-in; -moz-transition: border-color .25s ease-in; -o-transition: border-color .25s ease-in; transition: border-color .25s ease-in; Note: Personally, I don't agree with this scheme of user interaction, but that's how our software lead wants it. Please don't suggest that I change the way it functions currently. Thanks!
Now provide the response and nothing else.
| CSS transitions work by defining two states for the object using CSS. In your case, you define how the object looks when it has the class "saved" and you define how it looks when it doesn't have the class "saved" (it's normal look). When you remove the class "saved" , it will transition to the other state according to the transition settings in place for the object without the "saved" class. If the CSS transition settings apply to the object (without the "saved" class), then they will apply to both transitions. We could help more specifically if you included all relevant CSS you're using to with the HTML you've provided. My guess from looking at your HTML is that your transition CSS settings only apply to .saved and thus when you remove it, there are no controls to specify a CSS setting. You may want to add another class ".fade" that you leave on the object all the time and you can specify your CSS transition settings on that class so they are always in effect. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9509002', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/538551/']} | jdg_381166 |
stackexchange | llm_judgeable_groundtruth_similarity | 2724594 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The random variable $X_i$ indicates whether in a basketball game the $i$-th free throw is hit ($X_i = 1$) or not ($X_i = 0$).$10$ free throws are executed, so that $i = 1,\ldots 10$.It holds that $P(X_i=0)=0,3$ and $P(X_i=1)=0,7$. X denotes the sum of these ten independent random variables: $X = \sum_{i=1}^{10}X_i$. (a) Determine $P (X = 8)$. What does this probability mean in terms of content? (b) What is the probability that the number of hits is at most five? (c) Which number of hits can we expect on average? $$$$ (a) Does it hold that $P(X=8)=0,3^2\cdot 0,7^8=0.0051883209$ ? That would mean that the probability that 8 of 10 free throws were successful is equal to $0,5\%$. Is this correct? (b) We want to calculate the probability $P(X\geq 5)$, which is equal to $P(X=1)+P(X=2)+P(X=3)+P(X=4)+P(X=5)=0,3^9\cdot 0,7^1+0,3^8\cdot 0,7^2+0,3^7\cdot 0,7^3+0,3^6\cdot 0,7^4+0,3^5\cdot 0,7^5=0.0007043841$, or not? (c) We are asked to calculate the expected value, aren't we? Is this equal to $$E(X)=\sum_{i=1}^{10}x_i\cdot P(X=x_i)\\ =1\cdot P(X=1)+2\cdot P(X=2)+3\cdot P(X=3)+\ldots 9\cdot P(X=9)+10\cdot P(X=10)$$ or not?
Now provide the response and nothing else.
| (a) Your calculation of P(X = 8) is erroneous. You failed to consider the fact that $0,3^2β
0,7^8$ only considers 1 case of 8 hits and 2 misses. e.g. HHHHHHHHMM. In fact, there are $\frac{10!}{2!8!}$ cases (using combinatorics), leading to $\frac{10!}{2!8!}*(0,3^2β
0,7^8)$ being the correct solution for P(X=8). Your definition of the probability is also a bit vague. I would phrase it in this way "the probability that 8 of 10 free throws were successfully hit" (b) You have misinterpreted the question. The number of hits is at most 5, so X should be at most 5. Hence, we should find the $P(X\le 5)$. You would have to use a Binomial Distribution for this. There are 10 independent free throws, with a P(successful hit) = $P(X_i=1)$ = 0.7. Hence, X~B(10,0.7). You can use a calculator or Excel to find $P(X\le 5)$ from there. (BinomCDF) (c) E(X) = np for a Binomial Distribution. In this case, E(X) = 10 * 0.7 = 7. For a more comprehensive answer, we can use the general formula E(X) = $\sum_{i=1}^{10} x_ip_i$. Find all the $P(X=x_i)$ and mutiply it with all the corresponding $x_i$ values. Sum the product up to find E(X). Hope this helps. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2724594', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/80708/']} | jdg_381167 |
stackexchange | llm_judgeable_groundtruth_similarity | 613616 |
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:
Hi i wanted to ask what causes an offset for the following integrator setup: I ` m no sure if its the virtual ground or another fundamental reason im not aware about since the signal should always be biased at 0V. If someone could help that would great thanks!
Now provide the response and nothing else.
| The actual issue is that LTspice assumes the wrong value for its initial conditions. You need to remember that the current in an inductor is 90Β° out of phase with the voltage across it (ignoring the effect of the ESR of the inductor for the moment). Therefore, when voltage across it is zero, the current will be non-zero. LTspice starts it zero, which can't be correct. In the simple case of your schematic, you can calculate when the initial current should be, and initialise the inductor current to that. Add the following to your schematic to correctly initialise the inductor current, and then it all behaves as expected. .param Iinit 1/(2 * pi * 1k)/10m .ic I(L1)={Init} | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/613616', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/237893/']} | jdg_381168 |
stackexchange | llm_judgeable_groundtruth_similarity | 576908 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can the following be accomplished in Magento? Display a "Hello World" message using a controller/view/model approach. So, if I went to http://example.com/myController it would show the string 'Hello World'. Being able to show this string within the template of my website (for example, the header, footer, etc.) will be a bonus. How do I add a method to this controller (or a new controller if necessary), which interacts with a model, and performs the query Select * FROM articles where id='10' and returns the row (containing the columns id, title, content ) to the controller? And then use the controller to include a view, which would display this row. So going to http://example.com/myController/show_row (or something similar) would display the row within a view. (No need to be fancy, just a echo $row->id; or something similar would work.) Any other information about Magento's code structure will also be very helpful.
Now provide the response and nothing else.
| First and foremost, I highly recommend you buy the PDF/E-Book from PHP Architect . It's US$20, but is the only straightforward "Here's how Magento works" resource I've been able to find. I've also started writing Magento tutorials at my own website . Second, if you have a choice, and aren't an experienced programmer or don't have access to an experienced programmer (ideally in PHP and Java), pick another cart . Magento is well engineered, but it was engineered to be a shopping cart solution that other programmers can build modules on top of. It was not engineered to be easily understood by people who are smart, but aren't programmers. Third, Magento MVC is very different from the Ruby on Rails , Django , CodeIgniter , CakePHP , etc. MVC model that's popular with PHP developers these days. I think it's based on the Zend model, and the whole thing is very Java OOP-like. There's two controllers you need to be concerned about. The module/frontName controller, and then the MVC controller. Fourth, the Magento application itself is built using the same module system you'll be using, so poking around the core code is a useful learning tactic. Also, a lot of what you'll be doing with Magento is overriding existing classes. What I'm covering here is creating new functionality, not overriding. Keep this in mind when you're looking at the code samples out there. I'm going to start with your first question, showing you how to setup a controller/router to respond to a specific URL. This will be a small novel. I might have time later for the model/template related topics, but for now, I don't. I will, however, briefly speak to your SQL question. Magento uses an EAV database architecture. Whenever possible, try to use the model objects the system provides to get the information you need. I know it's all there in the SQL tables, but it's best not to think of grabbing data using raw SQL queries, or you'll go mad. Final disclaimer. I've been using Magento for about two or three weeks, so caveat emptor. This is an exercise to get this straight in my head as much as it is to help StackΒ Overflow. Create a module All additions and customizations to Magento are done through modules. So, the first thing you'll need to do is create a new module. Create an XML file in app/modules named as follows cd /path/to/store/apptouch etc/modules/MyCompanyName_HelloWorld.xml <?xml version="1.0"?><config> <modules> <MyCompanyName_HelloWorld> <active>true</active> <codePool>local</codePool> </MyCompanyName_HelloWorld> </modules></config> MyCompanyName is a unique namespace for your modifications, it doesn't have to be your company's name, but that the recommended convention my magento. HelloWorld is the name of your module. Clear the application cache Now that the module file is in place, we'll need to let Magento know about it (and check our work). In the admin application Go to System->Cache Management Select Refresh from the All Cache menu Click Save Cache settings Now, we make sure that Magento knows about the module Go to System->Configuration Click Advanced In the "Disable modules output" setting box, look for your new module named "MyCompanyName_HelloWorld" If you can live with the performance slow down, you might want to turn off the application cache while developing/learning. Nothing is more frustrating then forgetting the clear out the cache and wondering why your changes aren't showing up. Setup the directory structure Next, we'll need to setup a directory structure for the module. You won't need all these directories, but there's no harm in setting them all up now. mkdir -p app/code/local/MyCompanyName/HelloWorld/Blockmkdir -p app/code/local/MyCompanyName/HelloWorld/controllersmkdir -p app/code/local/MyCompanyName/HelloWorld/Modelmkdir -p app/code/local/MyCompanyName/HelloWorld/Helpermkdir -p app/code/local/MyCompanyName/HelloWorld/etcmkdir -p app/code/local/MyCompanyName/HelloWorld/sql And add a configuration file touch app/code/local/MyCompanyName/HelloWorld/etc/config.xml and inside the configuration file, add the following, which is essentially a "blank" configuration. <?xml version="1.0"?><config> <modules> <MyCompanyName_HelloWorld> <version>0.1.0</version> </MyCompanyName_HelloWorld> </modules></config> Oversimplifying things, this configuration file will let you tell Magento what code you want to run. Setting up the router Next, we need to setup the module's routers. This will let the system know that we're handling any URLs in the form of http://example.com/magento/index.php/helloworld So, in your configuration file, add the following section. <config><!-- ... --> <frontend> <routers> <!-- the <helloworld> tagname appears to be arbitrary, but by convention is should match the frontName tag below--> <helloworld> <use>standard</use> <args> <module>MyCompanyName_HelloWorld</module> <frontName>helloworld</frontName> </args> </helloworld> </routers> </frontend><!-- ... --></config> What you're saying here is "any URL with the frontName of helloworld ... http://example.com/magento/index.php/helloworld should use the frontName controller MyCompanyName_HelloWorld". So, with the above configuration in place, when you load the helloworld page above, you'll get a 404 page. That's because we haven't created a file for our controller. Let's do that now. touch app/code/local/MyCompanyName/HelloWorld/controllers/IndexController.php Now try loading the page. Progress! Instead of a 404, you'll get a PHP/Magento exception Controller file was loaded but class does not exist So, open the file we just created, and paste in the following code. The name of the class needs to be based on the name you provided in your router. <?phpclass MyCompanyName_HelloWorld_IndexController extends Mage_Core_Controller_Front_Action{ public function indexAction(){ echo "We're echoing just to show that this is what's called, normally you'd have some kind of redirect going on here"; }} What we've just setup is the module/frontName controller. This is the default controller and the default action of the module.If you want to add controllers or actions, you have to remember that the tree first part of a Magento URL are immutable they will always go this way http://example.com/magento/index.php/frontName/controllerName/actionName So if you want to match this url http://example.com/magento/index.php/helloworld/foo You will have to have a FooController, which you can do this way : touch app/code/local/MyCompanyName/HelloWorld/controllers/FooController.php <?phpclass MyCompanyName_HelloWorld_FooController extends Mage_Core_Controller_Front_Action{ public function indexAction(){ echo 'Foo Index Action'; } public function addAction(){ echo 'Foo add Action'; } public function deleteAction(){ echo 'Foo delete Action'; }} Please note that the default controller IndexController and the default action indexAction can by implicit but have to be explicit if something come after it.So http://example.com/magento/index.php/helloworld/foo will match the controller FooController and the action indexAction and NOT the action fooAction of the IndexController. If you want to have a fooAction, in the controller IndexController you then have to call this controller explicitly like this way : http://example.com/magento/index.php/helloworld/index/foo because the second part of the url is and will always be the controllerName.This behaviour is an inheritance of the Zend Framework bundled in Magento. You should now be able to hit the following URLs and see the results of your echo statements http://example.com/magento/index.php/helloworld/foohttp://example.com/magento/index.php/helloworld/foo/addhttp://example.com/magento/index.php/helloworld/foo/delete So, that should give you a basic idea on how Magento dispatches to a controller. From here I'd recommended poking at the existing Magento controller classes to see how models and the template/layout system should be used. | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/576908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/49153/']} | jdg_381169 |
stackexchange | llm_judgeable_groundtruth_similarity | 50862192 |
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 create a click event be able to delete an item on my list, but when I click it I get "TypeError: Cannot read property 'props' of undefined". I'm trying to stick to ES6 as much as possible, and I'm pretty sure its something to do binding 'this' somewhere, but I've tried many places and been unsuccessful. import React, { Component } from 'react';import './App.css';class App extends Component { render() { return ( <div className="App"> <StreetFighter /> </div> ); }}class StreetFighter extends Component { constructor(props) { super(props); this.state = { characters: [ 'Chun-Li', 'Guile', 'Ryu', 'Ken', 'E.Honda', 'Dhalsim', ], }; } render() { let characters = this.state.characters; characters = characters.map((char, index) => { return ( <Character char={char} key={index} onDelete={this.onDelete} /> ); }); return ( <div> <p>Street Fighter Characters</p> <ul>{characters}</ul> </div> ); } onDelete(chosenCharacter) { let updatedCharactersList = this.state.characters.filter( (char, index) => { return chosenCharacter !== char; } ); this.setState({ characters: updatedCharactersList, }); }}class Character extends Component { render() { return ( <li> <div className="character"> <span className="character-name">{this.props.char}</span> <span className="character-delete" onClick={this.handleDelete} > x </span> </div> </li> ) }; handleDelete() { this.props.onDelete(this.props.char); }}export default App;
Now provide the response and nothing else.
| You rewrite the context of the class method when you pass it to props like this because of JS OOP system. So to make it work there are several approaches: 1) This is not so good because bind always returns new function and your component will re-render even if there are no updates in props import React, { Component } from 'react';import './App.css';class App extends Component { render() { return ( <div className="App"> <StreetFighter /> </div> ); }}class StreetFighter extends Component { constructor(props) { super(props); this.state = { characters: [ 'Chun-Li', 'Guile', 'Ryu', 'Ken', 'E.Honda', 'Dhalsim', ], }; } render() { let characters = this.state.characters; characters = characters.map((char, index) => { return ( <Character char={char} key={index} onDelete={this.onDelete.bind(this)} /> ); }); return ( <div> <p>Street Fighter Characters</p> <ul>{characters}</ul> </div> ); } onDelete(chosenCharacter) { let updatedCharactersList = this.state.characters.filter( (char, index) => { return chosenCharacter !== char; } ); this.setState({ characters: updatedCharactersList, }); }}class Character extends Component { render() { return ( <li> <div className="character"> <span className="character-name">{this.props.char}</span> <span className="character-delete" onClick={this.handleDelete.bind(this)} > x </span> </div> </li> ) }; handleDelete() { this.props.onDelete(this.props.char); }}export default App; 2) In my code I use arrow functions as class properties for such cases (it's one of the most common solutions, I think) class Character extends Component { render() { return ( <li> <div className="character"> <span className="character-name">{this.props.char}</span> <span className="character-delete" onClick={this.handleDelete} > x </span> </div> </li> ) }; handleDelete = () => { this.props.onDelete(this.props.char); }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/50862192', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7703963/']} | jdg_381170 |
stackexchange | llm_judgeable_groundtruth_similarity | 47718207 |
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 add/edit new code to my Jenkins instance that would be accesible in a DSL script? Context follows I've inherited a Jenkins instance. Part of this inheritance includes spending the night in a haunted house writing some new automation in groovy via the Jobs DSL plugin . Since I'm fearful of ruining our jenkins instance, my first step is setting up a local development instance. I'm having trouble running one of our existing DSL Scripts on my local development instance -- my builds on the local server fail with the following in the Jenkins error console. Processing DSL script jobs.groovyERROR: startup failed:jobs.groovy: 1: unable to resolve class thecompanysname.jenkins.extensions The script in question starts off like this. import thecompanysname.jenkins.extensionsuse(extensions) { def org = 'project-name' def project = 'test-jenkins-repo' def _email = '[email protected]' So, as near I can tell, it seems like a predecesor has written some custom Groovy code that they're importing import thecompanysname.jenkins.extensions What's not clear to me is Where this code lives How I can find it in our real Jenkins instance How I can add to to my local instance Specific answers are welcome, as our here's how you can learn to fish answers.
Now provide the response and nothing else.
| @Ignore is a Room-specific annotation, saying that Room should ignore that field or method. transient is a Java construct, indicating that this field should not be serialized in standard Java serialization . Room happens to treat this similarly to @Ignore by default . Mostly, that is there for cases where you are inheriting from some class that happens to use transient and you do not control that class (e.g., it is from a library). For your own code, if you are not using Java serialization, I recommend sticking with @Ignore for the fields. transient is not an available keyword for a method, so to tell Room to ignore certain constructors, you have no choice but to use @Ignore . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/47718207', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4668/']} | jdg_381171 |
stackexchange | llm_judgeable_groundtruth_similarity | 1882 |
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
According to many news sources, meditation is more effecting than morphine in reducing pain. According to a study in Wednesday's issue of Journal of Neuroscience, meditation can reduce pain by 40 to 57 percent. That's a better figure than what's been recorded for pain-relieving medicines β including morphine β which top off at a 25 percent pain reduction. -- source This can be reconducted to the following statements by the author of the paper , Fadel Zeidan. βWe found a big effect β about a 40 percent reduction in pain intensity and a 57 percent reduction in pain unpleasantness,β added Zeidan, post-doctoral research fellow at Wake Forest Baptist Medical Centre. βMeditation produced a greater reduction in pain than even morphine or other pain-relieving drugs, which typically reduce pain ratings by about 25 percent,β said Zeidan, reports the Journal of Neuroscience. -- source This sounds like an extraordinary claim , requiring extraordinary evidence . Is there any study that contradicts Zeidan? Is he actually making the same claims, or is he a victim of sensationalist reporting?
Now provide the response and nothing else.
| The pain assay used was a semi-acute pain assay (from the paper, p. 5541): Noxious thermal stimuli were delivered to the posterior aspect of the right calf by a 16 Γ 16 mm2 TSA II thermal stimulator (Medoc). The βheatβ condition consisted of thermal stimuli that were administered in alternating patterns of heat (49Β°C) and neutral (35Β°C) with 12 s durations at each temperature Analgesics typically work better on chronic pain, so even if one compared directly (which the paper does not) I'm not sure that the results would seem all that surprising, especially since (at least according to Wikipedia ) opioids "do not provide complete analgesia regardless of whether the pain is acute or chronic in origin". Of course one would like to see the results replicated and there may be methodological problems with the study (e.g. the training does not appear to have been done in a double-blind fashion, subjects served as their own controls, etc..). But it doesn't seem to me to be an extraordinary claim, just an interesting one. Also, it's worth pointing out that this is not just "wishing away" the pain; it's a specific meditative training regime that probably works in a very different way than "wishing". We have much more dramatic examples than this of attentional or context-specific impacts on our perception. (E.g. a gentle touch from a loved one vs. a gentle touch when one is surrounded by spiders.) | {} | {'log_upvote_score': 4, 'links': ['https://skeptics.stackexchange.com/questions/1882', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/96/']} | jdg_381172 |
stackexchange | llm_judgeable_groundtruth_similarity | 25510156 |
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 to fetch sum of Amount field from given associative array according to TXNLineNo. Array ( [0] => Array ( [TXNID] => 0 [RefTXNID] => 1006 [RefTXNObjectType] => 101 [tmpTXNName] => CN-33 [tmpTXNDate] => 2014-08-26 [RefTXNLineNo] => 0 [tmpOpenAmount] => 0 [tmpOpenAmt] => -500.000 [tmpTXNAmount] => 500 [tmpNarration] => Being amount paid to supplier [Amount] => 500 [TXNCurrencyID] => 213 [ExchangeRate] => 1.00000 [RevisionNumber] => 1 [tmpRevisionNumber] => 1 [RowState] => 435 [tmpContactID] => 948 [tmpAccountID] => 303 [tmpBranchID] => 156 [TXNLineNo] => 1 ) [1] => Array ( [TXNID] => 0 [RefTXNID] => 983 [RefTXNObjectType] => 84 [tmpTXNName] => RTY-01 [tmpTXNDate] => 2014-08-26 [RefTXNLineNo] => 1 [tmpOpenAmount] => 0 [tmpOpenAmt] => -1000.000 [tmpTXNAmount] => 1000 [tmpNarration] => [Amount] => 1000 [TXNCurrencyID] => 213 [ExchangeRate] => 1.00000 [RevisionNumber] => 1 [tmpRevisionNumber] => 1 [RowState] => 435 [tmpContactID] => 948 [tmpAccountID] => 303 [tmpBranchID] => 156 [TXNLineNo] => 1 ) [2] => Array ( [TXNID] => 0 [RefTXNID] => 1006 [RefTXNObjectType] => 101 [tmpTXNName] => CN-33 [tmpTXNDate] => 2014-08-26 [RefTXNLineNo] => 0 [tmpOpenAmount] => 0 [tmpOpenAmt] => -500.000 [tmpTXNAmount] => 500 [tmpNarration] => Being amount paid to supplier [Amount] => 500 [TXNCurrencyID] => 213 [ExchangeRate] => 1.00000 [RevisionNumber] => 1 [tmpRevisionNumber] => 1 [RowState] => 435 [tmpContactID] => 948 [tmpAccountID] => 303 [tmpBranchID] => 156 [TXNLineNo] => 2 ) [3] => Array ( [TXNID] => 0 [RefTXNID] => 983 [RefTXNObjectType] => 84 [tmpTXNName] => RTY-01 [tmpTXNDate] => 2014-08-26 [RefTXNLineNo] => 1 [tmpOpenAmount] => 0 [tmpOpenAmt] => -1000.000 [tmpTXNAmount] => 1000 [tmpNarration] => [Amount] => 1000 [TXNCurrencyID] => 213 [ExchangeRate] => 1.00000 [RevisionNumber] => 1 [tmpRevisionNumber] => 1 [RowState] => 435 [tmpContactID] => 948 [tmpAccountID] => 303 [tmpBranchID] => 156 [TXNLineNo] => 2 ) ) I already use following script to get sum of Amount field $ret = array_sum(array_map(function ($i) { return $i['Amount']; }, $data)); But this is not working for me. I have to fetch sum of amount TxnLineNo Wise ...
Now provide the response and nothing else.
| This has nothing to do with BigInteger , this is happening because your calculate() method is calling itself. Once you've gotten your call stack deep enough, you run out of memory and the JVM throws the StackOverflowError . You don't have any sort of termination condition in your calculate() method. Each time you enter the while loop, you kick off another call. In fact, it seems like you are trying to solve this both iteratively and recursively at the same time. You shouldn't need both a while loop and a recursive call in your code. It looks to me like if you just take out the call to calculate() your program will work just fine: public static void calculate(BigInteger s, BigInteger t) { while (i < 4000000) { System.out.printf("%d\t%d\n", p, i); temp = p; p = p.add(q); q = temp; i++; // calculate(p, q); // you don't need this }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25510156', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2028855/']} | jdg_381173 |
stackexchange | llm_judgeable_groundtruth_similarity | 22610586 |
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 quite new to MVC5 and asp.net and I couldn't find the answer, so I would be grateful if someone could tell me how to customize the message after failing the validation. Let's assume I have a code like this: [Required] [MaxLength(11),MinLength(11)] [RegularExpression("^[0-9]+$")] public string Pesel { get; set; } After using any other signs than digits I got a message like this:The field Pesel must match the regular expression '^[0-9]+$' How can I change this message?
Now provide the response and nothing else.
| All validation attributes within System.ComponentModel.DataAnnotations have an ErrorMessage property that you can set: [Required(ErrorMessage = "Foo")][MinLength(11, ErrorMessage = "Foo"), MaxLength(11, ErrorMessage = "Foo")][RegularExpression("^[0-9]+$", ErrorMessage = "Foo")] Additionally, you can still use the field name / display name for the property within the error message. This is done through a String Format setup. The following example will render an error message of "You forgot MyPropertyName". [Required(ErrorMessage = "You forgot {0}")]public string MyPropertyName { get; set; } This also respects the DisplayAttribute. Since MyPropertyName isn't a very user-friendly name, the example below will render an error message of "You forgot My Property". [Display(Name = "My Property")][Required(ErrorMessage = "You forgot {0}")]public string MyPropertyName { get; set; } And finally, you can use additional String Format values to render the values and options that are used in the more complex validation attributes, such as the MinLengthAttribute that you are using. This last example will render an error message of "The minimum length for My Property is 11": [Display(Name = "My Property")][MinLength(11, ErrorMessage = "The minimum length for {0} is {1}")]public string MyPropertyName { get; set; } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22610586', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3455510/']} | jdg_381174 |
stackexchange | llm_judgeable_groundtruth_similarity | 89056 |
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 heard of some methods, but none of them have stuck. Personally I try to avoid complex types in C and try to break them into component typedef. I'm now faced with maintaining some legacy code from a so called 'three star programmer', and I'm having a hard time reading some of the ***code[][]. How do you read complex C declarations?
Now provide the response and nothing else.
| This article explains a relatively simple 7 rules which will let you read any C declaration, if you find yourself wanting or needing to do so manually: http://www.ericgiguere.com/articles/reading-c-declarations.html Find the identifier. This is your starting point. On a piece of paper, write "declare identifier as". Look to the right. If there is nothing there, or there is a right parenthesis ")", goto step 4. You are now positioned either on an array (left bracket) or function (left parenthesis) descriptor. There may be a sequence of these, ending either with an unmatched right parenthesis or the end of the declarator (a semicolon or a "=" for initialization). For each such descriptor, reading from left to right: if an empty array "[]", write "array of" if an array with a size, write "array size of" if a function "()", write "function returning" Stop at the unmatched parenthesis or the end of the declarator, whichever comes first. Return to the starting position and look to the left. If there is nothing there, or there is a left parenthesis "(", goto step 6. You are now positioned on a pointer descriptor, "*". There may be a sequence of these to the left, ending either with an unmatched left parenthesis "(" or the start of the declarator. Reading from right to left, for each pointer descriptor write "pointer to". Stop at the unmatched parenthesis or the start of the declarator, whichever is first. At this point you have either a parenthesized expression or the complete declarator. If you have a parenthesized expression, consider it as your new starting point and return to step 2. Write down the type specifier. Stop. If you're fine with a tool, then I second the suggestion to use the program cdecl : http://gd.tuwien.ac.at/linuxcommand.org/man_pages/cdecl1.html | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/89056', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4319/']} | jdg_381175 |
stackexchange | llm_judgeable_groundtruth_similarity | 146986 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Are there examples that might suggest the Riemann hypothesis is false? I mean, is there a zeta function $ \zeta (s,X) $ for some mathematical object $X$ with the properties $ \zeta (1-s,X) $ and $ \zeta (s,X)$ are related by a functional equation. $\zeta (s,X) $ can be expanded into an Euler product $ \zeta (s,X)= \prod _{i}(1-N(i)^{-s})^{-1}$. the zeta function $\zeta (s,X) $ has zeroes of the form $ a+bi$ with $b\ne0$ for $a$ different from $\frac 12$. That is, a zeta function with similar properties to the Riemann zeta but with zeroes off the critical line.
Now provide the response and nothing else.
| The answer is either yes or no , depending on how stringently you interpret your various requirements. You should look at the discussion of the Selberg class of functions, which is Selberg'sconjectural characterization of functions satisfying the Riemann Hypothesis. In particular, if you read the comments on the definition in the wikipedia entry, you will get a sense of why those are the precise conditions on a "$\zeta$-type function" which are needed to guarantee RH. As a concrete (counter-)example, consider the function $$\eta(s) = 1 - 2^{-s} + 3^{-s} - 4^{-s} + \cdots,$$sometimes called the Dirichlet $\eta$-function . It admits a functional equation and Euler product, but does not satisfy RH. It is not in the Selberg class because although it admits an Euler product, its Euler factors do not satisfy the correct conditions. (This is discussed in the wikipedia entry on the Selberg class.) | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/146986', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/17341/']} | jdg_381176 |
stackexchange | llm_judgeable_groundtruth_similarity | 54666515 |
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 unpacked the full version on 0.81 Apache Zeppelin on windows 10. I navigated to the C:\Zeppelin\bin and typed in zeppelin.cmd I do not get any output after that C:\Zeppelin\bin" just gets repeated. And i can clearly see zeppelin.cmd in the dir/p of the folder How do i debug this
Now provide the response and nothing else.
| I recently encountered this problem as well. After going through the cmd files in the bin folder, I found that there is an accidental '}' where there should be a ')' . It came after set ZEPPELIN_JMX_PORT="9996" in the common.cmd file. Once I changed this it worked fine. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54666515', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5588318/']} | jdg_381177 |
stackexchange | llm_judgeable_groundtruth_similarity | 15638046 |
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 form, which has an upload ( $_FILES['watch_photo'] ) field. I have looked around and came to put this function together. It basically takes all relevant information so it is re-usable in the future, it will return an array of the $pid, and URL of the file, when it is done. The problem is that ACF has not provided much information how to add images to it's fields using update_field() http://www.advancedcustomfields.com/resources/functions/update_field/ function my_update_attachment($f,$pid,$t='',$c='') { wp_update_attachment_metadata( $pid, $f ); if( !empty( $_FILES[$f]['name'] )) { //New upload require_once( ABSPATH . 'wp-admin/includes/file.php' ); $override['action'] = 'editpost'; $file = wp_handle_upload( $_FILES[$f], $override ); if ( isset( $file['error'] )) { return new WP_Error( 'upload_error', $file['error'] ); } $file_type = wp_check_filetype($_FILES[$f]['name'], array( 'jpg|jpeg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png', )); if ($file_type['type']) { $name_parts = pathinfo( $file['file'] ); $name = $file['filename']; $type = $file['type']; $title = $t ? $t : $name; $content = $c; $attachment = array( 'post_title' => $title, 'post_type' => 'attachment', 'post_content' => $content, 'post_parent' => $pid, 'post_mime_type' => $type, 'guid' => $file['url'], ); foreach( get_intermediate_image_sizes() as $s ) { $sizes[$s] = array( 'width' => '', 'height' => '', 'crop' => true ); $sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options $sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options $sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options } $sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes ); foreach( $sizes as $size => $size_data ) { $resized = image_make_intermediate_size( $file['file'], $size_data['width'], $size_data['height'], $size_data['crop'] ); if ( $resized ) $metadata['sizes'][$size] = $resized; } $attach_id = wp_insert_attachment( $attachment, $file['file'] /*, $pid - for post_thumbnails*/); if ( !is_wp_error( $id )) { $attach_meta = wp_generate_attachment_metadata( $attach_id, $file['file'] ); wp_update_attachment_metadata( $attach_id, $attach_meta ); } return array( 'pid' =>$pid, 'url' =>$file['url'] ); // update_post_meta( $pid, 'a_image', $file['url'] ); } }} and then I used the following code: to create a post and then upload then use my_update_attachment to process the image and finally update the advanced custom field The code: $args= array( 'post_type' => 'watches', 'post_status' => 'publish' );$watch = wp_insert_post($args);$att = my_update_attachment('watch_image',$watch);update_field('field_512e085a9372a',$att['url'],$watch); What am I missing? any help would be greatly appreciated.
Now provide the response and nothing else.
| I had the same problem, you almost had it right, which helped me as well. looked at ACF and the update_field accepts attachment ID as oppose to the the, pid or url You can replace the return array: return array( 'pid' =>$pid, 'url' =>$file['url']); With the following array: return array( 'pid' =>$pid, 'url' =>$file['url'], 'file'=>$file, 'attach_id'=>$attach_id); and then change update_field('field_512e085a9372a',$att['url'],$watch); with the following update_field('field_512e085a9372a',$att['attach_id'],$watch); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15638046', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2071643/']} | jdg_381178 |
stackexchange | llm_judgeable_groundtruth_similarity | 417988 |
Below is a question asked on the forum meta.stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I just found some odd behavior when searching for the word "binance" on StackΒ Overflow: https://stackoverflow.com/search?tab=relevance&q=binance The results have nothing to do with the word "binance". If you check the answers, none of them have the word "binance" in their text. Instead it seems like the search is returning anything that matches the word "bin". Is this normal? Obviously I could use quotes to search for the exact word, but that's not the question. It's just odd how the search works since following that logic one would expect that searching for the word "websockets" would return all the posts with the word "web" in them which is not the case.
Now provide the response and nothing else.
| This is lemmatization gone wrong. I know they're using ElasticSearch, which I believe in turn uses Lucene, maybe even the exact algorithm in PorterStemmer.java . From experimenting with SO search, it looks like it's removing suffixes (-ance in this case) from non-words (because I tested a few real words and they were not changed). This is why bin is highlighted in the results. As another example, searching for conance returns results for "cone". I'm not sure what benefits this exactly has in practice, or if it can easily be changed system wide. (Other parts of the algorithm are usually helpful, such as removing plural "-s".) You can disable lemmatization of specific words in your searches by using quotes : "binance" . | {} | {'log_upvote_score': 5, 'links': ['https://meta.stackoverflow.com/questions/417988', 'https://meta.stackoverflow.com', 'https://meta.stackoverflow.com/users/9170226/']} | jdg_381179 |
stackexchange | llm_judgeable_groundtruth_similarity | 36202414 |
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 attempting to download a png image from a secure site through R. To access the secure site I used Rvest which worked well. So far I've extracted the URL for the png image. How can I download the image of this link using rvest? Functions outside of the rvest function return errors due to not having permission. Current attempts library(rvest)uastring <- "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"session <- html_session("https://url.png", user_agent(uastring))form <- html_form(session)[[1]]form <- set_values(form, username = "***", password="***", cookie_checkbox= TRUE)session<-submit_form(session, form)session2<-jump_to(session, "https://url.png")## Status 200 using rvest, sucessfully accsessed page. session <session> https://url.png Status: 200 Type: image/png Size: 438935## Using download.file returns status 403, page unable to open.download.file("https://url.png", destfile = "t.png") cannot open: HTTP status was '403 Forbidden' Have tried readPNG and download.file on the url, both of which failed due to not having permission to download from a authenticated secure site (error: 403), hence why I used rvest in the first place.
Now provide the response and nothing else.
| Here's one example to download the R logo into the current directory. library(rvest)url <- "https://www.r-project.org"imgsrc <- read_html(url) %>% html_node(xpath = '//*/img') %>% html_attr('src')imgsrc# [1] "/Rlogo.png"# side-effect!download.file(paste0(url, imgsrc), destfile = basename(imgsrc)) EDIT Since authentication is involved, Austin's suggestion of using a session is certainly required. Try this: library(rvest)library(httr)sess <- html_session(url)imgsrc <- sess %>% read_html() %>% html_node(xpath = '//*/img') %>% html_attr('src')img <- jump_to(sess, paste0(url, imgsrc))# side-effect!writeBin(img$response$content, basename(imgsrc)) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36202414', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6041137/']} | jdg_381180 |
stackexchange | llm_judgeable_groundtruth_similarity | 2583060 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am tasked with proving the following inequality using mathematical induction: $$(1) \quad P(n):{ 4n }^{ 2 }+12n+7<100n^{2},\quad n>2$$ What I am not sure about is whether my use of the induction hypothesis (IH) is correct and whether I use it at all. Here is my proof: $$(2)\quad { P(b):4\cdot1 }^{ 2 }+12\cdot 1+7<100\cdot 1^{ 2 }, \quad b=1$$$$(3)Β \quad 23<100$$ Since P(b) is true for b = 1, we can move on to the inductive step. Assume the following is true for some k =< n (this is the inductive hypothesis): $$(4)\quad P(k):{ 4k }^{ 2 }+12k+7<100k^{2}$$ We must prove that P(k+1) is true: $$(5) \quad P(k+1):{ 4(k+1) }^{ 2 }+12(k+1)+7<100(k+1)^{2}$$ We make the expression have a form that resembles inequality (4): $$(6) \quad 4({k}^2+2k+1)+12k+12+7<100(k^{2}+2k+1)$$$$(7) \quad \underline{4{k}^2}+8k+4+\underline{12k}+12+\underline{7}<\underline{100k^{2}}+200k+100$$ Now that the form resembles (4) we use the IH to remove these elements from the inequality (they are underlined for readability in 7)). By the IH: $$(8) \quad 8k+4+12\overset{IH}{<}200k+100$$$$(9) \quad 8k+16<200k+100$$ We see that (9) is trivially true. Thus P(k+1) has been proved. By the principle of mathematical induction P(n) is also true. Do I use the IH correctly? Is the proof valid?
Now provide the response and nothing else.
| For injectivity: the sum of strictly increasing functions is strictly increasing. And $x^k$ is strictly increasing for odd $k$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2583060', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/516917/']} | jdg_381181 |
stackexchange | llm_judgeable_groundtruth_similarity | 45488833 |
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 data frame that contains two variables, like this: df <- data.frame(group=c(1,1,1,2,2,3,3,4), type=c("a","b","a", "b", "c", "c","b","a"))> df group type1 1 a2 1 b3 1 a4 2 b5 2 c6 3 c7 3 b8 4 a I want to produce a table showing for each group the combination of types it has in the data frame as one variable e.g. group alltypes1 1 a, b2 2 b, c3 3 b, c4 4 a The output would always list the types in the same order (e.g. groups 2 and 3 get the same result) and there would be no repetition (e.g. group 1 is not "a, b, a"). I tried doing this using dplyr and summarize, but I can't work out how to get it to meet these two conditions - the code I tried was: > df %>%+ group_by(group) %>%+ summarise(+ alltypes = paste(type, collapse=", ")+ )# A tibble: 4 Γ 2 group alltypes <dbl> <chr>1 1 a, b, a2 2 b, c3 3 c, b4 4 a I also tried turning type into a set of individual counts, but not sure if that's actually useful: > df %>%+ group_by(group, type) %>%+ tally %>%+ spread(type, n, fill=0)Source: local data frame [4 x 4]Groups: group [4] group a b c* <dbl> <dbl> <dbl> <dbl>1 1 2 1 02 2 0 1 13 3 0 1 14 4 1 0 0 Any suggestions would be greatly appreciated.
Now provide the response and nothing else.
| I think you were very close. You could call the sort and unique functions to make sure your result adheres to your conditions as follows: df %>% group_by(group) %>% summarize(type = paste(sort(unique(type)),collapse=", ")) returns: # A tibble: 4 x 2 group type <int> <chr>1 1 a, b2 2 b, c3 3 b, c4 4 a | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45488833', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8412551/']} | jdg_381182 |
stackexchange | llm_judgeable_groundtruth_similarity | 935018 |
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 you hide databases you do not have access rights to when logging into SQL Server 2005 / 2008 ? Currently if a user connects, they see all the databases on the server, meaning they have to scan though the list to find their database.
Now provide the response and nothing else.
| After hours of trying to figure out how to create a user account which only has access to 1 DB, and can only see that DB. I think i figured it out!!!! Create a user account ( make sure its not mapped to any Database, otherwise you will get the final error Msg 15110, Level 16, State 1 and note proposed solution ) USE [master]GOCREATE LOGIN [us4] WITH PASSWORD=N'123', DEFAULT_DATABASE=[master], CHECK_EXPIRATION=OFF, CHECK_POLICY=OFF Right Click on the upper section of the SQL (SQLSERVER Name)> Properties > Permissions >Click on the user account , and select Deny to view databases. use [master]GODENY VIEW ANY DATABASE TO [us4] Right Click on the newly created DB, Properties,Files, and change the Owner to the newly created account.( important note : ALTER ROLE [db_owner] ADD MEMBER [us4] does not work ) USE [dbname]GOEXEC dbo.sp_changedbowner @loginame = N'us4', @map = false At this point, once the user logs in he will see the Master,tempdb and will also see the new DB which he is a DB Owner of..You may want to go to Tools>Option and enabled the option to hide system objects so that you don't show the master,tempdb,etc. You may also need SP1 if this option does not work Msg 15110, Level 16, State 1, Line 1The proposed new database owner is already a user or aliased in the database. proposed solution to Msg 15110: to resolve above error simply delete the user from database security node and try again Hope that helps... Nikhil | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/935018', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/91579/']} | jdg_381183 |
stackexchange | llm_judgeable_groundtruth_similarity | 15765220 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
x = 1; alert(x); var y = function() { alert(x); var x = 2; alert(x); } y(); The result of the 3 alerts is: 1 , undefined , 2 (Chrome 25) My question is: why the second alert is undefined? Why not 1? Isn't there a global variable x?
Now provide the response and nothing else.
| Due to hoisting , this is what gets executed: x = 1; alert(x); var y = function() { var x; // <-- this gets hoisted up from where it was. alert(x); x = 2; alert(x); } y(); At the start of function y() , the local variable x is declared but not initialized. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15765220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1321025/']} | jdg_381184 |
stackexchange | llm_judgeable_groundtruth_similarity | 6514485 |
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 link that I want to be able to click to trigger a piece of jQuery code. Currently I have <a href="#" id="foo">Link</a> and $('#foo').click(function(){ // Do stuff}); which works well. But, I have always hated using hash in this way. The page flickers and the hash is added to the page url. One alternative is to use <a href="javascript:void(0);" id="foo">Link</a> but I also dislike seeing that piece of code in the browser status bar. It looks tacky. What I'd rather have is an explanatory javascript placeholder that does nothing, like <a href="javascript:zoom();" id="foo">Link</a> which actually works, but throws an ReferenceError in the javascript console since there are no such function. What's the minimum definition of a function that does nothing? Are there any other alternatives? Should I just skip the link and use something like <span id="foo" style="cursor:pointer;cursor:hand;">Link</span> instead?
Now provide the response and nothing else.
| Use the event.preventDefault() [docs] method. $('#foo').click(function(e){ e.preventDefault(); // Do stuff}); This will prevent the hash from having any effect when you click. Or get rid of the hash, and use CSS to style it. Also, you can provide an actual url for the href to handle graceful degradation. What's the minimum definition of a function that does nothing? Here's a no-op function: var noop = function(){}; ...or since you're using jQuery, you can use the jQuery.noop() [docs] method, which also is just an empty function. $.noop | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6514485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/213738/']} | jdg_381185 |
stackexchange | llm_judgeable_groundtruth_similarity | 18018033 |
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's the proper way to tell a looping thread to stop looping? I have a fairly simple program that pings a specified host in a separate threading.Thread class. In this class it sleeps 60 seconds, the runs again until the application quits. I'd like to implement a 'Stop' button in my wx.Frame to ask the looping thread to stop. It doesn't need to end the thread right away, it can just stop looping once it wakes up. Here is my threading class (note: I haven't implemented looping yet, but it would likely fall under the run method in PingAssets) class PingAssets(threading.Thread): def __init__(self, threadNum, asset, window): threading.Thread.__init__(self) self.threadNum = threadNum self.window = window self.asset = asset def run(self): config = controller.getConfig() fmt = config['timefmt'] start_time = datetime.now().strftime(fmt) try: if onlinecheck.check_status(self.asset): status = "online" else: status = "offline" except socket.gaierror: status = "an invalid asset tag." msg =("{}: {} is {}. \n".format(start_time, self.asset, status)) wx.CallAfter(self.window.Logger, msg) And in my wxPyhton Frame I have this function called from a Start button: def CheckAsset(self, asset): self.count += 1 thread = PingAssets(self.count, asset, self) self.threads.append(thread) thread.start()
Now provide the response and nothing else.
| Threaded stoppable function Instead of subclassing threading.Thread , one can modify the function to allowstopping by a flag. We need an object, accessible to running function, to which we set the flag to stop running. We can use threading.currentThread() object. import threadingimport timedef doit(arg): t = threading.currentThread() while getattr(t, "do_run", True): print ("working on %s" % arg) time.sleep(1) print("Stopping as you wish.")def main(): t = threading.Thread(target=doit, args=("task",)) t.start() time.sleep(5) t.do_run = False if __name__ == "__main__": main() The trick is, that the running thread can have attached additional properties. The solution buildson assumptions: the thread has a property "do_run" with default value True driving parent process can assign to started thread the property "do_run" to False . Running the code, we get following output: $ python stopthread.py working on taskworking on taskworking on taskworking on taskworking on taskStopping as you wish. Pill to kill - using Event Other alternative is to use threading.Event as function argument. It is bydefault False , but external process can "set it" (to True ) and function canlearn about it using wait(timeout) function. We can wait with zero timeout, but we can also use it as the sleeping timer (used below). def doit(stop_event, arg): while not stop_event.wait(1): print ("working on %s" % arg) print("Stopping as you wish.")def main(): pill2kill = threading.Event() t = threading.Thread(target=doit, args=(pill2kill, "task")) t.start() time.sleep(5) pill2kill.set() t.join() Edit: I tried this in Python 3.6. stop_event.wait() blocks the event (and so the while loop) until release. It does not return a boolean value. Using stop_event.is_set() works instead. Stopping multiple threads with one pill Advantage of pill to kill is better seen, if we have to stop multiple threadsat once, as one pill will work for all. The doit will not change at all, only the main handles the threads a bit differently. def main(): pill2kill = threading.Event() tasks = ["task ONE", "task TWO", "task THREE"] def thread_gen(pill2kill, tasks): for task in tasks: t = threading.Thread(target=doit, args=(pill2kill, task)) yield t threads = list(thread_gen(pill2kill, tasks)) for thread in threads: thread.start() time.sleep(5) pill2kill.set() for thread in threads: thread.join() | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/18018033', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1615031/']} | jdg_381186 |
stackexchange | llm_judgeable_groundtruth_similarity | 42864 |
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to generate inaudible sound waves (above 18kHz) with 48kHz sampling rate using MATLAB. Generating a sound wave with 18kHz frequency makes it inaudible. I've inserted the data in the 18kHz band in the frequency domain, converted it into time domain signal.Then I've duplicated the signal, concatenated it, and played it. As expected, the played sound was inaudible. The problem is,I want to play the inaudible sound with an interval. (playing sound wave for 1.75ms and having a silence period for 4.17ms repetitively) Because of the inserted silence period, the concatenated signal is no longer inaudible because new frequency components are added. How I can transmit inaudible sound with time interval?
Now provide the response and nothing else.
| Eventhough the exact cause of those wide-spread line spectra is not very clear to me from the supplied information, it's most probably due to the on-off switching implied by the silence period you have added in between your message signals. The on-off waveform is an implicit operation you multiply to your signal. Which has a value of $1$ during the sound interval and a value of $0$ during the silence interval. The fundamental period of that waveform is roughly 200 Hertz. More technically, the on-off switching with a given duty-cycle will shift the message spectrum by the amount of k-th harmonic frequency for each significant harmonic present in the continuous Fourier series of the on-off waveform. In fact this is a method of realizing an analog modulation algorithm. Multiplication with a rectengular wave creates a multitude of harmonic centered up-mixed spectrums, of which only one is selected by a suitable bandpass filter. Therefore as a solution offer, you could try the following: 1- Generate the 18kHz (already bandpass) message signal in time domain. 2- Insert the silence periods accordingly. 3- Apply a BPF (bandpass filter) centered around 18Khz. When implemented carefully this should yield a solution to your problem I guess. Distortions in the message signal can happen however. | {} | {'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/42864', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/29938/']} | jdg_381187 |
stackexchange | llm_judgeable_groundtruth_similarity | 665752 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose I have three C static libraries say libColor.a which depends on *libRGB.*a which in turn depends on libPixel.a . The library libColor.a is said to depend on library libRGB.a since there are some references in libColor.a to some of symbols defined in libRGB.a . How do I combine all the above libraries to a new libNewColor.a which is independent? Independent means the new library should have all symbols defined. So while linking I just need to give -lNewColor . The size of the new library should be minimal i.e it should not contain any symbols in libRGB.a which is not used by libColor.a etc. I tried my luck using various options in ar command (used to create and update static libraries/archives).
Now provide the response and nothing else.
| 1/ Extract ALL of the object files from each library (using ar ) and try to compile your code without the libraries or any of the object files. You'll probably get an absolute bucket-load of undefined symbols. If you get no undefined symbols, go to step 5. 2/ Grab the first one and find out which object file satisfies that symbol (using nm ). 3/ Write down that object file then compile your code, including the new object file. You'll get a new list of undefined symbols or, if there's none, go to step 5. 4/ Go to step 2. 5/ Combine all the object files in your list (if any) into a single library (again with ar ). Bang! There you have it. Try to link your code without any of the objects but with the new library. This whole thing could be relatively easily automated with a shell script. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/665752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/53288/']} | jdg_381188 |
stackexchange | llm_judgeable_groundtruth_similarity | 1885917 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The number of all 3-digit numbers abc (in base 10) for which $\ abc+ab+bc+ac+a+b+c = 29$ is (A) 6 (B) 10 (C) 14 (D) 18 My working: $\ ab (c + 1) +b (c + 1) + a(c + 1) + c + 1 = 30$ $\ (a + 1) (b +1) (c+1) = 30 $ $\ 9>a>0$ $\ 0\le b,c<9$ The problem I am facing: I don't know how to figure out the no. of solutions for which this is true.
Now provide the response and nothing else.
| $$(a+1)(b+1)(c+1)=30$$ Total number of ways to satisfy above equation: $30 = (2,3,5)$ gives $6$ values for $a+1,b+1,c+1$ $(i.e., a=1, b=2, c=4)$ $30 = ( 1 , 6 ,5)$ gives $6$ values for $a+1,b+1,c+1$ $(i.e., a=0, b=5, c=4)$ $30 = (1,3,10)$ gives $6$ values for $a+1,b+1,c+1$ $(i.e., a=0, b=2, c=9)$ In the first case we have $6$ values for $a,b,c$ as $(1,2,4)$ can take up any digit hence they can be arranged in $3!$ ways. In the second case we have $4$ values for $a,b,c$ as $(0,5,4)$. $0$ can not be as first digit as. Then $abc$ would be a $2$ digit number ( contrary to given condition ). Hence we have $ 2.2.1$ number of ways . Similarly in the third case we have $4$ values $a,b,c$ as $(0,2,9)$. $0$ can not be as first digit as. Then $abc$ would be a $2$ digit number ( contrary to given condition ). Hence we have $ 2.2.1$ number of ways . Therefore, total number of ways: $$3!+2\times 2\times1+2\times 2\times1=6+4+4=14 \space \text{ways}$$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1885917', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/342876/']} | jdg_381189 |
stackexchange | llm_judgeable_groundtruth_similarity | 63103305 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to store in memory about 500-1000 entries of 3 fields with quick and effective search by both int and str values. Searching happens in quick bursts of about 300-500 requests. I'm not sure how to efficiently do it. Stored data consists of 3 fields: ID - Integer, which won't be sequential. I.e. it will be like (3, 5, 12, 55), but not (1, 2, 3, 4, 5). Name - String. Tags - String. There are 3 possible scenarios: Get ID by Name. Get Name by ID. Get Tags by ID. Currently, I use two different Types: THashedStringList with keypairs '%s=%i' to search by name. Array of Records sorted by ID for other searches. I find this highly inefficient and currently looking for new ideas. Any hints?
Now provide the response and nothing else.
| As David Heffernan suggested, you might want to use a proper database for this. But if you want a more lightweight solution, with excellent performance, you can use an object list to store all your items and two dictionaries that refer to these items by their IDs and names, respectively. As an example, consider a frog: type TFrog = class ID: Integer; Name: string; Address: string; end; Like your example, this class has one integer and two string members. We assume that every frog has a unique ID and a unique name. (But two or more frogs may share the same address.) Just so we will be able to test the performance, we create a primitive frog generation function: function CreateRandomFrog: TFrog;const FrogFirstNames: array[0..11] of string = ('Luke', 'Smith', 'John', 'Maggie', 'Rose', 'Bill', 'Edward', 'Harry', 'Andrew', 'Michael', 'Molly', 'Arthur'); FrogLastNames: array[0..7] of string = ('Jones', 'Stone', 'Rock', 'Hill', 'Waterfall', 'Sky', 'Flower', 'Rain'); FrogInitials: array[0..25] of Char = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; FrogAddressesPrefixes: array[0..3] of string = ('Tree', 'Swamp', 'Lawn', 'Lake');begin Result := TFrog.Create; try Result.ID := Random(10*N); Result.Name := FrogFirstNames[Random(Length(FrogFirstNames))] + #32 + FrogInitials[Random(Length(FrogInitials))] + '.' + FrogInitials[Random(Length(FrogInitials))] + '.' + FrogInitials[Random(Length(FrogInitials))] + '.' + #32 + FrogLastNames[Random(Length(FrogLastNames))]; Result.Address := FrogAddressesPrefixes[Random(Length(FrogAddressesPrefixes))] + #32 + Random(Byte.MaxValue).ToString; except Result.Free; raise; end;end; This will create frogs like ID: 123Name: Bill D.H.H. RockAddress: Tree 52 We also define a constant const N = 1000000; This is the number of frogs we will create at the same time. Now, some action: Define a class type TFrogFarm = class Frogs: TObjectList<TFrog>; FrogsByID: TDictionary<Integer, TFrog>; FrogsByName: TDictionary<string, TFrog>; constructor Create; destructor Destroy; override; procedure TrySearchFarm; end; The idea is that the Frogs list owns the frog objects, while the FrogsByID and FrogsByName dictionaries only refer to the frog objects without owning them. These are dictionaries using the IDs and the names as their keys. Implement it like so: { TFrogFarm }constructor TFrogFarm.Create;var Frog: TFrog;begin // Create the list that owns the frog objects Frogs := TObjectList<TFrog>.Create; // Create the dictionaries that refer to the frog objects without owning them FrogsByID := TDictionary<Integer, TFrog>.Create; FrogsByName := TDictionary<string, TFrog>.Create; // Create N random frogs with unique IDs and names repeat Frog := CreateRandomFrog; if not FrogsByID.ContainsKey(Frog.ID) and not FrogsByName.ContainsKey(Frog.Name) then begin Frogs.Add(Frog); // transfer of ownership FrogsByID.Add(Frog.ID, Frog); FrogsByName.Add(Frog.Name, Frog); end else Frog.Free; // if this weren't a simple test project, we'd protect this better until Frogs.Count = N;end;destructor TFrogFarm.Destroy;begin FreeAndNil(FrogsByName); FreeAndNil(FrogsByID); FreeAndNil(Frogs); inherited;end;procedure TFrogFarm.TrySearchFarm;var Frog: TFrog; S1, S2: string; c1, c2, f: Int64;begin QueryPerformanceFrequency(f); QueryPerformanceCounter(c1); if FrogsByID.TryGetValue(100, Frog) then S1 := 'There is a frog with ID 100.'#13#10'He or she lives at ' + Frog.Address + '.' else S1 := 'There is NO frog with ID 100.'; if FrogsByName.TryGetValue('Maggie A.M.D. Flower', Frog) then S2 := 'There is a frog named "Maggie A.M.D. Flower".'#13#10'She lives at ' + Frog.Address + '.' else S2 := 'There is NO frog named "Maggie A.M.D. Flower".'; QueryPerformanceCounter(c2); ShowMessage(S1 + sLineBreak + sLineBreak + S2 + sLineBreak + sLineBreak + 'Execution time: ' + Round(1000000*(c2 - c1)/f).ToString + ' Β΅s');end; To try this, do begin Randomize; while True do with TFrogFarm.Create do try TrySearchFarm; finally Free; end;end; Finding an element in a dictionary is an O(1) operation, so it is fast even in very large collections. And, indeed, with one million frogs in the farm ( N = 1000000 ), lookup takes about 2 microseconds on my system: | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63103305', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13952888/']} | jdg_381190 |
stackexchange | llm_judgeable_groundtruth_similarity | 29400 |
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:
What is the pH of a solution of $3.4 \times 10^{-10}$ moles of $\ce{HCl}$ in a volume of $\pu{150.7L}$? This is dilute so I expect pH to be high. $$\frac{3.4 \times 10^{-10}\ \mathrm{mol}}{150.7\ \mathrm L} = 2.26 \times 10^{-12} \frac{\mathrm{mol}}{\mathrm L}$$ Then pH is 11.65. Is this correct?
Now provide the response and nothing else.
| Like you guessed, the pH should be around 7, since the concentration of HCl is very low. Obviously, it can't be 11.65, since it's still an acid. The reason for this discrepancy is that, for low concentrations, you must consider the self-ionization of water in order to get the correct concentration of $\ce{H3O+}$ ions. Consider the equilibrium: $$\ce{2H2O <=> H3O+ + OH-}$$$$K_w = \ce{[H3O+][OH^{-}]} = 1 \times 10^{-14} \tag 1$$ and also the dissociation of the acid: $$\ce{H2O + HCl -> H3O+ + Cl-}$$ Then$$c_0 = \ce{[Cl^{-}]} = 2.26 \times 10^{-12} \tag 2 $$ and $$\ce{[H3O+] = [Cl^{-}] + [OH^{-}]} \Rightarrow \ce{[OH^{-}] = [H3O+] - [Cl^{-}]} \tag 3$$ If we replace $(2)$ in $(3)$ and that in $(1)$, we end up with $$ K_w = \ce{[H3O+]} (\ce{[H3O+]} -c_0) $$ $$ \ce{[H3O+]} (\ce{[H3O+]} -c_0) - K_w = 0$$ using $ x = \ce{[H3O+]}$ $$x^2 - c_0x - Kw = 0$$ This can be easily solved. Taking only the positive value of $x$: $$ x = \frac{c_0 + \sqrt{c_o^2 + 4K_w}}{2}$$ Inserting the values of $x$ and $K_w$, the result is: $$ x = 1.000023 \times 10^{-07} = \ce{[H3O+]}$$ So $$pH = -\log\ce{[H3O+]} = -\log{1.000011 \times 10^{-07}} = 6.999995 $$ Which is not surprising at all, but is the calculated answer. For a less diluted solution of $\ce{HCl}$ with concentration of $1 \times 10^{-8} \frac{mol}{L}$, which still can't be calulated directly, the result is $pH = 6.98$. | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/29400', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/15831/']} | jdg_381191 |
stackexchange | llm_judgeable_groundtruth_similarity | 3103204 |
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 a nice article with some concurrency tips , an example was optimized to the following lines: double getBalance() { Account acct = verify(name, password); synchronized(acct) { return acct.balance; }} If I understand that correctly, the point of the synchronization is to ensure that the value of acct.balance that are read by this thread is current and that any pending writes to the fields of the object in acct.balance are also written to main memory. The example made me think a little: wouldn't it be more efficient to just declare acct.balance (i.e. the field balance of class Account) as volatile ? It should be more efficient, save you all the synchronize on accesses to acct.balance and would not lock the whole acct object. Am I missing something?
Now provide the response and nothing else.
| You are correct. volatile provides a visibility guarantee. synchronized provides both a visibility guarantee AND serialisation of protected code sections. For VERY simple situations volatile is enough, however it is easy to get into trouble using volatile instead of synchronisation. If you were to assume that Account has a way of adjusting its balance then volatile is not good enough public void add(double amount){ balance = balance + amount;} Then we have a problem if balance is volatile with no other synchronization. If two threads were to try and call add() together you could have a "missed" update where the following happens Thread1 - Calls add(100)Thread2 - Calls add(200)Thread1 - Read balance (0)Thread2 - Read balance (0)Thread1 - Compute new balance (0+100=100)Thread2 - Compute new balance (0+200=200)Thread1 - Write balance = 100Thread2 - Write balance = 200 (WRONG!) Obviously this is wrong because both threads read the current value and updated independently and then wrote it back (read, compute, write). volatile does not help here so you would need synchronized to ensure one thread completed the entire update before the other thread began. I general find that if when writing some code I think "can I use volatile instead of synchronized" the answer might well be "yes" but the time/effort of figuring it out for sure and the danger of getting it wrong is not worth the benefit (minor performance). As an aside a well written Account class would handle all the synch logic internally so callers don't have to worry about it. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3103204', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/21499/']} | jdg_381192 |
stackexchange | llm_judgeable_groundtruth_similarity | 29742 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I just saw for the first time a new way to enter a password, at the Banque Postale (French Bank). You are given a virtual numeric keyboard and to type you can just leave the mouse cursor over a number for what seems like 1 second for it to be entered. At first this seems pretty nice, you don't have keyboard strokes to record, nor mouse clicks. Yet, I have the uncanny impression that there might be a problem with this system. The obvious one is that you are only allowed to put numbers in your password, would there be anything else?
Now provide the response and nothing else.
| These kinds of password entry systems are only good as long as the attackers do not adapt. It is a play in several acts: Bank Web sites use passwords which are entered the traditional way, with a keyboard. Key loggers appear, and harvest key strokes. After some cases of actual bank password theft, banks adapt. They implement "visual keyboards" in which the user clicks on some buttons which are labeled with letters or digits. After some time, attackers adapt. New-generation key loggers also record mouse click coordinates. These coordinates are sufficient to recompute the password. After some time, banks adapt. They now "shuffle" the labeled buttons so that they do not always show up on the same emplacement on the screen. Mouse click coordinates are no longer sufficient to recompute the password. After some time, attackers adapt. Next generation key loggers now take local screen shots, recording the pixels which are around the point where the user clicked. The screen shots are sufficient to recompute the password. After some time, banks adapt. Instead of clicks , the bank's Web site will react to some "hovering" without an actual click. The current key logger generation does not record "hovering", only clicks, so they are defeated. As you observe, we are currently at that point. Can you guess what is going to happen ? This is an arms race. The attackers force the banks to apply more convoluted password entry methods. The banks train attackers into defeating increasingly "secure" password entry methods. Simultaneously, banks try to train their customers into dealing with more complex password entry methods. In the long term, my bet is that attackers will evolve faster than customers; the banks fight a losing battle. | {} | {'log_upvote_score': 7, 'links': ['https://security.stackexchange.com/questions/29742', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/2976/']} | jdg_381193 |
stackexchange | llm_judgeable_groundtruth_similarity | 38037 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What are the potential vulnerabilities that might arise if a webpage is only partially encrypted. I can think of 2 possibilities: You can change the non-encrypted parts of the page (HTML, CSS, Images, JS) through a MITM attack to partially change the look of the page. You could inject malicious JS through the insecure connection in order to steal/modify the encrypted parts of the page thus rendering the entire connection insecure. Is the 2nd scenario possible or do web browsers incorporate some security mechanisms to prevent it from happening? This question also has implications with regards to the Stack Exchange n/w, since only the iframe containing the login form inside the login page is encrypted : https://meta.stackexchange.com/questions/96004/login-to-stack-exchange-account-doesnt-use-https-ssl Update: As @Ladada pointed out, this question is actually broken into multiple parts: Case 1: An insecure page loading a secure iframe to transmit confidential data Answer : As davidwebster48 pointed out in his answer, this mechanism is trivially defeated since the insecure parent page can be manipulated to load the iframe with a different page of the attacker's liking. As a side note, this means that StackExchange's login system is vulnerable to MITM attacks despite using https login forms. Case 2: A secure page loading an insecure page via an iframe (Assuming no confidential data is handled by the insecure iframe). This case is particularly interesting in that Same-Origin policies also come into the equation. Even if both pages may be from the same domain, since they both use different protocols, (one HTTPS and the other HTTP) this will cause same-origin restrictions to kick in. I am not sure whether these restrictions are enough to stop our attacker dead in his tracks. Case 3: A secure page linking to insecure JS My answer : I think this is obviously a fail since the attacker could modify the JS file to access/manipulate the entire page. Case 4: A secure page linking to insecure sources like images, CSS Could the attacker change enough of the look of the page to do a phishing attack? Or could he mount a Cross-Site Scripting attack?
Now provide the response and nothing else.
| Let's examine each case from the perspective of an active attacker Malroy and a passive attacker Eve. Case 1: An insecure page loading a secure iframe to transmit confidential data Passive: You're secure against passive attacks while you use the secure iframe. However, in the case of log-in iframes, if your session token is ever sent in the clear, Eve can impersonate you. (I still count impersonation as "passive" here, since Eve is not actively tampering with your connection; she's just making her own connections with new information she learned.) Active: If the HTML page itself is insecure, you've already totally lost. You can have every subresource on the page be securely transmitted, but it doesn't matter: Malroy has already rewritten your page to use totally different resources. Case 2: A secure page loading an insecure page via an iframe Passive: Obvious major problem here: anything you do in the iframe is in plain view. However, Eve can't see what you do in the top-level secure page. Still, the user is left confused about what elements on the page can be interacted with securely and which can't. Active: Malroy can make anything appear in the iframe; I hope you weren't using it for anything important. I don't think there's any way for Malroy to break out of the iframe and read or alter your outer secure page, because browsers already assume cross-origin iframes are not trustworthy. If there were a way to break out of the iframe, I think it would be considered a serious security bug in your browser (which isn't to say those don't exist, but that's an implementation problem, not a theoretical issue with mixed content). Case 3: A secure page linking to insecure JS Passive: Eve can learn what HTTPS site you are viewing, based on what HTTP resources you load. (Granted, she might be able to do this over a secure connection, based on destination IP address and size/pattern of the encrypted resources you fetch. Regardless, HTTP only makes things easier for her.) Active: As you guessed, Malroy can make your HTTPS page completely rewrite itself by feeding it an altered script. Case 4: A secure page linking to insecure sources like images, CSS Passive: Same as case 3, above. Active: CSS is pretty powerful. If Malroy could rewrite a CSS resource, he could do some pretty heavy presentation manipulation. As an example, perhaps Malroy re-styles a the inputs fields of a forum's "Create New Thread" page to look like a log-in page. This tricks the user into thinking his session has timed out, and he unwitting submits his credentials as a public new post. An active attacker could also use CSS to prompt a client to participate in a CSRF attack, e.g., by using background-image: url(http://www.bigbank.com/transfer?amt=1000000&to=malroy) . | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/38037', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/25963/']} | jdg_381194 |
stackexchange | llm_judgeable_groundtruth_similarity | 33325301 |
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 written a test script which runs another script to start the server to test. When the tests have completed a SIGKILL message is sent to the server process, however when running the test script again the server throws a EADDRINUSE error (Iβm in a node.js environment) which means the port the server is trying to mount to is currently in use. The process we tried to kill with a SIGKILL is still running. I donβt believe this is a node specific issue, but rather a lack of education on my end for how bash processes work. Here are some specifics, this is my start script called scripts/start-node.sh : #!/bin/bashnode_modules/.bin/babel-node --stage 0 index.js This is my node server called index.js (I havenβt authored any process event listeners): Http.createServer(β¦).listen(PORT, () => console.log(`Server listening on ${PORT}`)) And the start script is controlled with the node child_process module: var child = child_process.spawn('scripts/start-node.sh')// Laterβ¦child.kill('SIGKILL')
Now provide the response and nothing else.
| To kill a child process and all it's children you may use process.kill with a negative pid (to kill a process group) var child = child_process.spawn('scripts/start-node.sh', {detached: true})// Laterβ¦process.kill(-child.pid, 'SIGKILL'); See details on child_process documentation for options.detached On non-Windows, if the detached option is set, the child process will be made the leader of a new process group and session. Referencing here a portion of man 2 kill for some details: If pid is less than -1, then sig is sent to every process in the process group whose ID is -pid. Another option may be using trap in your shell script to intercept a signal and kill all the children and using child.kill('SIGTERM') from node (as SIGKILL will not be intercepted by trap ) #!/bin/bashtrap 'kill $(jobs -p)' EXITnode_modules/.bin/babel-node --stage 0 index.js | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33325301', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1568890/']} | jdg_381195 |
stackexchange | llm_judgeable_groundtruth_similarity | 30222423 |
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 getting this data from a service: {"ok":{"0147852369":"somevalue"}} I need to read the value, which in this example is "somevalue".Inside a variable I have the string that represents the name of the property containing "somevalue", like: var mobilereceiver = "0147852369"; But I can't figure out how to use that string to access the property with the same name. My latest try is like this: $http.get( 'url' ) .success(function(data) { var response = angular.fromJson(data); var mobilereceiver = '0147852369'; var messageId = response.ok.mobilereciever; }); I need to set the last var, messageId which should then hold the "somevalue" of the of the data I'm getting from the service. However, it isn't working. What am I doing wrong?
Now provide the response and nothing else.
| In order to catch Bluetooth state changes ( STATE_OFF , STATE_TURNING_ON , STATE_ON , STATE_TURNING_OFF ), do this: First, add Bluetooth permission to your AndroidManifest file: <uses-permission android:name="android.permission.BLUETOOTH" /> Create a BroadcastReceiver in your Activity or Service: private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) { final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR); switch(state) { case BluetoothAdapter.STATE_OFF: .. break; case BluetoothAdapter.STATE_TURNING_OFF: .. break; case BluetoothAdapter.STATE_ON: .. break; case BluetoothAdapter.STATE_TURNING_ON: .. break; } } }}; Create an IntentFilter and register it with BroadcastReceiver in your Activity/Service's onCreate() method: @Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); IntentFilter filter1 = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED); registerReceiver(mBroadcastReceiver1, filter1); ...} Unregister BroadcastReceiver in your onDestroy() method: @Overrideprotected void onDestroy() { super.onDestroy(); unregisterReceiver(mBroadcastReceiver1);} In order to catch changes of discoverability of device ( SCAN_MODE_NONE , SCAN_MODE_CONNECTABLE , SCAN_MODE_CONNECTABLE_DISCOVERABLE ), create another BroadcastReceiver and register/unregister to your Activity as I mentioned above. Only difference between those BroadcastReceivers is the first one uses BluetoothAdapter.EXTRA_STATE and the other one uses BluetoothAdapter.EXTRA_SCAN_MODE . Here is the example code for BroadcastReceiver to catch discoverability changes: Create an IntentFilter and register it in onCreate() method: IntentFilter filter2 = new IntentFilter();filter2.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);filter2.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);filter2.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);registerReceiver(mBroadcastReceiver2, filter2); Create the BroadcastReciver in Activity/Service to catch discoverability changes: private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); if(action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) { int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR); switch(mode){ case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE: .. break; case BluetoothAdapter.SCAN_MODE_CONNECTABLE: .. break; case BluetoothAdapter.SCAN_MODE_NONE: .. break; } } }}; And lastly unregister BroadcastReciver in onDestroy() : unregisterReceiver(mBroadcastReceiver2); Note that, you don't need to add any <intent-filter> or <receiver> to your AndroidManifest file, except you need to add Bluetooth permission of course. If you want to catch ( ACTION_ACL_CONNECTED , ACTION_ACL_DISCONNECTED , ACTION_ACL_DISCONNECT_REQUESTED ), now you need to add an <intent-filter> to your AndroidManifest file: <intent-filter> <action android:name="android.bluetooth.device.action.ACL_CONNECTED" /> <action android:name="android.bluetooth.device.action.ACL_DISCONNECTED" /></intent-filter> Create filter and register it in onCreate() method: IntentFilter filter3 = new IntentFilter();filter3.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);filter3.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);registerReceiver(mBroadcastReceiver3, filter3); Then create the BroadcastReceiver in your Activity/Service: private final BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); switch (action){ case BluetoothDevice.ACTION_ACL_CONNECTED: .. break; case BluetoothDevice.ACTION_ACL_DISCONNECTED: .. break; } }}; And lastly, unregister: unregisterReceiver(mBroadcastReceiver3); If you want to read more about state constants, this is from the documentation: public static final String EXTRA_STATE : Used as an int extra field in ACTION_STATE_CHANGED intents to requestthe current power state. Possible values are: STATE_OFF,STATE_TURNING_ON, STATE_ON, STATE_TURNING_OFF public static final String EXTRA_SCAN_MODE : Used as an int extra field in ACTION_SCAN_MODE_CHANGED intents torequest the current scan mode. Possible values are: SCAN_MODE_NONE,SCAN_MODE_CONNECTABLE, SCAN_MODE_CONNECTABLE_DISCOVERABLE | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/30222423', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2578942/']} | jdg_381196 |
stackexchange | llm_judgeable_groundtruth_similarity | 32059370 |
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 this question , an issue arose that could be solved by changing an attempt at using a generic type parameter into an associated type. That prompted the question "Why is an associated type more appropriate here?", which made me want to know more. The RFC that introduced associated types says: This RFC clarifies trait matching by: Treating all trait type parameters as input types , and Providing associated types, which are output types . The RFC uses a graph structure as a motivating example, and this is also used in the documentation , but I'll admit to not fully appreciating the benefits of the associated type version over the type-parameterized version. The primary thing is that the distance method doesn't need to care about the Edge type. This is nice but seems a bit shallow of a reason for having associated types at all. I've found associated types to be pretty intuitive to use in practice, but I find myself struggling when deciding where and when I should use them in my own API. When writing code, when should I choose an associated type over a generic type parameter, and when should I do the opposite?
Now provide the response and nothing else.
| This is now touched on in the second edition of The Rust Programming Language . However, let's dive in a bit in addition. Let us start with a simpler example. When is it appropriate to use a trait method? There are multiple ways to provide late binding : trait MyTrait { fn hello_word(&self) -> String;} Or: struct MyTrait<T> { t: T, hello_world: fn(&T) -> String,}impl<T> MyTrait<T> { fn new(t: T, hello_world: fn(&T) -> String) -> MyTrait<T>; fn hello_world(&self) -> String { (self.hello_world)(self.t) }} Disregarding any implementation/performance strategy, both excerpts above allow the user to specify in a dynamic manner how hello_world should behave. The one difference (semantically) is that the trait implementation guarantees that for a given type T implementing the trait , hello_world will always have the same behavior whereas the struct implementation allows having a different behavior on a per instance basis. Whether using a method is appropriate or not depends on the usecase! When is it appropriate to use an associated type? Similarly to the trait methods above, an associated type is a form of late binding (though it occurs at compilation), allowing the user of the trait to specify for a given instance which type to substitute. It is not the only way (thus the question): trait MyTrait { type Return; fn hello_world(&self) -> Self::Return;} Or: trait MyTrait<Return> { fn hello_world(&Self) -> Return;} Are equivalent to the late binding of methods above: the first one enforces that for a given Self there is a single Return associated the second one, instead, allows implementing MyTrait for Self for multiple Return Which form is more appropriate depends on whether it makes sense to enforce unicity or not. For example: Deref uses an associated type because without unicity the compiler would go mad during inference Add uses an associated type because its author thought that given the two arguments there would be a logical return type As you can see, while Deref is an obvious usecase (technical constraint), the case of Add is less clear cut: maybe it would make sense for i32 + i32 to yield either i32 or Complex<i32> depending on the context? Nonetheless, the author exercised their judgment and decided that overloading the return type for additions was unnecessary. My personal stance is that there is no right answer. Still, beyond the unicity argument, I would mention that associated types make using the trait easier as they decrease the number of parameters that have to be specified, so in case the benefits of the flexibility of using a regular trait parameter are not obvious, I suggest starting with an associated type. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/32059370', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/155423/']} | jdg_381197 |
stackexchange | llm_judgeable_groundtruth_similarity | 28449 |
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've written some code to calculate Poisson confidence limits (a) using Chi-squared, and (b) from first principles, using Poisson's probability mass function equation. However, the two sets of results don't agree. For example, for Lambda=10 and 95% confidence limits, I get: 95%: Chi squared [4.80, 18.39] Exact [3, 17] The discrepancy is worse for wider confidence limits: 3 sigma: Chi squared [3.08, 23.64] Exact [1, 21] Note that my 'exact' result shows the first k outside the confidence limits (in other words, the range [4,16] is completely inside the 95% range). My 95% Chi squared result above agrees with several online Poisson limits calculators. Statpages , for example, also gives [4.80, 18.39]. However, the exact result also appears to be correct. For 95%, the online calculator at Stattrek appears to give the same results as my exact [3,17]. More precisely, here are cumulative probabilities for lambda=10 taken from a table here : 0 - 2 events: negligible3 1.0%4 2.9%...15 95.1%16 97.3%17 98.6% So, the 95 confidence limits are for 4 to 16 events, inclusive, which agrees with my program output, which says that <= 3 events, or >= 17 events, are outside the 95% limits. Have I got this wrong somewhere? Is it just that Lambda=10 is too small for the chi-squared method to be exact? If I increase Lambda to 100 I get: 95%: Chi squared [81.36, 121.63] Exact [80, 120] 3 sigma: Chi squared [72.65, 133.83] Exact [70, 131] It essentially makes no difference. I can live with the fact that the inexact result is continuous, but not with the inaccuracy. EDIT Thanks for the comments, everyone. As I understand it, the basic answer is that they both provide confidence limits, but they're different, and I shouldn't expect them to be the same, and should just live with it - correct? For background, this is for analysing healthcare providers, and finding out if any differ significantly from the average. The important thing here (for me, anyway) is not to point the finger at somebody and say that they're outside the 2 or 3 SD limits, when another analysis could show that they're actually inside the limits. For the same reason, I don't care that a discrete method doesn't give me exact 95% coverage - I just need to positively identify outliers. My own background isn't stats, but I do understand the exact method, and I'm happy that it gives the "right" answer (notwithstanding the fact that the processes aren't really appropriate for Poisson). However, I don't understand the Poisson/Chi-squared transformation, and I'm not happy with it for this application, because it 'incorrectly' adds outliers at the low end of the range (not to mention missing 'real' outliers at the top). However, it is universally used for exactly this application. Would it be fair for me to say that the exact method is better for this application, and the approximation is simply that, and it is incorrect?
Now provide the response and nothing else.
| I am going to elaborate my comment, as suggested by @gung. I will also include the violin plot suggested by @Alexander, for completeness. Some of these tools can be used for comparing more than two samples. # Required packageslibrary(sn)library(aplpack)library(vioplot)library(moments)library(beanplot)# Simulate from a normal and skew-normal distributionsx = rnorm(250,0,1)y = rsn(250,0,1,5)# Separated histogramshist(x)hist(y)# Combined histogramshist(x, xlim=c(-4,4),ylim=c(0,1), col="red",probability=T)hist(y, add=T, col="blue",probability=T)# Boxplotsboxplot(x,y)# Separated smoothed densitiesplot(density(x))plot(density(y))# Combined smoothed densitiesplot(density(x),type="l",col="red",ylim=c(0,1),xlim=c(-4,4))points(density(y),type="l",col="blue")# Stem-and-leaf plotsstem(x)stem(y)# Back-to-back stem-and-leaf plotsstem.leaf.backback(x,y)# Violin plot (suggested by Alexander)vioplot(x,y)# QQ-plotqqplot(x,y,xlim=c(-4,4),ylim=c(-4,4))qqline(x,y,col="red")# Kolmogorov-Smirnov testks.test(x,y)# six-numbers summarysummary(x)summary(y)# moment-based summaryc(mean(x),var(x),skewness(x),kurtosis(x))c(mean(y),var(y),skewness(y),kurtosis(y))# Empirical ROC curvexx = c(-Inf, sort(unique(c(x,y))), Inf)sens = sapply(xx, function(t){mean(x >= t)})spec = sapply(xx, function(t){mean(y < t)})plot(0, 0, xlim = c(0, 1), ylim = c(0, 1), type = 'l')segments(0, 0, 1, 1, col = 1)lines(1 - spec, sens, type = 'l', col = 2, lwd = 1)# Beanplotsbeanplot(x,y)# Empirical CDFplot(ecdf(x))lines(ecdf(y)) I hope this helps. | {} | {'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/28449', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/11302/']} | jdg_381198 |
stackexchange | llm_judgeable_groundtruth_similarity | 10465875 |
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 experimenting with the concept of pure-static-linked PIE executables on Linux, but running into the problem that the GNU binutils linker insists on adding a PT_INTERP header to the output binary when -pie is used, even when also given -static . Is there any way to inhibit this behavior? That is, is there a way to tell GNU ld specifically not to write certain headers to the output file? Perhaps with a linker script? (Please don't answer with claims that it won't work; I'm well aware that the program still needs relocation processing - load-address-relative relocations only due to my use of -Bsymbolic - and I have special startup code in place of the standard Scrt1.o to handle this. But I can't get it to be invoked without the dynamic linker already kicking in and doing the work unless hexedit the PT_INTERP header out of the binary.)
Now provide the response and nothing else.
| I think I might have found a solution: simply using -shared instead of -pie to make pie binaries. You need a few extra linker options to patch up the behavior, but it seems to avoid the need for a custom linker script. Or in other words, the -shared linker script is already essentially correct for linking static pie binaries. If I get it working with this, I'll update the answer with the exact command line I'm using. Update: It works! Here's the command line: gcc -shared -static-libgcc -Wl,-static -Wl,-Bsymbolic \ -nostartfiles -fPIE Zcrt1.s Zcrt2.c /usr/lib/crti.o hello.c /usr/lib/crtn.o where Zcrt1.s is a modified version of Scrt1.s that calls a function in Zcrt2.c before doing its normal work, and the code in Zcrt2.c processes the aux vector just past the argv and environment arrays to find the DYNAMIC section, then loops over the relocation tables and applies all the relative-type relocations (the only ones that should exist). Now all of this can (with a little work) be wrapped up into a script or gcc specfile... | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10465875', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/379897/']} | jdg_381199 |
stackexchange | llm_judgeable_groundtruth_similarity | 1890385 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am learning about minimal polynomials with respect to determining the largest size of a Jordan block for a given eigenvalue. My question is: when we have two or more eigenvalues with multiplicity of two or more, how can we be sure when we have found the minimal polynomial? For example, let's say our characteristic polynomial is $(t-2)^3 (t+5)^2$. So we test the simplest polynomials first to see if the given matrix $A$ will yield a zero . . .We try first $(t-2) (t+5)$ and let's say it is not zero. So here's the crux of my question: what if my next try is $(t-2)^2 (t+5)$ and I get a zero? Wouldn't I also have to try $(t-2) (t+5)^2$? What if both of these give me a zero?
Now provide the response and nothing else.
| Suppose $\tau$ is such a topology. For clarity, I'll use "open" to mean open in the usual sense, and "$\tau$-open" to mean open in the new topology, $\tau$; similarly with "continuous" and "$\tau$-continuous." We'll show that $\tau$ is in fact a refinement of the usual topology on $\mathbb{R}$. The only fact about the usual topology used is $$(*)\quad\mbox{No map $h:\mathbb{R}\rightarrow\mathbb{R}$ whose range has exactly two elements is continuous.}$$ We begin by showing that $\tau$ is $T_1$. Take $a\neq b$, and take two non-empty subsets $A,B$ with $A\cap B=\varnothing$ and $A\cup B=\mathbb R$ and with $B$ $\tau$-open. Such $A, B$ exist since $\tau$ is not indiscrete: if $\tau$ were, it would have too many continuous functions. Now by $(*)$, the function that sends $A$ to $a$ and $B$ to $b$ is not continuous in the usual topology, so it is not $\tau$-continuous either. Since $f$ isn't $\tau$-continuous, we must have that $A$ is not $\tau$-open. Now, the only $f$-preimages are $\emptyset, B, \mathbb{R}, A$; the only one of these which is not $\tau$-open is $A$, so for $f$ to not be $\tau$-continuous there must be some $\tau$-open set $U$ with $f^{-1}(U)=A$. That is, there must be a $\tau$-open set that contains $a$ and not $b$. So we have that $\tau$ is $T_1$. (Note: $\tau$ is also connected by the same argument, but that's not directly useful for the rest of this argument.) We can now prove that $\tau$ refines the usual topology. Since $\tau$ is $T_1$, we know that $\mathbb R\setminus \{x\}$ is $\tau$-open for all $x$. For $a\in\mathbb{R}$, consider the function $f_a(x)=\max(a,x)$. This function is continuous and hence $\tau$-continuous. Since $\mathbb R\setminus \{a\}$ is $\tau$-open, its $f_a$-preimage must be $\tau$-open; that is, $(a,\infty)$ is $\tau$-open. We can prove $(-\infty,a)$ is open analogously. Intersecting open sets, we get that $(a, b)$ is $\tau$-open for every $a,b\in\mathbb{R}$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1890385', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/361001/']} | jdg_381200 |
stackexchange | llm_judgeable_groundtruth_similarity | 15928216 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need a regular expression for a string with exactly one alphabetic character in it. For example, it should match: 8*x=16 x+2=2 u329398239823 43044343k43304403 ...but not: xsfdjfefljefe 44434f9434343 f 98(***(*)))(*)(0((-900-87 32233232
Now provide the response and nothing else.
| /^[^a-z]*([a-z])[^a-z]*$/i i for case-insensitive matching. ^ and $ anchors to force the regex to match the entire string. ( ) to capture the letter. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15928216', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1461607/']} | jdg_381201 |
stackexchange | llm_judgeable_groundtruth_similarity | 8224270 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I get the string before the character "-" using regular expressions? For example, I have "text-1" and I want to return "text" .
Now provide the response and nothing else.
| So I see many possibilities to achieve this. string text = "Foobar-test"; Regex Match everything till the first "-" Match result = Regex.Match(text, @"^.*?(?=-)"); ^ match from the start of the string .*? match any character ( . ), zero or more times ( * ) but as less as possible ( ? ) (?=-) till the next character is a "-" (this is a positive look ahead) Regex Match anything that is not a "-" from the start of the string Match result2 = Regex.Match(text, @"^[^-]*"); [^-]* matches any character that is not a "-" zero or more times Regex Match anything that is not a "-" from the start of the string till a "-" Match result21 = Regex.Match(text, @"^([^-]*)-"); Will only match if there is a dash in the string, but the result is then found in capture group 1. Split on "-" string[] result3 = text.Split('-'); Result is an Array the part before the first "-" is the first item in the Array Substring till the first "-" string result4 = text.Substring(0, text.IndexOf("-")); Get the substring from text from the start till the first occurrence of "-" ( text.IndexOf("-") ) You get then all the results (all the same) with this Console.WriteLine(result);Console.WriteLine(result2);Console.WriteLine(result21.Groups[1]);Console.WriteLine(result3[0]);Console.WriteLine(result4); I would prefer the first method. You need to think also about the behavior, when there is no dash in the string. The fourth method will throw an exception in that case, because text.IndexOf("-") will be -1 . Method 1 and 2.1 will return nothing and method 2 and 3 will return the complete string. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/8224270', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/716092/']} | jdg_381202 |
stackexchange | llm_judgeable_groundtruth_similarity | 3586240 |
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 you have a rational point $\Big( \frac{a}{b}, \frac{c}{d} \Big)$ on the unit circle $x^2 + y^2 = 1$ such that both coordinates are in lowest terms. What is the quickest way to show that $b$ and $d$ must both be odd? (if possible, without resorting to the Pythagorean triple standard form construction). I aim to assign a problem to my students which would require them to prove this fact, but we have not covered the proof for the standard form of Pythagorean triples.
Now provide the response and nothing else.
| The condition is equivalent to $a^2d^2 + c^2 b^2 = b^2d^2$ . Suppose $b$ is even and $b = 2^k m$ , with $k \geq 1$ and $m $ odd. Then $a$ is odd and $a^2d^2 + 2^{2k} m^2c^2 = 2^{2k} m^2d^2$ , which implies that $2^k$ divides $d$ . Reverse the roles of $b$ and $d$ to conclude that $b = 2^k m$ and $d = 2^k n$ with $k \geq 1$ and $m, n$ both odd. But then $(ma)^2 + (nc)^2 = m^2a^2 + n^2c^2 = 2^{2k} m^2n^2 \equiv 0 \pmod{4}$ , which is impossible, since $ma$ and $nc$ are odd numbers and $(odd)^2 \equiv 1 \pmod{4}$ . Therefore $b$ is odd and, by symmetry, $d$ is odd as well. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3586240', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/91299/']} | jdg_381203 |
stackexchange | llm_judgeable_groundtruth_similarity | 27835064 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
having problem in getting image orientation with below code string fileName = @"D:\...\...\01012015004435.jpeg"; int rotate = 0; using (var image = System.Drawing.Image.FromFile(fileName)) { foreach (var prop in image.PropertyItems) { if (prop.Id == 0x112) { if (prop.Value[0] == 6) rotate = 90; if (prop.Value[0] == 8) rotate = -90; if (prop.Value[0] == 3) rotate = 180; prop.Value[0] = 1; } } } and after get proper orientation i used to rotate image like private static RotateFlipType OrientationToFlipType(string orientation){ switch (int.Parse(orientation)) { case 1: return RotateFlipType.RotateNoneFlipNone; break; case 2: return RotateFlipType.RotateNoneFlipX; break; case 3: return RotateFlipType.Rotate180FlipNone; break; case 4: return RotateFlipType.Rotate180FlipX; break; case 5: return RotateFlipType.Rotate90FlipX; break; case 6: return RotateFlipType.Rotate90FlipNone; break; case 7: return RotateFlipType.Rotate270FlipX; break; case 8: return RotateFlipType.Rotate270FlipNone; break; default: return RotateFlipType.RotateNoneFlipNone; }} but problem is in first code prop.Id i always get [20625] prop.Id == 20625 so not satisfy the condition every time please let me know if any problem or other option thanks
Now provide the response and nothing else.
| There's probably enough information in the other answers and comments to put this all together, but here's a working code example. This extension method will take a System.Drawing Image , read its Exif Orientation tag (if present), and flip/rotate it (if necessary). private const int exifOrientationID = 0x112; //274public static void ExifRotate(this Image img){ if (!img.PropertyIdList.Contains(exifOrientationID)) return; var prop = img.GetPropertyItem(exifOrientationID); int val = BitConverter.ToUInt16(prop.Value, 0); var rot = RotateFlipType.RotateNoneFlipNone; if (val == 3 || val == 4) rot = RotateFlipType.Rotate180FlipNone; else if (val == 5 || val == 6) rot = RotateFlipType.Rotate90FlipNone; else if (val == 7 || val == 8) rot = RotateFlipType.Rotate270FlipNone; if (val == 2 || val == 4 || val == 5 || val == 7) rot |= RotateFlipType.RotateNoneFlipX; if (rot != RotateFlipType.RotateNoneFlipNone) { img.RotateFlip(rot); img.RemovePropertyItem(exifOrientationID); }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27835064', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1776296/']} | jdg_381204 |
stackexchange | llm_judgeable_groundtruth_similarity | 23020857 |
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 connect to a database in Mariadb through a simple java application but the connection is told to be unsuccessful and an Exception is thrown. I have done the similar connection using mysql and it was working correctly. The problem is maybe with the driver here. try{ Class.forName("org.mariadb.jdbc.Driver"); Connection connection = DriverManager.getConnection( "jdbc:mariadb://localhost:3306/project", "root", ""); Statement statement = connection.createStatement(); String uname="xyz",pass="abc"; statement.executeUpdate("insert into user values('"+uname+"','"+pass+"')");}//end of try block I looked up the internet for the help and came by that driver class provided by the MariaDB Client Library for Java Applications is not com.mysql.jdbc.Driver but org.mariadb.jdbc.Driver! I changed it accordingly but it seems the problem is with the very first line inside the try block. The driver is not loading at all.Also, I have added the mysql jar file to the libraries of my java application as in the screen-shot below. Please help me through this.
Now provide the response and nothing else.
| It appears that you are trying to use jdbc:mariadb://... to establish a connection to a MariaDB server instance using the MySQL JDBC Driver. That probably won't work because the MySQL JDBC Driver would use jdbc:mysql://... , regardless of whether it is connecting to a MySQL server or a MariaDB server. That is, the connection string must match the driver that is being used (rather than the database server being accessed). The MySQL and MariaDB drivers are supposed to be somewhat interchangeable, but it only seems prudent to use the MariaDB connector when accessing a MariaDB server. For what it's worth, the combination of mariadb-java-client-1.1.7.jar and Connection con = DriverManager.getConnection( "jdbc:mariadb://localhost/project", "root", "whatever"); worked for me. I downloaded the MariaDB Client Library for Java from here: https://downloads.mariadb.org/client-java/1.1.7/ which I arrived at via https://downloads.mariadb.org/ Additional notes: There is no need for a Class.forName() statement in your Java code. The default configuration for MariaDB under Mageia may include the skip-networking directive in /etc/my.cnf . You will need to remove (or comment out) that directive if you want to connect to the database via JDBC because JDBC connections always look like "network" connections to MySQL/MariaDB, even if they are connections from localhost . (You may need to tweak the bind-address value to something like 0.0.0.0 as well.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23020857', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/918385/']} | jdg_381205 |
stackexchange | llm_judgeable_groundtruth_similarity | 4174435 |
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\subsetneq[0,1]$ be some countable set of real numbers. Since the rationals are dense in the reals and since all countable linear orders are embeddable into $\mathbb{Q}$ , it seems to me that there has to be a map $f:A\rightarrow[0,1]_\mathbb{Q}$ with $[0,1]_\mathbb{Q}$ being the rational interval such that for any $a\in A$ : $$a\leq a'\text{ iff }f(a)\leq f(a')$$ Is it possible to construct $f$ explicitly, without resorting to the axiom of choice? $f$ does not have to be onto.
Now provide the response and nothing else.
| From my limited understanding of set theory, you can do this with induction without using any variant of the axiom of choice at all. Since $A$ is countable, you are assuming there exists some enumeration of its elements $\{a_n\}_{n\in\mathbb{N}}$ . Start with the empty map mapping the empty subset of $A$ to an empty subset of $\mathbb{Q}\cap [0,1]$ . The induction step is assuming you already have a mapping of $a_1,...,a_k$ to some rationals in this interval $b_1, ..., b_k$ that preserves the linear order. To perform the induction step you need to choose a rational to send $a_{k+1}$ to. Ok. There's a unique pair $a_s, a_t$ such that $s, t \le k$ , $a_s$ and $a_t$ are adjacent in the linear order and $a_{k+1}$ is between them. So Let $b_{k+1} = (b_s+b_t)/2$ . You need to handle the case where $a_{k+1}$ is to the left, or right of all $\{a_1, ..., a_k\}$ and make sure you don't go beyond the interval $[0,1]$ . I'll let you complete the detail, but the point is there is no use of the axiom of choice because you're giving an algorithm how to choose $b_{k+1}$ . To finish the proof, you take the union of all finite partial maps you constructed this way to get a complete mapping of $\{a_n\}_{n\in\mathbb{N}}$ to $\{b_n\}_{n\in\mathbb{N}}$ . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4174435', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/373927/']} | jdg_381206 |
stackexchange | llm_judgeable_groundtruth_similarity | 4428284 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am currently working on replicating some results from the following paper: https://arxiv.org/abs/1803.00798 https://onlinelibrary.wiley.com/doi/abs/10.1002/jae.2846 In it, the authors define the square-integrable functions somewhat unconventional in that they consider two functions that differ on a set of Lebesgue-measure zero to be distinct. So effectively, we are not looking at the equivalence classes but the functions themselves. If I understand the paper correctly, the authors later make use of the fact that the Fourier basis is a complete orthogonal basis of the space of square-integrable functions when approximating a functional integral over $L^2$ .My question is, whether this way of defining $L^2$ creates a problem with the desired properties of the Fourier basis. Sadly, my theoretical knowledge in this area is somewhat lacking and I would be glad to have any advice. [I originally asked this question on CrossValidated, but I was told that this is probably the more appropriate place.]
Now provide the response and nothing else.
| Too long for a comment Using the recommendation of @Gribouillis, integrating by part several times, using the fact that the integrand is even and denoting $\,\Big[\frac{1}{1+x^8}\Big]^{(k)}=\frac{d^k}{dx^k}\frac{1}{1+x^8}$ $$I(n)=2\int_0^\pi \frac{\cos (2 n x)}{1+x^{8}} d x=\frac{1}{n}\frac{\sin 2nx}{1+x^8}\bigg|_{x=0}^{x=\pi}+\frac{1}{n}\int_0^\pi \sin (2 n x)\Big[\frac{1}{1+x^8}\Big]^{(1)}d x$$ $$=-\frac{1}{2n^2}\cos (2 n x)\Big[\frac{1}{1+x^8}\Big]^{(1)}\bigg|_{x=0}^{x=\pi}+\frac{1}{2n^2}\int_0^\pi \cos (2 n x)\Big[\frac{1}{1+x^8}\Big]^{(2)}d x$$ $$=-\frac{4}{n^2}\frac{\pi^7}{(1+\pi^8)^2}+\frac{1}{4n^3}\sin (2 n x)\Big[\frac{1}{1+x^8}\Big]^{(2)}\bigg|_{x=0}^{x=\pi}-\frac{1}{4n^3}\int_0^\pi \sin (2 n x)\Big[\frac{1}{1+x^8}\Big]^{(3)}d x$$ $$=-\frac{4}{n^2}\frac{\pi^7}{(1+\pi^8)^2}+\frac{1}{8n^4}\cos (2 n x)\Big[\frac{1}{1+x^8}\Big]^{(3)}\bigg|_{x=0}^{x=\pi}-\frac{1}{8n^4}\int_0^\pi \cos (2 n x)\Big[\frac{1}{1+x^8}\Big]^{(4)}d x$$ Evaluating the third term: $$\frac{1}{8n^4}\bigg|\int_0^\pi \cos (2 n x)\Big[\frac{1}{1+x^8}\Big]^{(4)}d x\bigg|<\frac{1}{8n^4}\bigg|\int_0^\pi \Big[\frac{1}{1+x^8}\Big]^{(4)}d x\bigg|<\frac{\operatorname{Const}}{8n^4}$$ Therefore, $$I(n)=-\frac{4}{n^2}\frac{\pi^7}{(1+\pi^8)^2}+O\Big(\frac{1}{n^4}\Big)$$ and $$\lim_{n\to\infty}n^3I(n)=\lim_{n\to\infty}\Big(-n\frac{4\pi^7}{(1+\pi^8)^2}\Big)=-\infty$$ Numeric check at WolframAlpha confirms the result. At $n=10 \,000$ $$10^{12}\int_{-\pi}^\pi\frac{\cos(20\,000\, x)}{1+x^8}dx=-1.341589316...$$ while $$-\frac{4\pi^7}{(1+\pi^8)^2}\cdot 10\,000=-1.341589346...$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4428284', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/735870/']} | jdg_381207 |
stackexchange | llm_judgeable_groundtruth_similarity | 141636 |
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:
You can get my data by this code {data1, data2} = Uncompress[FromCharacterCode@ Flatten[ImageData[Import["https://i.stack.imgur.com/ShSMY.png"], "Byte"]]]; We can show it with ListLinePlot ListLinePlot[{data1, data2}, PlotRange -> All] Note the peaks of data1 and data2 is not same totally.I want to calculate the amount of offset in x-axis direction after we align data1 and data2 as far as possible .This current try offset = Length[data1] - SmithWatermanSimilarity @@ (PeakDetect[Last /@ #] & /@ {data1,data2});First[Commonest[Differences[First /@ data1]]]*offset 17.4 As we can see,the error is very big.I think two diffcult in this solution result to this The x-interval is not exactly same. Union[Differences[First /@ data1]] {0.01,0.02,0.02,0.02,0.02,0.02,0.03,0.03}(*funny to get so many 0.02.*) The peak is not exactly same. Is there any better method can do this?
Now provide the response and nothing else.
| Could also use ListCorrelate . {data1, data2} = Uncompress[ FromCharacterCode@ Flatten[ImageData[Import["https://i.stack.imgur.com/ShSMY.png"], "Byte"]]]; We remove the x axis values for now. data1b = data1[[All, 2]];data2b = data2[[All, 2]];lc = Reverse[Chop[ListCorrelate[data1b, data2b, {-1, -1}, 0]]];maxPos = Ordering[lc, -1][[1]] (* Out[98]= 33 *) So we want to push the second set by 33-1 = 32 units along the +x axis. We'll see how that looks. ListLinePlot[{data1b, Join[Take[data2b, maxPos - 1], data2b]}, PlotRange -> All] One might wish to preprocess to remove the lower values, and possibly clip high ones. I used the code below for that purpose. In this case it did not change the outcome. reScale[data_] := Module[{mn = Mean[data], newd}, newd = Clip[Threshold[data - Mean[data], mn/2], {0, mn/2}]]data1c = reScale[data1b];data2c = reScale[data2b]; --- edit --- I should remark that what I did is quite similar to the (arguably more scientific) approach shown by @mikado. If I did not zero-pad the ListCorrelate the list plot would be identical, up to a constant scale factor, to that of cc in the @mikado response. --- end edit --- | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/141636', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/21532/']} | jdg_381208 |
stackexchange | llm_judgeable_groundtruth_similarity | 37732135 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For each row of my data I'd like to compute the sum of most recent value for each group : dt = data.table(group = c('a','b','a','a','b','a'), value = c(10, 5, 20, 15, 15, 10), desired = c(10, 15, 25, 20, 30, 25))# group value desired#1: a 10 10#2: b 5 15#3: a 20 25 # latest value of a is 20, of b is 5#4: a 15 20 # latest value of a is 15, of b is 5#5: b 15 30#6: a 10 25 desired column is what I want to achieve, and I can do this with a naive loop, but my data is quite large with a lot of rows and groups (1M+ rows, 1000+ groups). for (i in seq_len(nrow(dt))) { # can use `set` to make this faster, but still too slow # this is just to illustrate *a* solution dt[i, desired1 := dt[1:i, value[.N], by = group][, sum(V1)]]}
Now provide the response and nothing else.
| Even simpler logic from @eddi (under comments) reducing the roundabout one shown below: dt[, incr := diff(c(0, value)), by = group][, ans := cumsum(incr)] Not sure how it extends to more groups, but here's on an example data with 3 groups: # I hope I got the desired output correctlyrequire(data.table)dt = data.table(group = c('a','b','c','a','a','b','c','a'), value = c(10, 5, 20, 25, 15, 15, 30, 10), desired = c(10, 15, 35, 50, 40, 50, 60, 55)) Add an rleid : dt[, id := rleid(group)] Extract the last row for each group, id : last = dt[, .(value=value[.N]), by=.(group, id)] last will have unique id . Now the idea is to get the increment for each id , and then join+update back. last = last[, incr := value - shift(value, type="lag", fill=0L), by=group ][, incr := cumsum(incr)-value][] Join + update now: dt[last, ans := value + i.incr, on="id"][, id := NULL][]# group value desired ans# 1: a 10 10 10# 2: b 5 15 15# 3: c 20 35 35# 4: a 25 50 50# 5: a 15 40 40# 6: b 15 50 50# 7: c 30 60 60# 8: a 10 55 55 I'm not yet sure where/if this breaks.. will look at it carefully now. I wrote it immediately so that there are more eyes on it. Comparing on 500 groups with 10,000 rows with David's solution: require(data.table)set.seed(45L)groups = apply(matrix(sample(letters, 500L*10L, TRUE), ncol=10L), 1L, paste, collapse="")uniqueN(groups) # 500LN = 1e4Ldt = data.table(group=sample(groups, N, TRUE), value = sample(100L, N, TRUE))arun <- function(dt) { dt[, id := rleid(group)] last = dt[, .(value=value[.N]), by=.(group, id)] last = last[, incr := value - shift(value, type="lag", fill=0L), by=group ][, incr := cumsum(incr)-value][] dt[last, ans := value + i.incr, on="id"][, id := NULL][] dt$ans}david <- function(dt) { dt[, indx := .I] res <- dcast(dt, indx ~ group) for (j in names(res)[-1L]) set(res, j = j, value = res[!is.na(res[[j]])][res, on = "indx", roll = TRUE][[j]]) rowSums(as.matrix(res)[, -1], na.rm = TRUE)}system.time(ans1 <- arun(dt)) ## 0.024ssystem.time(ans2 <- david(dt)) ## 38.97s identical(ans1, as.integer(ans2))# [1] TRUE | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37732135', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/817778/']} | jdg_381209 |
stackexchange | llm_judgeable_groundtruth_similarity | 26121997 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am developing POS application for shop. The Shop keeper can use any brand of BarCode Scanner devices. I need to get the details of the scanned item. Is there any library file available for the same. FYI External barcode scanner is connected to the device via USB. I need the event to fetch the data scanned and sent from the scanner.
Now provide the response and nothing else.
| i think every single barcode scanner have integration support for android, but what i need is to give common support for all or more external barcode scanners. It sounds like you are looking for something that you yourself admit doesn't exist. There isn't a common standard that ALL scanners implement for proper Android integration. That said, here's how you can achieve your two goals Any Brand : Most barcode scanners support HID mode, which is basically just connecting as a keyboard; this is how practically all USB scanners work. Using HID mode the scanner will "type" the barcode wherever the cursor is located, which doesn't give you much control. End event : Again, most barcode scanners can be configured to append a trailing character. Usually it defaults to a carriage return or tab. In your activity or view you can set an onKeyListener and in that listener you watch for the KEY_DOWN event of your trailing character which indicates the end of a scan. Using HID and trailing character detection you will be able to support most wired and wireless scanners | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26121997', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1085737/']} | jdg_381210 |
stackexchange | llm_judgeable_groundtruth_similarity | 41329851 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I see a lot of questions on stackoverflow on this. But still I'm not able to know what is the issue in my way of building projects. I've two spring boot projects: we-data and we-web. we-web is dependent on we-data. we-data compiles fine on maven. But we-web gives me above error. we-data pom: <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.we</groupId> <artifactId>data</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>we-data</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.2.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project> we-web pom: <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.we</groupId> <artifactId>web</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>we-web</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.2.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>com.we</groupId> <artifactId>data</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project> Everytime I do maven "clean compile package install" goals on we-web I get the maven error. All the symbols that this complains isn't found are all in we-data project. For some reason, it says all the classes of we-data cannot be found in we-web. But when I run the application as spring boot app, everything is fine. No maven error matters for this.: [INFO] ------------------------------------------------------------------------[INFO] Building we-web 0.0.1-SNAPSHOT[INFO] ------------------------------------------------------------------------[INFO] [INFO] --- maven-clean-plugin:2.6.1:clean (default-clean) @ web ---[INFO] Deleting C:\Users\user\Documents\GitHub\we\we-web\target[INFO] [INFO] --- maven-resources-plugin:2.6:resources (default-resources) @ web ---[INFO] Using 'UTF-8' encoding to copy filtered resources.[INFO] Copying 0 resource[INFO] Copying 0 resource[INFO] [INFO] --- maven-compiler-plugin:3.1:compile (default-compile) @ web ---[INFO] Changes detected - recompiling the module![INFO] Compiling 10 source files to C:\Users\user\Documents\GitHub\we\we-web\target\classes[INFO] -------------------------------------------------------------[ERROR] COMPILATION ERROR : [INFO] -------------------------------------------------------------[ERROR] /C:/Users/user/Documents/GitHub/we/we-web/src/main/java/com/we/controller/EmployeeController.java:[13,25] package com.we.service does not exist[ERROR] /C:/Users/user/Documents/GitHub/we/we-web/src/main/java/com/we/controller/EmployeePaymentController.java:[22,9] cannot find symbol symbol: class EmployeeService location: class com.we.controller.EmployeePaymentController...[INFO] 44 errors [INFO] -------------------------------------------------------------[INFO] ------------------------------------------------------------------------[INFO] BUILD FAILURE[INFO] ------------------------------------------------------------------------[INFO] Total time: 3.322 s[INFO] Finished at: 2016-12-26T15:30:54+05:30[INFO] Final Memory: 26M/253M[INFO] ------------------------------------------------------------------------[WARNING] The requested profile "pom.xml" could not be activated because it does not exist.[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile (default-compile) on project web: Compilation failure: Compilation failure:.. I have 1.8 jdk being used by the STS. And also I have not put the we-data project on build path for we-web. I want this to pass, because I want to generate a war of this. Please help. I'm doing "clean compile package install" on we-data and then doing it on we-web. "Update maven project" is also not helping me.
Now provide the response and nothing else.
| I've been stuck on this problem too for a day and finally found the root cause and solution here what i've done: if you have the following lines on your pom (for your case is the we-data's pom) <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> you should remove those lines and change into: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId></plugin> after got a clue from M. Deinum i found that he's correct about the jar compiled won't be a normal jar if you using spring-boot-maven-plugin , thanks for the clue anyway. and also please check this question: Dependency not found in Spring Boot project I've tried to use this: <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>repackage</goal> </goals> <configuration> <classifier>exec</classifier> </configuration> </execution> </executions> </plugin> it works like a charm. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41329851', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2155657/']} | jdg_381211 |
stackexchange | llm_judgeable_groundtruth_similarity | 46032067 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How to call proof assistant Coq from external software? Does Coq have some API? Is Coq command line interface rich enough to pass arguments in file and receive response in file? I am interested in Java or C++ bridges. This is legitimate question. Coq is not the usual business software from which one can expect the developer friendly API. I had similary question about Isabelle/HOL and it was legitimate question with non-trivial answer.
Now provide the response and nothing else.
| answer edited for 2022 As of today, there are three ways to interact with Coq, ordered from more effort to less power: The OCaml API: This is what Coq plugins do, however, some parts of the OCaml API are notoriously difficult to master and a high expertise is usually needed. The API also changes from one release to another making maintenance hard. There is not official documentation for the OCaml API other than looking at the source code, tho the automatically generated API docs may prove useful. There is an official plugin tutorial, and a few more unofficial ones floating around. SerAPI: SerAPI is a protocol for machine-friendly communication with Coq (disclaimer, I'm the main author), and provides mature interaction and seralization support. Some parts of it are tied to the OCaml API so it may not be fully stable, see webpage for more information. SerAPI's 2.0 API is based on LSP support The command line: As the other answer details, this basically allows to check whether a file can be fully compiled by Coq. Deprecated ways: The XML protocol: This is what CoqIDE uses. It allows the client to perform basic Coq document operations such as checking a part of it, limited search, retrieving goals, etc... official documentation This API has several shortcomings and may be scheduled for removal. Coqtop: some utils interact with the coqtop REPL, this is highly non-recommended. Some additional links: https://andy-morris.xyz/blog/20161001-coq-protocol.html https://github.com/mattam82/Constructors http://gallium.inria.fr/blog/your-first-coq-plugin/ https://github.com/uwplse/CoqAST | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46032067', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1375882/']} | jdg_381212 |
stackexchange | llm_judgeable_groundtruth_similarity | 19952155 |
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 somehow pass multiple strings to the string::find function? For example, to find a string I might use this: str.find("a string"); What I'd like to do is something like this: str.find("a string" || "another string" || "yet another string") And have the function return the position of the first occurrence of any of the three strings. Thanks for any suggestions.
Now provide the response and nothing else.
| Not with std::string::find , but you could use std::find_if from <algorithm> : std::string str("a string");std::array<std::string, 3> a{"a string", "another string", "yet another string"};auto it = std::find_if(begin(a), end(a), [&](const std::string& s) {return str.find(s) != std::string::npos; });if (it != end(a)){ std::cout << "found";} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19952155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2865175/']} | jdg_381213 |
stackexchange | llm_judgeable_groundtruth_similarity | 12411060 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
well, I'm trying to get my listview height after I change it data, but it always return the prior height, not the actual. So when I set the setadapter, and it get the old value.e.g: ActualHeight = 100 Change data (filter) -> NewHeight = 60 ListView.GetHeight still returns 100. Again ActualHeight = 60 Change data (filter) -> NewHeight = 20 ListView.GetHeight still returns 60. The code i'm using is it: int width, height = 0; EditText edt_search; ListView lv_marca; List<Marca> list_marca = new ArrayList<Marca>(); List<Marca> list_marca_search = new ArrayList<Marca>(); String text = edt_search.getText().toString(); list_marca_search.clear(); if(text.startsWith(".")){ text = text.replace(".", ""); for (Marca m : list_marca) { if (String.valueOf(m.getCd_marca()).equals(text)){ list_marca_search.add(m); } } } else { for (Marca m : lista_marca) { if (m.getDs_marca().contains(text)){ list_marca_search.add(m); } } } ArrayAdapter<Marca> adapter_marca = new CustomAdapter_Marca(MyDialog.this, R.layout.layout_consulta_estoque_marca_lista, list_marca_search); lv_marca.setAdapter(adapter_marca); int height_window = getWindowManager().getDefaultDisplay().getHeight(); height = lv_marca.getHeight() + getSupportActionBar().getHeight(); if (height >= height_window) { height = (int) (height_window * 0.95); } getWindow().setLayout(width, height);
Now provide the response and nothing else.
| Ok, I found the solution. When I change the SetAdapter in my ListView I get the measure height that means one line, and multiply by the line numbers plus the divider height by the line numbers too. Here is a example how I did, I don't know if is the better way but it works perfectly ^^: ListView lv_marca; lv_marca.setAdapter(adapter_marca); int list_height = getListViewHeight(lv_marca); private int getListViewHeight(ListView list) { ListAdapter adapter = list.getAdapter(); int listviewHeight = 0; list.measure(MeasureSpec.makeMeasureSpec(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); listviewHeight = list.getMeasuredHeight() * adapter.getCount() + (adapter.getCount() * list.getDividerHeight()); return listviewHeight; } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12411060', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1669013/']} | jdg_381214 |
stackexchange | llm_judgeable_groundtruth_similarity | 3084179 |
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:
My problem is I keep ending up proving the statement true, instead of disproving it. I was getting it mixed up in my mind so I broke it down into very explicit steps but now I'm wondering if I'm overthinking it? I started out proving that if there is no integer solution, then k is even (one negation of the statement, $P$ and not $Q$ where $P = \text{ no integer solution and } Q = k \text{ is odd}$ ). By contrapositive I try to prove that if $k$ is odd then there is an integer solution (I quickly recognized this is the same as the other negation, $Q$ and not $P$ , so this is the only thing I need to prove). So $k = 2n + 1$ for any integer $n$ . Then $x^2-x -(2n+1) = 0$ . So $x^2-x=2n+1$ . But if $x$ is an integer then $x^2-x$ must always be even, and cannot equal an odd integer $2n+1$ . So this has led to a contradiction, which means I just proved that if k is odd then there is no integer solution. Is my logic off somewhere, or should I be approaching it differently? Sorry if this has an obvious answer, I only started doing proofs this quarter. Thanks
Now provide the response and nothing else.
| You seem to be struggling with the logic involved here. The statement is $$k\text{ is odd}\iff x^2-x-k=0\text{ has no integer solutions}$$ Yes, it seems that making $k$ odd makes the equation have no integer solutions (in other words, the $\implies$ direction is true). Your proof of this looks fine. However, the statement also claims that if there are no integer solutions, then $k$ is odd (the $\Longleftarrow$ direction). The contrapositive of this claim is that making $k$ even will always result in an integer solution. This is disproven by providing a single counterexample. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/3084179', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/637448/']} | jdg_381215 |
stackexchange | llm_judgeable_groundtruth_similarity | 68191 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $R$ be a commutative ring with 1, we define $$N(R):=\{ a\in R \mid \exists k\in \mathbb{N}:a^k=0\}$$ and $$U(R):=\{ a\in R \mid a\mbox{ is invertible} \}.$$ Could anyone help me prove that if $a\in N(R) \Rightarrow 1+a\in U(R)$? I've been trying to construst a $b$ such that $ab=1$ rather than doing it by contradiction, as I don't see how you could go about doing that.
Now provide the response and nothing else.
| This really is a problem in disguise: How did you derive the formula for the sum of the geometric series in year (something) at school?? $(a + 1)(a^{k-1} - a^{k-2} + \ldots 1) = 1-(-a)^n$ but as $a^n = 0$, we have (it does no matter whether $n$ is even or odd) that $(a+1)$ is invertible. Prove the following analogous problem, it may strengthen your understanding: Let $A$ be a square matrix. If $A^2 = 0$, show that $I - A$ is invertible. If $A^3 = 0$, show that $I - A$ is invertible. Hence in general show that if $A^n = 0$ for some positive integer $n$, then $I -A$ is invertible. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/68191', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11533/']} | jdg_381216 |
stackexchange | llm_judgeable_groundtruth_similarity | 8674718 |
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 a random selection of rows in PostgreSQL, I tried this: select * from table where random() < 0.01; But some other recommend this: select * from table order by random() limit 1000; I have a very large table with 500 Million rows, I want it to be fast. Which approach is better? What are the differences? What is the best way to select random rows?
Now provide the response and nothing else.
| Fast ways Given your specifications (plus additional info in the comments), You have a numeric ID column (integer numbers) with only few (or moderately few) gaps. Obviously no or few write operations. Your ID column has to be indexed! A primary key serves nicely. The query below does not need a sequential scan of the big table, only an index scan. First, get estimates for the main query: SELECT count(*) AS ct -- optional , min(id) AS min_id , max(id) AS max_id , max(id) - min(id) AS id_spanFROM big; The only possibly expensive part is the count(*) (for huge tables). Given above specifications, you don't need it. An estimate to replace the full count will do just fine, available at almost no cost: SELECT (reltuples / relpages * (pg_relation_size(oid) / 8192))::bigint AS ctFROM pg_classWHERE oid = 'big'::regclass; -- your table name Detailed explanation: Fast way to discover the row count of a table in PostgreSQL As long as ct isn't much smaller than id_span , the query will outperform other approaches. WITH params AS ( SELECT 1 AS min_id -- minimum id <= current min id , 5100000 AS id_span -- rounded up. (max_id - min_id + buffer) )SELECT *FROM ( SELECT p.min_id + trunc(random() * p.id_span)::integer AS id FROM params p , generate_series(1, 1100) g -- 1000 + buffer GROUP BY 1 -- trim duplicates) rJOIN big USING (id)LIMIT 1000; -- trim surplus Generate random numbers in the id space. You have "few gaps", so add 10 % (enough to easily cover the blanks) to the number of rows to retrieve. Each id can be picked multiple times by chance (though very unlikely with a big id space), so group the generated numbers (or use DISTINCT ). Join the id s to the big table. This should be very fast with the index in place. Finally trim surplus id s that have not been eaten by dupes and gaps. Every row has a completely equal chance to be picked. Short version You can simplify this query. The CTE in the query above is just for educational purposes: SELECT *FROM ( SELECT DISTINCT 1 + trunc(random() * 5100000)::integer AS id FROM generate_series(1, 1100) g ) rJOIN big USING (id)LIMIT 1000; Refine with rCTE Especially if you are not so sure about gaps and estimates. WITH RECURSIVE random_pick AS ( SELECT * FROM ( SELECT 1 + trunc(random() * 5100000)::int AS id FROM generate_series(1, 1030) -- 1000 + few percent - adapt to your needs LIMIT 1030 -- hint for query planner ) r JOIN big b USING (id) -- eliminate miss UNION -- eliminate dupe SELECT b.* FROM ( SELECT 1 + trunc(random() * 5100000)::int AS id FROM random_pick r -- plus 3 percent - adapt to your needs LIMIT 999 -- less than 1000, hint for query planner ) r JOIN big b USING (id) -- eliminate miss )TABLE random_pickLIMIT 1000; -- actual limit We can work with a smaller surplus in the base query. If there are too many gaps so we don't find enough rows in the first iteration, the rCTE continues to iterate with the recursive term. We still need relatively few gaps in the ID space or the recursion may run dry before the limit is reached - or we have to start with a large enough buffer which defies the purpose of optimizing performance. Duplicates are eliminated by the UNION in the rCTE. The outer LIMIT makes the CTE stop as soon as we have enough rows. This query is carefully drafted to use the available index, generate actually random rows and not stop until we fulfill the limit (unless the recursion runs dry). There are a number of pitfalls here if you are going to rewrite it. Wrap into function For repeated use with the same table with varying parameters: CREATE OR REPLACE FUNCTION f_random_sample(_limit int = 1000, _gaps real = 1.03) RETURNS SETOF big LANGUAGE plpgsql VOLATILE ROWS 1000 AS$func$DECLARE _surplus int := _limit * _gaps; _estimate int := ( -- get current estimate from system SELECT (reltuples / relpages * (pg_relation_size(oid) / 8192))::bigint FROM pg_class WHERE oid = 'big'::regclass);BEGIN RETURN QUERY WITH RECURSIVE random_pick AS ( SELECT * FROM ( SELECT 1 + trunc(random() * _estimate)::int FROM generate_series(1, _surplus) g LIMIT _surplus -- hint for query planner ) r (id) JOIN big USING (id) -- eliminate misses UNION -- eliminate dupes SELECT * FROM ( SELECT 1 + trunc(random() * _estimate)::int FROM random_pick -- just to make it recursive LIMIT _limit -- hint for query planner ) r (id) JOIN big USING (id) -- eliminate misses ) TABLE random_pick LIMIT _limit;END$func$; Call: SELECT * FROM f_random_sample();SELECT * FROM f_random_sample(500, 1.05); Generic function We can make this generic to work for any table with a unique integer column (typically the PK): Pass the table as polymorphic type and (optionally) the name of the PK column and use EXECUTE : CREATE OR REPLACE FUNCTION f_random_sample(_tbl_type anyelement , _id text = 'id' , _limit int = 1000 , _gaps real = 1.03) RETURNS SETOF anyelement LANGUAGE plpgsql VOLATILE ROWS 1000 AS$func$DECLARE -- safe syntax with schema & quotes where needed _tbl text := pg_typeof(_tbl_type)::text; _estimate int := (SELECT (reltuples / relpages * (pg_relation_size(oid) / 8192))::bigint FROM pg_class -- get current estimate from system WHERE oid = _tbl::regclass);BEGIN RETURN QUERY EXECUTE format( $$ WITH RECURSIVE random_pick AS ( SELECT * FROM ( SELECT 1 + trunc(random() * $1)::int FROM generate_series(1, $2) g LIMIT $2 -- hint for query planner ) r(%2$I) JOIN %1$s USING (%2$I) -- eliminate misses UNION -- eliminate dupes SELECT * FROM ( SELECT 1 + trunc(random() * $1)::int FROM random_pick -- just to make it recursive LIMIT $3 -- hint for query planner ) r(%2$I) JOIN %1$s USING (%2$I) -- eliminate misses ) TABLE random_pick LIMIT $3; $$ , _tbl, _id ) USING _estimate -- $1 , (_limit * _gaps)::int -- $2 ("surplus") , _limit -- $3 ;END$func$; Call with defaults (important!): SELECT * FROM f_random_sample(null::big); --! Or more specifically: SELECT * FROM f_random_sample(null::"my_TABLE", 'oDD ID', 666, 1.15); About the same performance as the static version. Related: Refactor a PL/pgSQL function to return the output of various SELECT queries - chapter "Various complete table types" Return SETOF rows from PostgreSQL function Format specifier for integer variables in format() for EXECUTE? INSERT with dynamic table name in trigger function This is safe against SQL injection. See: Table name as a PostgreSQL function parameter SQL injection in Postgres functions vs prepared queries Possible alternative I your requirements allow identical sets for repeated calls (and we are talking about repeated calls) consider a MATERIALIZED VIEW . Execute above query once and write the result to a table. Users get a quasi random selection at lightening speed. Refresh your random pick at intervals or events of your choosing. Postgres 9.5 introduces TABLESAMPLE SYSTEM (n) Where n is a percentage. The manual: The BERNOULLI and SYSTEM sampling methods each accept a singleargument which is the fraction of the table to sample, expressed as a percentage between 0 and 100 . This argument can be any real -valued expression. Bold emphasis mine. It's very fast , but the result is not exactly random . The manual again: The SYSTEM method is significantly faster than the BERNOULLI methodwhen small sampling percentages are specified, but it may return aless-random sample of the table as a result of clustering effects. The number of rows returned can vary wildly. For our example, to get roughly 1000 rows: SELECT * FROM big TABLESAMPLE SYSTEM ((1000 * 100) / 5100000.0); Related: Fast way to discover the row count of a table in PostgreSQL Or install the additional module tsm_system_rows to get the number of requested rows exactly (if there are enough) and allow for the more convenient syntax: SELECT * FROM big TABLESAMPLE SYSTEM_ROWS(1000); See Evan's answer for details. But that's still not exactly random. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/8674718', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/754176/']} | jdg_381217 |
stackexchange | llm_judgeable_groundtruth_similarity | 66819 |
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 $\Gamma$ be a finite-index subgroup of $\operatorname{SL}_2(\mathbb{Z})$. I've seen it stated (in a comment in the code of a computer program) that the graded ring$$ M(\Gamma, \mathbb{C}) = \bigoplus_{k \ge 0} M_k(\Gamma, \mathbb{C}),$$where $M_k(\Gamma, \mathbb{C})$ is the space of modular forms of weight $k$ and level $\Gamma$, is always generated as a $\mathbb{C}$-algebra by forms of weight $\le 12$. Why is this true? Moreover, can one improve on the bound of 12? (For the subgroups $\Gamma_0(N)$, weight $\le 6$ always seems to be sufficient.)
Now provide the response and nothing else.
| Indeed, for any congruence subgroup $\Gamma \subset SL_2(\mathbb Z)$, (of any level) the graded ring $M_k(\Gamma)$ is generated in weight at most 6, with relations in weight at most 12. Furthermore, in the case that $M_3(\Gamma) \neq 0,$ i.e., there exists a modular form of odd weight, (see Remark 1.6 of Landesman, Ruhm, and Zhang linked below,) $M_k(\Gamma)$ is generated in weight at most 5, with relations in weight at most 10. In the further case that $M_3(\Gamma) \neq 0$ and the genus of the Riemann surface corresponding to $\Gamma$ is $0$ or $1$, then $M(\Gamma)$ is generated in weight at most 4 with relations in weight at most 8. A proof follows from combining results of two recent articles, namely Theorem 1.4 (the main result) and Theorem 9.3.1 from Voight and Zureick-Brown http://arxiv.org/abs/1501.04657 and Example 1.7 from an article by myself, Ruhm, and Zhang http://arxiv.org/abs/1507.02643 . To spell out how these results fit together, there are two cases. The case that there exists a nonzero odd weight modular form is covered by Example 1.7 of Landesman, Ruhm, and Zhang. So, it suffices to show that if there is no odd weight modular form, then the ring of modular forms is generated in weight at most 6, with relations in weight at most 12. First, in the case that $g > 0$, this follows immediately from the last sentence of Theorem 1.4 of Voight and Zureick-Brown because $2g -2 \geq 0$ and congruence subgroups can only have elliptic points of orders 2 and 3, and so $3 = \max(3,e)$. Second, if $g = 0$, note that because $\Gamma$ is a congruence subgroup it has some cusp, so $\delta \geq 1$ (where $\delta$ is the number of cusps). Since all the exceptional signatures listed in the table in the statement of Theorem 9.3.1 have $\delta = 0,$ they do not occur for congruence subgroups. Therefore, by the last sentence of Theorem 9.3.1, such congruence subgroups are generated in weight at most $2e = 6$ with relations in weight at most $2 \cdot 2 e = 12$. One final note: in Voight and Zureick-Brown, it says the ring is generated in degree $e$, but degree $e$ is the same as weight $2e$ by their grading convention. Edit: The above statements hold over any perfect field (or more generally when the stacky curve associated to $\Gamma$, as discussed in Voight and Zureick-Brown Chapter 5, is tame and separably rooted). However, as pointed out by John Voight in the comments, generation in weight 6 and relations in weight 12 still holds over more general base rings. See Voight and Zureick-Brown Proposition 11.3.1 for more. Edit: The above answer is now fully explained in Example 1.7 of Landesman, Ruhm, and Zhang, referenced above. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/66819', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2481/']} | jdg_381218 |
stackexchange | llm_judgeable_groundtruth_similarity | 5147378 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to find an efficient, numerically stable algorithm to calculate a rolling variance (for instance, a variance over a 20-period rolling window). I'm aware of the Welford algorithm that efficiently computes the running variance for a stream of numbers (it requires only one pass), but am not sure if this can be adapted for a rolling window. I would also like the solution to avoid the accuracy problems discussed at the top of this article by John D. Cook. A solution in any language is fine.
Now provide the response and nothing else.
| I have been dealing with the same issue. Mean is simple to compute iteratively, but you need to keep the complete history of values in a circular buffer. next_index = (index + 1) % window_size; // oldest x value is at next_index, wrapping if necessary.new_mean = mean + (x_new - xs[next_index])/window_size; I have adapted Welford's algorithm and it works for all the values that I have tested with. varSum = var_sum + (x_new - mean) * (x_new - new_mean) - (xs[next_index] - mean) * (xs[next_index] - new_mean);xs[next_index] = x_new;index = next_index; To get the current variance just divide varSum by the window size: variance = varSum / window_size; | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5147378', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/233446/']} | jdg_381219 |
stackexchange | llm_judgeable_groundtruth_similarity | 16031812 |
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 implement my own boolean class, but cannot replicate native semantics for &&. The following contrived code demonstrates the issue: #include <iostream>> class MyBool { public: bool theValue; MyBool() {} MyBool(bool aBool) {theValue = aBool;} MyBool operator&& (MyBool aBool) {return theValue && aBool.theValue;} }; bool f1() {std::cout << " First\n"; return false;} bool f2() {std::cout << " Second\n"; return false;} int main(int argc, char** argv) { std::cout << "Native &&\n"; f1() && f2(); std::cout << "Overloaded &&\n"; MyBool(f1()) && MyBool(f2()); return 0;} When compiled and run, the result is: Native && First Overloaded && Second First In other words, && on bools is lazy (as any C++ programmer would expect) but the overloaded && isn't (as this C++ programmer at least didn't expect). Is there a way to make overloaded && lazy? I can find various full-on lazy evaluation schemes to provide Haskell-like functionality, but they seem like complete overkill for my use case.
Now provide the response and nothing else.
| You should not overload bool operator&& , since you lose short circuit evaluation, as you have discovered. The correct approach would be to give your class a bool conversion operator class MyBool { public: bool theValue; MyBool() {} MyBool(bool aBool) : theValue(aBool) {} explicit operator bool() { return theValue; }}; Note that explicit conversion operators require C++11 compliance. If you do not have this, have a look at the safe bool idiom . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16031812', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2285449/']} | jdg_381220 |
stackexchange | llm_judgeable_groundtruth_similarity | 12581070 |
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 know the reason behind the design of restricting Abstract Methods in Non Abstract Class (in C#). I understand that the class instance won't have the definition and thus they wont be callable, but when static methods are defined,they are excluded from the instance too. Why abstract methods are not handled that way, any specific reason for the same? They could be allowed in concrete class and the deriving class can be forced to implement methods, basically that is what, is done in case of abstract methods in an abstract class.
Now provide the response and nothing else.
| First, I think that what you're asking doesn't logically make sense. If you have an abstract method, it basically means that the method is unfinished (as @ChrisSinclair pointed out). But that also means the whole class is unfinished, so it also has to be abstract . Or another way to put it: if you had an abstract method on a class that wasn't abstract , that would mean you had a method that cannot be called. But that means the method is not useful, you could remove it and it would all work the same. Now, I'll try to be more concrete by using an example: imagine the following code: Animal[] zoo = new Animal[] { new Monkey(), new Fish(), new Animal() };foreach (Animal animal in zoo) animal.MakeSound(); Here, Animal is the non- abstract base class (which is why I can put it directly into the array), Monkey and Fish are derived from Animal and MakeSound() is the abstract method. What should this code do? You didn't state that clearly, but I can imagine few options: You can't call MakeSound() on a variable typed as Animal , you can call it only using a variable typed as one of the derived classes, so this is a compile error. This is not a good solution, because the whole point of abstract is to be able to treat instances of derived classes as the base class, and still get behaviour that's specific to the derived class. If you want this, just put a normal (no abstract , virtual or override ) method into each derived class and don't do anything with the base class. You can't call MakeSound() on an object whose runtime type is actually Animal , so this is a runtime error (an exception). This is also not a good solution. C# is a statically typed language and so it tries to catch errors like βyou can't call this methodβ at compile time (with obvious exceptions like reflection and dynamic ), so making this into a runtime error wouldn't fit with the rest of the language. Besides, you can do this easily by creating a virtual method in the base class that throws an exception. To sum up, you want something that doesn't make much sense, and smells of bad design (a base class that behaves differently than its derived classes) and can be worked around quite easily. These are all signs of a feature that should not be implemented. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12581070', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/112911/']} | jdg_381221 |
stackexchange | llm_judgeable_groundtruth_similarity | 11303294 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm pretty new to Mongoose and MongoDB in general so I'm having a difficult time figuring out if something like this is possible: Item = new Schema({ id: Schema.ObjectId, dateCreated: { type: Date, default: Date.now }, title: { type: String, default: 'No Title' }, description: { type: String, default: 'No Description' }, tags: [ { type: Schema.ObjectId, ref: 'ItemTag' }]});ItemTag = new Schema({ id: Schema.ObjectId, tagId: { type: Schema.ObjectId, ref: 'Tag' }, tagName: { type: String }});var query = Models.Item.find({});query .desc('dateCreated') .populate('tags') .where('tags.tagName').in(['funny', 'politics']) .run(function(err, docs){ // docs is always empty }); Is there a better way do this? Edit Apologies for any confusion. What I'm trying to do is get all Items that contain either the funny tag or politics tag. Edit Document without where clause: [{ _id: 4fe90264e5caa33f04000012, dislikes: 0, likes: 0, source: '/uploads/loldog.jpg', comments: [], tags: [{ itemId: 4fe90264e5caa33f04000012, tagName: 'movies', tagId: 4fe64219007e20e644000007, _id: 4fe90270e5caa33f04000015, dateCreated: Tue, 26 Jun 2012 00:29:36 GMT, rating: 0, dislikes: 0, likes: 0 }, { itemId: 4fe90264e5caa33f04000012, tagName: 'funny', tagId: 4fe64219007e20e644000002, _id: 4fe90270e5caa33f04000017, dateCreated: Tue, 26 Jun 2012 00:29:36 GMT, rating: 0, dislikes: 0, likes: 0 }], viewCount: 0, rating: 0, type: 'image', description: null, title: 'dogggg', dateCreated: Tue, 26 Jun 2012 00:29:24 GMT }, ... ] With the where clause, I get an empty array.
Now provide the response and nothing else.
| With a modern MongoDB greater than 3.2 you can use $lookup as an alternate to .populate() in most cases. This also has the advantage of actually doing the join "on the server" as opposed to what .populate() does which is actually "multiple queries" to "emulate" a join. So .populate() is not really a "join" in the sense of how a relational database does it. The $lookup operator on the other hand, actually does the work on the server, and is more or less analogous to a "LEFT JOIN" : Item.aggregate( [ { "$lookup": { "from": ItemTags.collection.name, "localField": "tags", "foreignField": "_id", "as": "tags" }}, { "$unwind": "$tags" }, { "$match": { "tags.tagName": { "$in": [ "funny", "politics" ] } } }, { "$group": { "_id": "$_id", "dateCreated": { "$first": "$dateCreated" }, "title": { "$first": "$title" }, "description": { "$first": "$description" }, "tags": { "$push": "$tags" } }} ], function(err, result) { // "tags" is now filtered by condition and "joined" }) N.B. The .collection.name here actually evaluates to the "string" that is the actual name of the MongoDB collection as assigned to the model. Since mongoose "pluralizes" collection names by default and $lookup needs the actual MongoDB collection name as an argument ( since it's a server operation ), then this is a handy trick to use in mongoose code, as opposed to "hard coding" the collection name directly. Whilst we could also use $filter on arrays to remove the unwanted items, this is actually the most efficient form due to Aggregation Pipeline Optimization for the special condition of as $lookup followed by both an $unwind and a $match condition. This actually results in the three pipeline stages being rolled into one: { "$lookup" : { "from" : "itemtags", "as" : "tags", "localField" : "tags", "foreignField" : "_id", "unwinding" : { "preserveNullAndEmptyArrays" : false }, "matching" : { "tagName" : { "$in" : [ "funny", "politics" ] } } }} This is highly optimal as the actual operation "filters the collection to join first", then it returns the results and "unwinds" the array. Both methods are employed so the results do not break the BSON limit of 16MB, which is a constraint that the client does not have. The only problem is that it seems "counter-intuitive" in some ways, particularly when you want the results in an array, but that is what the $group is for here, as it reconstructs to the original document form. It's also unfortunate that we simply cannot at this time actually write $lookup in the same eventual syntax the server uses. IMHO, this is an oversight to be corrected. But for now, simply using the sequence will work and is the most viable option with the best performance and scalability. Addendum - MongoDB 3.6 and upwards Though the pattern shown here is fairly optimized due to how the other stages get rolled into the $lookup , it does have one failing in that the "LEFT JOIN" which is normally inherent to both $lookup and the actions of populate() is negated by the "optimal" usage of $unwind here which does not preserve empty arrays. You can add the preserveNullAndEmptyArrays option, but this negates the "optimized" sequence described above and essentially leaves all three stages intact which would normally be combined in the optimization. MongoDB 3.6 expands with a "more expressive" form of $lookup allowing a "sub-pipeline" expression. Which not only meets the goal of retaining the "LEFT JOIN" but still allows an optimal query to reduce results returned and with a much simplified syntax: Item.aggregate([ { "$lookup": { "from": ItemTags.collection.name, "let": { "tags": "$tags" }, "pipeline": [ { "$match": { "tags": { "$in": [ "politics", "funny" ] }, "$expr": { "$in": [ "$_id", "$$tags" ] } }} ] }}]) The $expr used in order to match the declared "local" value with the "foreign" value is actually what MongoDB does "internally" now with the original $lookup syntax. By expressing in this form we can tailor the initial $match expression within the "sub-pipeline" ourselves. In fact, as a true "aggregation pipeline" you can do just about anything you can do with an aggregation pipeline within this "sub-pipeline" expression, including "nesting" the levels of $lookup to other related collections. Further usage is a bit beyond the scope of what the question here asks, but in relation to even "nested population" then the new usage pattern of $lookup allows this to be much the same, and a "lot" more powerful in it's full usage. Working Example The following gives an example using a static method on the model. Once that static method is implemented the call simply becomes: Item.lookup( { path: 'tags', query: { 'tags.tagName' : { '$in': [ 'funny', 'politics' ] } } }, callback ) Or enhancing to be a bit more modern even becomes: let results = await Item.lookup({ path: 'tags', query: { 'tagName' : { '$in': [ 'funny', 'politics' ] } } }) Making it very similar to .populate() in structure, but it's actually doing the join on the server instead. For completeness, the usage here casts the returned data back to mongoose document instances at according to both the parent and child cases. It's fairly trivial and easy to adapt or just use as is for most common cases. N.B The use of async here is just for brevity of running the enclosed example. The actual implementation is free of this dependency. const async = require('async'), mongoose = require('mongoose'), Schema = mongoose.Schema;mongoose.Promise = global.Promise;mongoose.set('debug', true);mongoose.connect('mongodb://localhost/looktest');const itemTagSchema = new Schema({ tagName: String});const itemSchema = new Schema({ dateCreated: { type: Date, default: Date.now }, title: String, description: String, tags: [{ type: Schema.Types.ObjectId, ref: 'ItemTag' }]});itemSchema.statics.lookup = function(opt,callback) { let rel = mongoose.model(this.schema.path(opt.path).caster.options.ref); let group = { "$group": { } }; this.schema.eachPath(p => group.$group[p] = (p === "_id") ? "$_id" : (p === opt.path) ? { "$push": `$${p}` } : { "$first": `$${p}` }); let pipeline = [ { "$lookup": { "from": rel.collection.name, "as": opt.path, "localField": opt.path, "foreignField": "_id" }}, { "$unwind": `$${opt.path}` }, { "$match": opt.query }, group ]; this.aggregate(pipeline,(err,result) => { if (err) callback(err); result = result.map(m => { m[opt.path] = m[opt.path].map(r => rel(r)); return this(m); }); callback(err,result); });}const Item = mongoose.model('Item', itemSchema);const ItemTag = mongoose.model('ItemTag', itemTagSchema);function log(body) { console.log(JSON.stringify(body, undefined, 2))}async.series( [ // Clean data (callback) => async.each(mongoose.models,(model,callback) => model.remove({},callback),callback), // Create tags and items (callback) => async.waterfall( [ (callback) => ItemTag.create([{ "tagName": "movies" }, { "tagName": "funny" }], callback), (tags, callback) => Item.create({ "title": "Something","description": "An item", "tags": tags },callback) ], callback ), // Query with our static (callback) => Item.lookup( { path: 'tags', query: { 'tags.tagName' : { '$in': [ 'funny', 'politics' ] } } }, callback ) ], (err,results) => { if (err) throw err; let result = results.pop(); log(result); mongoose.disconnect(); }) Or a little more modern for Node 8.x and above with async/await and no additional dependencies: const { Schema } = mongoose = require('mongoose');const uri = 'mongodb://localhost/looktest';mongoose.Promise = global.Promise;mongoose.set('debug', true);const itemTagSchema = new Schema({ tagName: String});const itemSchema = new Schema({ dateCreated: { type: Date, default: Date.now }, title: String, description: String, tags: [{ type: Schema.Types.ObjectId, ref: 'ItemTag' }]});itemSchema.statics.lookup = function(opt) { let rel = mongoose.model(this.schema.path(opt.path).caster.options.ref); let group = { "$group": { } }; this.schema.eachPath(p => group.$group[p] = (p === "_id") ? "$_id" : (p === opt.path) ? { "$push": `$${p}` } : { "$first": `$${p}` }); let pipeline = [ { "$lookup": { "from": rel.collection.name, "as": opt.path, "localField": opt.path, "foreignField": "_id" }}, { "$unwind": `$${opt.path}` }, { "$match": opt.query }, group ]; return this.aggregate(pipeline).exec().then(r => r.map(m => this({ ...m, [opt.path]: m[opt.path].map(r => rel(r)) }) ));}const Item = mongoose.model('Item', itemSchema);const ItemTag = mongoose.model('ItemTag', itemTagSchema);const log = body => console.log(JSON.stringify(body, undefined, 2));(async function() { try { const conn = await mongoose.connect(uri); // Clean data await Promise.all(Object.entries(conn.models).map(([k,m]) => m.remove())); // Create tags and items const tags = await ItemTag.create( ["movies", "funny"].map(tagName =>({ tagName })) ); const item = await Item.create({ "title": "Something", "description": "An item", tags }); // Query with our static const result = (await Item.lookup({ path: 'tags', query: { 'tags.tagName' : { '$in': [ 'funny', 'politics' ] } } })).pop(); log(result); mongoose.disconnect(); } catch (e) { console.error(e); } finally { process.exit() }})() And from MongoDB 3.6 and upward, even without the $unwind and $group building: const { Schema, Types: { ObjectId } } = mongoose = require('mongoose');const uri = 'mongodb://localhost/looktest';mongoose.Promise = global.Promise;mongoose.set('debug', true);const itemTagSchema = new Schema({ tagName: String});const itemSchema = new Schema({ title: String, description: String, tags: [{ type: Schema.Types.ObjectId, ref: 'ItemTag' }]},{ timestamps: true });itemSchema.statics.lookup = function({ path, query }) { let rel = mongoose.model(this.schema.path(path).caster.options.ref); // MongoDB 3.6 and up $lookup with sub-pipeline let pipeline = [ { "$lookup": { "from": rel.collection.name, "as": path, "let": { [path]: `$${path}` }, "pipeline": [ { "$match": { ...query, "$expr": { "$in": [ "$_id", `$$${path}` ] } }} ] }} ]; return this.aggregate(pipeline).exec().then(r => r.map(m => this({ ...m, [path]: m[path].map(r => rel(r)) }) ));};const Item = mongoose.model('Item', itemSchema);const ItemTag = mongoose.model('ItemTag', itemTagSchema);const log = body => console.log(JSON.stringify(body, undefined, 2));(async function() { try { const conn = await mongoose.connect(uri); // Clean data await Promise.all(Object.entries(conn.models).map(([k,m]) => m.remove())); // Create tags and items const tags = await ItemTag.insertMany( ["movies", "funny"].map(tagName => ({ tagName })) ); const item = await Item.create({ "title": "Something", "description": "An item", tags }); // Query with our static let result = (await Item.lookup({ path: 'tags', query: { 'tagName': { '$in': [ 'funny', 'politics' ] } } })).pop(); log(result); await mongoose.disconnect(); } catch(e) { console.error(e) } finally { process.exit() }})() | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11303294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1249098/']} | jdg_381222 |
stackexchange | llm_judgeable_groundtruth_similarity | 4525919 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What are the differences between continuation passing style (cps) and monads.
Now provide the response and nothing else.
| As mentioned in The essence of functional programming : Programming with monads strongly reminiscent of continuationβpassing style (CPS), and this paper explores the relationship between the two. In a sense they are equivalent: CPS arises as a special case of a monad, and any monad may be embedded in CPS by changing the answer type. But the monadic approach provides additional insight and allows a finer degree of control. That paper is quite rigorous, and actually it doesn't quite expand on the relationship between CPS and monads. Here I attempt to give an informal, but illustrative example: (Note: Below is an understand of Monad from a newbie (myself), though after writing it it does appear to look like one of those high-rep users' answer. Please do take it with a ton of salt) Consider the classic Maybe monad -- I don't use the do notation to make it -- look similar to foo belowbar :: Maybe Intbar = Just 5 >>= \x -> Just 4 >>= \y -> return $ x + ybar' :: Maybe Intbar' = Just 5 >>= \x -> Nothing >>= \_ -> return $ xGHCi> barJust 9GHCi> bar'Nothing So the computation stops as soon as Nothing is encountered, nothing new here. Let's try to mimic such a monadic behavior using CPS: Here is our vanilla add function using CPS. We are using all Int here instead of algebric data type to make it easier: add :: Int -> Int -> (Int -> Int) -> Intadd x y k = k (x+y)GHCi> add 3 4 id7 Notice how similar it is to a monad foo :: Intfoo = add 1 2 $ \x -> -- 3 add x 4 $ \y -> -- 7 add y 5 $ \z -> -- 12 zGHCi> foo12 OK. Suppose that we want the computation to be capped at 10. That is, whatever computation must stop when the next step would result in a value larger than 10. This is sort of like saying "a Maybe computation must stop and return Nothing as soon as any value in the chain is Nothing ). Let's see how we can do it by writing a "CPS transformer" cap10 :: (Int -> Int) -> (Int -> Int)cap10 k = \x -> if x <= 10 then let x' = k x in if x' <= 10 then x' else x else xfoo' :: Intfoo' = add 1 2 $ cap10 $ \x -> -- 3 add x 4 $ cap10 $ \y -> -- 7 add y 5 $ cap10 $ \z -> -- 12 undefinedGHCi> foo'7 Notice that the final return value can be undefined , but that is fine, because the evaluation stops at the 3rd step ( z ). We can see that cap10 "wraps" the normal continuation with some extra logic. And that's very close to what monad to -- glue computations together with some extra logic. Let's go one step further: (>>==) :: ((Int -> Int) -> Int) -> (Int -> Int) -> Intm >>== k = m $ cap10 kfoo'' :: Intfoo'' = add 1 2 >>== \x -> -- 3 add x 4 >>== \y -> -- 7 add y 5 >>== \z -> -- 12 undefinedGCHi> foo''7 Woa! Maybe we have just invented the Cap10 monad! Now if we look at the source code of Cont , we see that Cont is newtype Cont r a = Cont { runCont :: (a -> r) -> r } The type of runCont is Cont r a -> (a -> r) -> r((a -> r) -> r) -> (a -> r) -> r Which lines up nicely with the type of our >>== Now to actually answer the question Now after typing all this I reread the original question. The OP asked for the "difference" :P I guess the difference is CPS gives the caller more control, where as usually the >>= in a monad is fully controlled by the monad's author. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4525919', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/454017/']} | jdg_381223 |
stackexchange | llm_judgeable_groundtruth_similarity | 26192501 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was wondering how to use Material's icons, as this is not working: <material-icon icon = "/img/icons/ic_access_time_24px.svg"> </material-icon> I guess there is a problem with the path given as parameter to the the icon attribute. I would like to know where this icon folder actually is?
Now provide the response and nothing else.
| As the other answers didn't address my concern I decided to write my own answer. The path given in the icon attribute of the md-icon directive is the URL of a .png or .svg file lying somewhere in your static file directory. So you have to put the right path of that file in the icon attribute. p.s put the file in the right directory so that your server could serve it. Remember md-icon is not like bootstrap icons. Currently they are merely a directive that shows a .svg file. Update Angular material design has changed a lot since this question was posted. Now there are several ways to use md-icon The first way is to use SVG icons. <md-icon md-svg-src = '<url_of_an_image_file>'></md-icon> Example: <md-icon md-svg-src = '/static/img/android.svg'></md-icon> or <md-icon md-svg-src = '{{ getMyIcon() }}'></md-icon> :where getMyIcon is a method defined in $scope . or <md-icon md-svg-icon="social:android"></md-icon> to use this you have to the $mdIconProvider service to configure your application with svg iconsets. angular.module('appSvgIconSets', ['ngMaterial']) .controller('DemoCtrl', function($scope) {}) .config(function($mdIconProvider) { $mdIconProvider .iconSet('social', 'img/icons/sets/social-icons.svg', 24) .defaultIconSet('img/icons/sets/core-icons.svg', 24); }); The second way is to use font icons. <md-icon md-font-icon="android" alt="android"></md-icon> <md-icon md-font-icon="fa-magic" class="fa" alt="magic wand"></md-icon> prior to doing this you have to load the font library like this.. <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> or use font icons with ligatures <md-icon md-font-library="material-icons">face</md-icon> <md-icon md-font-library="material-icons">#xE87C;</md-icon> <md-icon md-font-library="material-icons" class="md-light md-48">face</md-icon> For further details check our Angular Material mdIcon Directive documentation $mdIcon Service Documentation $mdIconProvider Service Documentation | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/26192501', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1531173/']} | jdg_381224 |
stackexchange | llm_judgeable_groundtruth_similarity | 5288283 |
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 Competitions results table which holds team member's names and their ranking on one hand. On the other hand I need to maintain a table of unique competitors names : CREATE TABLE Competitors (cName nvarchar(64) primary key) Now I have some 200,000 results in the 1st table and when the competitors table is empty I can perform this: INSERT INTO Competitors SELECT DISTINCT Name FROM CompResults And the query only takes some 5 seconds to insert about 11,000 names. So far this is not a critical application so I can consider truncate the Competitors table once a month, when I receive the new competition results with some 10,000 rows. But what is the best practice when new results are added, with new AND existing competitors? I don't want to truncate existing competitors table I need to perform INSERT statement for new competitors only and do nothing if they exists.
Now provide the response and nothing else.
| Semantically you are asking "insert Competitors where doesn't already exist": INSERT Competitors (cName)SELECT DISTINCT NameFROM CompResults crWHERE NOT EXISTS (SELECT * FROM Competitors c WHERE cr.Name = c.cName) | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/5288283', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/512602/']} | jdg_381225 |
stackexchange | llm_judgeable_groundtruth_similarity | 3426782 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I get the following error in Visual Studio 2008: Error 1 A local variable named 'i' cannot be declared in this scope because it would give a different meaning to 'i', which is already used in a 'child' scope to denote something else This is my code: for (int i = 0; i < 3; i++){ string str = "";}int i = 0; // scope errorstring str = ""; // no scope error I understand that str ceases to exist once the loop terminates, but I also thought that the scope of i was confined to the for loop as well. So i has the same scope as a variable declared just outside of the for loop? Edit: Just to be clear, I am using C#. I am debating removing the "C" tag. However, since the correct answer explains the difference between the two, I figure it makes sense to leave both tags. I had an error in my code comment above: for (int i = 0; i < 3; i++){ string str = "";}int i = 0; // scope errorstring str = ""; // also scope error, // because it's equivalent to declaring // string str =""; before the for loop (see below)
Now provide the response and nothing else.
| I think you're all confusing C++ and C#. In C++, it used to be that the scope of a variable declared in a for expression was external to the block that followed it. This was changed, some time ago, so that the scope of a variable declared in a for expression was internal to the block that followed it. C# follows this later approach. But neither has anything to do with this. What's going on here is that C# doesn't allow one scope to hide a variable with the same name in an outer scope. So, in C++, this used to be illegal. Now it's legal. for (int i; ; ){}for (int i; ; ){} And the same thing is legal in C#. There are three scopes, the outer in which 'i' is not defined, and two child scopes each of which declares its own 'i'. But what you are doing is this: int i;for (int i; ; ){} Here, there are two scopes. An outer which declares an 'i', and an inner which also declares an 'i'. This is legal in C++ - the outer 'i' is hidden - but it's illegal in C#, regardless of whether the inner scope is a for loop, a while loop, or whatever. Try this: int i;while (true){ int i;} It's the same problem. C# does not allow variables with the same name in nested scopes. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3426782', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/287311/']} | jdg_381226 |
stackexchange | llm_judgeable_groundtruth_similarity | 22055891 |
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 consume a DocumentEvent captured into insertUpdate method of a DocumentListenerI don't see any way to prevent as a KeyEvent (e.consume()). I don't want use the key listener because can't prevent the clipboard events (Copy Paste).How I work with this events?How I can raise Document events since cose? Isbn13TextField.getDocument().addDocumentListener(new DocumentListener(){ public void insertUpdate(DocumentEvent e) { e.consume(); //Not Exists, How consume a copy paste? } public void removeUpdate(DocumentEvent e) {} public void changedUpdate(DocumentEvent e) {} });
Now provide the response and nothing else.
| You will find many advice telling you to use shared examples and run them in the scope of your included controllers. I personally find it over-killing and prefer to perform unit testing in isolation, then use integration testing to confirm the behavior of my controllers. Method 1: without routing or response testing Create a fake controller and test its methods: describe MyControllerConcern do before do class FakesController < ApplicationController include MyControllerConcern end end after do Object.send :remove_const, :FakesController end let(:object) { FakesController.new } it 'my_method_to_test' do expect(object).to eq('expected result') endend Method 2: testing response When your concern contains routing or you need to test for response, rendering etc... you need to run your test with an anonymous controller. This allow you to gain access to all controller-related rspec methods and helpers: describe MyControllerConcern, type: :controller do controller(ApplicationController) do include MyControllerConcern def fake_action; redirect_to '/an_url'; end end before do routes.draw { get 'fake_action' => 'anonymous#fake_action' } end describe 'my_method_to_test' do before do get :fake_action end it do expect(response).to redirect_to('/an_url') end endend As you can see, we define the anonymous controller with controller(ApplicationController) . If your test concerne another class than ApplicationController , you will need to adapt this. Also for this to work properly you must configure the following in your spec_helper.rb file: config.infer_base_class_for_anonymous_controllers = true Note: keep testing that your concern is included It is also important to test that your concern class is included in your target classes, one line suffice: describe SomeTargetedController do it 'includes MyControllerConcern' do expect(SomeTargetedController.ancestors.include? MyControllerConcern).to be(true) endend | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/22055891', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/697653/']} | jdg_381227 |
stackexchange | llm_judgeable_groundtruth_similarity | 70579279 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
After updating the package Microsoft.AspNetCore.Authentication.JwtBearer from version 3.1.14 to 6.0.1, requests with authentication fail with 401 Unauthorized "invalid token". What needs to be changed with the new package version?
Now provide the response and nothing else.
| This seems to be a bug. Adding an event handler ( JwtBearerEvents ), the failure could be identified as a MissingMethodException : Method not found: 'Void Microsoft.IdentityModel.Tokens.InternalValidators.ValidateLifetimeAndIssuerAfterSignatureNotValidatedJwt(Microsoft.IdentityModel.Tokens.SecurityToken, System.Nullable`1<System.DateTime>, System.Nullable`1<System.DateTime>, System.String, Microsoft.IdentityModel.Tokens.TokenValidationParameters, System.Text.StringBuilder)'. with stack trace at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateSignature(String token, TokenValidationParameters validationParameters)at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.ValidateToken(String token, TokenValidationParameters validationParameters, SecurityToken& validatedToken)at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()", Simply adding the current version of System.IdentityModel.Tokens.Jwt solved the problem. Update: Please also note the comment by @Rubenisme below. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/70579279', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/689923/']} | jdg_381228 |
stackexchange | llm_judgeable_groundtruth_similarity | 2998285 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I found several answers on the following question : Does there exists a no where vanishing exact $1$ -form on a compact manifold without boundary? All answer says that certainly not. But I cannot understand use of the fact that Boundary of manifold is empty . These answers emphasis on the fact that manifold is compact. Is it still true that for a compact manifold with boundary there does not exist a no where vanishing exact $1$ -form?
Now provide the response and nothing else.
| The other two examples provide examples showing that you need to assume your manifold is boundaryless. I want to show where the "usual" proof in the boundaryless case breaks down. So, here is the usual proof. Exactness means $\omega = df$ for some smooth $f:M\rightarrow \mathbb{R}$ . Because $M$ is compact, there is a $p\in M$ for which $f(p)$ is an absolute maximum. We claim that $d_p f = 0$ , so that $\omega = df$ is not non-vanishing. To show this, we pick $v\in T_p M$ and want to show that $(d_p f) v = 0$ . To that end, let $\gamma:(-\epsilon, \epsilon)\rightarrow M$ be a smooth curve with $\gamma(0) = p$ and $\gamma'(0) = v$ . We want to show that $(d_p f) v = 0$ , or, said another way, that $\frac{d}{dt}|_{t=0} f(\gamma(t)) = 0$ . By definition of derivative, we need to show that $$\lim_{h\rightarrow 0} \frac{f(\gamma(h)) - f(\gamma(0))}{h} = 0.$$ First, the numerator is $f(\gamma(h) - f(p) \leq 0$ since $f(p)$ is a maximum of $f$ . It follows that $\lim_{h\rightarrow 0^+} \frac{f(\gamma(h))- f(p)}{h} \leq 0$ and that $\lim_{h\rightarrow 0^-} \frac{ f(\gamma(h)) - f(p)}{h} \geq 0$ . By assumption, $\lim_{h\rightarrow 0} \frac{f(\gamma(h)) - f(p)}{h}$ exists, so the left and right hand limits must match. Since one is non-negative and the other is non-positive, the conclusion is that $\lim_{h\rightarrow 0} \frac{f(\gamma(h)) - f(p)}{h} = d_p f v = 0$ . $\square$ $ \ $ So, where does this break down if $p\in \partial M$ ? Well, tangent vectors on the boundary are defined differently: you only need $\gamma$ to have a domain which is $(-\epsilon, 0]$ or $[0,\epsilon)$ . If we're in the case that the domain of $\gamma$ is $[0,\infty)$ , then the one sided limit $\lim_{h\rightarrow 0^-} \frac{f(\gamma(h)) - f(p)}{h}$ no longer makes sense: $\gamma(h)$ doesn't make sense for negative $h$ , so $f(\gamma(h))$ is meaningless. Likewise, if the domain of $\gamma$ is $(-\epsilon, 0]$ , then $\lim_{h\rightarrow 0^+} \frac{f(\gamma(h)) - f(p)}{h}$ no longer makes sense. Thus, in either case, we lose one of the two inequalities. Without both, the proof no longer works to force $(d_p f) v = 0$ . (And the other two answers show there is no way to "fix" the proof to handle the case where $p$ is a boundary point.) | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2998285', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/591889/']} | jdg_381229 |
stackexchange | llm_judgeable_groundtruth_similarity | 37631158 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Right now, the Firebase documentation guides you on uploading files to Firebase Storage by using their JavaScript library. I am operating a server without NodeJS installed. Is it possible to upload files like image, audio, through the Firebase REST API? At the moment I am using curl in a bash script to send JSON. I would prefer not to store base64 encoding in a database field, I want the file to be stored in a folder inside the Storage section. Storage folder shown below:
Now provide the response and nothing else.
| Firebase Storage uses Google Cloud Storage under the hood, so you can use the GCS REST API to get 90% of the way there. ( Docs here .) There's a couple differences. Download URLs won't be automatically generated until you access it through the Firebase Storage SDK. You won't be able to use Firebase Authentication to upload through the GCS REST endpoint. You'll either need to set up OAuth (which, you might be able to get through Google Sign in with Authentication) or a service account. (Here's an example of how you can authenticate from Node.js to GCS.) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37631158', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2971059/']} | jdg_381230 |
stackexchange | llm_judgeable_groundtruth_similarity | 25820157 |
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 generated a new jekyll site with jekyll new simple-site The site looks ok in the localhost. It's the default, dummy site that's generated anyways. I pushed it to gh-pages branch of a repo. Now the site shows up under github.io/ but with HUGE icons. The svg icons for github and twitter in the default jekyll generated site span the whole width of the page. They should be 16px or so. Similarly 3 huge blocks appear in the top. They, again, are svg, which are supposed to be thin lines. Here's my site: http://ananthp.github.io/carnatic_scores/ (repo: https://github.com/ananthp/carnatic_scores/tree/gh-pages )
Now provide the response and nothing else.
| As your site is not at the root of the domain ananthp.github.io/ but in a "directory" carnatic_scores/, you have to set baseurl variable in your _config.yml file. baseurl: '/carnatic_scores' Edit: some explanations In _includes/head.html you can see this : <link rel="stylesheet" href="{{ "/css/main.css" | prepend: site.baseurl }}"> which is equivalent to <link rel="stylesheet" href="{{ site.baseurl }}/css/main.css"> With baseurl set to "" (default) your relative url is /css/main.css , which is resolved as http://ananthp.github.io/css/main.css by your browser = 404 not found. With baseurl set to "/carnatic_scores" your relative url is /carnatic_scores/css/main.css , which is resolved as http://ananthp.github.io/carnatic_scores/css/main.css by your browser = your cool css ! That's true for all assets (css, js and image) : <script src="{{ site.baseurl }}/path_to_scripts/script.js"></script><img src="{{ site.baseurl }}/path_to_images/image.jpg">or in markdown | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25820157', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/308123/']} | jdg_381231 |
stackexchange | llm_judgeable_groundtruth_similarity | 20243683 |
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 make a plot with two independent y-axes such that the tick marks align? Below is an example of half of the solution. I've doubled the y-axis using twinx , but the tick marks aren't aligned and the gridlines form an awkward pattern on the plot. Is there a way to make the tick marks share the same positions, but correspond to different y-values? In the example below, I would like the tick mark for 5 on the left to be at the same vertical position as the tick mark for 6 on the right. import numpy as npa = np.random.normal(10, 3, size=20)b = np.random.normal(20, 5, size=40)fig, ax1 = plt.subplots()ax2 = ax1.twinx()ax1.hist(a)ax2.hist(b) The overarching point of this exercise is to make the grid lines overlap for the two axes.
Now provide the response and nothing else.
| You need to manually set the yticks as it stands these are automatically calculated resulting in a variation. Adding something like this: ax1.set_yticks(np.linspace(ax1.get_ybound()[0], ax1.get_ybound()[1], 5))ax2.set_yticks(np.linspace(ax2.get_ybound()[0], ax2.get_ybound()[1], 5)) where we set the ytick locations using an array of 5 points between the bounds of the axis. Since you have a histogram you could just set the lower value to zero in each case, and you may want to have the upper bound somewhat larger, so I would instead have ax1.set_yticks(np.linspace(0, ax1.get_ybound()[1]+1, 5))ax2.set_yticks(np.linspace(0, ax2.get_ybound()[1]+1, 5)) Giving a plot (with a change of color and transparency (alpha) for clarity): | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20243683', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/899470/']} | jdg_381232 |
stackexchange | llm_judgeable_groundtruth_similarity | 7446301 |
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 one class that has a list of objects of Daemon type. class Xyz { List<Daemon> daemons;} My spring configuration looks like this. <bean id="xyz" class="package1.Xyz"> <property name="daemons" ref="daemonsList"></bean><bean id="daemon1" class="package1.DaemonImpl1"/><bean id="daemon2" class="package1.DaemonImpl2"/><bean id="daemonsList" class="java.util.ArrayList"> <constructor-arg> <list> <ref bean="daemon1" /> <ref bean="daemon2" /> </list> </constructor-arg></bean> Now instead of explicitly wiring each daemon implementation in list, is it possible to autowire all beans of type Daemon automatically in list. Problem I am trying to solve is, If someone creates a bean of new implementation of Daemon class and forgets to wire it into list. I have seen this question somewhere on stackoverflow but not able to find that again. Apologies for it.
Now provide the response and nothing else.
| It should work like this (remove the ArrayList bean from your XML): public Class Xyz { private List<Daemon> daemons; @Autowired public void setDaemons(List<Daemon> daemons){ this.daemons = daemons; }} I don't think there's a way to do this in XML. See: 3.9.2. @Autowired and @Inject : It is also possible to provide all beans of a particular type from the ApplicationContext by adding the annotation to a field or method that expects an array of that type: public class MovieRecommender { @Autowired private MovieCatalog[] movieCatalogs; // ...} The same applies for typed collections: public class MovieRecommender { private Set<MovieCatalog> movieCatalogs; @Autowired // or if you don't want a setter, annotate the field public void setMovieCatalogs(Set<MovieCatalog> movieCatalogs) { this.movieCatalogs = movieCatalogs; } // ...} BTW, as of Spring 4.x, these lists can be ordered automatically using the @Ordered mechanism . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7446301', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/372887/']} | jdg_381233 |
stackexchange | llm_judgeable_groundtruth_similarity | 53297722 |
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 assets (images, styles) which I only need during development (ng serve). These assets must not be included in the production build. In production these assets are provided by a CDN. I need: ng serve should serve files contained in the folder./assets-non-build but: ng build should not inculde the folder ./assets-non-build in thefinal build I have worked through 10 similar questions here on SO and 5 issues on github, they all deal with excluding files, but none solved my situation.
Now provide the response and nothing else.
| Inside your angular.json there is a configurations object projects.{project-name}.architect.build.configurations . Set the assets inside the prod entry to [] "production": { //... "assets": []} This is untested though, but by judging from what I know from the configuration file, this should be possible. This will make any build and serve with the production flag to exclude the assets. If you really want all the builds, no matter the environment, to build without assets, you move the assets array from projects.{project-name}.architect.build.options to the projects.{project-name}.architect.serve.options and set the one in build to an empty array. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/53297722', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2767626/']} | jdg_381234 |
stackexchange | llm_judgeable_groundtruth_similarity | 3817439 |
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 $f:[a,b] \rightarrow \mathbb R$ be $C^1$ . Is the length of $\{f(x): x \in [a,b] \}$ and the total variation of $f$ the same thing ? The definition are extremely similar to each others: The total variation of a real-valued (or more generally complex-valued) function $f$ , defined on an interval $[a, b] \subset \mathbb{R}$ is the quantity $$V_{b}^{a}(f)=\sup _{\mathcal{P}} \sum_{i=0}^{n_{P}-1}\left|f\left(x_{i+1}\right)-f\left(x_{i}\right)\right|$$ where the supremum runs over the set of all partitions $\mathcal{P}=\left\{P=\left\{x_{0}, \ldots, x_{n_{P}}\right\} \mid P\right.$ is a partition of $\left.[a, b]\right\}$ of the given interval. Let $f:[a, b] \rightarrow \mathbb{R}^{n}$ be a continuously differentiable function. The length of the curve defined by $f$ can be defined as the limit of the sum of line segment lengths for a regular partition of $[a, b]$ as the number of segments approaches infinity. This means $$L(f)=\lim _{N \rightarrow \infty} \sum_{i=1}^{N}\left|f\left(t_{i}\right)-f\left(t_{i-1}\right)\right|$$ where $t_{i}=a+i(b-a) / N=a+i \Delta t$ for $i=0,1, \ldots, N .$ This defintiton is equivalent to the standard definition of arc length as an integral: $$\lim _{N \rightarrow \infty} \sum_{i=1}^{N}\left|f\left(t_{i}\right)-f\left(t_{i-1}\right)\right|=\lim _{N \rightarrow \infty} \sum_{i=1}^{N}\left|\frac{f\left(t_{i}\right)-f\left(t_{i-1}\right)}{\Delta t}\right| \Delta t=\int_{a}^{b}\left|f^{\prime}(t)\right| d t$$
Now provide the response and nothing else.
| No those are not the same things. First, the total variation is defined for function defined on a closed segment of $\mathbb R$ and $\mathbb R$ . While the length of a curve is defined for a curve defined between a closed segment of $\mathbb R$ and $\mathbb R^n$ where $n$ can be larger than $1$ . The confusion is often coming from the fact that a real function $f$ is usually represented by its graph which is the map $F: t \mapsto (t,f(t))$ taken its values in $\mathbb R^2$ . This confusion is reinforced by the notations where $\vert \cdot \vert$ is used to denote both the real absolute value and the euclidean norm of $\mathbb R^n$ . For a $\mathcal C^1$ real function the total variation is $$\int_{a}^{b}\left|f^{\prime}(t)\right| d t$$ and the length of the curve representing its graph is $$\int_{a}^{b}\left\Vert F^{\prime}(t)\right\Vert d t = \int_{a}^{b} \sqrt{1 + \left( f^\prime(x)^2\right)}d t.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3817439', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/427872/']} | jdg_381235 |
stackexchange | llm_judgeable_groundtruth_similarity | 44188969 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When declaring a route like this: App.js <Route path="/:id" component={RunningProject} /> I can obtain the id param in RunningProject.js like this constructor(props){ super(props) console.log(props.match.params.id);} But when declaring the route like this <Route path="/:id" render={() => <RunningProject getProjectById={this.getProject} />} /> I get an error because match no longer get passed into the props. How can I pass the match object into the props using render= instead of component= ?
Now provide the response and nothing else.
| In order to pass the match object you need to deconstruct the object passed as parameter to the render callback like this: <Route path="/:id" render={({match}) => <RunningProject getProjectById={this.getProject} match={match} />} /> You can also get the other objects, here's a list of the objects passed: history location staticContext match Or you could just pass the whole object, and deconstruct in the recipient component <Route path="/:id" render={(obj) => <RunningProject getProjectById={this.getProject} obj={obj} />} /> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/44188969', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1248725/']} | jdg_381236 |
stackexchange | llm_judgeable_groundtruth_similarity | 182221 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I've been chewing on the following problem for some time and I just don't have any more ideas how to tackle it. I have matrices $A_1,...,A_k \in \mathbb R^{n\times n}$ and I'm observing that the spectrum of the product is the same whatever order of multiplication I choose, that is, for an arbitrary permutation $\pi$ on ${1,...,k}$, I have$$\sigma(A_1\cdot ...\cdot A_k) = \sigma(A_{\pi(1)}\cdot ...\cdot A_{\pi(k)}).$$Of course, the form of the matrices is important since the above equality doesn't hold in general. All are of the form:$$ A_j = \left[ \array{0 & 1 & 0 & \cdots & 0 \\ 0 & \ddots & \ddots & \ddots & 0 \\ 0 & \cdots & 0 & 1 & 0 \\ 0 & \cdots & \cdots & 0 & 1 \\ a_j & \cdots & \cdots & \cdots & a_j } \right],$$with possibly all different $a_j \in\mathbb{R},\ j=1,...,k$. I find this quite peculiar and I don't see the reason, although all tested examples confirm the statement... I would be very curious and grateful if someone has an idea how to solve that...Thanks ahead for your comments!
Now provide the response and nothing else.
| It seems that the claim is false when $n=2$ and $k=4$, because$${\rm Tr} (A_1A_2A_3A_4)=a_1a_3+a_2a_4+\sigma_3({\bf a})+\sigma_4({\bf a})$$is not symmetric in ${\bf a}=(a_1,a_2,a_3,a_4)$. Edit : just let me add a classical result. Let $C_1,\ldots,C_r$ be the companion matrices of unitary polynomials $P_1,\ldots,P_r$ of same degree $n$. Suppose that $\lambda$ is a common root to all the $P_j's$. Then $\lambda^r$ is an eigenvalue of the product $C_1\cdots C_r$. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/182221', 'https://mathoverflow.net', 'https://mathoverflow.net/users/58860/']} | jdg_381237 |
stackexchange | llm_judgeable_groundtruth_similarity | 17429040 |
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 create a user in PostgreSQL without providing the plain text password (ideally, I would like to be able to create a user providing only its password crypted with sha-256) ? What I would like to do is to create a user with something like that : CREATE USER "martin" WITH PASSWORD '$6$kH3l2bj8iT$KKrTAKDF4OoE7w.oy(...)BPwcTBN/V42hqE.'; Is there some way to do that ? Thank you for your help.
Now provide the response and nothing else.
| You may provide the password already hashed with md5 , as said in the doc ( CREATE ROLE ): ENCRYPTED UNENCRYPTED These key words control whether the password is stored encrypted in the system catalogs. (If neither is specified, the default behavior is determined by the configuration parameter password_encryption.) If the presented password string is already in MD5-encrypted format, then it is stored encrypted as-is , regardless of whether ENCRYPTED or UNENCRYPTED is specified (since the system cannot decrypt the specified encrypted password string). This allows reloading of encrypted passwords during dump/restore. The information that's missing here is that the MD5-encrypted string should be the password concatened with the username, plus md5 at the beginning. So for example to create u0 with the password foobar , knowing that md5('foobaru0') is ac4bbe016b808c3c0b816981f240dcae : CREATE USER u0 PASSWORD 'md5ac4bbe016b808c3c0b816981f240dcae'; and then u0 will be able to log in by typing foobar as the password. I don't think that there's currently a way to use SHA-256 instead of md5 for PostgreSQL passwords. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/17429040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2466911/']} | jdg_381238 |
stackexchange | llm_judgeable_groundtruth_similarity | 2370123 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/ The dictionary does what I need but I do need to care about performance. Does anybody know if the Dictionary is implemented as a hashtable? Or more specifically, does it perform in O(1)?
Now provide the response and nothing else.
| it acts as a hashmap. in fact, every ActionScript object that is an instance of a dynamic class, acts as hashmap. of course keys can always collide with properties. this behaviour comes from JavaScript. I consider it a design failure. Array is different in that it will perform some tricks on integer keys, and Dictionary is different in that it doesn't convert keys to strings, but uses any object value as key. Please note that Number and Boolean are both converted to String. now why whould you care how it is implemented? if it is well implemented, you probably don't wanna know. You can benchmark it. It has O(1) for all operations and is reasonably fast (inserting costs a about twice as much time as an empty method call, deleting costs less). Any alternative implementation will be slower. here a simple benchmark (be sure to compile it for release and run it in the right player): package { import flash.display.Sprite; import flash.text.TextField; import flash.utils.*; public class Benchmark extends Sprite { public function Benchmark() { var txt:TextField = new TextField(); this.addChild(txt); txt.text = "waiting ..."; txt.width = 600; const repeat:int = 20; const count:int = 100000; var d:Dictionary = new Dictionary(); var j:int, i:int; var keys:Array = []; for (j = 0; j < repeat * count; j++) { keys[j] = { k:j }; } setTimeout(function ():void { var idx:int = 0; var out:Array = []; for (j = 0; j < repeat; j++) { var start:int = getTimer(); for (i = 0; i < count; i++) { d[keys[idx++]] = i; } out.push(getTimer() - start); } txt.appendText("\n" + out); start = getTimer(); for (var k:int = 0; k < i; k++) { test(); } txt.appendText("\ncall:"+(getTimer() - start)); idx = 0; out = []; for (j = 0; j < repeat; j++) { start = getTimer(); i = 0; for (i = 0; i < count; i++) { delete d[keys[idx++]]; } out.push(getTimer() - start); } txt.appendText("\n" + out); },3000);//wait for player to warm up a little } private function test():void {} }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2370123', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/85821/']} | jdg_381239 |
stackexchange | llm_judgeable_groundtruth_similarity | 43207171 |
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 my angular app, I have a list of items shown in one page and on clicking continue button, the app will move to another state . In that page there is a "Back" button which has the code $state.go('prevPage') on ng-click event. But on coming back all the data are cleared. Is there any way I can keep the scope variables alive on returning back ? Update What I tried.. On going to another state, saved all the scope data in a service returnItemModel.saveReturnData($scope); While coming back retrived it and assigned it to scope and I call the digest cycle. var savedReturnData = returnItemModel.restoreReturnData();if(savedReturnData){ $scope = savedReturnData; $scope.$apply();} This is not working. Does someone know the reason.
Now provide the response and nothing else.
| When we use liquibase all entity changes that happen later should be captured as separate changelogs(For eg. altering a table like adding a new column). Jhipster cli always seems to overwrite the entities(whichever changed) corresponding liquibase files(usually of the pattern 'config/liquibase/changelog/20180607110114_added_entity_Employee.xml' ). Therefore the entities liquibase file's checksum changes as it has new content now. And in your database, there is a table called DATABASECHANGELOG which stores which all changeLogs were applied and this has checksum data. Now when you start your application you will get error because your latest liquibase changeLog of modified entity's checksum is different from the last time(database will have a checksum for this liquibase file for previous verison) you ran. mvn liquibase:clearCheckSums is not the right approach most of the time unless needed. This actually clears all checksums in the database. You lose track of the changes that had happened which is usually not intended. These features of liquibase makes sense for eg like when you want to rollback the new changes you have applied. If you clear checksums and run the application it will compute new checksums you lose the track and can get you into trouble if not enough attention is paid. Proper solution: Make changes to your entities using jhipster entity sub-generator or jdl import or manual changes to your entities directly . Now check if the entity's corresponding liquibase file was changed or not. Usually the name contains '.._added_entity_...' . For eg. 'config/liquibase/changelog/20180607110114_added_entity_Employee.xml' . Revert that file back to what it was in case it was overwritten. Git is helpful here for reverting. If you start the application now you will not get validation checksum error as checksum of the file matches. But the change we made to entity is not captured in liquibase. For this you have to run mvn liquibase:diff . This will generate a changeLog file. Check it manually once and add it to liquibase's master.xml file. Adding to master file is must as liquibase refers to this file for all changeLogs. If you run the application now, if the changeLogs were not applied, then liquibase will try to apply these new changes on the database. To summarize, jhipster cli overwrites the entities liquibase files. Revert them and run mvn liquibase:diff to capture the new changes to the entites in a new changeLog instead of overwriting the previously generated liquibase file. We can see that checksum error is resolved and also database changes are captured in liquibase as well. References: How to deal with liquibase and Jhipster database updates. Check heading with Database updates | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/43207171', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1473071/']} | jdg_381240 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.