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 | 39945308 |
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 these table on mu PostgreSQL 9.05: Table: core Fields: name , description , data data field is a json field, with (for example): {"id": "100", "tax": "4,5"} Always is one json per data. My question is: can I get all JSON fields as query fields? return like these: name, description, id, tax.... The problem is: my JSON does have various fields, can be Id, tax or other.
Now provide the response and nothing else.
| You can't do that "dynamically". You need to specify the columns you want to have: select name, description, id, data ->> 'tax' as tax, data ->> 'other_attribute' as other_attributefrom core; If you do that a lot, you might want to put that into a view. Another option is to create an object type in Postgres that represents the attributes in your JSON, e.g. create type core_type as (id integer, tax numeric, price numeric, code varchar); You can then cast the JSON to that type and the corresponding attributes from the JSON will automatically be converted to columns: With the above type and the following JSON: {"id": "100", "tax": "4.5", "price": "10", "code": "YXCV"} you can do: select id, (json_populate_record(null::core_type, data)).*from core; and it will return: id | tax | price | code---+------+-------+----- 1 | 4.50 | 10 | YXCV But you need to make sure that every JSON value can be cast to the type of the corresponding object field. If you change the object type, any query using it will automatically be updated. So you can manage the columns you are interested in, through a central definition. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39945308', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1623295/']} | jdg_77241 |
stackexchange | llm_judgeable_groundtruth_similarity | 4835691 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have used following piece of code to execute schtasks command from VB6. While executing it, ignores folder if they contains spaces. For example, "C:\program files\test\test.exe" will be converted to "c:\program " . How do I solve this issue? MyAppname = Chr(34) & App.Path & "\" & App.EXEName & ".exe" & Chr(34)StrCommand = "schtasks /create /sc ONLOGON /RL HIGHEST /tn myapp /tr " & MyAppname Shell StrCommand, vbHide New task added as "c:\program" instead of "C:\program files\test\test.exe" Thanks in advance.
Now provide the response and nothing else.
| Escaping quotes in VB6 or VBScript strings is simple in theory although often frightening when viewed. You escape a double quote with another double quote. An example: "c:\program files\my app\app.exe" If I want to escape the double quotes so I could pass this to the shell execute function listed by Joe or the VB6 Shell function I would write it: escapedString = """c:\program files\my app\app.exe""" How does this work? The first and last quotes wrap the string and let VB know this is a string. Then each quote that is displayed literally in the string has another double quote added in front of it to escape it. It gets crazier when you are trying to pass a string with multiple quoted sections. Remember, every quote you want to pass has to be escaped. If I want to pass these two quoted phrases as a single string separated by a space (which is not uncommon): "c:\program files\my app\app.exe" "c:\documents and settings\steve" I would enter this: escapedQuoteHell = """c:\program files\my app\app.exe"" ""c:\documents and settings\steve""" I've helped my sysadmins with some VBScripts that have had even more quotes. It's not pretty, but that's how it works. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4835691', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107748/']} | jdg_77242 |
stackexchange | llm_judgeable_groundtruth_similarity | 1570146 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have this ajax call to a doop.php . function doop(){ var old = $(this).siblings('.old').html(); var new = $(this).siblings('.new').val(); $.ajax({ url: 'doop.php', type: 'POST', data: 'before=' + old + '&after=' + new, success: function(resp) { if(resp == 1) { $(this).siblings('.old').html(new); } } }); return false; } My problem is that the $(this).siblings('.old').html(new); line isn't doing what it's supposed to do. thanks.. all helpful comments/answers are voted up. Update: it appears that half of the problem was the scope (thanks for the answers that helped me clarify that), but the other half is that I'm trying to use ajax in a synchronous manner. I've created a new post
Now provide the response and nothing else.
| First of all new is a reserved word . You need to rename that variable. To answer your question, Yes, you need to save this in a variable outside the success callback, and reference it inside your success handler code: var that = this;$.ajax({ // ... success: function(resp) { if(resp == 1) { $(that).siblings('.old').html($new); } }}) This is called a closure . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1570146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/184362/']} | jdg_77243 |
stackexchange | llm_judgeable_groundtruth_similarity | 728476 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm working with derivatives and need to know if $\sin^2(x)$ the same as $\sin(x^2)$? I almost don't want to ask because my last question was closed. It was a valid question and so is this one. I've been trying to find the answer on my own but the answers I've discovered are conflicting. Any clarification here is appreciated.
Now provide the response and nothing else.
| Here is a graphical verification that these two functions are not equal. All the other answers are fine, but it is worth clarifying some other ambiguous notation in math. Trig functions are notorious for the confusion they create when involving exponents. The conventions listed below are not necessarily optimal but being aware of them is helpful for the future: $\sin^2(x) = (\sin(x))^2$ "The square of the sine of $x$." $\sin(x^2)$ "The sine of $x^2$." $\sin^{-1}(x) = \arcsin(x)$ "The inverse sine of x. That is, if $y=\sin^{-1}(x)$, then $\sin(y) = x$." $\sin(x^{-1}) = \sin\left(\dfrac{1}{x}\right)$ "The sine of the reciprocal of $x$ (where $x\neq0$)." ${(\sin(x))}^{-1} = \dfrac{1}{\sin(x)} = \csc(x)$ "The reciprocal of the sine of $x$. More commonly denoted the cosecant of $x$." Other functions seem to adopt similar notation: $\ln^2(x) = (\ln(x))^2$ "The square of the natural logarithm of $x$." $\ln(x^2)$ "The natural logarithm of $x^2$." But it only goes so far. I hope no one ever uses $-1$ as an exponent of the natural logarithm to indicate "the inverse natural logarithm of $x$"...because you would just denote that $e^x$. That is, $\ln^{-1}(x) = \dfrac{1}{\ln(x)} \neq e^x$ "The reciprocal of the natural logarithm of $x$ (where $x\neq 1$)." The Golden Rule Whatever notation you are using: if you have any hint of ambiguity, throw in another pair of parentheses in the appropriate places! | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/728476', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/135344/']} | jdg_77244 |
stackexchange | llm_judgeable_groundtruth_similarity | 77064 |
Below is a question asked on the forum politics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What are the criteria for a protest to be a strong incentivizing factor for policy change in China? https://www.cnn.com/2022/12/08/china/china-zero-covid-relaxation-reaction-intl-hnk/index.html Workers across China have dismantled some of the physical signs of thecountry’s zero-Covid controls, peeling health code scanning signs offmetro station walls and closing some checkpoints after the governmentunveiled an overhaul of its pandemic policy. It seems China decided to change its COVID policy after multiple protests across the country. I thought China rarely listened to the demands of the protestors, but in this case they did. I am wondering in what situation the Chinese leadership seriously considers policy change due to protests. There seem to be other historical precedents I am not aware of and I would like to know how useful protests are in China to change the course of government policies.
Now provide the response and nothing else.
| Chinese government repression is not inscrutably arbitrary, but instead primarily focused against threats to the regime. That also means that there is room for compromise and limited tolerance of protests that do not fundamentally threaten the regime. Even with the incident on Tiananmen square on June 4th 1989, typically held up as the prime example of Chinese government repression, we can see that in the lead up the government was willing to make some compromises and opened dialogue with the protestors. The point where the government turned to repression was the point when senior officials started feeling that the protests had begun to threaten the fundamental political order. The internal division among the top officials before the fateful vote for martial law was between those who felt the protests threatened to overthrow the regime itself, and those that felt the movement only wanted reforms. In other words, the difference was between those who saw the movement as fundamentally anti-Party and those who saw it as demanding reform within the system . This distinction continues into the modern day in the policy of the government. Environmental protestors are substantially less repressed than other types of protestors and the (central) government does often accede to localized protests with localized demands. Protestors in Hunan protesting mismanagement by local rural banks succeeded in getting the central government to announce compensation for their deposits. Protests about delays in construction of pre-sold homes related to the recent real estate crisis succeeded in causing the government to place pressure on developers to accelerate construction and the government pressed banks to give developers the liquidity they need. The case of the chained trafficked woman and the beating in a restaurant of a woman who rejected a man's advances, both led to arrests after national outrage happened. The common thread running through all of this is that none of these protests have demands that fundamentally threaten the political order of the regime. Contrast the attitude of the government in those cases to the ruthless attitude towards Uyghur and Tibetan separatism, both of which make demands that necessarily threaten the stability of the current regime. Even with the Hong Kong protests, whose demands for political reforms did fundamentally threaten the political order of the regime, the government did give concessions to begin with, like withdrawing the extradition bill. But note that withdrawing the bill did not relate to any of the demands for political reforms the protestors put forth. On a side note, it's true that many of these protests are still repressed to some degree. But it's important here to distinguish between the central government and local governments, the latter of which often takes a more heavy-handed approach to protestors in general because local protests aren't good for the political careers of local political leaders, and oftentimes, the central government is somewhat more conciliatory than local governments. In sum, the Chinese government does not repress for the sake of repression. It is pragmatic, and selectively represses protests and social movements that threaten the fundamental nature of the political order, while it is more open to compromise when demands do not threaten the fundamental nature of the political order. In the case of the COVID protests, the demands of protestors for the government to relax pandemic restrictions clearly is not a fundamental threat to the political order of the regime, so it's not surprising that the government is willing to compromise. | {} | {'log_upvote_score': 6, 'links': ['https://politics.stackexchange.com/questions/77064', 'https://politics.stackexchange.com', 'https://politics.stackexchange.com/users/38301/']} | jdg_77245 |
stackexchange | llm_judgeable_groundtruth_similarity | 2941109 |
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:
So, I previously asked the question Draw a Square Without a Compass, Only a Straightedge . From the comments and answers, it appears that that question is not solvable.Given that the question I originally saw was on an actual exam (entrance exam for Cambridge undergraduate from the 90s, or maybe 80s), this got me thinking: odds are, I've misremembered the question! I think I have remembered it correctly now, and so pose the following question. Is it possible to, given a square drawn on a plane, using only an unmarked straightedge, construct another square with twice the area? If so, how is this done?
Now provide the response and nothing else.
| From an arbitrary point A on the top half of the vertical side of the square, construct the sequence of points to finish with a square twice the area of the original square. That is, the diagonal of a smaller unit square being $\sqrt2$ and forming the side of the larger square with double the area. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2941109', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/132487/']} | jdg_77246 |
stackexchange | llm_judgeable_groundtruth_similarity | 105460 |
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
If we can make RNA vaccines against COVID-19 and we know which errors in our DNA leads to different kinds of cancer, can we make a vaccine that will teach our immune system to detect and destroy cancer cells?
Now provide the response and nothing else.
| It is not only possible, these vaccines are in active development. Biontech (the company which developed the Comirnaty Corona vaccine) was founded to develop vaccines against cancer, Moderna is developing similar approaches. It was the research on the cancer vaccines and the development of the mRNA vaccine approach in general made the fast vaccine development for the SARS-CoV-2 vaccine possible. Biontech has published results of a mRNA based cancer vaccine against melanomna in the summer of 2020 (reference 1) which shows promising results, Moderna has shown data from a phase I study on head and neck squamous cell carcinoma (reference 2). See references 3 and 4 for an overview over the topic. References: An RNA vaccine drives immunity in checkpoint-inhibitor-treatedmelanoma Moderna Announces Clinical Updates on Personalized Cancer VaccineProgram mRNA vaccine for cancer immunotherapy mRNA vaccines — a new era in vaccinology | {} | {'log_upvote_score': 6, 'links': ['https://biology.stackexchange.com/questions/105460', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/68556/']} | jdg_77247 |
stackexchange | llm_judgeable_groundtruth_similarity | 17313325 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We have a program that generates PDF documents, the staff member who uses these documents needs to hand sign all the generated pages (some 700+). What I would like to do is have a scaned image of his signature and insert it on every page in the existing PDF. My question thus is how is this done easyest ussing vb.net
Now provide the response and nothing else.
| Refering to this , it can be solved by creating a blank bitmap with the same dimensions and the correct PixelFormat and the draw on that bitmap. // The original bitmap with the wrong pixel format. // You can check the pixel format with originalBmp.PixelFormatBitmap originalBmp = (Bitmap)Image.FromFile("YourFileName.gif");// Create a blank bitmap with the same dimensionsBitmap tempBitmap = new Bitmap(originalBmp.Width, originalBmp.Height);// From this bitmap, the graphics can be obtained, because it has the right PixelFormatusing(Graphics g = Graphics.FromImage(tempBitmap)){ // Draw the original bitmap onto the graphics of the new bitmap g.DrawImage(originalBmp, 0, 0); // Use g to do whatever you like g.DrawLine(...);}// Use tempBitmap as you would have used originalBmp embedded in itreturn tempBitmap; | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17313325', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/992947/']} | jdg_77248 |
stackexchange | llm_judgeable_groundtruth_similarity | 22725281 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I tried to update an existing data-target with a data-target="#testModal1" to point to the #testModal2 modal using jquery .data , but even after the data attribute change it still is linked to #testModal1 //Jquery:$('#testButton').data('target', '#testModal2') <!-- HTML: --><button id='testButton' data-toggle="modal" data-target="#testModal1"> Test </button><div class="modal fade" id="testModal1" tabindex="-1" role="dialog" aria-hidden="true" style='display:none'> <div class="modal-dialog"> <div class="modal-content"> Testing Testing 1 </div> </div></div><div class="modal fade" id="testModal2" tabindex="-1" role="dialog" aria-hidden="true" style='display:none;'> <div class="modal-dialog"> <div class="modal-content"> Testing Testing 2 </div> </div></div>
Now provide the response and nothing else.
| Let's look in the jQuery documetation what .data() is: .data() Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements. .data( key, value ) Description : Store arbitrary data associated with the matched elements. key Type: String A string naming the piece of data to set. value Type: Object The new data value; it can be any Javascript type including Array or Object. Using $('#testButton').data('target','#testModal2') you will not modify the data-target attribute but you will store the string "#testModal2" in "target" field. Then $('#testButton').data('target') will return "#testModal2" . It's true that .data('key') can be used to return the data-key attribute value. But you cannot set it using .data('key', 'newValue' ). To set an attribute value the most common and easy way is to use .attr() method. So, the answer is easy: change data in attr and use data-target instead of target : $('#testButton').attr('data-target','#testModal2'); JSFIDDLE | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/22725281', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1678772/']} | jdg_77249 |
stackexchange | llm_judgeable_groundtruth_similarity | 47066905 |
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 struggling with understanding the merge function in D3, despite reading through the D3 API countless times. The API says: "This method is commonly used to merge the enter and update selections after a data-join. After modifying the entering and updating elements separately, you can merge the two selections and perform operations on both without duplicate code." Here's an example of the supposedly straightforward use of it, in a force directed chart, where the ticked function is called with every tick: var simulation = d3.forceSimulation(nodes) .force("charge", chargeForce) .force("center", centerForce) .on("tick", ticked); function ticked() { var u = d3.select("svg").selectAll("circle").data(nodes) u.enter().append("circle").attr("r",5) .merge(u) // What is the merge function doing here? .attr("cx", d => d.x) .attr("cy", d => d.y) u.exit().remove() // Why is it necessary to remove excess objects w/ the exit selection? } I understand how data-binding works, and how enter() and exit() selections work. However, I've never had to use a "merge" before, and I don't understand it is doing here. If someone could briefly walk through what is going on in this function step-by-step, that would be extremely useful. I'm sure others have similar questions.
Now provide the response and nothing else.
| The documentation explains very well what that function does, so what it does is instead of you having to do this u.attr("cx", d => d.x) .attr("cy", d => d.y);u.enter().append("circle").attr("r",5) .attr("cx", d => d.x) .attr("cy", d => d.y); You can just call attr once like u.enter().append("circle").attr("r",5) .merge(u) // after this point, any updates will apply to both u and u.enter() selections .attr("cx", d => d.x) .attr("cy", d => d.y) It will set attributes cx and cy on both u -the update selection and u.enter() -the enter selection Why is it necessary to remove excess objects w/ the exit selection? Because the exit selection contains any extra DOM elements that were not bound to the elements in the array you passed to data() , you can do whatever you need on the exit colllection, for example setting the styles by calling u.exit().style(...) , etc. instead of calling remove to delete them from the DOM | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47066905', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7860026/']} | jdg_77250 |
stackexchange | llm_judgeable_groundtruth_similarity | 174341 |
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:
For a long time, I thought the terms "magnon" and "spinon" were equivalent, describing the collective spin excitation in a system. Lately, I have seen remarks in the literature that they indeed do differ, however I don't know in what sense. Can somebody, please, explain, how exactly do these technical terms differ?
Now provide the response and nothing else.
| The two answers given so far are wrong. A magnon is an excitation carrying spin-$1$. A spinon is an excitation carryong spin-$\frac{1}{2}$. This has nothing to do with it being an excitation above a ferro- or antiferromagnet. The difference is much more dramatic, such that magnons are 'normal'/standard, yet spinons are very special. Suppose you have some $SU(2)$-symmetric Hamiltonian (in more than one spatial dimension) made out of spin-$\frac{1}{2}$ particles which is in a ground state that spontaneously breaks the $SU(2)$. If you flip a single spin you've created a magnon, not a spinon. Intuitively you might think a spin-flip in a spin-$\frac{1}{2}$ system carries a half-integer spin, but that's not true: while it is true that $|\downarrow\rangle$ and $|\uparrow\rangle$ each carry a half-integer spin, their difference is an integer spin. In other words: magnetic phases (in more than one dimension) have magnon quasi-particles. Spinons are much weirder. In fact since any local spin operator changes an integer amount of spin, you cannot create a single spinon with a local operator! Hence spinons are examples of fractionalized particles: they can only arise as part of a physical disturbance. For example spin liquids can give rise to spinons. A less exotic but still nice example is the spin-$\frac{1}{2}$ Heisenberg chain in one dimension where a single spin flip actually creates two emergent quasi-particles (two spinons). In a way a similar thing already happens in the transverse-field Ising chain $H = -\sum S^x_n S^x_{n+1} + g \; S^z_n$: imagine going to the ordered phase and applying a single spin-flip operator -- can you see how this actually creates two quasi-particles? | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/174341', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/14416/']} | jdg_77251 |
stackexchange | llm_judgeable_groundtruth_similarity | 10811586 |
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 mean do they use ping-pong messages to get user connection information? In short, how they know where to send for coming request?
Now provide the response and nothing else.
| For iOS , these apps use APNS (Apple Push Notification Service). This is a service provided by Apple that helps applications to alert users when something happens. In short (and simplified), it works like this When the app is installed, the user is asked if the app should be allowed to send push messages to the phone. If the user accepts, the app registers to the APNS server (hosted by Apple) and registers a "device token". This token is a serial number that helps the Apple Server to keep track of the phone. The app connects to the application server (for example Viber's server) and sends the device token also to this server. The server will connect it to a specific user. When the user receives a call, the viber server contacts the APNS server, which in turn alerts the user. The APNS server keeps track of all apps the user has on his/her phone. It will handle notifications for all of them. The connection between the iPhone and the APNS server is built-in to the iOS platform and it happens automatically on a regular basis. When the APNS server is told by the viber server that something is happening for specific device token, the APNS server will contact that specific phone and send a message to the phone. In this case the user will be told that he/she has an incoming call from viber. Documentation for APNS can be found here: Local and push notification programming guide When it comes to Android , there is a equivalent service, C2DM My guess is that these apps are working in a similar way on Android using this service. If you need a little help getting started with Push, there is a great service called Urban Airship that makes things a lot easier, it support both iOS, Android and other platforms. EDIT:In the case where the application is already open the connection can either be kept open using a socket connection, or content can be refreshed by polling. It depends on how time critical the application is. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10811586', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1125438/']} | jdg_77252 |
stackexchange | llm_judgeable_groundtruth_similarity | 9994241 |
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 bind a command to a menuitem in WPF. I'm using the same method that's been working for all my other command bindings, but I can't figure out why it doesn't work here. I'm currently binding my commands like this: Command = "{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.MyCommand}" This is where it goes wrong (this is inside a UserControl) <Button Height="40" Margin="0,2,0,0" CommandParameter="{Binding Name}" Command = "{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.ConnectCommand}"> <Button.ContextMenu> <ContextMenu> <MenuItem Header="Remove" CommandParameter="{Binding Name}" Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.RemoveCommand}"/> </ContextMenu> </Button.ContextMenu> ... The first command binding works like it should, but the second one refuses to do anything.I've tried changing the ancestor level and naming my Control to access it through ElementName instead of RelativeSource, but still no change. It keeps saying "Cannot find source for binding with reference..." What am I missing?
Now provide the response and nothing else.
| (Edit) Since you mentioned this is in an ItemsControl's template, things are different: 1) Get the BindingProxy class from this blog (and read the blog, as this is interesting information): How to bind to data when the DataContext is not inherited . Basically the elements in the ItemsControl (or ContextMenu) are not part of the visual or logical tree, and therefore cannot find the DataContext of your UserControl. My apologies for not writing more on this here, but the author has done a good job explaining it step by step, so there's no way I could give a complete explanation in just a few lines. 2) Do something like this: (you may have to adapt it a bit to make it work in your control): a. This will give you access to the UserControl DataContext using a StaticResource: <UserControl.Resources><BindingProxy x:Key="DataContextProxy" Data="{Binding}" /></UserControl.Resources> b. This uses the DataContextProxy defined in (a): <Button.ContextMenu> <ContextMenu> <MenuItem Header="Remove" CommandParameter="{Binding Name}" Command="{Binding Path=Data.RemoveCommand, Source={StaticResource DataContextProxy}}"/> </ContextMenu> This has worked for us in things like trees and datagrids. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9994241', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/637811/']} | jdg_77253 |
stackexchange | llm_judgeable_groundtruth_similarity | 2000668 |
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 solving an exercise in which I'm asked to show that $$1=\frac{4}{\pi}\sum_{n=1}^\infty{\frac{\sin((2n-1)x)}{2n-1}}, 0<x<\pi$$ I am considering solving this exercise by finding the function given by this sum, but I am pretty sure there is a more elegant solution. Thanks!
Now provide the response and nothing else.
| Hint: Calculate the Fourier Series of $$f(x) =\left\{ \begin{array}{c c} 1 & \mbox{ if } 0 \leq x \leq \pi \\-1 & \mbox{ if } -\pi \leq x \leq 0\end{array} \right.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2000668', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/234715/']} | jdg_77254 |
stackexchange | llm_judgeable_groundtruth_similarity | 83526 |
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:
After recently learning about filters and ultrafilters, we looked into further problems and properties. I am having trouble with this one: If $X$ is an infinite set, then the set of all ultrafilters on $X$ is uncountable.
Now provide the response and nothing else.
| A family of sets is said to be almost disjoint if the intersection of any two distinct members of the family is finite. For each real number $x$ let $\langle q_n(x):n\in\mathbb{N}\rangle$ be a sequence of distinct rational numbers converging to $x$ , and let $A_x=\{q_n(x):n\in\mathbb{N}\}$ . Let $\mathscr{A}=\{A_x:x\in\mathbb{R}\}$ . Suppose that $x,y\in\mathbb{R}$ with $x\ne y$ . There is some $\epsilon>0$ such that $(x-\epsilon,x+\epsilon)\cap(y-\epsilon,y+\epsilon)=\varnothing$ , and there is an $m\in\mathbb{N}$ such that $q_n(x)\in(x-\epsilon,x+\epsilon)$ and $q_n(y)\in(y-\epsilon,y+\epsilon)$ whenever $n\ge m$ . It follows that $A_x\cap A_y\subseteq\{q_n(x):n<m\}\cup\{q_n(y):n<m\}$ and hence that $A_x\cap A_y$ is finite. $\mathscr{A}$ is therefore an almost disjoint family of subsets of $\mathbb{Q}$ . Moreover, $|\mathscr{A}|=|\mathbb{R}|=2^\omega=\mathfrak{c}$ . For each $x\in\mathbb{R}$ let $\mathscr{U}_x$ be a non-principal ultrafilter on $A_x$ , and let $$\mathscr{V}_x=\{V\subseteq\mathbb{Q}:\exists U\in\mathscr{U}_x[U\subseteq V]\}\;;$$ it’s not hard to check that $\mathscr{V}_x$ is a non-principal ultrafilter on $\mathbb{Q}$ . Now suppose that $\mathscr{V}_x=\mathscr{V}_y$ for some $x,y\in\mathbb{R}$ . $A_x\in\mathscr{V}_x$ and $A_y\in\mathscr{V}_y=\mathscr{V}_x$ so $A_x\cap A_y\in\mathscr{V}_x$ . If $x\ne y$ , $A_x\cap A_y$ is finite. But $\mathscr{V}_x$ is a non-principal ultrafilter, so it contains no finite sets, and therefore we must have $x=y$ . Thus, $\{\mathscr{V}_x:x\in\mathbb{R}\}$ is a family of $2^\omega=\mathfrak{c}$ distinct non-principal ultrafilters on $\mathbb{Q}$ (and hence certainly an uncountable family). Now let $S$ be any infinite set. $\mathbb{Q}$ is countable, so $|S|\ge|\mathbb{Q}|$ , and there is therefore an injection $\varphi:\mathbb{Q}\to S$ . For each $x\in\mathbb{R}$ let $$\mathscr{W}_x=\bigg\{W\subseteq S:\exists V\in\mathscr{V}_x\big[\varphi[V]\subseteq W\big]\bigg\}\;;$$ it’s not hard to check that $\mathscr{W}_x$ is a non-principal ultrafilter on $S$ and that $\mathscr{W}_x=\mathscr{W}_y$ if and only if $x=y$ . Thus, $\{\mathscr{W}_x:x\in\mathbb{R}\}$ is a family of $2^\omega=\mathfrak{c}$ distinct non-principal ultrafilters on $S$ . As Carl mentioned in the comments, it’s actually possible to show that there are $2^{2^{|X|}}$ ultrafilters on any infinite set $X$ , but that takes a bit more work. If I have time, I may add that argument later. Added: Let $X$ be an infinite set. A family $\mathscr{A}$ of subsets of $X$ is independent if $$\bigcap_{A\in\mathscr{F}}A\cap\bigcap_{A\in\mathscr{G}}(X\setminus A)\ne\varnothing$$ whenever $\mathscr{F}$ and $\mathscr{G}$ are disjoint finite subsets of $\mathscr{A}$ . Theorem: (Hausdorff) Let $\kappa=|X|$ ; then there is an independent family $\mathscr{A}$ of subsets of $X$ such that $|\mathscr{A}|=2^\kappa$ . Assuming the theorem, it’s not hard to show that there are $2^{2^\kappa}$ ultrafilters on $X$ . Let $\mathscr{A}$ be an independent family of subsets of $X$ such that $|\mathscr{A}|=2^\kappa$ . For each $f:\mathscr{A}\to\{0,1\}$ and $A\in\mathscr{A}$ let $$\hat f(A)=\begin{cases}A,&f(A)=1\\X\setminus A,&f(A)=0\;,\end{cases}$$ and define $$\mathscr{F}_f=\left\{\bigcap_{A\in\mathscr{G}}\hat f(A):\mathscr{G}\subseteq\mathscr{A}\text{ is finite}\right\}.$$ Clearly each $\mathscr{F}_f$ is closed under finite intersections and is therefore a filterbase on $X$ . For each $f:\mathscr{A}\to\{0,1\}$ let $\mathscr{U}_f$ be an ultrafilter on $X$ extending $\mathscr{F}$ . If $f,g:\mathscr{A}\to\{0,1\}$ are distinct, there is an $A\in\mathscr{A}$ such that $f(A)\ne g(A)$ and hence $\hat f(A)\cap \hat g(A)=\varnothing$ ; since $\hat f(A)\in\mathscr{U}_f$ and $\hat g(A)\in\mathscr{U}_g$ , it follows that $\mathscr{U}_f\ne\mathscr{U}_g$ . Thus, $$\left\{\mathscr{U}_f:f\in {}^\mathscr{A}\{0,1\}\right\}$$ is a family of $2^{2^\kappa}$ distinct ultrafilters on $X$ . (Since every ultrafilter on $X$ is a subset of $\wp(X)$ , it’s clear that there can be no more than this.) Proof of Theorem: Let $Y=\{\langle F,\mathscr{H}\;\rangle:F\subseteq X\text{ is finite and }\mathscr{H}\subseteq\wp(F)\}$ For each $A\subseteq X$ let $$Y_A=\bigg\{\langle F,\mathscr{H}\;\rangle\in Y:A\cap F\in\mathscr{H}\bigg\},$$ and let $\mathscr{Y}=\{Y_A:A\subseteq X\}$ ; clearly $|\mathscr{Y}|=2^{|X|}=2^\kappa$ , and I claim that $\mathscr{Y}$ is an independent family of subsets of $Y$ . To see this, suppose that $\mathscr{F}$ and $\mathscr{G}$ are disjoint finite subsets of $\mathscr{Y}$ , say $\mathscr{F}=\{Y_{A_1},\dots,Y_{A_m}\}$ and $\mathscr{G}=\{Y_{A_{m+1}},\dots,Y_{A_{m+n}}\}$ . To show that $$Y_{A_1}\cap\dots\cap Y_{A_m}\cap (Y\setminus Y_{A_{m+1}})\cap\dots\cap(Y\setminus Y_{A_{m+n}})\ne\varnothing\;,$$ we must find $\langle F,\mathscr{H}\;\rangle\in Y$ such that $A_k\cap F\in\mathscr{H}$ for $k=1,\dots,m$ and $A_k\cap F\notin\mathscr{H}\;$ for $k=m+1,\dots,m+n$ . The sets $A_k$ are all distinct, so for each pair of indices $\langle i,k\rangle$ such that $1\le i<k\le m+n$ there is an $x(i,k)\in X$ that belongs to exactly one of $A_i$ and $A_k$ . Let $F=\{x(i,k):1\le i<k\le m+n\}$ , and let $\mathscr{H}=\{A_k\cap F:1\le k\le m\}$ ; clearly $\langle F,\mathscr{H}\;\rangle\in Y$ , and $A_k\cap F\in\mathscr{H}\;$ for $k=1,\dots,m$ . Moreover, the choice of $F$ ensures that the sets $A_k\cap F$ ( $k=1,\dots,m+n$ ) are all distinct, so $A_k\cap F\notin\mathscr{H}\;$ for $k=m+1,\dots,m+n$ . Thus, $\mathscr{Y}$ is indeed independent. To complete the proof, note that $|Y|=|X|=\kappa$ , so there is a bijection $\varphi:Y\to X$ . Let $\mathscr{A}=\{\varphi[S]:S\in\mathscr{Y}\}$ ; clearly $\mathscr{A}$ is an independent family of subsets of $X$ of cardinality $2^\kappa$ . | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/83526', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/11815/']} | jdg_77255 |
stackexchange | llm_judgeable_groundtruth_similarity | 3471988 |
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 variable float slope that sometimes will have a value of nan when printed out since a division by 0 sometimes happens. I am trying to do an if-else for when that happens. How can I do that? if (slope == nan) doesn't seem to work.
Now provide the response and nothing else.
| Two ways, which are more or less equivalent: if (slope != slope) { // handle nan here} Or #include <math.h>...if (isnan(slope)) { // handle nan here} ( man isnan will give you more information, or you can read all about it in the C standard) Alternatively, you could detect that the denominator is zero before you do the divide (or use atan2 if you're just going to end up using atan on the slope instead of doing some other computation). | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/3471988', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/166940/']} | jdg_77256 |
stackexchange | llm_judgeable_groundtruth_similarity | 17511968 |
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 DBN (deep belief network) from nolearn based on scikit-learn. I have already built a Network which can classify my data very well, now I am interested in exporting the model for deployment, but I don't know how (I am training the DBN every time I want to predict something). In matlab I would just export the weight matrix and import it in another machine. Does someone know how to export the model/the weight matrix to be imported without needing to train the whole model again?
Now provide the response and nothing else.
| First, install joblib . You can use: >>> import joblib>>> joblib.dump(clf, 'my_model.pkl', compress=9) And then later, on the prediction server: >>> import joblib>>> model_clone = joblib.load('my_model.pkl') This is basically a Python pickle with an optimized handling for large numpy arrays. It has the same limitations as the regular pickle w.r.t. code change: if the class structure of the pickle object changes you might no longer be able to unpickle the object with new versions of nolearn or scikit-learn. If you want long-term robust way of storing your model parameters you might need to write your own IO layer (e.g. using binary format serialization tools such as protocol buffers or avro or an inefficient yet portable text / json / xml representation such as PMML ). | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17511968', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/363131/']} | jdg_77257 |
stackexchange | llm_judgeable_groundtruth_similarity | 6115459 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Even trivially small Haskell programs turn into gigantic executables. I've written a small program, that was compiled (with GHC) to the binary with the size extending 7 MB! What can cause even a small Haskell program to be compiled to the huge binary? What, if anything, can I do to reduce this?
Now provide the response and nothing else.
| Let's see what's going on, try $ du -hs A 13M A $ file A A: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.27, not stripped $ ldd A linux-vdso.so.1 => (0x00007fff1b9ff000) libXrandr.so.2 => /usr/lib/libXrandr.so.2 (0x00007fb21f418000) libX11.so.6 => /usr/lib/libX11.so.6 (0x00007fb21f0d9000) libGLU.so.1 => /usr/lib/libGLU.so.1 (0x00007fb21ee6d000) libGL.so.1 => /usr/lib/libGL.so.1 (0x00007fb21ebf4000) libgmp.so.10 => /usr/lib/libgmp.so.10 (0x00007fb21e988000) libm.so.6 => /lib/libm.so.6 (0x00007fb21e706000) ... You see from the ldd output that GHC has produced a dynamically linked executable, but only the C libraries are dynamically linked ! All the Haskell libraries are copied in verbatim. Aside: since this is a graphics-intensive app, I'd definitely compile with ghc -O2 There's two things you can do. Stripping symbols An easy solution: strip the binary: $ strip A$ du -hs A5.8M A Strip discards symbols from the object file. They are generally only needed for debugging. Dynamically linked Haskell libraries More recently, GHC has gained support for dynamic linking of both C and Haskell libraries . Most distros now distribute a version of GHC built to support dynamic linking of Haskell libraries. Shared Haskell libraries may be shared amongst many Haskell programs, without copying them into the executable each time. At the time of writing Linux and Windows are supported. To allow the Haskell libraries to be dynamically linked, you need to compile them with -dynamic , like so: $ ghc -O2 --make -dynamic A.hs Also, any libraries you want to be shared should be built with --enabled-shared : $ cabal install opengl --enable-shared --reinstall $ cabal install glfw --enable-shared --reinstall And you'll end up with a much smaller executable, that has both C and Haskell dependencies dynamically resolved. $ ghc -O2 -dynamic A.hs [1 of 4] Compiling S3DM.V3 ( S3DM/V3.hs, S3DM/V3.o )[2 of 4] Compiling S3DM.M3 ( S3DM/M3.hs, S3DM/M3.o )[3 of 4] Compiling S3DM.X4 ( S3DM/X4.hs, S3DM/X4.o )[4 of 4] Compiling Main ( A.hs, A.o )Linking A... And, voilà! $ du -hs A124K A which you can strip to make even smaller: $ strip A$ du -hs A84K A An eensy weensy executable, built up from many dynamically linked C and Haskell pieces: $ ldd A libHSOpenGL-2.4.0.1-ghc7.0.3.so => ... libHSTensor-1.0.0.1-ghc7.0.3.so => ... libHSStateVar-1.0.0.0-ghc7.0.3.so =>... libHSObjectName-1.0.0.0-ghc7.0.3.so => ... libHSGLURaw-1.1.0.0-ghc7.0.3.so => ... libHSOpenGLRaw-1.1.0.1-ghc7.0.3.so => ... libHSbase-4.3.1.0-ghc7.0.3.so => ... libHSinteger-gmp-0.2.0.3-ghc7.0.3.so => ... libHSghc-prim-0.2.0.0-ghc7.0.3.so => ... libHSrts-ghc7.0.3.so => ... libm.so.6 => /lib/libm.so.6 (0x00007ffa4ffd6000) librt.so.1 => /lib/librt.so.1 (0x00007ffa4fdce000) libdl.so.2 => /lib/libdl.so.2 (0x00007ffa4fbca000) libHSffi-ghc7.0.3.so => ... One final point: even on systems with static linking only, you can use -split-objs , to get one .o file per top level function, which can further reduce the size of statically linked libraries. It needs GHC to be built with -split-objs on, which some systems forget to do. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/6115459', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_77258 |
stackexchange | llm_judgeable_groundtruth_similarity | 34990187 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I understand that the end of a string is indicated by a null character, but i cannot understand the output of the following code. #include <stdio.h>#include <string.h>intmain(void){ char s[] = "Hello\0Hi"; printf("%d %d", strlen(s), sizeof(s));} OUTPUT: 5 9 If strlen() detects the end of the string at the end of o, then why doesn't sizeof() do the same thing? Even if it doesn't do the same thing, isn't '\0' A null character (i.e, only one character), so shouldn't the answer be 8?
Now provide the response and nothing else.
| The sizeof operator does not give you the length of a string but instead the size of the type of it's operand. Since in your code the operand is an array, sizeof is giving you the size of the array including both null characters. If it were like this const char *string = "This is a large text\0This is another string";printf("%zu %zu\n", strlen(string), sizeof(string)); the result will be very different because string is a pointer and not an array. Note: Use the "%zu" specifier for size_t which is what strlen() returns, and is the type of the value given by sizeof . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34990187', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5231693/']} | jdg_77259 |
stackexchange | llm_judgeable_groundtruth_similarity | 66547 |
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:
So an Evil Twin Wifi hotspot is a hotspot with the same SSID and/or same MAC that when the victim auto-connect to this hotspot, all traffic go through this evil twin and thus the information transferred will not be secured. An evil twin requires the knowing of the password of the original hotspot. However, what if a person created one with the wrong password? This is my theory. The victim might auto-connect to this evil hotspot, and the person logs every attempt. If the evil hotspot has a closer proximity than the original one, the victim is almost 100% will first attempt to connect to the fake one. Since the attempt is logged, the password of the original one could be acquired through this method. I tried setting up two hotspot with two different MAC but same SSID. I first connect my device to the hotspot A, then I turn off the hotspot A, and turn on hotspot B. The device automatically connects to it. It seems the device does not care what the original MAC address is. Both Android and iOS behave the same. This seems to post a security threat, however I only tested the auto-connect part. Will the device actually send the stored password to the fake hotspot if it has the same SSID and encryption method? Does this actually work? What can I do to prevent this from happening?
Now provide the response and nothing else.
| For WPA, The authentication process is known as a four-way handshake. It's a bit complex to describe but in short, the access point will know that there was an unsuccessful attempt to connect, but it will not know what key was actually supplied. Fortunately, this would mean that the bogus wifi ap will not be able to figure out the key to the "real" ap. Both WPA2-PSK and WPA2-EAP result in a Pairwise Master Key (PMK) known to both the supplicant (client) and the authenticator (AP). (In PSK the PMK is derived directly from the password, whereas in EAP it is a result of the authentication process.) The four-way WPA2 handshake essentially makes the supplicant and authenticator prove to each other that they both know the PMK, and creates the temporal keys used to actually secure network data. Capturing the four-way handshake will not divulge the PMK or PSK (since capturing the handshake is trivial over wireless this would be a major vulnerability). The PMK isn't even sent during the handshake, instead it is used to calculate a Message Integrity Check (MIC). You basically need to perform a dictionary or bruteforce attack on the handshake until you find a password which results in the same MIC as in the packets. Source: Four-way Handshake in WPA-Personal (WPA-PSK) So you would be able to capture a "message integrity check," but you would have to perform a brute force on this MIC to figure out the password. So in a way, yes, you CAN capture something similar to a hash, but it's still not very useful. Plus, there is no need to set up an "evil twin" ap to capture a 4-way handshake; you can just sniff the packets out of the air. | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/66547', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/8512/']} | jdg_77260 |
stackexchange | llm_judgeable_groundtruth_similarity | 351866 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm a software developer recently in charge of entire project (project manager). The project I'm working on (with 6 other persons) is a complex Java-based application that's being developed for over 5 years. The entire time we were using SVN, without branching. Now, I would like to switch to Git as I do believe Git will provide superior branching and ease some development. Anyway, before I do switch, I have to tell you about the current workflow we're having with SVN, I have to hear opinion from people experienced with Git and to tell you what are the things I expect from Git. Please tell me if Git can provide the things I need the way I need them, because if I switch the entire project to Git and then it turns out I have to revert it to SVN (for any reason), I would be dead :) . The principle we're following with SVN is: Each team member is working on a single feature. When such feature is done, a local copy of dev's code is updated against SVN master and feature is deployed for testing. If testing by clients passed, the person developing the code pushes it to our main (and only) branch with a proper commit message that explains the feature, ticket number and so on. If, during "update before deploying for testing" the team member gets into conflicts, he's cherry-picking conflicting files line by line. When time comes that we deploy new features to production, I load the production code from a particular folder on the disk (like "physical branch"), I sync that code to the current state of the SVN, going class by class, reviewing committed changed and taking the code meant for that particular deploy. Usually, it happens that out of 230 classes we have in the repo (and not in production workspace) bewteen 30 and 50 classes are with conflicts because of the features we don't need on production yet. Sometimes, clients ask for the latest features before wanting some older features. If both feature they want and features they don't affect the same file, I have to manually skip some particular file from commit version number 3 to commit version number 6 without taking any changes from commits 4 or 5. Now, if another file is also affected, it happens that another file from version, say, 35, I have to update to version 40 without taking any changes done between 35 and 40.With SVN, it's easy, I sync a particular file and pick only the lines of codes ignoring all others. It takes time but I am in a position to tell clients "we'll postpone this for X days". Also, if two developers are working on different features that largely affect the same subsystem or big number of the same files, in order to avoid nasty conflicts and collisions I usually tell clients "we can't develop both things in the same time, we'll postpone feature B till feature A is done and tested" and one of the devs get to work on something else. Now, from Git the only thing I basically need is: Nice Windows GUI (for SVN we're using "Subclipse" plugin for Eclipse). I'm really not into investing a lot of time just learning or remembering how to push a branch or view the history or do something similar if it can be done with the click of a button. For me, the version control system should be just a tool - not something my devs should spend more than a day learning how to use because of CLI and advanced things we'll never use or require. With SVN we use only 4 commands: commit, update, synchronize (to see the differences) and "history". Ok, sometimes we do use "compare with version X from repo" but not so often. The ability to achieve nice code storage by using only a few basic commands (button clicks to be precise :D ): push / pull, fetch / commit, branch / merge, view history. Nothing fancy or advanced which would take a lot of time to learn or understand. The ability to partially take commits. For example: commit consists of 10 files. I take all changes from 8 files, but for two files I do cherry-pick in a manner that from current production version 5 I take two lines of code from file commit version 7 and few lines from file commit version 9 (effectively keeping those two files in "undefined version" so that I can supply my clients with the newest changes without all code changes preceding that newest feature I want). To achieve this point, for me it's not a problem to allocate an entire day digging through history and commits regardless if it's SVN or Git. That's my "preparing deploy" day anyway :) Having numerical commit versions, not HASH-based ones! Is it possible with Git? I really have limited experience with Git, only on some small projects and I can't afford to move the entire code base from one system to another :( Please give me some advice.
Now provide the response and nothing else.
| IMHO you are approaching this from the wrong side. You probably need first and foremost a better workflow, utilizing branches, and not necessarily another tool . Why not start using feature branches with SVN ? If you are going to develop two major features in parallel, just create individual branches for the features and assign them as a temporary "work space" for the part of the team which is going to implement the features. That is a fairly simple and easy to grasp branching model, SVN supports this well, and as long as the centralized repo model of SVN is not a problem for your team, it might be all you need. You "newbie" developer will still just use "commit, update, synchronize, history" on the branch you assigned to him (and a daily "merge from trunk into my feature branch"), only the person who will integrate the features back into the trunk some day will have to know some more SVN commands. This integration step will become much easier than you current "cherry picking" approach, since you do not have to sort out which code change belongs to a certain feature afterwards in the cumbersome and error-prone manner you described. When you go this route and reach the point where you and your team want to do more complex branches, and you notice SVN is not be sufficient any more, for example, when you need a tool for doing distributed, local branches, then it is time to switch to Git. But currently, it seems you are not there yet. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/351866', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/276700/']} | jdg_77261 |
stackexchange | llm_judgeable_groundtruth_similarity | 929510 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm a developer and we are using Quartz.Net, widely used scheduling library with SQL backing store to run cluster of jobs servers (VMs on ESXI cluster). Quartz.Net requires that time will be synchronized between job server instances and recommends using NTP for it. The clocks must be within a second of each other. Our sysadmins using windows NTP to sync time with domain controller. Synchronization of VMs with ESXI host is off. They keep insisting that's "within second" is not correct requirement and that cannot be met w/o hardware GPS-syncing devices. Their SLA & monitoring level are "within 3 minutes". We are experiencing periodic (once in 2-3 months) Quartz instances out-of-sync behavior that consistent with time being out of sync. Is it correct for us to ask for "within second" or we need to ditch Quartz entirely? If yes, what changes are recommended for our setup?
Now provide the response and nothing else.
| This is 2018. Windows is capable of keeping servers synchronized within 2 ms or so, as required by MIFID II Regulations. So, your problem is a non-problem. Our sysadmins using windows NTP to sync time with domain controller. Synchronization of VMs with ESXI host is off. Why? The host can handle this a lot better (being hardware) and you have a lot fewer. Your sysadmins shoot themselves in the foot, then complain they are bleeding. They keep insisting that's "within second" is not correct requirement and that cannot be met w/o hardware GPS-syncing devices. Their SLA & monitoring level are "within 3 minutes". OLD - ancient - Windows synchronized within that timeframe because the Kerberos tickets had a 5 minute validity. But this is, as I said, 2018. The financial industry has quite brutal requirements these days and MS has handled that for - since 2012, I think. 2016 put it fully into effect. Millisecond accuracy over the internet is a solved problem - solved 50 years ago actually, for a decent connection. NTP can handle it. You may have to put up a cheap hardware box if you want to cut down on traffic (i.e. make your own tier 3 NTP time source), but that again is not even expensive. Is it correct for us to ask for "within second" or we need to ditch Quartz entirely? You need to program for occasional time issues - as you would do with hardware. But "within second" is a joke of a requirement - it is trivial to meet under normal circumstances. Some references: https://docs.microsoft.com/en-us/windows-server/networking/windows-time-service/accurate-time Government Regulations like: 50 ms accuracy for FINRA in the US 1 ms ESMA (MiFID II) in the EU. Lots of detail and instructions there. This is an amazing read actually if you have to solve this problem. You may have to upgrade your hypervisor - they talk all about Hyper-V. VMWare should be able to do the same, but not sure how old your version is. | {} | {'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/929510', 'https://serverfault.com', 'https://serverfault.com/users/123211/']} | jdg_77262 |
stackexchange | llm_judgeable_groundtruth_similarity | 4353739 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This question is actually inspired from another one here on SO and I wanted to expand it a bit. Having an associative array in PHP is it possible to sort its values, but where the values are equal to preserve the original key order, using one (or more) of PHP's built in sort function? Here is a script I used to test possible solutions (haven't found any): <?phpheader('Content-type: text/plain');for($i=0;$i<10;$i++){ $arr['key-'.$i] = rand(1,5)*10;}uasort($arr, function($a, $b){ // sort condition may go here // // Tried: return ($a == $b)?1:($a - $b); // // Tried: return $a >= $b; //});print_r($arr);?> Pitfall : Because the keys are ordered in the original array, please don't be tempted to suggest any sorting by key to restore to the original order. I made the example with them ordered to be easier to visually check their order in the output.
Now provide the response and nothing else.
| Since PHP does not support stable sort after PHP 4.1.0 , you need to write your own function. This seems to do what you're asking: http://www.php.net/manual/en/function.usort.php#38827 As the manual says, "If two members compare as equal, their order in the sorted array is undefined." This means that the sort used is not "stable" and may change the order of elements that compare equal. Sometimes you really do need a stable sort. For example, if you sort a list by one field, then sort it again by another field, but don't want to lose the ordering from the previous field. In that case it is better to use usort with a comparison function that takes both fields into account, but if you can't do that then use the function below. It is a merge sort, which is guaranteed O(n*log(n)) complexity, which means it stays reasonably fast even when you use larger lists (unlike bubblesort and insertion sort, which are O(n^2)). <?phpfunction mergesort(&$array, $cmp_function = 'strcmp') { // Arrays of size < 2 require no action. if (count($array) < 2) return; // Split the array in half $halfway = count($array) / 2; $array1 = array_slice($array, 0, $halfway); $array2 = array_slice($array, $halfway); // Recurse to sort the two halves mergesort($array1, $cmp_function); mergesort($array2, $cmp_function); // If all of $array1 is <= all of $array2, just append them. if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) { $array = array_merge($array1, $array2); return; } // Merge the two sorted arrays into a single sorted array $array = array(); $ptr1 = $ptr2 = 0; while ($ptr1 < count($array1) && $ptr2 < count($array2)) { if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) { $array[] = $array1[$ptr1++]; } else { $array[] = $array2[$ptr2++]; } } // Merge the remainder while ($ptr1 < count($array1)) $array[] = $array1[$ptr1++]; while ($ptr2 < count($array2)) $array[] = $array2[$ptr2++]; return;}?> Also, you may find this forum thread interesting. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4353739', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/321468/']} | jdg_77263 |
stackexchange | llm_judgeable_groundtruth_similarity | 328673 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there an elegant way in Perl to find the newest file in a directory (newest by modification date)? What I have so far is searching for the files I need, and for each one get it's modification time, push into an array containing the filename, modification time, then sort it. There must be a better way.
Now provide the response and nothing else.
| Your way is the "right" way if you need a sorted list (and not just the first, see Brian's answer for that). If you don't fancy writing that code yourself, use this use File::DirList;my @list = File::DirList::list('.', 'M'); Personally I wouldn't go with the ls -t method - that involves forking another program and it's not portable. Hardly what I'd call "elegant"! Regarding rjray's solution hand coded solution, I'd change it slightly: opendir(my $DH, $DIR) or die "Error opening $DIR: $!";my @files = map { [ stat "$DIR/$_", $_ ] } grep(! /^\.\.?$/, readdir($DH));closedir($DH);sub rev_by_date { $b->[9] <=> $a->[9] }my @sorted_files = sort rev_by_date @files; After this, @sorted_files contains the sorted list, where the 0th element is the newest file, and each element itself contains a reference to the results of stat , with the filename itself in the last element: my @newest = @{$sorted_files[0]};my $name = pop(@newest); The advantage of this is that it's easier to change the sorting method later, if desired. EDIT: here's an easier-to-read (but longer) version of the directory scan, which also ensures that only plain files are added to the listing: my @files;opendir(my $DH, $DIR) or die "Error opening $DIR: $!";while (defined (my $file = readdir($DH))) { my $path = $DIR . '/' . $file; next unless (-f $path); # ignore non-files - automatically does . and .. push(@files, [ stat(_), $path ]); # re-uses the stat results from '-f'}closedir($DH); NB: the test for defined() on the result of readdir() is because a file called '0' would cause the loop to fail if you only test for if (my $file = readdir($DH)) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/328673', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13523/']} | jdg_77264 |
stackexchange | llm_judgeable_groundtruth_similarity | 1852695 |
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 an array with volatile items, and can't find a way to do that. private volatile T[] _arr; This means that the _arr reference is volatile, however it does not guarantee anything about the items inside the _arr object itself. Is there any way to mark the _arr's Items as volatile? Thanks. EDIT: The following code built according to binarycoder's answer.Is this code thread-safe to use? public class VolatileArray<T>{ private T[] _arr; public VolatileArray(int length) { _arr = new T[length]; } public VolatileArray(T[] arr) { _arr = arr; } public T this[int index] { get { T value = _arr[index]; Thread.MemoryBarrier(); return value; } set { Thread.MemoryBarrier(); _arr[index] = value; } } public int Length { get { return _arr.Length; } }}
Now provide the response and nothing else.
| Since it is possible to pass array elements by reference, you can use Thread.VolatileRead and Thread.VolatileWrite . It is useful to understand that the volatile keyword works behind the scenes by using Thread.MemoryBarrier . You could write: // Readx = _arr[i];Thread.MemoryBarrier();// WriteThread.MemoryBarrier();_arr[i] = x; Note that volatile and MemoryBarrier are advanced techniques that are both easy to get wrong. For example, see How do I Understand Read Memory Barriers and Volatile . Usually you are better off with higher level constructs such as lock , Monitor , ReaderWriterLockSlim , and others. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1852695', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/191727/']} | jdg_77265 |
stackexchange | llm_judgeable_groundtruth_similarity | 44691745 |
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 ParentComponent => ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: ''. Current value: '[object Object]'. at viewDebugError (vendor.bundle.js:8962) at expressionChangedAfterItHasBeenCheckedError (vendor.bundle.js:8940) Parent component Html <div> <app-child-widget [allItems]="allItems" (notify)="eventCalled($event)"></app-child-widget><div> Parent component export class ParentComponent implements OnInit { returnedItems: Array<any> = []; allItems: Array<any> = []; constructor( ) { } ngOnInit() { this.allItems = // load from server... } eventCalled(items: Array<any>): void { this.returnedItems = items; }} Child component @Component({ selector: 'app-child-widget', templateUrl: 'child.component.html', styleUrls: ['./child.component.css']})export class ChildComponent implements OnInit { @Output() notify: EventEmitter<any> = new EventEmitter(); @Input() private allItems: Array<any>; constructor() { } ngOnInit() { doSomething(); } doSomething() { this.notify.emit(allItems); }}
Now provide the response and nothing else.
| The article Everything you need to know about the ExpressionChangedAfterItHasBeenCheckedError error explains this behavior in great details Cause Your problem is very similar to this one but instead of updating parent property through a service you're updating it through synchronous event broadcasting. Here is the quote from the linked answer : During digest cycle Angular performs certain operations on child directives. One of such operations is updating inputs and calling ngOnInit lifecycle hook on child directives/components. What's important is that these operations are performed in strict order: Update inputs Call ngOnInit So in your case Angular updated input binding allItems on child component, then called onInit on child component which caused an update to allItems of parent component. Now you have data inconsistency. Parent component has one value while the child another. If Angular continues synchronizing changes you'll get an infinite loop. That's why during next change detection cycle Angular detected that allItems was changed and thrown an error. Solution It seems that this is an application design flaw as you're updating details from both parent and child component. If it's not, then you can solve the problem by emitting the event asynchronously like this: export class ChildComponent implements OnInit { @Output() notify: EventEmitter<any> = new EventEmitter(true); ^^^^^^------------- But you have to be very careful. If you use any other hook like ngAfterViewChecked that is being called on every digest cycle, you'll end up in cyclic dependency! | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44691745', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/663011/']} | jdg_77266 |
stackexchange | llm_judgeable_groundtruth_similarity | 132677 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In any formal system S that is susceptible to Godel's proof, we can make a formula G which is undecidable. That should mean that we can add either $G$ or $\neg G$ as an axiom to S and still end up with a consistent system, but I'm not sure exactly how $S + \neg G$ can be consistent. So, $G$ says: "There does not exist a number $n$, which is the Godel number for a proof of $G$." If G were provable, it would be false, and the system would be inconsistent (because $G$ implies $\neg G$). If $\neg G$ were provable, however, the system does not have to be blatantly inconsistent, but only omega-inconsistent. $\neg G$ says "There does exist a number $n$, which is the Godel number for a proof of $G$." But it doesn't specify what that number is. So S can still have theorems: "1 does not prove $G$", "2 does not prove $G$", "3 does not prove $G$" and so on, and it would only be omega-inconsistent (since there is no provable statement that is blatantly the negation of another). But we assume that $S$ is omega-consistent, so we are forced to conclude that $G$ is undecidable. Okay. (as a side-note, I thought that Godel's proof didn't need the assumption of omega-consistency, but it seems required here ... ?) Now, I understand what happens when you add $G$ to S. In this new $S+G$ system, $G$ says, "There is no number which is the Godel number of a proof for $G$ in S", which is, of course, true (and presumably consistent). But in $S + \neg G$, $\neg G$ says "There is a number which is the Godel number of a proof for $G$ in S"; yet, since every provable statement of $G$ is also provable in $S + \neg G$, this new system will also say "1 does not prove $G$ in S", "2 does not prove $G$ in S", ... and so on. So isn't $S + \neg G$ omega-inconsistent? And doesn't that go against the idea that we should be able to add either $G$ or $\neg G$ to S and still end up with a consistent system? Does that "consistency promise" not extend to omega-consistency? If not, isn't there a "logically better" way to extend S, even though both extensions are possible?
Now provide the response and nothing else.
| Your conclusion that $S+\neg G$ is not $\omega$-consistent is right. It is (assuming that $S$ is consistent) consistent , but fails to be $\omega$-consistent. Being $\omega$-consistent is a stronger condition than consistency, satisfied by fewer systems. Would it be "logically better" to extend $S$ in an $\omega$-consistent way than in one that isn't? I don't think so. As a sometimes Platonist, I would certainly favor the extension $S+G$ over $S+\neg G$, perhaps even claiming that the former is true whereas the latter isn't, but that preference is not based on logical properties (being true is not a logical property). Part of the confusion is that "$\omega$-consistency" is something of a misnormer -- because the name contains "consistency" one is tempted to think that like ordinary consistency it is an intrinsic property of the theory. But really it isn't; saying that a theory is $\omega$-consistent is a statement between the relation between what the theory proves and arithmetic at the meta-level. Being $\omega$-consistent is a necessary criterion for the theorems of the theory to be truths about the intuitive naturals, but failure to express arithmetic truth is not a logical problem for the theory -- it is innocent of our ambitions about what we might like it to model or not. One might consider modifications of the concept of $\omega$-consistency such that it looks more intrinsic to the theory. For example we could define that a theory $T$ is $\omega'$-consistent iff, whenever $T\vdash \exists x. \phi(x)$ there is some closed term $t$ such that $T\vdash \phi(t)$. (The difference is that in ordinary $\omega$-consistency we require $t$ to be a "numeral"; the generalized definition allows arbitrary closed terms). However, under this generalization it is still not clear why one would consider $\omega'$-consistency to be a desirable property of theories in general , even if we don't intend the theory to model arithmetic. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/132677', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/23387/']} | jdg_77267 |
stackexchange | llm_judgeable_groundtruth_similarity | 58873919 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two Angular projects using these versions: 9.0.0-next.6 8.1.0 In the version 9 I used this to provide and inject the window obhject: @NgModule({ providers: [ { provide: Window, useValue: window }, ]})export class TestComponent implements OnInit { constructor(@Inject(Window) private window: Window)} Which works fine. Taking this approach to version 8 throwed warnings and errors during compilation: Warning: Can't resolve all parameters for TestComponent … I solved it by using single quotes, like this: @NgModule({ providers: [ { provide: 'Window', useValue: window }, ]})export class TestComponent implements OnInit { constructor(@Inject('Window') private window: Window)} What is the difference between both version? What is the difference in Angular 8 and 9 that causes this thing?
Now provide the response and nothing else.
| In order for your app to work with Server Side Rendering I suggest you not only use window through token, but also create this token in SSR friendly manner, without referencing window at all. Angular has built-in DOCUMENT token for accessing document . Here's what I came up with for my projects to use window through tokens: import {DOCUMENT} from '@angular/common';import {inject, InjectionToken} from '@angular/core';export const WINDOW = new InjectionToken<Window>( 'An abstraction over global window object', { factory: () => { const {defaultView} = inject(DOCUMENT); if (!defaultView) { throw new Error('Window is not available'); } return defaultView; }, },); Edit: Since this is something people often need, we've used this technique to create a tiny open-source library with injection tokens for global objects, so you can use it: https://github.com/ng-web-apis/common It has a sister library for mocks to be used with SSR in Angular Universal: https://github.com/ng-web-apis/universal Overall, check out our hub for native APIs in Angular: https://ng-web-apis.github.io/ | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58873919', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2711071/']} | jdg_77268 |
stackexchange | llm_judgeable_groundtruth_similarity | 21708553 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have this xaml <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:l="clr-namespace:My.Windows" > <ObjectDataProvider x:Key="TitledWindow_Test" MethodName="Test" ObjectInstance={x:Type l:TitledWindow}"> <ControlTemplate x:Key="TitledWindowControlTemplateKey" x:Name="PART_ControlTemplate" TargetType="{x:Type l:TitledWindow}" <Rectangle> <Rectangle.Style> <EventSetter Event="Mouse.MouseEnter" Handler="{StaticResource TitledWindow_Test}"> </Rectangle.Style> </Rectangle> </ControlTemplate></ResourceDictionary> And my c# code: namespace My.Windows{ public partial class TitledWindow : Window { public void Test() { MessageBox.Show("Test"); } }} The problem is that i get the following error: Error 1 'ResourceDictionary' root element requires a x:Class attribute to support eventhandlers in the XAML file. Either remove the event handler for the MouseEnter event,or add a x:Class attribute to the root element.
Now provide the response and nothing else.
| Well you can do that by attaching code behind to your ResourceDictionary . Few simple steps to achieve that are: Say ResourceDictionary file name is CustomResources.xaml . Add another file in same directory besides your ResourceDictionary with name CustomResources.xaml.cs . Create partial class CustomResources inheriting from ResourceDictionary. Declare your handler for MouseEnter and code behind is ready. using System;using System.Windows;namespace WpfApplication1{ public partial class CustomResources : ResourceDictionary { public void MouseEnter(object sender, EventArgs e) { MessageBox.Show("Test"); } }} Now, in XAML set x:Class attribute and set handler to MouseEnter . XAML : <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="WpfApplication1.CustomResources" xmlns:local="clr-namespace:WpfApplication1"> <ControlTemplate x:Key="TitledWindowControlTemplateKey" x:Name="PART_ControlTemplate" TargetType="{x:Type local:TitleWindow}"> <Rectangle> <Rectangle.Style> <Style TargetType="Rectangle"> <EventSetter Event="Mouse.MouseEnter" Handler="MouseEnter"/> </Style> </Rectangle.Style> </Rectangle> </ControlTemplate> </ResourceDictionary> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21708553', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2321908/']} | jdg_77269 |
stackexchange | llm_judgeable_groundtruth_similarity | 2098825 |
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:
Someone sent me this, but since it's been ages since I followed discrete mathematics, it's all very vague to me.The question is to find the errors in this proof: $\neg p \vee (q \& r)$ (Prem) $\neg p \rightarrow s$ (Prem) $\neg p \vee q $ (1. Sim) $\neg(s \& t)$ (Hyp) $\neg s$ (4. NC) $p$ (2, 5; MP) $q$ (3, 6; DS) $\neg(s\&t) \rightarrow q$ (4, 7; VB)
Now provide the response and nothing else.
| Notice that $$\int_{-1}^1\sqrt{1+x^2}\ dx<\int_{-1}^1\sqrt{1+1^2}\ dx=2\sqrt2$$ Likewise, $$\int_{-1}^1\sqrt{1+x^2}\ dx>\int_{-1}^1\sqrt{1+0^2}\ dx=2$$ where we used $$\int_a^b\min_{t\in(a,b)}f(t)\ dx\le\int_a^bf(x)\ dx\le\int_a^b\max_{t\in(a,b)}f(t)\ dt$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2098825', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_77270 |
stackexchange | llm_judgeable_groundtruth_similarity | 54303445 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm having a main view with UIScrollview it's child and than another view as scrollview's child. After setting the scroll view's content size it's child view's height isn't increasing. This is the hierarchy-MainView--Scrollview---ContentView i've set the scrollview's constraint as top bottom left right to 0. The content view's constraints are top bottom left right to 0 and equal width and height to main view.But the content view's height isn't increasing.
Now provide the response and nothing else.
| Do this: Create a home.cshtml file page like this:Note that two @page directive are employed since optional parameters are not supported yet.The first permits navigation to the component without a parameter. The second @page directive takes the {username} route parameter and assigns the value to the Username property. Pages/home.cshtml @page "/home"@page "/home/{username}"<h1>@Username is authenticated!</h1>@functions { // Define a property to contain the parameter passed from the auth page [Parameter] private string Username { get; set; };} Do this in your auth.cshtml @functions{ public string Username { get; set; } public string url = "/home"; public async Task AuthAsync() { var ticket=await this.auth.AuthenticateAsync(Username); // Attach the parameter to the url urihelper.NavigateTo(url + "/" + Username); } } Hope this helps... | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/54303445', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4806586/']} | jdg_77271 |
stackexchange | llm_judgeable_groundtruth_similarity | 14231353 |
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 use CASE statement in SELECT. I select from user table, and (as one attribute) I also use nested SQL: SELECT registrationDate, (SELECT COUNT(*) FROM Articles WHERE userId = Users.userId) as articleNumber, hobbies, ...FROM USERS and then I would like to do a CASE statement to get rank of user (rank is dependent on articleNumber). I tried like this: SELECT registrationDate, (SELECT COUNT(*) FROM Articles WHERE Articles.userId = Users.userId) as articleNumber, ranking = CASE WHEN articleNumber < 2 THEN 'Ama' WHEN articleNumber < 5 THEN 'SemiAma' WHEN articleNumber < 7 THEN 'Good' WHEN articleNumber < 9 THEN 'Better' WHEN articleNumber < 12 THEN 'Best' ELSE 'Outstanding' END, hobbies, etc...FROM USERS Parsing displays no error, but when I try to run it I get error: Msg 207, Level 16, State 1, Procedure GetUserList, Line XY Invalid column name 'articleNumber'. CASE doesn't "recognize" my nested SELECT, I guess. I helped myself with some other solutions like SQL Server 2008 - Case / If statements in SELECT Clause but nothing seems to work. I also didn't find any similar problem with '<' and '>' comparison. Any help would be greatly appreciated ;)
Now provide the response and nothing else.
| Please select the same in the outer select. You can't access the alias name in the same query. SELECT *, (CASE WHEN articleNumber < 2 THEN 'Ama' WHEN articleNumber < 5 THEN 'SemiAma' WHEN articleNumber < 7 THEN 'Good' WHEN articleNumber < 9 THEN 'Better' WHEN articleNumber < 12 THEN 'Best' ELSE 'Outstanding' END) AS ranking FROM( SELECT registrationDate, (SELECT COUNT(*) FROM Articles WHERE Articles.userId = Users.userId) as articleNumber, hobbies, etc... FROM USERS)x | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/14231353', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1659240/']} | jdg_77272 |
stackexchange | llm_judgeable_groundtruth_similarity | 533639 |
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:
If I use a RNG to generate a set of standard normal draws $(Z_i)$ , anyone can get samples from a normal distribution with $(\mu, \sigma^2)$ of their choosing via $X_i=Z_i.\sigma+\mu$ . This doesn't require them to do any random number generating themselves (i.e. they don't need a RNG) Is the same thing possible for Poisson distributions? i.e. If I generate a set of Poisson draws with $\lambda=1$ (or some other $\lambda$ ), is it possible for another person to get Poisson samples with whatever $\lambda$ they want, without having to use an RNG? (I realise you could use the normal approximation $N(\lambda,\sqrt\lambda)$ if $\lambda$ is large, but what if this isn't the case?)
Now provide the response and nothing else.
| No, that is not possible. For instance, assume we want to "transform" Poisson realizations with $\lambda=1$ to Poisson samples with $\lambda'=5$ . The PMF at $0$ for $\lambda=1$ is $\frac{1}{e}\approx 0.368$ , so about 36.8% of the original samples will be $0$ . But the cumulative distribution function for $\lambda'=5$ is only $0.265$ for $x=3$ . That is, we would need somehow map an original observation of $0$ to transformed observations $0,1,2,3,4$ - and this in a way that satisfies the PMF for the new $\lambda'$ . This is simply not possible without a RNG. The same holds for "transformations" between any two discrete distributions (except of course for trivial cases). | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/533639', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/205515/']} | jdg_77273 |
stackexchange | llm_judgeable_groundtruth_similarity | 2292895 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have to figure out how to get the path of points that make up a geodesic on a triangular mesh: If we know the position and initial direction of a 2D walker restricted to the surface of the mesh, how do we find the path it will take? How do we find the geodesic along the surface of the mesh, from one known point to another known point? For example, shows one such path in red. We know which triangles are touching each other. I need to figure out the following: The point at which the hypothetical red line intersects the edge of the triangle. Assuming it intersects the triangle, what is the new direction based on this path?
Now provide the response and nothing else.
| Let's say the vertices of the current triangle are $\vec{v}_1 = ( x_1 , y_1 , z_1 )$ , $\vec{v}_2 = ( x_2 , y_2 , z_2 )$ , and $\vec{v}_3 = ( x_3 , y_3 , z_3 )$ , the point in the triangle is $\vec{p} = ( x_p , y_p , z_p )$ , and the direction to move from point $\vec{p}$ is $\vec{d} = ( x_d , y_d , z_d )$ . Point $\vec{p}$ must be within the triangle plane, $$\left ( \vec{p} - \vec{v}_i \right ) \cdot \vec{n} = 0$$ where $i$ is $1$ , $2$ , or $3$ -- if it is true for one, it is true for all three --, and $\vec{n}$ is the normal of the triangle plane, $$\vec{n} = \left ( \vec{v}_2 - \vec{v}_1 \right ) \times \left ( \vec{v}_3 - \vec{v}_1 \right )$$ Similarly, $\vec{d}$ must be within the triangle plane too, $$\vec{d} \cdot \vec{n} = 0$$ The line starting at $\vec{p}$ in direction $\vec{d}$ will intersect one or more of the edges, $$\vec{p} + r_{ij} \vec{d} = \vec{v}_i + t_{ij} \left ( \vec{v}_j - \vec{v}_i \right )$$ where $i,j$ is $1,2$ or $2,3$ or $3,1$ . For each $i,j$ pair we have three equations, $$\begin{cases}x_p + r_{ij} x_d = x_i + t_{ij} ( x_j - x_i ) \\y_p + r_{ij} y_d = y_i + t_{ij} ( y_j - y_i ) \\z_p + r_{ij} z_d = z_i + t_{ij} ( z_j - z_i ) \end{cases}$$ You can use any pair above to solve $r_{ij}$ and $t_{ij}$ . (I'd use the pair with the largest $\lvert c_d \rvert \lvert c_j - c_i \rvert$ .)The edge that is intersected first, is the edge between vertices $i$ and $j$ where $r_{ij}$ reaches its smallest positive value. Let's assume that the edge is shared with another triangle. If we rotate the other triangle around the shared edge, so that it becomes planar with the current triangle, we can continue the line from the intersection point in direction $\vec{d}$ . Rotating the triangle and the direction back to the original orientation, the direction becomes $\vec{q}$ . If the surface normal for the current triangle is $\vec{n}_1$ and the new triangle $\vec{n}_2$ , then the rotation axis unit vector $\hat{a}$ and angle $\varphi$ fulfill $$\begin{array}{c}\hat{a} = \frac{ \vec{n}_1 \times \vec{n}_2 }{ \lVert \vec{n}_1 \times \vec{n}_2 \rVert} \\\sin\varphi = \lVert \left ( \frac{\vec{n}_1}{\lVert\vec{n}_1\rVert} \right ) \times \left ( \frac{\vec{n}_2}{\lVert\vec{n}_2\rVert} \right ) \lVert \\\cos\varphi = \left ( \frac{\vec{n}_1}{\lVert\vec{n}_1\rVert} \right ) \cdot \left ( \frac{\vec{n}_2}{\lVert\vec{n}_2\rVert} \right ) \end{array}$$ You can use Rodrigues' rotation formula to rotate $\vec{d}$ : $$\vec{q} = \vec{d} \cos\varphi + \left ( \hat{a} \times \vec{d} \right ) \sin\varphi + \hat{a} \left ( \hat{a} \cdot \vec{d} \right ) ( 1 - \cos\varphi )$$ Another option is to use planar coordinates, say $(u, v)$ , within each triangle. (Because these coordinates are specific to each triangle, and even specific to how the vertices are labeled, I call these triangle coordinates .) Origin is at triangle vertex $\vec{v}_j$ , and the unit vector $\hat{e}_{ij}$ is $$\hat{e}_{ij} = \frac{ \vec{v}_j - \vec{v}_i }{ \lVert \vec{v}_j - \vec{v}_i \rVert }$$ If we consider a pair of triangles sharing the edge $\vec{v}_i - \vec{v}_j$ , only the $v$ axis ( $\hat{e}_{k}$ ) differs for the two triangles. In the first triangle, it is $$\hat{e}_k = \frac{ \vec{v}_k - \vec{v}_i - \hat{e}_{ij} \left ( \hat{e}_{ij} \cdot ( \vec{v}_k - \vec{v}_i ) \right ) }{\lVert \vec{v}_k - \vec{v}_i - \hat{e}_{ij} \left ( \hat{e}_{ij} \cdot ( \vec{v}_k - \vec{v}_i ) \right ) \rVert }$$ It is computed the exact same way for the second triangle, too, except that the $\vec{v}_k$ is the third vertex for the second triangle. Since $\hat{e}_{ij}$ and $\hat{e}_k$ are unit vectors, $\lVert\hat{e}_{ij}\rVert = 1$ (and $\hat{e}_{ij} \cdot \hat{e}_{ij} = 1$ ), and $\lVert\hat{e}_{k}\rVert = 1$ (and $\hat{e}_k \cdot \hat{e}_k = 1$ ). Both $\hat{e}_k$ 's are perpendicular to $\hat{e}_{ij}$ . If the two triangles are coplanar, and we use $\hat{e}_{k , 1}$ for $\hat{e}_k$ in the first triangle, and $\hat{e}_{k , 2}$ for $\hat{e}_k$ in the second triangle, then that means that $$\begin{cases}\hat{e}_{k , 1} \cdot \hat{e}_{ij} = 0 \\\hat{e}_{k , 2} \cdot \hat{e}_{ij} = 0 \end{cases}$$ The key observation is this: If the two triangles were coplanar, $\hat{e}_{k,2} = -\hat{e}_{k,1}$ If a 3D direction vector in the plane of the two triangles corresponds to $( u , v )$ in the first triangle, then $(u , -v )$ in the second triangle corresponds to the exact same 3D direction If the two triangles are not coplanar, then direction $(u, v)$ in the first triangle corresponds to direction $(u, -v)$ in the second triangle in the "geodesic sense" (that is, if the two triangles were coplanar, the directions would be the same). Any 3D point $\vec{p}$ on the triangle plane can be described using triangle coordinates $(u, v)$ : $$\begin{cases}u = \left ( \vec{p} - \vec{v}_i \right ) \cdot \hat{e}_{ij} \\v = \left ( \vec{p} - \vec{v}_i \right ) \cdot \hat{e}_{k} \end{cases} \iff\vec{p} = \vec{v}_i + u \, \hat{e}_{ij} + v \, \hat{e}_{k}$$ For the direction vector $\vec{d}$ , we use $$\begin{cases}u = \vec{d} \cdot \hat{e}_{ij} \\v = \vec{d} \cdot \hat{e}_{k} \end{cases} \iff\vec{d} = u \, \hat{e}_{ij} + v \, \hat{e}_{k}$$ Note that if $\vec{p}$ is on the plane, then $$\vec{p} \cdot \left ( \hat{e}_{ij} \times \hat{e}_k \right ) = 0$$ because the triangle normal $\vec{n}$ is parallel to $\hat{e}_ij \times \hat{e}_k$ . If you have solved $t_{ij}$ for the shared edge intersection point using the previous method, the intersection point is at $$\begin{cases}u = \frac{t_{ij}}{\lVert \vec{v}_j - \vec{v}_i \rVert} \\v = 0 \end{cases}$$ by definition: $t_{ij} = 0$ if it is at $\vec{v}_i$ , $1$ if at $\vec{v}_j$ , with $t_{ij}$ linear with respect to location. It is possible to solve $t_{ij}$ in the triangle coordinates directly. Essentially, you calculate the point and the direction in three orientations ( $(i,j,k)$ is $(1,2,3)$ , $(2,3,1)$ , or $(3,1,2)$ ), and pick the one that yields the smallest $r \ge 0$ . In each orientation, you calculate the $(u_0 , v_0)$ corresponding to the starting point, and $(u_\Delta , v_\Delta)$ corresponding to the direction, and if $v_\Delta \lt 0$ , $$r = -\frac{v_0}{v_\Delta}$$ Note that if $v_\Delta \ge 0$ for some orientation $i, j, k$ , or if $$u_0 + r u_\Delta \lt 0$$ or if $$u_0 + r u_\Delta \gt \lVert \vec{v}_j - \vec{v}_i \rVert$$ then this orientation is not valid. At least one orientation will be valid for a non-degenerate triangle (triangle with area greater than zero). Choosing the $i, j, k$ that yields the smallest positive valid $r$ basically chooses the orientation where the chosen direction will intersect edge $i,j$ first. The intersection in the chosen orientation $i, j, k$ will occur at coordinates $$\left ( u_0 + r u_\Delta , 0 \right )$$ and the "geodesically same direction" in the new triangle will be $$\left ( u_\Delta , -v_\Delta \right )$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2292895', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/289789/']} | jdg_77274 |
stackexchange | llm_judgeable_groundtruth_similarity | 36090 |
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Church was associated with the Simply Typed Lambda Calculus . Indeed, it seems he explained the Simply Typed Lambda Calculus in order to reduce misunderstanding about the Lambda Calculus. When John McCarthy created Lisp - he based it on the Lambda Calculus . This is by his own admission when he published "Recursive functions of symbolic expressions and their computation by machine, Part I" . You can read it here . At the core of Mathematica is a Lisp-like system , but instead of being based purely on the Lambda Calculus, it is based on a term-rewriting system . Here the author states state: Mathematica is fundamentally a term rewriting system... a more general concept than the Lambda Calculus behind Lisp. It seems that the Lambda Calculus is a small part of a much more general category. (Quite eye-opening as a thought this was more of a foundational concept). I'm trying to read more about this to get some perspective on it. My question is: How is Lambda Calculus a specific type of Term Writing system?
Now provide the response and nothing else.
| The answer is it depends what you mean by Term Rewrite System . When it was introduced, the concept of Term Rewrite Systems , or TRSes, described what is now called first order TRSes , which is simply a set of computation rules of the form $$ l\rightarrow r $$ where $l$ and $r$ are first order terms of the form $$ t :=\ x\ \mid\ f(t_1,\ldots,t_n) $$ where $x$ is a variable and $f$ is a function symbol taken from some arbitrary, but fixed set $\Sigma$, called the signature , which also fixes a number of arguments for each $f\in\Sigma$. There are a couple of common restrictions imposed on rules, e.g. $\mathrm{Var}(r)\subseteq\mathrm{Var}(l)$ but we don't need to go into them here. With this definition, the usual lambda calculus, with the $\beta$ rule:$$ (\lambda x. t)\ u \rightarrow t[u/x]$$cannot be expressed, as the constructor "$\lambda$" binds the occurrence of $x$ in $t$ (application is fine though). One possible solution, and one which is older than the theory of rewriting systems itself, is to turn each $\lambda$ term into another kind of term, which does not involve binding. One way is the famous $SK$ combinator calculus, which is a rewrite rule with the signature $\Sigma=\{S,\ K, \mathrm{app}\}$ and the rules$$ \mathrm{app}(\mathrm{app}(K,x),y)\rightarrow x$$and$$\mathrm{app}(\mathrm{app}(\mathrm{app}(S, x), y), z)\rightarrow \mathrm{app}(\mathrm{app}(x, z),\mathrm{app}(y, z)) $$ There is another, more intuitive encoding which involves lambda terms with de Bruijn indices and explicit substitutions, but I won't go into it here. Despite the first order encodings, it became clear that the technical issues with the reduction behavior of the $\lambda$ calculus were better addressed by extending the notion of TRS to include constructors with binders. This is often referred to by the term Higher Order Rewrite Systems . Terms are now taken of the form $$ t\ :=\ x(t_1,\ldots, t_n)\ \mid\ f(x^1_1\ldots x^1_{i_1}.t_1,\ldots,x^n_1\ldots x^n_{i_n}.t_n) $$ Where again $f\in\Sigma$, but now each $x^i_j$ is bound in $t_i$. Signatures need to specify how many variables are bound by each argument. Now we can write $\mathrm{abs}(x.t)$ for the term representing $\lambda x.t$. With a little work, you can define appropriate notions of substitution. Here there is less consensus about what constitutes a rewrite rule . One issue is that we want rewriting to be decidable, and so it needs to be decidable whether a left hand side matches a term. But this is usually taken to be modulo $\beta\eta$ which is believed to be decidable, but with only extremely complex and slow algorithms (and just $\beta$ is undecidable!). Therefore left-hand sides are restricted to be in some nice subset, often the "Miller patterns". A number of results for the first-order case generalize, though there are a few nasty surprises. It's also common to just take first order systems, and simply add $\lambda$ and application to the term structure, along with ad hoc $\beta$ and $\eta$ reductions. This yields rather reasonable systems, at the cost of (some) generality. Of course the usual $\lambda$ calculus can be directly written in these systems. For example the $\beta$ rule: $$\mathrm{app}(\mathrm{abs}(x.y(x)),z)\rightarrow y(z) $$ A pretty decent overview of the definitions and basic results is given by Nipkow and Prehofer here . | {} | {'log_upvote_score': 5, 'links': ['https://cstheory.stackexchange.com/questions/36090', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/608/']} | jdg_77275 |
stackexchange | llm_judgeable_groundtruth_similarity | 210697 |
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 have just read an article which mentions that, when Grothendieck considered using etale morphism, he did borrow the idea from Riemann that multivalued function on an open subset of complex plane should live in Riemann surface covering it instead of the open subset itself.The question is: how these things are related? Any detailed explanation is very welcome and appreciated. More generally, what are the good properties etale morphism has which make it essential in solving Weil conjecture.I understand that Grothendieck tried to search for a cohomology theory in algebraic geometry which is similar to classical cohomology theory on manifold theory but I dont know what obstructions are there preventing a cohomology theory in AG behaves similar to one in manifold for which etale site was introduced to overcome them.
Now provide the response and nothing else.
| I can tell you how they are related. Before Riemann people would say, for example, the complex square root function (for $z\neq 0$) is two valued, but for any small region of (non-zero) complex numbers you can make it single valued by picking one branch. Riemann had a vastly better idea: there is a two-sheeted covering surface for the complex plane (ramified at 0) with square root a single-valued function on that cover. Serre, who was well aware of the connection to Riemann, found a theory of 1-dimensional cohomology that worked correctly for the Weil conjectures, using not sheaves but fiber bundles, where a fiber bundle is considered locally trivial (and called "isotrivial"), not when it restricts to product bundles on small enough parts, but if it can be made into a product bundle by pulling it back along such a cover. Well, Serre also saw how he could state the algebraic conditions needed to make this work, not only over the complex numbers, but over any field. Those conditions are now taken as the definition of a finite etale map. Grothendieck, with Artin and others, including Serre, made it work in all dimensions and for that purpose preferred to drop the requirement that the map be finite. As to this works for the Weil Conjectures, let add a bit on why Serre first thought his "unramified maps" (which later gave way to the slightly different etale maps) were the way to such a cohomology, and why Grothendieck then decided this was exactly the way. You should combine this with Peter Dalakov's concise modern statement of the facts in his comment, and Will Sawin's beautiful account of what a cohomology theory for those conjectures would have to be like. No one who was interested in the Weil Conjectures when they first appeared believed fields in finite characteristic would support any close analogue to the analytic topology on complex numbers. In hindsight people today pretty much agree with that, but at the time most considered this a decisive obstacle to any cohomological proof of the Weil Conjectures. And no one before Serre's FAC saw how to use Zariski topology to prove any very serious results. Serre's FAC immediately persuaded a lot of people that algebraic geometry over arbitrary fields could, and in fact must, use the Zariski topology. But many structures which intuitively ought to be "locally trivial" are clearly not so if "locally" means "on small enough Zariski open sets." Zariski open sets just never are small -- they are dense on any connected component. Serre wrestled with precisely this problem for several years. And then in 1958, with Riemann's original works explicitly in mind, Serre said let us allow "local trivialization" of fiber bundles just the way Riemann "trivialized" multiple valued functions into single valued ones-- let us trivialize them by pullback along unramified Riemann surface covers -- except using a purely algebraic definition of "unramified" so it works over any field, and indeed for varieties of any dimension. A strikingly plausible idea once you think of it. But does it work? By the kind of deep, detailed skill that Serre typically conjoins to his insights, he got it to work for dimension one cohomology (of varieties of any dimension). It works in the precise sense that it delivers the $H^1$ part of the long exact cohomology sequences you would want for the Weil Conjectures. Serre knew well how hard he had to work to get these $H^1$s. So he was skeptical when Grothendieck first announced this had to work for cohomology in all dimensions. But Grothendieck had utter faith in his general theory of derived functor cohomology: once Serre identified the correct basics, they had to deliver the whole theory. Well it turned out to take a lot more specific work, and there is the long and on-going story of the standard conjectures which were meant to make the cohomological proof much simpler than it yet is, but Grothendieck's faith was essentially justified. As to the history I would slightly modify what Will Sawin says. He puts the key issues very well. But Weil did not believe there could be an actual cohomology theory for varieties in finite characteristic. I believe he believed there would be some more direct comparison theorem between varieties in finite characteristic, and their lifts to characteristic zero, which would make the conjectures follow from simplicial cohomology. And he did not especially believe that such a comparison would be the way to prove the conjectures. He probably leaned to the idea that the relation to simplicial cohomology of complex manifolds would be an enlightening corollary to some other kind of proof. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/210697', 'https://mathoverflow.net', 'https://mathoverflow.net/users/68893/']} | jdg_77276 |
stackexchange | llm_judgeable_groundtruth_similarity | 752711 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible log all dropped connections by IPTables and set a iptables.log file for logging in /var/log/?
Now provide the response and nothing else.
| You can do this my configuring iptables to 'mark' the messages e.g. iptables -A INPUT -s 192.0.2.0/24 -j LOG --log-prefix='[iptables] ' Which will cause a log message that is prefixed with the text [iptables] Now you can configure your rsyslog to send these messages to a particular log file by adding a suitable entry to it's configuration e.g. :msg,contains,"[iptables] " /var/log/iptables.log | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/752711', 'https://serverfault.com', 'https://serverfault.com/users/-1/']} | jdg_77277 |
stackexchange | llm_judgeable_groundtruth_similarity | 265809 |
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:
Suppose two amounts of water of the same mass, but with different temperature, are mixed. Then the entropy of the hot water decreases, but the entropy of the cold water increases due to heat transfer. But how is the entropy of whole system increased? And how is this irreversible? (Or am I getting the concept of entropy wrong?)
Now provide the response and nothing else.
| The bottom line is that hot water loses heat at high temperature, giving a small negative entropy change while the cold water gain heat at low temperature resulting in a high entropy change. The net entropy change is positive. We can explicitly see this: At any instant, the infinitesimal change in the entropy of the system is$$dS=\frac{dQ_H}{T_H}+\frac{dQ_C}{T_C},$$where $dQ_H<0$ and $dQ_C>0$ are the heat exchanged by the hot and cold water respectively. The corresponding temperatures are $T_H$ and $T_C$. Since$$|dQ_H|=|dQ_C|\equiv dQ>0,$$we can write$$dS=dQ\left(\frac{1}{T_C}-\frac{1}{T_H}\right)=dQ\left(\frac{T_H-T_C}{T_HT_C}\right)>0.$$At any instant the temperature of the hot water is greater than the temperature of the cold water. So the $dS$ above is always positive and the process is irreversible at any intermediate state. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/265809', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/65843/']} | jdg_77278 |
stackexchange | llm_judgeable_groundtruth_similarity | 52032324 |
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 ONLY the editText can be scroll-able. How to do it? As shown in the image below, when user enter the address, the editText becomes like that. Can someone help me, which part do I miss? Java coding:- final EditText yourMessage = (EditText) findViewById(R.id.contactMsg); XML Coding:- <EditText android:id="@+id/contactMsg" android:layout_width="288dp" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="390dp" android:background="#FFF" android:drawableLeft="@drawable/ic_action_clipboards" android:ems="10" android:hint="Message" android:inputType="textMultiLine" android:padding="2dp" android:textSize="18sp" />
Now provide the response and nothing else.
| You need to create a dummy variable for x-axis. Then use geom_col which is similar to geom_bar(stat = "identity") to plot the stacked barplot + geom_text to put the text on the bar. The plot you showed used theme_economist from the ggthemes package. library(tidyverse)Ancestry <- data.frame(Race = c("European", "African American", "Asian", "Hispanic", "Other"), Proportion = c(40, 30, 10, 15, 5))Ancestry <- Ancestry %>% mutate(Year = "2006")ggplot(Ancestry, aes(x = Year, y = Proportion, fill = Race)) + geom_col() + geom_text(aes(label = paste0(Proportion, "%")), position = position_stack(vjust = 0.5)) + scale_fill_brewer(palette = "Set2") + theme_minimal(base_size = 16) + ylab("Percentage") + xlab(NULL) library(ggthemes)ggplot(Ancestry, aes(x = Year, y = Proportion, fill = Race)) + geom_col() + geom_text(aes(label = paste0(Proportion, "%")), position = position_stack(vjust = 0.5)) + theme_economist(base_size = 14) + scale_fill_economist() + theme(legend.position = "right", legend.title = element_blank()) + theme(axis.title.y = element_text(margin = margin(r = 20))) + ylab("Percentage") + xlab(NULL) Created on 2018-08-26 by the reprex package (v0.2.0.9000). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52032324', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8729567/']} | jdg_77279 |
stackexchange | llm_judgeable_groundtruth_similarity | 6977668 |
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 designing a web API which requires fast read only access to a large dataset which will be hopefully be constantly stored and ready for access. Access will be from a static class which will just do some super fast lookups on the data. So, I want to pre-cache a Dictionary<string,Dictionary<string,Dictionary<string,myclass>>> , with the total number of elements at the third level dictionary being around 1 Million, which will increase eventually, but lets say not more than 2 million ever. 'myclass' is a small class with a (small) list of strings, an int, an enum and a couple of bools, so nothing major. It should be a bit over 100mb in memory. From what I can tell, the way to do this is simply call my StaticClass.Load() method to read all this data in from a file with the Application_Start event in Global.asax. I am wondering what the things I need to consider/worry about with this. I am guessing it is not just as simple as calling Load() and then assuming everything will be OK for future access. Will the GC know to leave the data there even if the API is not hit for a couple of hours? To complicate things, I want to reload this data every day as well. I think I'll just be able to throw out the old dataset and load the new one in from another file, but I'll get to that later. Cheers
Now provide the response and nothing else.
| you can query for individual columns, which returns named tuples that do in fact act pretty much like your mapped object if you're just passing off to a template or something: http://www.sqlalchemy.org/docs/orm/tutorial.html#querying or you can establish various columns on the mapped class as "deferred", either configurationally or using options: http://docs.sqlalchemy.org/en/latest/orm/loading_columns.html#deferred-column-loading there's an old ticket in trac for something called "defer_everything_but()", if someone felt like providing tests and such there's no reason that couldn't be a feature add, here's a quick version: from sqlalchemy.orm import class_mapper, deferdef defer_everything_but(entity, cols): m = class_mapper(entity) return [defer(k) for k in set(p.key for p in m.iterate_properties if hasattr(p, 'columns')).difference(cols)]s = Session()print s.query(A).options(*defer_everything_but(A, ["q", "p"])) defer() should really accept multiples, added ticket #2250 for that (edit: as noted in the comment this is in 0.9 as load_only() ) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6977668', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/442370/']} | jdg_77280 |
stackexchange | llm_judgeable_groundtruth_similarity | 1769409 |
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:
A trigonometric polynomial was defined as $$f(x) = \frac{a_0}{2} + \sum_{k=1}^{n}(a_k \cos(kx) + b_k \sin(kx))$$ I heard somewhere that trigonometric polynomials have a ring structure, i.e. a product of two polynomials is again a polynomial. I was wondering how can one see it. A direct attempt to multiply two polynomials seem to result in a mess. Edit : Using a suggestion from nicomezi from below I go to the complex representation: $$f(x) = \frac{a_0}{2} + \frac{1}{2} \sum_{k=1}^{n}(e^{ikx}z_k + e^{-ikx} \bar z_k )$$ We can also "hide" the first term: $$f(x)=\frac{1}{2} \sum_{k=0}^{n}(e^{ikx}z_k + e^{-ikx} \bar z_k ), z_0 = a_0$$ Now when we multiply two polynomials of degrees $n$ and $m$ we get a sum of terms of the form: $$\frac{1}{4}(e^{ikx}z_k + e^{-ikx} \bar z_k )(e^{ilx}z_l + e^{-ilx} \bar z_l )= \frac{1}{4}(e^{i(k+l)x}z_kz_l + e^{-i(k+l)x}\overline{z_k z_l}) + \frac{1}{4}(e^{i(k-l)x}z_k\bar z_l + e^{-i(k-l)x} \overline{z_k \bar z_l}), 1 \le k \le n, 1 \le l \le m$$ So each term is a polynomial of degree $(k+l)$, thus the whole product is a polynomial of degree $(n+m)$.
Now provide the response and nothing else.
| There is no need to multiply two polynomials, that does, indeed, result in a mess. Instead, all you need to show is that: $\cos(kx)\cos(lx)$ is a trigonometric polynomial, $\cos(kx)\sin(lx)$ is a trigonometric polynomial, and $\sin(kx)\sin(lx)$ is a trigonometric polynomial. The rest comes from linearity. Let's check $\cos(kx)\sin(lx)$ is a trigonometric polynomial; the rest of the cases are very similar. Since $e^{ikx}=\cos(kx)+i\sin(kx)$, $\cos(kx)=\frac{1}{2}\left(e^{ikx}+e^{-ikx}\right)$. Similarly, $\sin(lx)=\frac{1}{2}\left(ie^{-ilx}-ie^{ilx}\right)$. Therefore, $$\cos(kx)\sin(lk)=\frac{1}{4}\left(ie^{i(k-l)x}+ie^{-i(k+l)x}-ie^{i(k+l)x}-ie^{i(l-k)x}\right).$$Since our answer should be real, we are only interested in the real part of this, which is:$$\cos(kx)\sin(lx)=-\frac{1}{2}\sin((k-l)x)+\frac{1}{2}\sin((k+l)x)$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1769409', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/100051/']} | jdg_77281 |
stackexchange | llm_judgeable_groundtruth_similarity | 23503 |
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
No, not that cat! Catalytic converters - or "cats" - have a nasty habit of failing with age. What are the symptoms associated with a cat that's gone bad? Are there any tests that could definitively confirm that a cat has gone bad?
Now provide the response and nothing else.
| Cats can stop functioning in a couple of ways: physical deformation due to high temperatures According to this article , the catalyst melts at temperatures above 2100 °F (1200 °C). In the event of a meltdown, the catalyst gets permanently damaged, at which point it doesn't scrub the nastiness out of the exhaust gases and serves as a major exhaust restriction. inhibition of the chemical reaction, usually due to fouling of the catalyst inside Unburnt fuel can accumulate in the cats over time, which inhibits the chemical reaction and increases the restrictiveness of the exhaust. The clogging leads to bigger problems related to engine inoperability. A danger associated with built-up hydrocarbons is that if a spark finds its way into the cat, it will turn into a secondary combustion chamber, destroying the catalyst . Testing cats There are several ways to assess the health of a cat: Measure temps The catalytic reaction is exothermic in nature, so the exit side the cat should be hotter than the inlet side. Paulster2's answer outlines a way to test for the presence of the chemical reaction by measuring temperature across the cat. If exhaust side isn't hotter by 200 °F (93 °C), the reaction isn't taking place and the cat isn't doing its job. Consult the lambdas The big caveat with this approach is that it assumes the lambda sensors in question are healthy. In narrowband setups, the voltage output of the pre-cat lambda sensor should flit between 0.1 V (lean) and 0.9 V (rich). Since the chemical reaction inside the cat consumes oxygen, the post-cat lambda should show a stable signal which corresponds to a rich condition. The image below summarizes the expected results. Check for restrictions Clogging usually occurs due to the accumulation of unburnt hydrocarbons, which is often a sign of bigger problems with engine operability. Clogged catalytic converters result in a very high engine backpressure, which results in noticeable loss of power and the engine's refusal to run at higher RPM's. A very conclusive test shown by this video involves measuring pressure drop across the catalytic converter. It helps to have pre- and post-cat lambda sensors for this test: unscrew the lambda sensors that sandwich the suspect cat attach a fitting into the bung that allows for a pressure gauge or vacuum gauge to be plumbed in In the video, Matt uses some pipe with a 22 mm thread cut into one end, but even a cork could do. measure pressure drop. There should be minimal pressure drop across the cat. Any value greater than 2 psi would be a strong indication of clogging in the catalytic converter. Note - Since the post-cat exhaust pressure is almost atmospheric, it is possible to do this with just the pre-cat O2 sensor bung, with one caveat that restrictions may be caused by other downstream elements such as mufflers. Use an OBD-II scan tool The OBD-II protocol assigns P0420 and P0430 for Bank 1 and Bank 2 cat efficiencies respectively. The exact logic by which the engine computer sets these codes will vary between manufacturers and models, but they will invariably involve assessing the signal coming from the pre-cat and post-cat lambda sensors, as outlined in 2 . Once again, this assumes fully-functional lambda probes, so a faulty lambda sensor may trigger a false-positive P0420 code. Propane test | {} | {'log_upvote_score': 4, 'links': ['https://mechanics.stackexchange.com/questions/23503', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/675/']} | jdg_77282 |
stackexchange | llm_judgeable_groundtruth_similarity | 7905140 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I just cannot get the point: If '\0' is an empty char and if a string is a kind of array of chars why this happens? char value = '\0';bool isEmpty = value.ToString() == string.Empty; // This returns FALSE because // '\0'.ToString() returns "\0" // where I expect it to be // string.empty
Now provide the response and nothing else.
| There's no such thing as an "empty char", so your assumption in the first sentence is incorrect. A string with a single character (U+0000) is not the same as an empty string - for a start, the length of the first string is 1, not 0. Calling ToString() on a char will always return a string of length 1, containing just that character. That's the only thing that it makes sense to do, IMO. I don't know why you would expect anything else. While U+0000 is often used as a terminating character, it's not the same as the character "not existing". The string "Foo\0Bar" is not the same as "FooBar", and shouldn't be treated the same. In short: it's your expectations which are incorrect, not .NET :) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7905140', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/136141/']} | jdg_77283 |
stackexchange | llm_judgeable_groundtruth_similarity | 169197 |
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:
we receive a weekly security report for our websites. It said our SSH version was outdated (we have OpenSSH_6.7p1, they recommend 7.5 or later). Since there is no stable version for our distribution yet, we thought we'd just close port 22 on all internet facing machines (good practice anyways isn't it?). Today came the new report. It still states 10 issues regarding the SSH version. So my questions are: How can they find out the SSH version if the port is closed? wouldn't closing the port successfully mitigate all SSH security issues, no matter the version?
Now provide the response and nothing else.
| “SSH version is outdated” is not necessarily a security problem. Their recommendation is to install the latest version, but there is no benefit in running the latest version unless you want the latest features. For security, what matters is that you have all the security fixes applied . Many distributions apply security fixes to the version they ship. For example, CentOS 6 still ships OpenSSH 5.3p1 and will be receiving security updates until 2020; CentOS 7, the current release, ships OpenSSH 6.6.1p1. Debian jessie ships OpenSSH 6.7p1 and will also be receiving security updates until 2020, while the latest release stretch ships OpenSSH7.4p1. In general, you should not install packages outside your distribution for critical infrastructure components such as OpenSSH. If you do, make sure to subscribe to security bulletins and apply security updates as soon as possible. If you just install OpenSSH 7.5 now and forget about it later, you're significantly weakening your security. If you get a report that only says “version is outdated” and doesn't even try to determine whether the proper security patches have been applied, it's a bad report. Closing external SSH access on servers that don't need them is a good idea regardless. One machine where the security updates are falling behind, or one machine where a user's password or key have been compromised, could get the attacker into your network. It's often a good idea to limit external access to a single gateway machine (or a small set of machines for redundancy) where updates and account are more closely monitored. Closing the port in the firewall will mitigate the issue of direct access. Indirect access (where the attacker gets into the network on a machine that's doing nothing important, and uses that as a relay to get into more important machine) will still be a concern. You can check SSH access by yourself by running ssh -v MACHINENAME from outside. If MACHINENAME is running an SSH server and the firewall doesn't block you, you'll see a line like debug1: Remote protocol version 2.0, remote software version OpenSSH_6.7p1 Debian-5+deb8u3 That, as I write, is the current version on Debian jessie and is perfectly fine. | {} | {'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/169197', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/59205/']} | jdg_77284 |
stackexchange | llm_judgeable_groundtruth_similarity | 7780890 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My original query is doing joins using the WHERE clause rather than JOIN. I realized that this was not returning movies that did not have any stars or genres did not show up so I think I have to do a LEFT JOIN in order to show every movie. Here is my original SQL: SELECT *FROM movies m, stars s, stars_in_movies sm, genres g, genres_in_movies gmWHERE m.id = sm.movie_idAND sm.star_id = s.idAND gm.genre_id = g.idAND gm.movie_id = m.idAND m.title LIKE '%the%'AND s.first_name LIKE '%Ben%'ORDER BY m.title ASCLIMIT 5; I tried to do a LEFT JOIN on movies I'm definitely doing something wrong. SELECT *FROM movies m, stars s, stars_in_movies sm, genres g, genres_in_movies gmLEFT JOIN movies m1 ON m1.id = sm.movie_idLEFT JOIN movies m2 ON m2.id = gm.movie_idAND sm.star_id = s.idAND gm.genre_id = g.idORDER BY m.title ASCLIMIT 5; I get ERROR 1054 (42S22): Unknown column 'sm.movie_id' in 'on clause' so clearly I'm doing the join wrong, I just don't see what it is.
Now provide the response and nothing else.
| Don't mix the comma operator with JOIN - they have different precedence! There is even a warning about this in the manual : However, the precedence of the comma operator is less than of INNER JOIN, CROSS JOIN, LEFT JOIN, and so on. If you mix comma joins with the other join types when there is a join condition, an error of the form Unknown column 'col_name' in 'on clause' may occur. Information about dealing with this problem is given later in this section. Try this instead: SELECT *FROM movies mLEFT JOIN ( stars s JOIN stars_in_movies sm ON sm.star_id = s.id) ON m.id = sm.movie_id AND s.first_name LIKE '%Ben%'LEFT JOIN ( genres g JOIN genres_in_movies gm ON gm.genre_id = g.id) ON gm.movie_id = m.idWHERE m.title LIKE '%the%'ORDER BY m.title ASCLIMIT 5; | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7780890', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/266535/']} | jdg_77285 |
stackexchange | llm_judgeable_groundtruth_similarity | 43929437 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I created a database using 'CREATE DATABASE Gameshop;' for my class and I need to hand it in as an '.sql' file but, I don't know where to look for the file or how to create it. I am worried I will lose all of my work if I attempt something and fail. Thank you!
Now provide the response and nothing else.
| I suggest the following solution: create self-signed CA certificate and the web server certificate signed by this CA. When you install this small chain to your web server it will work with Chrome. Create configuration file for your CA MyCompanyCA.cnf with contents (you can change it to your needs): [ req ]distinguished_name = req_distinguished_namex509_extensions = root_ca[ req_distinguished_name ]countryName = Country Name (2 letter code)countryName_min = 2countryName_max = 2stateOrProvinceName = State or Province Name (full name)localityName = Locality Name (eg, city)0.organizationName = Organization Name (eg, company)organizationalUnitName = Organizational Unit Name (eg, section)commonName = Common Name (eg, fully qualified host name)commonName_max = 64emailAddress = Email AddressemailAddress_max = 64[ root_ca ]basicConstraints = critical, CA:true Create the extensions configuration file MyCompanyLocalhost.ext for your web server certificate: subjectAltName = @alt_namesextendedKeyUsage = serverAuth[alt_names]DNS.1 = localhostDNS.2 = mypc.mycompany.com Then execute the following commands: openssl req -x509 -newkey rsa:2048 -out MyCompanyCA.cer -outform PEM -keyout MyCompanyCA.pvk -days 10000 -verbose -config MyCompanyCA.cnf -nodes -sha256 -subj "/CN=MyCompany CA"openssl req -newkey rsa:2048 -keyout MyCompanyLocalhost.pvk -out MyCompanyLocalhost.req -subj /CN=localhost -sha256 -nodesopenssl x509 -req -CA MyCompanyCA.cer -CAkey MyCompanyCA.pvk -in MyCompanyLocalhost.req -out MyCompanyLocalhost.cer -days 10000 -extfile MyCompanyLocalhost.ext -sha256 -set_serial 0x1111 As result you will get MyCompanyCA.cer, MyCompanyLocalhost.cer and MyCompanyLocalhost.pvk files that you can install to the web server. How to check that it works with Chrome before installing certificates to the web server. Execute the following command on your local PC to run web server simulator: openssl s_server -accept 15000 -cert MyCompanyLocalhost.cer -key MyCompanyLocalhost.pvk -CAfile MyCompanyCA.cer -WWW Then you can access this page at https://localhost:15000/ You will see an error that MyCompanyLocalhost.cer is not trusted, if you want to eliminate this error also - then install MyCompanyCA.cer to the certificate trusted list of your OS. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43929437', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8000818/']} | jdg_77286 |
stackexchange | llm_judgeable_groundtruth_similarity | 391181 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the difference between a 302 and 303 response? http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html 10.3.3 302 Found 10.3.4 303 See Other Are these interchangeable or why would one be used over the other? Could you please provide a use case of when one would be used (and the other would not) ?
Now provide the response and nothing else.
| The description on the page to which you linked seem to be fairly descriptive of their intended purpose: A 302 redirect indicates that the redirect is temporary -- clients should check back at the original URL in future requests. A 303 redirect is meant to redirect a POST request to a GET resource (otherwise, the client assumes that the request method for the new location is the same as for the original resource). If you're redirecting a client as part of your web application but expect them to always start at the web application (for example, a URL shortener), a 302 redirect seems to make sense. A 303 redirect is for use when you are receiving POST data from a client (e.g., a form submission) and you want to redirect them to a new web page to be retrieved using GET instead of POST (e.g., a standard page request). But see this note from the status code definitions -- most clients will do the same thing for either a 302 or 303: Note: RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request. However, most existing user agent implementations treat 302 as if it were a 303 response, performing a GET on the Location field-value regardless of the original request method. The status codes 303 and 307 have been added for servers that wish to make unambiguously clear which kind of reaction is expected of the client. | {} | {'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/391181', 'https://serverfault.com', 'https://serverfault.com/users/78503/']} | jdg_77287 |
stackexchange | llm_judgeable_groundtruth_similarity | 33728908 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Using this code I am able to send single SMS only.When Gridview is having only one row code is sending SMS but when Gridview is having more than one row code is not sending SMS. When I am providing a fixed string like 'Hi' or 'Hellow' its sending SMS to multiple recipients.I am not experienced coder so I am not having idea why this is happening. protected void btnallocate_Click(object sender, EventArgs e){ int n = 0; int studentchecked = 0; foreach (GridViewRow row in grdallocatestudent.Rows) { CheckBox chkallocate = (CheckBox)row.Cells[0].FindControl("chkallocate"); if (chkallocate.Checked) { ds = new DataSet(); Label lblstudentid = (Label)row.Cells[1].FindControl("lblstudentid"); Label lblname = (Label)row.Cells[1].FindControl("lblname"); Label lblprimarymob = (Label)row.Cells[6].FindControl("lblprimarymob"); Label lblsecondarymob = (Label)row.Cells[7].FindControl("lblsecondarymob"); Label lblcoursename = (Label)row.Cells[9].FindControl("lblcoursename"); Label lblbatchdate = (Label)row.Cells[12].FindControl("lblbatchdate"); Label lbltimefrom = (Label)row.Cells[13].FindControl("lbltimefrom"); Label lbltimeto = (Label)row.Cells[14].FindControl("lbltimeto"); int batchid = Convert.ToInt32(drlbatch.SelectedValue); string batchname = drlbatch.SelectedItem.Text; int studentid = Convert.ToInt32(lblstudentid.Text); string primarymob = lblprimarymob.Text; string secondarymob = lblsecondarymob.Text; string name = lblname.Text; string coursename = lblcoursename.Text; //getbatchinfo(batchid); int courseid = Convert.ToInt32(drlcourse.SelectedValue); int franchiseeid = Convert.ToInt32(Session["Franchisee"]); string batchdate = lblbatchdate.Text; string timefrom = lbltimefrom.Text; string timeto = lbltimeto.Text; //string timefrom = Convert.ToString(dt.Rows[0][4]); //string timeto = Convert.ToString(dt.Rows[0][5]); string message = "Dear " + name + ", Your batch " + batchname + " will be on " + batchdate + " from " + timefrom + " " + timeto + " for course " + coursename; studentchecked = studentchecked + 1; //string message = "Hi!!!"; n = b.insertbatchallocation(batchid, studentid, courseid, batchdate, franchiseeid, message); SendSMS1(message, primarymob); SendSMS1(message, secondarymob); } } drlcourse.ClearSelection(); drlbatch.ClearSelection(); getstudentsforallocation(Convert.ToInt32(drlcourse.SelectedValue), Convert.ToInt32(drlbatch.SelectedValue)); if (studentchecked > 0 && n > 0) { ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), Guid.NewGuid().ToString(), "alert('Students batch allocation successfull');", true); } else { ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), Guid.NewGuid().ToString(), "alert('Check at least one Checkbox for allocating students to batch');", true); }}public void SendSMS1(string message, string contact){ //HTTP connection HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://fast.admarksolution.com/vendorsms/pushsms.aspx?user=kiran&password=abc123&msisdn=91" + contact + "&sid=PRERNA&msg=" + message + "&fl=0&gwid=2"); //Get response from Ozeki NG SMS Gateway Server and read the answer HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse(); System.IO.StreamReader respStreamReader = new System.IO.StreamReader(myResp.GetResponseStream()); string responseString = respStreamReader.ReadToEnd(); respStreamReader.Close(); myResp.Close();}
Now provide the response and nothing else.
| >= Xcode 8 In Xcode 8, as Bruce said, this happens when Qt tries to find xcrun when it should be looking for xcodebuild . Open the file: Qt_install_folder/5.7/clang_64/mkspecs/features/mac/default_pre.prf Replace: isEmpty($$list($$system("/usr/bin/xcrun -find xcrun 2>/dev/null"))) With: isEmpty($$list($$system("/usr/bin/xcrun -find xcodebuild 2>/dev/null"))) ~> Xcode 8 Before Xcode 8, this problem occurs when command line tools are installed after Xcode is installed. What happens is the Xcode-select developer directory gets pointed to /Library/Developer/CommandLineTools . Point Xcode-select to the correct Xcode Developer directory with the command: sudo xcode-select -switch /Applications/Xcode.app/Contents/Developer Confirm the license agreement with the command: sudo xcodebuild -license This will prompt you to read through the license agreement. Enter agree to accept the terms. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/33728908', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5213884/']} | jdg_77288 |
stackexchange | llm_judgeable_groundtruth_similarity | 78632 |
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 would like to use imputation for replacing missing values in my data set under certain constraints. For example, I'd like the imputed variable x1 to be greater or equal to the sum of my two other variables, say x2 and x3 . I also want x3 to be imputed by either 0 or >= 14 and I want x2 to be imputed by either 0 or >= 16 . I tried defining these constraints in SPSS for multiple imputation, but in SPSS I can only define maximum and minimum values. Is there any way to define further constraints in SPSS or do you know any R package which would let me define such constraints for imputation of missing values? My data is as follows: x1 =c(21, 50, 31, 15, 36, 82, 14, 14, 19, 18, 16, 36, 583, NA,NA,NA, 50, 52, 26, 24) x2 = c(0, NA, 18,0, 19, 0, NA, 0, 0, 0, 0, 0, 0,NA,NA, NA, 22, NA, 0, 0) x3 = c(0, 0, 0, 0, 0, 54, 0 ,0, 0, 0, 0, 0, 0, NA, NA, NA, NA, 0, 0, 0) dat=data.frame(x1=x1, x2=x2, x3=x3) > dat x1 x2 x3 1 21 0 0 2 50 NA 0 3 31 18 0 4 15 0 0 5 36 19 0 6 82 0 54 7 14 NA 0 8 14 0 0 9 19 0 0 10 18 0 0 11 16 0 0 12 36 0 0 13 583 0 0 14 NA NA NA 15 NA NA NA 16 NA NA NA 17 50 22 NA 18 52 NA 0 19 26 0 0 20 24 0 0
Now provide the response and nothing else.
| One solution is to write your own custom imputation functions for the mice package. The package is prepared for this and the setup surprisingly pain-free. First we setup the data as suggested: dat=data.frame(x1=c(21, 50, 31, 15, 36, 82, 14, 14, 19, 18, 16, 36, 583, NA,NA,NA, 50, 52, 26, 24), x2=c(0, NA, 18,0, 19, 0, NA, 0, 0, 0, 0, 0, 0,NA,NA, NA, 22, NA, 0, 0), x3=c(0, 0, 0, 0, 0, 54, 0 ,0, 0, 0, 0, 0, 0, NA, NA, NA, NA, 0, 0, 0)) Next we load the mice package and see what methods it choose by default: library(mice)# Do a non-imputationimp_base <- mice(dat, m=0, maxit = 0)# Find the methods that mice choosesimp_base$method# Returns: "pmm" "pmm" "pmm"# Look at the imputation matriximp_base$predictorMatrix# Returns:# x1 x2 x3#x1 0 1 1#x2 1 0 1#x3 1 1 0 The pmm stands for predictive mean matching - probably the most popular imputation algorithm for imputing continuous variables. It calculates the predicted value using a regression model and picks the 5 closest elements to the predicted value (by Euclidean distance ). These chosen elements are called the donor pool and the final value is chosen at random from this donor pool. From the prediction matrix we find that the methods get the variables passed that are of interest for the restrictions. Note that the row is the target variable and the column the predictors. If x1 did not have 1 in the x3 column we would have to add this in the matrix: imp_base$predictorMatrix["x1","x3"] <- 1 Now to the fun part, generating the imputation methods. I've chosen a rather crude method here where I discard all values if they don't meet the criteria. This may result in long loop time and it may potentially be more efficient to keep the valid imputations and only redo the remaining ones, it would require a little more tweaking though. # Generate our custom methodsmice.impute.pmm_x1 <- function (y, ry, x, donors = 5, type = 1, ridge = 1e-05, version = "", ...) { max_sum <- sum(max(x[,"x2"], na.rm=TRUE), max(x[,"x3"], na.rm=TRUE)) repeat{ vals <- mice.impute.pmm(y, ry, x, donors = 5, type = 1, ridge = 1e-05, version = "", ...) if (all(vals < max_sum)){ break } } return(vals) }mice.impute.pmm_x2 <- function (y, ry, x, donors = 5, type = 1, ridge = 1e-05, version = "", ...) { repeat{ vals <- mice.impute.pmm(y, ry, x, donors = 5, type = 1, ridge = 1e-05, version = "", ...) if (all(vals == 0 | vals >= 14)){ break } } return(vals) }mice.impute.pmm_x3 <- function (y, ry, x, donors = 5, type = 1, ridge = 1e-05, version = "", ...) { repeat{ vals <- mice.impute.pmm(y, ry, x, donors = 5, type = 1, ridge = 1e-05, version = "", ...) if (all(vals == 0 | vals >= 16)){ break } } return(vals) } Once we are done defining the methods we simple change the previous methods. If you only want to change a single variable then you can simply use imp_base$method["x2"] <- "pmm_x2" but for this example we will change all (the naming is not necessary): imp_base$method <- c(x1 = "pmm_x1", x2 = "pmm_x2", x3 = "pmm_x3")# The predictor matrix is not really necessary for this example# but I use it just to illustrate in case you would like to # modify itimp_ds <- mice(dat, method = imp_base$method, predictorMatrix = imp_base$predictorMatrix) Now let's have a look at the third imputed dataset: > complete(imp_ds, action = 3) x1 x2 x31 21 0 02 50 19 03 31 18 04 15 0 05 36 19 06 82 0 547 14 0 08 14 0 09 19 0 010 18 0 011 16 0 012 36 0 013 583 0 014 50 22 015 52 19 016 14 0 017 50 22 018 52 0 019 26 0 020 24 0 0 Ok, that does the job. I like this solution as you can piggyback on top of mainstream functions and just add the restrictions that you find meaningful. Update In order to enforce the rigorous restraints @t0x1n mentioned in the comments, we may want to add the following abilities to the wrapper function: Save valid values during the loops so that data from previous, partially successful runs is not discarded An escape mechanism in order to avoid infinite loops Inflate the donor pool after trying x times without finding a suitable match (this primarily applies to pmm) This results in a slightly more complicated wrapper function: mice.impute.pmm_x1_adv <- function (y, ry, x, donors = 5, type = 1, ridge = 1e-05, version = "", ...) { # The mice:::remove.lindep may remove the parts required for # the test - in those cases we should escape the test if (!all(c("x2", "x3") %in% colnames(x))){ warning("Could not enforce pmm_x1 due to missing column(s):", c("x2", "x3")[!c("x2", "x3") %in% colnames(x)]) return(mice.impute.pmm(y, ry, x, donors = 5, type = 1, ridge = 1e-05, version = "", ...)) } # Select those missing max_vals <- rowSums(x[!ry, c("x2", "x3")]) # We will keep saving the valid values in the valid_vals valid_vals <- rep(NA, length.out = sum(!ry)) # We need a counter in order to avoid an eternal loop # and for inflating the donor pool if no match is found cntr <- 0 repeat{ # We should be prepared to increase the donor pool, otherwise # the criteria may become imposs donor_inflation <- floor(cntr/10) vals <- mice.impute.pmm(y, ry, x, donors = min(5 + donor_inflation, sum(ry)), type = 1, ridge = 1e-05, version = "", ...) # Our criteria check correct <- vals < max_vals if (all(!is.na(valid_vals) | correct)){ valid_vals[correct] <- vals[correct] break }else if (any(is.na(valid_vals) & correct)){ # Save the new valid values valid_vals[correct] <- vals[correct] } # An emergency exit to avoid endless loop cntr <- cntr + 1 if (cntr > 200){ warning("Could not completely enforce constraints for ", sum(is.na(valid_vals)), " out of ", length(valid_vals), " missing elements") if (all(is.na(valid_vals))){ valid_vals <- vals }else{ valid_vals[is.na(valid_vals)] <- vals[is.na(valid_vals)] } break } } return(valid_vals)} Note that this does not perform that well, most likely due to that the suggested data set fails the constraints for all cases without missing. I need to increase the loop length to 400-500 before it even starts to behave. I assume that this is unintentional, your imputation should mimic how the actual data is generated. Optimization The argument ry contains the non-missing values and we could possibly speed up the loop by removing the elements that we have found eligible imputations, but as I'm unfamiliar with the inner functions I have refrained from this. I think the most important thing when you have strong constraints that take time to full-fill is to parallelize your imputations ( see my answer on CrossValidated ). Most have today computers with 4-8 cores and R only uses one of them by default. The time can be (almost) sliced in half by doubling the number of cores. Missing parameters at imputation Regarding the problem of x2 being missing at the time of imputation - mice actually never feeds missing values into the x - data.frame . The mice method includes filling in some random value at start. The chain-part of the imputation limits the impact from this initial value. If you look at the mice -function you can find this prior to the imputation call (the mice:::sampler -function): ...if (method[j] != "") { for (i in 1:m) { if (nmis[j] < nrow(data)) { if (is.null(data.init)) { imp[[j]][, i] <- mice.impute.sample(y, ry, ...) } else { imp[[j]][, i] <- data.init[!ry, j] } } else imp[[j]][, i] <- rnorm(nrow(data)) }}... The data.init can be supplied to the mice function and the mice.imput.sample is a basic sampling procedure. Visiting sequence If visiting sequence is important you can specify the order in which the mice -function runs the imputations. Default is from 1:ncol(data) but you can set the visitSequence to be anything you like. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/78632', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/11691/']} | jdg_77289 |
stackexchange | llm_judgeable_groundtruth_similarity | 48046814 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Imagine you want to align a series of x86 assembly instructions to certain boundaries. For example, you may want to align loops to a 16 or 32-byte boundary, or pack instructions so they are efficiently placed in the uop cache or whatever. The simplest way to achieve this is single-byte NOP instructions, followed closely by multi-byte NOPs . Although the latter is generally more efficient, neither method is free: NOPs use front-end execution resources, and also count against your 4-wide 1 rename limit on modern x86. Another option is to somehow lengthen some instructions to get the alignment you want. If this is done without introducing new stalls, it seems better than the NOP approach. How can instructions be efficiently made longer on recent x86 CPUs? In the ideal world lengthening techniques would simultaneously be: Applicable to most instructions Capable of lengthening the instruction by a variable amount Not stall or otherwise slow down the decoders Be efficiently represented in the uop cache It isn't likely that there is a single method that satisfies all of the above points simultaneously, so good answers will probably address various tradeoffs. 1 The limit is 5 or 6 on AMD Ryzen.
Now provide the response and nothing else.
| Consider mild code-golfing to shrink your code instead of expanding it , especially before a loop. e.g. xor eax,eax / cdq if you need two zeroed registers, or mov eax, 1 / lea ecx, [rax+1] to set registers to 1 and 2 in only 8 total bytes instead of 10. See Set all bits in CPU register to 1 efficiently for more about that, and Tips for golfing in x86/x64 machine code for more general ideas. Probably you still want to avoid false dependencies, though. Or fill extra space by creating a vector constant on the fly instead of loading it from memory. (Adding more uop-cache pressure could be worse, though, for the larger loop that contains your setup + inner loop. But it avoids d-cache misses for constants, so it has an upside to compensate for running more uops.) If you weren't already using them to load "compressed" constants, pmovsxbd , movddup , or vpbroadcastd are longer than movaps . dword / qword broadcast loads are free (no ALU uop, just a load). If you're worried about code alignment at all, you're probably worried about how it sits in the L1I cache or where the uop-cache boundaries are, so just counting total uops is no longer sufficient, and a few extra uops in the block before the one you care about may not be a problem at all. But in some situations, you might really want to optimize decode throughput / uop-cache usage / total uops for the instructions before the block you want aligned. Padding instructions, like the question asked for: Agner Fog has a whole section on this: "10.6 Making instructions longer for the sake of alignment" in his "Optimizing subroutines in assembly language" guide . (The lea , push r/m64 , and SIB ideas are from there, and I copied a sentence / phrase or two, otherwise this answer is my own work, either different ideas or written before checking Agner's guide.) It hasn't been updated for current CPUs, though: lea eax, [rbx + dword 0] has more downsides than it used to vs mov eax, ebx , because you miss out on zero-latency / no execution unit mov . If it's not on the critical path, go for it though. Simple lea has fairly good throughput, and an LEA with a large addressing mode (and maybe even some segment prefixes) can be better for decode / execute throughput than mov + nop . Use the general form instead of the short form (no ModR/M) of instructions like push reg or mov reg,imm . e.g. use 2-byte push r/m64 for push rbx . Or use an equivalent instruction that is longer, like add dst, 1 instead of inc dst , in cases where there are no perf downsides to inc so you were already using inc . Use SIB byte . You can get NASM to do that by using a single register as an index, like mov eax, [nosplit rbx*1] ( see also ), but that hurts the load-use latency vs. simply encoding mov eax, [rbx] with a SIB byte. Indexed addressing modes have other downsides on SnB-family, like un-lamination and not using port7 for stores . So it's best to just encode base=rbx + disp0/8/32=0 using ModR/M + SIB with no index reg . (The SIB encoding for "no index" is the encoding that would otherwise mean idx=RSP). [rsp + x] addressing modes require a SIB already (base=RSP is the escape code that means there's a SIB), and that appears all the time in compiler-generated code. So there's very good reason to expect this to be fully efficient to decode and execute (even for base registers other than RSP) now and in the future. NASM syntax can't express this, so you'd have to encode manually. GNU gas Intel syntax from objdump -d says 8b 04 23 mov eax,DWORD PTR [rbx+riz*1] for Agner Fog's example 10.20. ( riz is a fictional index-zero notation that means there's a SIB with no index). I haven't tested if GAS accepts that as input. Use an imm32 and/or disp32 form of an instruction that only needed imm8 or disp0/disp32 . Agner Fog's testing of Sandybridge's uop cache ( microarch guide table 9.1 ) indicates that the actual value of an immediate / displacement is what matters, not the number of bytes used in the instruction encoding. I don't have any info on Ryzen's uop cache. So NASM imul eax, [dword 4 + rdi], strict dword 13 (10 bytes: opcode + modrm + disp32 + imm32) would use the 32small, 32small category and take 1 entry in the uop cache, unlike if either the immediate or disp32 actually had more than 16 significant bits. (Then it would take 2 entries, and loading it from the uop cache would take an extra cycle.) According to Agner's table, 8/16/32small are always equivalent for SnB. And addressing modes with a register are the same whether there's no displacement at all, or whether it's 32small, so mov dword [dword 0 + rdi], 123456 takes 2 entries, just like mov dword [rdi], 123456789 . I hadn't realized [rdi] + full imm32 took 2 entries, but apparently that' is the case on SnB. Use jmp / jcc rel32 instead of rel8 . Ideally try to expand instructions in places that don't require longer jump encodings outside the region you're expanding. Pad after jump targets for earlier forward jumps, pad before jump targets for later backward jumps, if they're close to needing a rel32 somewhere else. i.e. try to avoid padding between a branch and its target, unless you want that branch to use a rel32 anyway. You might be tempted to encode mov eax, [symbol] as 6-byte a32 mov eax, [abs symbol] in 64-bit code, using an address-size prefix to use a 32-bit absolute address. But this does cause a Length-Changing-Prefix stall when it decodes on Intel CPUs. Fortunately, none of NASM/YASM / gas / clang do this code-size optimization by default if you don't explicitly specify a 32-bit address-size, instead using 7-byte mov r32, r/m32 with a ModR/M+SIB+disp32 absolute addressing mode for mov eax, [abs symbol] . In 64-bit position-dependent code, absolute addressing is a cheap way to use 1 extra byte vs. RIP-relative . But note that 32-bit absolute + immediate takes 2 cycles to fetch from uop cache, unlike RIP-relative + imm8/16/32 which takes only 1 cycle even though it still uses 2 entries for the instruction. (e.g. for a mov -store or a cmp ). So cmp [abs symbol], 123 is slower to fetch from the uop cache than cmp [rel symbol], 123 , even though both take 2 entries each. Without an immediate, there's no extra cost for Note that PIE executables allow ASLR even for the executable, and are the default in many Linux distro , so if you can keep your code PIC without any perf downsides, then that's preferable. Use a REX prefix when you don't need one, e.g. db 0x40 / add eax, ecx . It's not in general safe to add prefixes like rep that current CPUs ignore, because they might mean something else in future ISA extensions. Repeating the same prefix is sometimes possible (not with REX, though). For example, db 0x66, 0x66 / add ax, bx gives the instruction 3 operand-size prefixes, which I think is always strictly equivalent to one copy of the prefix. Up to 3 prefixes is the limit for efficient decoding on some CPUs. But this only works if you have a prefix you can use in the first place; you usually aren't using 16-bit operand-size, and generally don't want 32-bit address-size (although it's safe for accessing static data in position-dependent code). A ds or ss prefix on an instruction that accesses memory is a no-op , and probably doesn't cause any slowdown on any current CPUs. (@prl suggested this in comments). In fact, Agner Fog's microarch guide uses a ds prefix on a movq[esi+ecx],mm0 in Example 7.1. Arranging IFETCH blocks to tune a loop for PII/PIII (no loop buffer or uop cache), speeding it up from 3 iterations per clock to 2. Some CPUs (like AMD) decode slowly when instructions have more than 3 prefixes. On some CPUs, this includes the mandatory prefixes in SSE2 and especially SSSE3 / SSE4.1 instructions. In Silvermont, even the 0F escape byte counts. AVX instructions can use a 2 or 3-byte VEX prefix . Some instructions require a 3-byte VEX prefix (2nd source is x/ymm8-15, or mandatory prefixes for SSSE3 or later). But an instruction that could have used a 2-byte prefix can always be encoded with a 3-byte VEX. NASM or GAS {vex3} vxorps xmm0,xmm0 . If AVX512 is available, you can use 4-byte EVEX as well. Use 64-bit operand-size for mov even when you don't need it , for example mov rax, strict dword 1 forces the 7-byte sign-extended-imm32 encoding in NASM, which would normally optimize it to 5-byte mov eax, 1 . mov eax, 1 ; 5 bytes to encode (B8 imm32)mov rax, strict dword 1 ; 7 bytes: REX mov r/m64, sign-extended-imm32.mov rax, strict qword 1 ; 10 bytes to encode (REX B8 imm64). movabs mnemonic for AT&T. You could even use mov reg, 0 instead of xor reg,reg . mov r64, imm64 fits efficiently in the uop cache when the constant is actually small (fits in 32-bit sign extended.) 1 uop-cache entry, and load-time = 1, the same as for mov r32, imm32 . Decoding a giant instruction means there's probably not room in a 16-byte decode block for 3 other instructions to decode in the same cycle, unless they're all 2-byte. Possibly lengthening multiple other instructions slightly can be better than having one long instruction. Decode penalties for extra prefixes: P5: prefixes prevent pairing, except for address/operand-size on PMMX only. PPro to PIII: There is always a penalty if an instruction has more than one prefix. This penalty is usually one clock per extra prefix. (Agner's microarch guide, end of section 6.3) Silvermont: it's probably the tightest constraint on which prefixes you can use, if you care about it. Decode stalls on more than 3 prefixes, counting mandatory prefixes + 0F escape byte. SSSE3 and SSE4 instructions already have 3 prefixes so even a REX makes them slow to decode. some AMD: maybe a 3-prefix limit, not including escape bytes, and maybe not including mandatory prefixes for SSE instructions. ... TODO: finish this section. Until then, consult Agner Fog's microarch guide. After hand-encoding stuff, always disassemble your binary to make sure you got it right . It's unfortunate that NASM and other assemblers don't have better support for choosing cheap padding over a region of instructions to reach a given alignment boundary. Assembler syntax NASM has some encoding override syntax : {vex3} and {evex} prefixes, NOSPLIT , and strict byte / dword , and forcing disp8/disp32 inside addressing modes. Note that [rdi + byte 0] isn't allowed, the byte keyword has to come first. [byte rdi + 0] is allowed, but I think that looks weird. Listing from nasm -l/dev/stdout -felf64 padding.asm line addr machine-code bytes source line num 4 00000000 0F57C0 xorps xmm0,xmm0 ; SSE1 *ps instructions are 1-byte shorter 5 00000003 660FEFC0 pxor xmm0,xmm0 6 7 00000007 C5F058DA vaddps xmm3, xmm1,xmm2 8 0000000B C4E17058DA {vex3} vaddps xmm3, xmm1,xmm2 9 00000010 62F1740858DA {evex} vaddps xmm3, xmm1,xmm210 11 12 00000016 FFC0 inc eax13 00000018 83C001 add eax, 114 0000001B 4883C001 add rax, 115 0000001F 678D4001 lea eax, [eax+1] ; runs on fewer ports and doesn't set flags16 00000023 67488D4001 lea rax, [eax+1] ; address-size and REX.W17 00000028 0501000000 add eax, strict dword 1 ; using the EAX-only encoding with no ModR/M 18 0000002D 81C001000000 db 0x81, 0xC0, 1,0,0,0 ; add eax,0x1 using the ModR/M imm32 encoding19 00000033 81C101000000 add ecx, strict dword 1 ; non-eax must use the ModR/M encoding20 00000039 4881C101000000 add rcx, strict qword 1 ; YASM requires strict dword for the immediate, because it's still 32b21 00000040 67488D8001000000 lea rax, [dword eax+1]22 23 24 00000048 8B07 mov eax, [rdi]25 0000004A 8B4700 mov eax, [byte 0 + rdi]26 0000004D 3E8B4700 mov eax, [ds: byte 0 + rdi]26 ****************** warning: ds segment base generated, but will be ignored in 64-bit mode27 00000051 8B8700000000 mov eax, [dword 0 + rdi]28 00000057 8B043D00000000 mov eax, [NOSPLIT dword 0 + rdi*1] ; 1c extra latency on SnB-family for non-simple addressing mode GAS has encoding-override pseudo-prefixes {vex3} , {evex} , {disp8} , and {disp32} These replace the now-deprecated .s , .d8 and .d32 suffixes . GAS doesn't have an override to immediate size, only displacements. GAS does let you add an explicit ds prefix, with ds mov src,dst gcc -g -c padding.S && objdump -drwC padding.o -S , with hand-editting: # no CPUs have separate ps vs. pd domains, so there's no penalty for mixing ps and pd loads/shuffles 0: 0f 28 07 movaps (%rdi),%xmm0 3: 66 0f 28 07 movapd (%rdi),%xmm0 7: 0f 58 c8 addps %xmm0,%xmm1 # not equivalent for SSE/AVX transitions, but sometimes safe to mix with AVX-128 a: c5 e8 58 d9 vaddps %xmm1,%xmm2, %xmm3 # default {vex2} e: c4 e1 68 58 d9 {vex3} vaddps %xmm1,%xmm2, %xmm3 13: 62 f1 6c 08 58 d9 {evex} vaddps %xmm1,%xmm2, %xmm3 19: ff c0 inc %eax 1b: 83 c0 01 add $0x1,%eax 1e: 48 83 c0 01 add $0x1,%rax 22: 67 8d 40 01 lea 1(%eax), %eax # runs on fewer ports and doesn't set flags 26: 67 48 8d 40 01 lea 1(%eax), %rax # address-size and REX # no equivalent for add eax, strict dword 1 # no-ModR/M .byte 0x81, 0xC0; .long 1 # add eax,0x1 using the ModR/M imm32 encoding 2b: 81 c0 01 00 00 00 add $0x1,%eax # manually encoded 31: 81 c1 d2 04 00 00 add $0x4d2,%ecx # large immediate, can't get GAS to encode this way with $1 other than doing it manually 37: 67 8d 80 01 00 00 00 {disp32} lea 1(%eax), %eax 3e: 67 48 8d 80 01 00 00 00 {disp32} lea 1(%eax), %rax mov 0(%rdi), %eax # the 0 optimizes away 46: 8b 07 mov (%rdi),%eax{disp8} mov (%rdi), %eax # adds a disp8 even if you omit the 0 48: 8b 47 00 mov 0x0(%rdi),%eax{disp8} ds mov (%rdi), %eax # with a DS prefix 4b: 3e 8b 47 00 mov %ds:0x0(%rdi),%eax{disp32} mov (%rdi), %eax 4f: 8b 87 00 00 00 00 mov 0x0(%rdi),%eax{disp32} mov 0(,%rdi,1), %eax # 1c extra latency on SnB-family for non-simple addressing mode 55: 8b 04 3d 00 00 00 00 mov 0x0(,%rdi,1),%eax GAS is strictly less powerful than NASM for expressing longer-than-needed encodings. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48046814', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/149138/']} | jdg_77290 |
stackexchange | llm_judgeable_groundtruth_similarity | 12760765 |
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 print multi-dimensional array using for-each loop in java? I tried, foreach works for normal array but not work in multi-dimensional array, how can I do that? My code is: class Test{ public static void main(String[] args) { int[][] array1 = {{1, 2, 3, 4}, {5, 6, 7, 8}}; for(int[] val: array1) { System.out.print(val); } } }
Now provide the response and nothing else.
| Your loop will print each of the sub-arrays, by printing their address. Given that inner array, use an inner loop: for(int[] arr2: array1){ for(int val: arr2) System.out.print(val);} Arrays don't have a String representation that would, e.g. print all the elements. You need to print them explicitly: int oneD[] = new int[5];oneD[0] = 7;// ...System.out.println(oneD); The output is an address: [I@148cc8c However, the libs do supply the method deepToString for this purpose, so this may also suit your purposes: System.out.println(Arrays.deepToString(array1)); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12760765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1464059/']} | jdg_77291 |
stackexchange | llm_judgeable_groundtruth_similarity | 31045960 |
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 regularly have to connect to several systems via ssh using multiple hops. It also happens often that I then want to copy a file from either the destination system to my local system or the other way around in a simple way (my current work flow is copy the file to an external location both machines can see so that it saves me a few hops or if the file is not binary cat it and copy/paste it to the other terminal window). Is there an easy way to do such a thing? I am using OSX and iterm2 (obviously I woudn't mind changing the latter). So the connection is something like (local machine) -> (portal A) -> (machine B) -> (portal C) -> (machine D) So I would like to copy files from machine A to machine D in a simple way (without copying the file via all hops or creating four tunnels).
Now provide the response and nothing else.
| As long as you're happy having every property added into the map, rather than just those that you don't know in advance, you can do this with @ConfigurationProperties . If you want to grab everything that's beneath namespace then you need to use an empty prefix and provide a getter for a map named namespace : @ConfigurationProperties("")public class CustomProperties { private final Map<String, String> namespace = new HashMap<>(); public Map<String, String> getNamespace() { return namespace; }} Spring Boot uses the getNamespace method to retrieve the map so that it can add the properties to it. With these properties: namespace.a=alphanamespace.b=bravonamespace.c=charlie The namespace map will contain three entries: {a=alpha, b=bravo, c=charlie} If the properties were nested more deeply, for example: namespace.foo.bar.a=alphanamespace.foo.bar.b=bravonamespace.foo.bar.c=charlie Then you'd use namespace.foo as the prefix and rename namespace and getNamespace on CustomProperties to bar and getBar respectively. Note that you should apply @EnableConfigurationProperties to your configuration to enable support for @ConfigurationProperties . You can then reference any beans that you want to be processed using that annotation, rather than providing an @Bean method for them, or using @Component to have them discovered by component scanning: @SpringBootApplication@EnableConfigurationProperties(CustomProperties.class)public class YourApplication { // …} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/31045960', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1045606/']} | jdg_77292 |
stackexchange | llm_judgeable_groundtruth_similarity | 8758 |
Below is a question asked on the forum arduino.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I use the interrupt function to fill an array with values received from digitalRead() . void setup() { Serial.begin(115200); attachInterrupt(0, test_func, CHANGE);}void test_func() { if (digitalRead(pin) == HIGH) { test_array[x] = 1; } else if(digitalRead(pin) == LOW) { test_array[x] = 0; } x = x + 1;} That problem is that when I print test_array there are values like: 111 or 000 . As I understand it, if I use the CHANGE option in the attachInterrupt() function, then the data sequence should always be 0101010101 without repeating. The data changes quite fast since it comes from a radio module.
Now provide the response and nothing else.
| As a sort of prologue to this overly long answer... This question got me deeply captivated with the problem of interruptlatency, to the point of losing sleep in counting cycles instead ofsheep. I am writing this response more for sharing my findingsthan for just answering the question: most of this material may actuallynot be at a level suitable for a proper answer. I hope it will beuseful, however, for readers that land here in search of solutions forlatency problems. The first few sections are expected to be useful to awide audience, including the original poster. Then, it gets hairy alongthe way. Clayton Mills already explained in his answer that there is some latencyin responding to interrupts. Here I will focus on quantifying thelatency (which is huge when using the Arduino libraries), and on themeans to minimize it. Most of what follows is specific to the hardwareof the Arduino Uno and similar boards. Minimizing the interrupt latency on the Arduino (or how to get from 99 down to 5 cycles) I will use the original question as a working example, and restate theproblem in terms of interrupt latency. We have some external event thattriggers an interrupt (here: INT0 on pin change). We need to take someaction when the interrupt is triggered (here: read a digital input). Theproblem is: there is some delay between the interrupt being triggeredand our taking the appropriate action. We call this delay " interruptlatency ". A long latency is detrimental in many situations. In thisparticular example, the input signal may change during the delay, inwhich case we get a faulty reading. There is nothing we can do to avoidthe delay: it is intrinsic to the way interrupts work. We can, however,try to make it as short as possible, which should hopefully minimize thebad consequences. The first obvious thing we can do is take the time-critical action,inside the interrupt handler, as soon as possible. This means calling digitalRead() once (and only once) at the very beginning of thehandler. Here is the zeroth version of the program upon which we willbuild: #define INT_NUMBER 0#define PIN_NUMBER 2 // interrupt 0 is on pin 2#define MAX_COUNT 200volatile uint8_t count_edges; // count of signal edgesvolatile uint8_t count_high; // count of high levels/* Interrupt handler. */void read_pin(){ int pin_state = digitalRead(PIN_NUMBER); // do this first! if (count_edges >= MAX_COUNT) return; // we are done count_edges++; if (pin_state == HIGH) count_high++;}void setup(){ Serial.begin(9600); attachInterrupt(INT_NUMBER, read_pin, CHANGE);}void loop(){ /* Wait for the interrupt handler to count MAX_COUNT edges. */ while (count_edges < MAX_COUNT) { /* wait */ } /* Report result. */ Serial.print("Counted "); Serial.print(count_high); Serial.print(" HIGH levels for "); Serial.print(count_edges); Serial.println(" edges"); /* Count again. */ count_high = 0; count_edges = 0; // do this last to avoid race condition} I tested this program, and the subsequent versions, by sending it trainsof pulses of varying widths. There is enough spacing between the pulsesto ensure that no edge is missed: even if the falling edge is receivedbefore the previous interrupt is done, the second interrupt request willbe put on hold and eventually serviced. If a pulse is shorter than theinterrupt latency, the program reads 0 on both edges. The reportednumber of HIGH levels is then the percentage of correctly read pulses. What happens when the interrupt is triggered? Before trying to improve the code above, we will take a look at theevents that unfold right after the interrupt is triggered. The hardwarepart of the story is told by the Atmel documentation. The software part,by disassembling the binary. Most of the time, the incoming interrupt is serviced right away. It mayhappen, however, that the MCU (meaning "microcontroller") is in themiddle of some time-critical task, where interrupt servicing isdisabled. This is typically the case when it is already servicinganother interrupt. When this happens, the incoming interrupt request isput on hold and serviced only when that time-critical section is done.This situation is hard to avoid completely, because there are quite afew of those critical sections in the Arduino core library (which I willcall " libcore " in the following). Fortunately, these sections areshort and run only every so often. Thus, most of the time, our interruptrequest will be serviced right away. In the following, I will assumethat we do not care about those few instances when this is not the case. Then, our request is serviced immediately. This still involves a lot ofstuff that can take quite a while. First, there is a hardwired sequence.The MCU will finish executing the current instruction. Fortunately, mostinstructions are single-cycle, but some can take up to four cycles.Then, the MCU clears an internal flag that disables further servicing ofinterrupts. This is intended to prevent nested interrupts. Then, the PCis saved into the stack. The stack is an area of RAM reserved for thiskind of temporary storage. The PC (meaning " Program Counter ") is aninternal register holding the address of the next instruction the MCU isabout to execute. This is what allows the MCU to know what to do next,and saving it is essential because it will have to be restored in orderfor the main program to resume from where it was interrupted. The PC isthen loaded with a hardwired address specific to the request received,and this is the end of the hardwired sequence, the rest beingsoftware-controlled. The MCU now executes the instruction from that hardwired address. Thisinstruction is called an " interrupt vector ", and is generally a "jump"instruction that will bring us to a special routine called an ISR(" Interrupt Service Routine "). In this case, the ISR is called"__vector_1", a.k.a. "INT0_vect", which is a misnomer because it isan ISR, not a vector. This particular ISR comes from libcore. Like anyISR, it starts with a prologue that saves a bunch of internal CPUregisters on the stack. This will allow it to use those registers and,when it is done, restore them to their previous values in order not todisturb the main program. Then, it will look for the interrupt handlerthat was registered with attachInterrupt() , and it will call thathandler, which is our read_pin() function above. Our function willthen call digitalRead() from libcore. digitalRead() will look intosome tables in order to map the Arduino port number to the hardware I/Oport it has to read and the associated bit number to test. It will alsocheck whether there is a PWM channel on that pin that would need to bedisabled. It will then read the I/O port... and we are done. Well, weare not really done servicing the interrupt, but the time-critical task(reading the I/O port) is done, and it is all that matters when we arelooking at latency. Here is a short summary of all the above, together with the associateddelays in CPU cycles: hardwired sequence: finish current instruction, prevent nestedinterrupts, save PC, load address of vector (≥ 4 cycles) execute interrupt vector: jump to ISR (3 cycles) ISR prologue: save registers (32 cycles) ISR main body: locate and call user-registered function (13 cycles) read_pin: call digitalRead (5 cycles) digitalRead: find the relevant port and bit to test (41 cycles) digitalRead: read the I/O port (1 cycle) We will assume the best case scenario, with 4 cycles for thehardwired sequence. This gives us a total latency of 99 cycles, orabout 6.2 µs with a 16 MHz clock. In the following, I willexplore some tricks that can be used to lower this latency. They comeroughly in increasing order of complexity, but they all need us tosomehow dig into the internals of the MCU. Use direct port access The obvious first target for shortening the latency is digitalRead() .This function provides a nice abstraction to the MCU hardware, but it istoo inefficient for time-critical work. Getting rid of this one isactually trivial: we just have to replace it with digitalReadFast() ,from the digitalwritefast library. This cuts the latency almost by half at the cost of a smalldownload! Well, that was too easy to be any fun, I will rather show you how to doit the hard way. The purpose is to get us started into low-level stuff.The method is called " direct port access " and is nicely documented onthe Arduino reference at the page on PortRegisters . At thispoint, it is a good idea to download and take a look at the ATmega328Pdatasheet .This 650-page document may seem somewhat daunting at first look. It is,however, well organised into sections specific to each of the MCUperipherals and features. And we only need to check the sectionsrelevant to what we are doing. In this case, it is the section named I/O ports . Here is a summary of what we learn from those readings: The Arduino pin 2 is actually called PD2 (i.e. port D, bit 2) on theAVR chip. We get the whole port D at once by reading a special MCU register called"PIND". We then check bit number 2 by doing a bitwise logical and (the C ‘&’operator) with 1 << 2 . So, here is our modified interrupt handler: #define PIN_REG PIND // interrupt 0 is on AVR pin PD2#define PIN_BIT 2/* Interrupt handler. */void read_pin(){ uint8_t sampled_pin = PIN_REG; // do this first! if (count_edges >= MAX_COUNT) return; // we are done count_edges++; if (sampled_pin & (1 << PIN_BIT)) count_high++;} Now, our handler will read the I/O register as soon as it is called. Thelatency is 53 CPU cycles. This simple trick saved us 46 cycles! Write your own ISR The next target for cycle-trimming is the INT0_vect ISR. This ISR isneeded for providing the functionality of attachInterrupt() : we canchange interrupt handlers at any time during program execution. However,although nice to have, this is not really useful for our purpose. Thus,instead of having the libcore's ISR locate and call our interrupthandler, we will save a few cycles by replacing the ISR by ourhandler. This is not as hard as it sounds. ISRs can be written like normalfunctions, we just have to be aware of their specific names, and definethem using a special ISR() macro from avr-libc. At this point it wouldbe good to have a look at the avr-libc's documentation oninterrupts ,and at the datasheet section named External Interrupts . Here is theshort summary: We have to write a bit in a special hardware register called EICRA( External Interrupt Control Register A ) in order to configure theinterrupt to be triggered on any change of the pin value. This will bedone in setup() . We have to write a bit in another hardware register called EIMSK( External Interrupt MaSK register ) in order to enable the INT0interrupt. This will also be done in setup() . We have to define the ISR with the syntax ISR(INT0_vect) { ... } . Here is the code for the ISR and setup() , everything else isunchanged: /* Interrupt service routine for INT0. */ISR(INT0_vect){ uint8_t sampled_pin = PIN_REG; // do this first! if (count_edges >= MAX_COUNT) return; // we are done count_edges++; if (sampled_pin & (1 << PIN_BIT)) count_high++;}void setup(){ Serial.begin(9600); EICRA = 1 << ISC00; // sense any change on the INT0 pin EIMSK = 1 << INT0; // enable INT0 interrupt} This comes with a free bonus: since this ISR is simpler than the one itreplaces, it needs less registers to do its job, then theregister-saving prologue is shorter. Now we are down to a latency of 20cycles. Not bad considering that we started close to 100! At this point I would say we are done. Mission accomplished. Whatfollows is only for those who are not afraid of getting their handsdirty with some AVR assembly. Otherwise you can stop reading here, andthank-you for getting so far. Write a naked ISR Still here? Good! For proceeding further, it would be helpful to have atleast some very basic idea of how assembly works, and to take a look atthe Inline AssemblerCookbook from the avr-libc documentation. At this point, our interrupt entrysequence looks like this: hardwired sequence (4 cycles) interrupt vector: jump to ISR (3 cycles) ISR prologue: save regs (12 cycles) first thing in the ISR body: read the IO port (1 cycle) If we want to do better, we have to move the reading of the port intothe prologue. The idea is the following: reading the PIND register willclobber one CPU register, thus we need to save at least one registerbefore doing that, but the other registers can wait. We then need towrite a custom prologue that reads the I/O port right after saving thefirst register. You have already seen in the avr-libc interruptdocumentation (you have read it, right?) that an ISR can be made naked , in which case the compiler will emit no prologue or epilogue,allowing us to write our own custom version. The problem with this approach is that we will probably end up writingthe whole ISR in assembly. Not a big deal, but I would rather have thecompiler write those boring prologues and epilogues for me. So, here isthe dirty trick: we will split the ISR in two parts: the first part will be a short assembly fragment that will save a single register to the stack read PIND into that register store that value into a global variable restore the register from the stack jump to the second part the second part will be regular C code with compiler-generatedprologue and epilogue Our previous INT0 ISR is then replaced by this: volatile uint8_t sampled_pin; // this is now a global variable/* Interrupt service routine for INT0. */ISR(INT0_vect, ISR_NAKED){ asm volatile( " push r0 \n" // save register r0 " in r0, %[pin] \n" // read PIND into r0 " sts sampled_pin, r0 \n" // store r0 in a global " pop r0 \n" // restore previous r0 " rjmp INT0_vect_part_2 \n" // go to part 2 :: [pin] "I" (_SFR_IO_ADDR(PIND)));}ISR(INT0_vect_part_2){ if (count_edges >= MAX_COUNT) return; // we are done count_edges++; if (sampled_pin & (1 << PIN_BIT)) count_high++;} Here we are using the ISR() macro to have the compiler instrument INT0_vect_part_2 with the required prologue and epilogue. The compilerwill complain that "‘INT0_vect_part_2’ appears to be a misspelledsignal handler", but the warning can be safely ignored. Now the ISR hasa single 2-cycle instruction before the actual port read, and the totallatency is only 10 cycles. Use the GPIOR0 register What if we could have a register reserved for this specific job? Then,we would not need save anything before reading the port. We can actuallyask the compiler to bind a global variable to aregister .This, however, would require us to recompile the whole Arduino core andlibc in order to make sure the register is always reserved. Not reallyconvenient. On the other hand, the ATmega328P happens to have threeregisters that are not used by the compiler nor any library, and areavailable for storing whatever we want. They are called GPIOR0, GPIOR1and GPIOR2 ( General Purpose I/O Registers ). Although they are mappedin the I/O address space of the MCU, these are actually not I/Oregisters: they are just plain memory, like three bytes of RAM thatsomehow got lost in a bus and ended up in the wrong address space. Theseare not as capable as the internal CPU registers, and we cannot copyPIND into one of these with the in instruction. GPIOR0 is interesting,though, in that it is bit-addressable , just like PIND. This will allowus to transfer the information without clobbering any internal CPUregister. Here is the trick: we will make sure that GPIOR0 is initially zero (itis actually cleared by hardware at boot time), then we will use the sbic (Skip next instruction if some Bit in some I/o register is Clear)and the sbi (Set to 1 some Bit in some I/o register) instructions asfollows: sbic PIND, 2 ; skip the following if bit 2 of PIND is clearsbi GPIOR0, 0 ; set to 1 bit 0 of GPIOR0 This way, GPIOR0 will end up being 0 or 1 depending on the bit we wantedto read from PIND. The sbic instruction takes 1 or 2 cycles to executedepending on whether the condition is false or true. Obviously, the PINDbit is accessed on the first cycle. In this new version of the code, theglobal variable sampled_pin is not useful anymore, since it isbasically replaced by GPIOR0: /* Interrupt service routine for INT0. */ISR(INT0_vect, ISR_NAKED){ asm volatile( " sbic %[pin], %[bit] \n" " sbi %[gpio], 0 \n" " rjmp INT0_vect_part_2 \n" :: [pin] "I" (_SFR_IO_ADDR(PIND)), [bit] "I" (PIN_BIT), [gpio] "I" (_SFR_IO_ADDR(GPIOR0)));}ISR(INT0_vect_part_2){ if (count_edges < MAX_COUNT) { count_edges++; if (GPIOR0) count_high++; } GPIOR0 = 0;} It should be noted that GPIOR0 has to always be reset in the ISR. Now, the sampling of the PIND I/O register is the very first thing doneinside the ISR. Total latency is 8 cycles. This is about the best we cando before getting stained with terribly sinful kludges. This is again agood opportunity to stop reading... Put the time-critical code in the vector table For those still here, here is our current situation: hardwired sequence (4 cycles) interrupt vector: jump to ISR (3 cycles) ISR body: read the IO port (on 1st cycle) There is obviously little room for improvement. The only way we couldshorten the latency at this point is by replacing the interrupt vectoritself by our code. Be warned that this should be immensely distastefulto anyone who values clean software design. But it is possible, and Iwill show you how. The layout of the ATmega328P vector table can be found in the datasheet,section Interrupts , subsection Interrupt Vectors in ATmega328 andATmega328P . Or by disassembling any program for this chip. Here is howit looks like. I am using avr-gcc and avr-libc's conventions (__initis vector 0, addresses are in bytes) which are different from Atmel's. address │ instruction │ comment────────┼─────────────────┼────────────────────── 0x0000 │ jmp __init │ reset vector 0x0004 │ jmp __vector_1 │ a.k.a. INT0_vect 0x0008 │ jmp __vector_2 │ a.k.a. INT1_vect 0x000c │ jmp __vector_3 │ a.k.a. PCINT0_vect ... 0x0064 │ jmp __vector_25 │ a.k.a. SPM_READY_vect Each vector has a 4-byte slot, filled with a single jmp instruction.This is a 32-bit instruction, unlike most AVR instructions which are16-bit. But a 32-bit slot is too small to hold the first part of ourISR: we can fit the sbic and sbi instructions, but not the rjmp .If we do that, the vector table ends up looking like this: address │ instruction │ comment────────┼─────────────────┼────────────────────── 0x0000 │ jmp __init │ reset vector 0x0004 │ sbic PIND, 2 │ the first part... 0x0006 │ sbi GPIOR0, 0 │ ...of our ISR 0x0008 │ jmp __vector_2 │ a.k.a. INT1_vect 0x000c │ jmp __vector_3 │ a.k.a. PCINT0_vect ... 0x0064 │ jmp __vector_25 │ a.k.a. SPM_READY_vect When INT0 fires, PIND will be read, the relevant bit will be copied intoGPIOR0, and then the execution will fall through to the next vector.Then, the ISR for INT1 will be called, instead of the ISR for INT0. Thisis creepy, but since we are not using INT1 anyway, we will just "hijack"its vector for servicing INT0. Now, we just have to write our own custom vector table to override thedefault one. It turns out it is not so easy. The default vector table isprovided by the avr-libc distribution, in an object file calledcrtm328p.o that is automatically linked with any program we build.Unlike library code, object-file code is not meant to be overridden:trying to do that will give a linker error about the table being definedtwice. This means we have to replace the whole crtm328p.o with ourcustom version. One option is to download the full avr-libc sourcecode , do ourcustom modifications in gcrt1.S ,then build this as a custom libc. Here I went for a lighter, alternative approach. I wrote a customcrt.S, which is a simplified version of the original from avr-libc. Itlacks a few rarely used features, like the ability to define a "catchall" ISR, or to be able to terminate the program (i.e. freeze theArduino) by calling exit() . Here is the code. I trimmed the repetitivepart of the vector table in order to minimize scrolling: #include <avr/io.h>.weak __heap_end.set __heap_end, 0.macro vector name .weak \name .set \name, __vectors jmp \name.endm.section .vectors__vectors: jmp __init sbic _SFR_IO_ADDR(PIND), 2 ; these 2 lines... sbi _SFR_IO_ADDR(GPIOR0), 0 ; ...replace vector_1 vector __vector_2 vector __vector_3 [...and so forth until...] vector __vector_25.section .init2__init: clr r1 out _SFR_IO_ADDR(SREG), r1 ldi r28, lo8(RAMEND) ldi r29, hi8(RAMEND) out _SFR_IO_ADDR(SPL), r28 out _SFR_IO_ADDR(SPH), r29.section .init9 jmp main It can be compiled with the following command line: avr-gcc -c -mmcu=atmega328p silly-crt.S The sketch is identical to the previous one except that there is noINT0_vect, and INT0_vect_part_2 is replaced by INT1_vect: /* Interrupt service routine for INT1 hijacked to service INT0. */ISR(INT1_vect){ if (count_edges < MAX_COUNT) { count_edges++; if (GPIOR0) count_high++; } GPIOR0 = 0;} To compile the sketch, we need a custom compile command. If you havefollowed so far, you probably know how to compile from the command line.You have to explicitly request silly-crt.o to be linked to your program,and add the -nostartfiles option to avoid linking in the originalcrtm328p.o. Now, the reading of the I/O port is the very first instruction executedafter the interrupt triggers. I tested this version by sending it shortpulses from another Arduino, and it can catch (although not reliably)the high level of pulses as short as 5 cycles. There is nothing more wecan do to shorten the interrupt latency on this hardware. | {} | {'log_upvote_score': 5, 'links': ['https://arduino.stackexchange.com/questions/8758', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/7440/']} | jdg_77293 |
stackexchange | llm_judgeable_groundtruth_similarity | 4124268 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
$$\lim_{x\to0}2^{\cot x}$$ So it turns out that the limit does not exist but here's the thing. I can't compute this limit $$\lim_{x\to0}{\cot x}$$ this is all I did $$\lim_{x\to0}{\cot x}=\lim_{x\to0}\frac{\cos x}{\sin x}=\lim_{x\to0}\frac{x\cos x }{x\sin x}=\lim_{x\to0}\frac{\cos x}{x}$$ then nothing comes to mind. I feel like this is a really easy problem but I've been trying to solve thins for over an hour and I'm stuck. Could you please help me? Thanks in advance.
Now provide the response and nothing else.
| Since $\lim_{x\to0^+}\frac1{\sin x}=\infty$ , $\lim_{x\to0^-}\frac1{\sin x}=-\infty$ , and $\lim_{x\to0}\cos x=1$ , you have $$\lim_{x\to0^+}\cot x=\infty\quad\text{and}\quad\lim_{x\to0^-}\cot x=-\infty.$$ So $$\lim_{x\to0^+}2^{\cot x}=\infty\quad\text{and}\quad\lim_{x\to0^-}2^{\cot x}=0.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4124268', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/864508/']} | jdg_77294 |
stackexchange | llm_judgeable_groundtruth_similarity | 9537824 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm using a select method on a dataset to retreive the results that match my condition: foreach (DataRow dr in dsPone2.Tables["tt-pone"].Select(strWhereCondition)){ dsPone.Tables["tt-pone"].ImportRow(dr);} How do I change the strWhereCondition from strWhereCondition += " AND poneid = 0 and aoneid = 0 and tranid = 0"; To where tranid is NOT 0? Do I use <> or != ?
Now provide the response and nothing else.
| As is so often the case, consulting the documentation is the way forward. DataTable.Select(string) redirects to DataColumn.Expression to document what's allowed in a filter expression - and the "Operators" list shows <> but not != . Personally I would try to avoid string-based filtering and use LINQ to DataSet instead, but of course that requires .NET 3.5 or higher. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9537824', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/521518/']} | jdg_77295 |
stackexchange | llm_judgeable_groundtruth_similarity | 2204647 |
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 select controls on a HTML page and using Jquery toset change event. But the event fires on the page load and does not fire whenI try to change values in the select controls. Any ideas why? $(function() { $('select[id^=Start], select[id^=Finish], select[id^=Lunch]').change(CalculateHours($(this)));});
Now provide the response and nothing else.
| Your syntax is wrong. By writing change(CalculateHours($(this)) , you are calling the CalculateHours function and passing its return value to jQuery's change method as if it were a function. You would only write this if your function returned another function and you wanted to addd the returned function as an event handler. You need to write .change(function() { CalculateHours($(this)); }) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2204647', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/40568/']} | jdg_77296 |
stackexchange | llm_judgeable_groundtruth_similarity | 21085446 |
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 happened to come across the below code snippet in a video on C++11, where the author uses auto main()->int I didn't understand this. I tried to compile in g++ using -std=c++11 and it works.Can somebody explain to me what is going on here? I tried to search using "auto main()->int" but didn't find any help.
Now provide the response and nothing else.
| C++11 introduced a notation for trailing return types : If a function declaration is introduced with auto , the return type will be specified after the parameters and a -> sequence. That is, all that does is to declare main() to return int . The significance of trailing return types is primarily for function template where it is now possible to use parameters to the function together with decltype() to determine the return type. For example: template <typename M, typename N>auto multiply(M const& m, N const& n) -> decltype(m * n); This declares the function multiply() to return the type produced by m * n . Putting the use of decltype() in front of multiply() would be invalid because m and n are not, yet, declared. Although it is primarily useful for function template, the same notation can also be used for other function. With C++14 the trailing return type can even be omitted when the function is introduced with auto under some conditions. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/21085446', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2711579/']} | jdg_77297 |
stackexchange | llm_judgeable_groundtruth_similarity | 50526880 |
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 to com.android.support.constraint:constraint-layout:1.1.0 The constraint layout crashes saying: All children of constraint layout should have ids to use constraintset I have set ids to all views even then it's crashing. java.lang.RuntimeException: All children of ConstraintLayout must have ids to use ConstraintSet at android.support.constraint.ConstraintSet.clone(ConstraintSet.java:687) at com.zoho.notebook.views.SettingsViewNavBar.showNoteSettingsView(SettingsViewNavBar.java:594) at com.zoho.notebook.views.SettingsViewNavBar.onClick(SettingsViewNavBar.java:303)
Now provide the response and nothing else.
| I had the same bug in my code. I had ids for all the views in xml, but I was manually adding a view to the constraint layout(a Tooltip view) with constraintParent.addView(childView) and while the dynamically added view is still on the parent if the constraint layout is redrawn (app goes to bg and resumed) this exception was getting triggered. I fixed it by generating a view id for the dynamic view like this CustomViewChildView childView = new CustomViewChildView()childView.setId(View.generateViewId()); and then adding it to the constraint layout. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/50526880', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7664651/']} | jdg_77298 |
stackexchange | llm_judgeable_groundtruth_similarity | 15789168 |
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 this object to rotate around its center rather than the top left corner.The code looks like this: switch (event.keyCode) { case 37: car.rotation = -90; car.x -= 5; break; So when i press the left key, the car turns left but as it is now it jumps up a bit because its rotating around the top corner. Thanks
Now provide the response and nothing else.
| The following will rotate around center : public function rotateAroundCenter(object:DisplayObject, angleDegrees:Number):void { if (object.rotation == angleDegrees) { return; } var matrix:Matrix = object.transform.matrix; var rect:Rectangle = object.getBounds(object.parent); var centerX = rect.left + (rect.width / 2); var centerY = rect.top + (rect.height / 2); matrix.translate(-centerX, -centerY); matrix.rotate((angleDegrees / 180) * Math.PI); matrix.translate(centerX, centerY); object.transform.matrix = matrix; object.rotation = Math.round(object.rotation);} It translates the center of the object to 0,0 then rotate it and then translate it back. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15789168', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2240525/']} | jdg_77299 |
stackexchange | llm_judgeable_groundtruth_similarity | 8576902 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Aside from writing the wrong query and not having permissions to access a table, when mysql_query returns false? Are there any other cases?
Now provide the response and nothing else.
| See the reference guide: For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error. For other type of SQL statements, INSERT, UPDATE, DELETE, DROP, etc, mysql_query() returns TRUE on success or FALSE on error. The returned result resource should be passed to mysql_fetch_array(), and other functions for dealing with result tables, to access the returned data. Use mysql_num_rows() to find out how many rows were returned for a SELECT statement or mysql_affected_rows() to find out how many rows were affected by a DELETE, INSERT, REPLACE, or UPDATE statement. mysql_query() will also fail and return FALSE if the user does not have permission to access the table(s) referenced by the query. http://php.net/manual/en/function.mysql-query.php Edit: Clarification of what those errors actually are. So we have list of things that can return false: When a MySQL statement which returns a resultset gets an error When a MySQL statement which doesn't return anything gets an error When a user does not have MySQL permission to access a table reference In my opinion the first 2 are the ones that are a bit diffuse. What are the possible errors? There are 59 different client errors you can get from MySQL. These are more system related errors which we can presume that php will handle and probably wrap into a smaller amount of abstract errors. Except for those client errors you have a set of more abstract errors which you can encounter during usage which is more related to using the actual API inside the application rather than the raw access to the MySQL server. Those are: Access denied Can't connect to [local] MySQL server Lost connection to MySQL server Client does not support authentication protocol Password Fails When Entered Interactively Host 'host_name' is blocked Too many connections Out of memory MySQL server has gone away Packet too large Communication Errors and Aborted Connections The table is full Can't create/write to file Commands out of sync Ignoring user Table 'tbl_name' doesn't exist Can't initialize character set Table corruption issues Syntax related issues Here are the references of what I just said: List of the client errors List of the common errors dealing with the API References about query related issues Table related issues Other issues related to known bugs | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8576902', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1024132/']} | jdg_77300 |
stackexchange | llm_judgeable_groundtruth_similarity | 25327107 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have this simple snippet in a WordPress widget: <h3>Kevin Smith</h3><h2>The Official Kevin Smith Website</h2> The name is changed for privacy. Is there any possible way I get get these to appear on the same line? I'm a CSS dummy, but I've tried doing things like: <div display:inline><h3>Kevin Smith</h3><h2>The Official Kevin Smith Website</h2></div> But this doesn't work for reasons that are most likely obvious to CSS gurus. Any guidance in how I can achieve putting these on the same line would be greatly appreciated! * UPDATED SOLUTION * For anybody with similar issues, I just used this -- with the help of @antyrat and @jacefarm: <div style="display:inline">Kevin Smith</div><p style="display:inline">The Official Kevin Smith Website</p> That way, I was able to style the div differently than the p, and they're both inline -- which is precisely what I was attempting to achieve.
Now provide the response and nothing else.
| Inline styles on HTML elements are written as HTML attributes. You would use the 'style' attribute and give it a value that is wrapped in quotes. Also, you need to have a semi-colon after each CSS '[property]: [value];' pair passed into the 'style' attribute, just like you would in a standard CSS stylesheet. <div> <h3 style="display: inline;">Kevin Smith</h3> <h2 style="display: inline;">The Official Kevin Smith Website</h2> </div> Alternatively, you could assign a class to the parent 'div' element, such as 'title', and then style the 'h3' and 'h2' tags in your CSS stylesheet, like this: HTML <div class="title"> <h3>Kevin Smith</h3> <h2>The Official Kevin Smith Website</h2> </div> CSS .title h2, .title h3 { display: inline; } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25327107', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1100032/']} | jdg_77301 |
stackexchange | llm_judgeable_groundtruth_similarity | 335783 |
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have read a book called Clean Code by Robert C. Martin. In this book I've seen many methods to clean up code like writing small functions, choosing names carefully, etc. It seems by far the most interesting book about clean code I've read. However, today my boss didn't like the way I wrote code after reading this book. His arguments were Writing small functions is a pain because it forces you to move into each small function to see what the code is doing. Put everything in a main big loop even if the main loop is more than 300 lines, it is faster to read. Only write small functions if you have to duplicate code. Don't write a function with the name of the comment, put your complex line of code (3-4 lines) with a comment above; similarly you can modify the failing code directly This is against everything I've read. How do you usually write code? One main big loop, no small functions? The language I use is mainly Javascript. I really have difficulties reading now since I've deleted all my small clearly named functions and put everything in a big loop. However, my boss likes it this way. One example was: // The way I would write itif (isApplicationInProduction(headers)) { phoneNumber = headers.resourceId;} else { phoneNumber = DEV_PHONE_NUMBER;}function isApplicationInProduction(headers) { return _.has(headers, 'resourceId');}// The way he would write it// Take the right resourceId if application is in productionphoneNumber = headers.resourceId ? headers.resourceId : DEV_PHONE_NUMBER; In the book I've read for example comments are considered as failure to write clean code because they are obsolete if you write small functions and often leads to non-updated comments (you modify your code and not the comment). However what I do is delete the comment and write a function with the name of the comment. Well, I would like some advice, which way/practice is better to write clean code?
Now provide the response and nothing else.
| Taking the code examples first. You favour: if (isApplicationInProduction(headers)) { phoneNumber = headers.resourceId;} else { phoneNumber = DEV_PHONE_NUMBER;}function isApplicationInProduction(headers) { return _.has(headers, 'resourceId');} And your boss would write it as: // Take the right resourceId if application is in productionphoneNumber = headers.resourceId ? headers.resourceId : DEV_PHONE_NUMBER; In my view, both have problems. As I read your code, my immediate thought was "you can replace that if with a ternary expression". Then I read your boss' code and thought "why's he replaced your function with a comment?". I'd suggest the optimal code is between the two: phoneNumber = isApplicationInProduction(headers) ? headers.resourceId : DEV_PHONE_NUMBER;function isApplicationInProduction(headers) { return _.has(headers, 'resourceId');} That gives you the best of both worlds: a simplified test expression and the comment is replaced with testable code. Regarding your boss' views on code design though: Writing small functions is a pain because it forces you to move into each small functions to see what the code is doing. If the function is well-named, this isn't the case. isApplicationInProduction is self-evident and it should not be necessary to examine the code to see what it does. In fact the opposite is true: examining the code reveals less as to the intention than the function name does (which is why your boss has to resort to comments). Put everything in a main big loop even if the main loop is more than 300 lines, it is faster to read It may be faster to scan through, but to truly "read" the code, you need to be able to effectively execute it in your head. That's easy with small functions and is really, really hard with methods that are 100's of lines long. Write only small functions if you have to duplicate code I disagree. As your code example shows, small, well-named functions improve readability of code and should be used whenever eg you aren't interested in the "how", only the "what" of a piece of functionality. Don't write a function with the name of the comment, put your complex line of code (3-4 lines) with a comment above. Like this you can modify the failing code directly I really can't understand the reasoning behind this one, assuming it really is serious. It's the sort of thing I'd expect to see written in parody by The Expert Beginner twitter account. Comments have a fundamental flaw: they aren't compiled/interpreted and so can't be unit tested. The code gets modified and the comment gets left alone and you end up not knowing which is right. Writing self-documenting code is hard, and supplementary docs (even in the form of comments) are sometimes needed. But "Uncle Bob"'s view that comments are a coding failure holds true all too often. Get your boss to read the Clean Code book and try to resist making your code less readable just to satisfy him. Ultimately though, if you can't persuade him to change, you have to either fall in line or find a new boss that can code better. | {} | {'log_upvote_score': 9, 'links': ['https://softwareengineering.stackexchange.com/questions/335783', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/253246/']} | jdg_77302 |
stackexchange | llm_judgeable_groundtruth_similarity | 12405575 |
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 facing a very common problem: I layed out an activity and now it turns out it should display a few items within this ScrollView . The normal way to do that would be to use the existing ListAdapter , connect it to a ListView and BOOM I'd have my list of items. BUT You should not place a nested ListView in a ScrollView as it screws up the scrolling - even Android Lint complains about it. So here's my question: How do I connect a ListAdapter to a LinearLayout or something similar? I know this solution won't scale for a lot of items but my lists is very short (< 10 items) so reusage of views is not really needed. Performance wise I can live with placing all views directly into the LinearLayout . One solution I came up with would be to place my existing activity layout in the headerView section of the ListView . But this feels like abusing this mechanism so I'm looking for a cleaner solution. Ideas? UPDATE: In order to inspire the right direction I add a sample layout to show my problem: <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/news_detail_layout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:visibility="visible"> <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#FFF" > <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:paddingLeft="@dimen/news_detail_layout_side_padding" android:paddingRight="@dimen/news_detail_layout_side_padding" android:paddingTop="@dimen/news_detail_layout_vertical_padding" android:paddingBottom="@dimen/news_detail_layout_vertical_padding" > <TextView android:id="@+id/news_detail_date" android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center_horizontal" android:text="LALALA" android:textSize="@dimen/news_detail_date_height" android:textColor="@color/font_black" /> <Gallery android:id="@+id/news_detail_image" android:layout_height="wrap_content" android:layout_width="fill_parent" android:paddingTop="5dip" android:paddingBottom="5dip" /> <TextView android:id="@+id/news_detail_headline" android:layout_height="wrap_content" android:layout_width="fill_parent" android:gravity="center_horizontal" android:text="Some awesome headline" android:textSize="@dimen/news_detail_headline_height" android:textColor="@color/font_black" android:paddingTop="@dimen/news_detail_headline_paddingTop" android:paddingBottom="@dimen/news_detail_headline_paddingBottom" /> <TextView android:id="@+id/news_detail_content" android:layout_height="wrap_content" android:layout_width="fill_parent" android:text="Here comes a lot of text so the scrollview is really needed." android:textSize="@dimen/news_detail_content_height" android:textColor="@color/font_black" /> <!--- HERE I NEED THE LIST OF ITEMS PROVIDED BY THE EXISTING ADAPTER. They should be positioned at the end of the content, so making the scrollview smaller is not an option. ----> </LinearLayout> </ScrollView></LinearLayout> UPDATE 2 I changed the headline to make it easier to understand (got a downvote, doh!).
Now provide the response and nothing else.
| You probably should just manually add your items to LinearLayout : LinearLayout layout = ... // Your linear layout.ListAdapter adapter = ... // Your adapter.final int adapterCount = adapter.getCount();for (int i = 0; i < adapterCount; i++) { View item = adapter.getView(i, null, null); layout.addView(item);} EDIT : I rejected this approach when I needed to display about 200 non-trivial list items, it is very slow - Nexus 4 needed about 2 seconds to display my "list", that was unacceptable. So I turned to Flo's approach with headers. It works much faster because list views are created on demand when user scrolls, not at the time the view is created. Resume: The manual addition of views to layout is easier to code (thus potentially less moving parts and bugs), but suffers from performance problems, so if you have like 50 views or more, I advise to use the header approach. Example. Basically the activity (or fragment) layout transforms to something like this (no ScrollView needed anymore): <ListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/my_top_layout" android:layout_width="fill_parent" android:layout_height="fill_parent"/> Then in onCreateView() (I'll use an example with a fragment) you need to add a header view and then set an adapter (I assume the header resource ID is header_layout ): ListView listView = (ListView) inflater.inflate(R.layout.my_top_layout, container, false);View header = inflater.inflate(R.layout.header_layout, null);// Initialize your header here.listView.addHeaderView(header, null, false);BaseAdapter adapter = // ... Initialize your adapter.listView.setAdapter(adapter);// Just as a bonus - if you want to do something with your list items:view.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // You can just use listView instead of parent casted to ListView. if (position >= ((ListView) parent).getHeaderViewsCount()) { // Note the usage of getItemAtPosition() instead of adapter's getItem() because // the latter does not take into account the header (which has position 0). Object obj = parent.getItemAtPosition(position); // Do something with your object. } }}); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/12405575', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/409349/']} | jdg_77303 |
stackexchange | llm_judgeable_groundtruth_similarity | 39391107 |
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 investigated performance degradation and tracked it down to slow HashSets. I have structs with nullable values that are used as a primary key. For example: public struct NullableLongWrapper{ private readonly long? _value; public NullableLongWrapper(long? value) { _value = value; }} I noticed that creating a HashSet<NullableLongWrapper> is exceptionally slow. Here's an example using BenchmarkDotNet : ( Install-Package BenchmarkDotNet ) using System.Collections.Generic;using System.Linq;using BenchmarkDotNet.Attributes;using BenchmarkDotNet.Configs;using BenchmarkDotNet.Jobs;using BenchmarkDotNet.Running;public class Program{ static void Main() { BenchmarkRunner.Run<HashSets>(); }}public class Config : ManualConfig{ public Config() { Add(Job.Dry.WithWarmupCount(1).WithLaunchCount(3).WithTargetCount(20)); }}public struct NullableLongWrapper{ private readonly long? _value; public NullableLongWrapper(long? value) { _value = value; } public long? Value => _value;}public struct LongWrapper{ private readonly long _value; public LongWrapper(long value) { _value = value; } public long Value => _value;}[Config(typeof (Config))]public class HashSets{ private const int ListSize = 1000; private readonly List<long?> _nullables; private readonly List<long> _longs; private readonly List<NullableLongWrapper> _nullableWrappers; private readonly List<LongWrapper> _wrappers; public HashSets() { _nullables = Enumerable.Range(1, ListSize).Select(i => (long?) i).ToList(); _longs = Enumerable.Range(1, ListSize).Select(i => (long) i).ToList(); _nullableWrappers = Enumerable.Range(1, ListSize).Select(i => new NullableLongWrapper(i)).ToList(); _wrappers = Enumerable.Range(1, ListSize).Select(i => new LongWrapper(i)).ToList(); } [Benchmark] public void Longs() => new HashSet<long>(_longs); [Benchmark] public void NullableLongs() => new HashSet<long?>(_nullables); [Benchmark(Baseline = true)] public void Wrappers() => new HashSet<LongWrapper>(_wrappers); [Benchmark] public void NullableWrappers() => new HashSet<NullableLongWrapper>(_nullableWrappers);} Result: Method | Median | Scaled----------------- |---------------- |--------- Longs | 22.8682 us | 0.42 NullableLongs | 39.0337 us | 0.62 Wrappers | 62.8877 us | 1.00 NullableWrappers | 231,993.7278 us | 3,540.34 Using a struct with a Nullable<long> compared to a struct with a long is 3540 times slower! In my case it made the difference between 800ms and <1ms. Here is the environment information from BenchmarkDotNet: OS=Microsoft Windows NT 6.1.7601 Service Pack 1 Processor=Intel(R) Core(TM) i7-5600U CPU 2.60GHz, ProcessorCount=4 Frequency=2536269 ticks, Resolution=394.2799 ns, Timer=TSC CLR=MS.NET 4.0.30319.42000, Arch=64-bit RELEASE [RyuJIT] GC=Concurrent Workstation JitModules=clrjit-v4.6.1076.0 What is the reason performance is this poor?
Now provide the response and nothing else.
| This is happening because every one of the elements of _nullableWrappers has the same hash code returned by GetHashCode() , which is resulting in the hashing degenerating into O(N) access rather than O(1). You can verify this by printing out all the hash codes. If you modify your struct as so: public struct NullableLongWrapper{ private readonly long? _value; public NullableLongWrapper(long? value) { _value = value; } public override int GetHashCode() { return _value.GetHashCode(); } public long? Value => _value;} it works much more quickly. Now, the obvious question is WHY is the hash code of every NullableLongWrapper the same. The answer to that is discussed in this thread . However, it doesn't quite answer the question, since Hans' answer revolves around the struct having TWO fields from which to choose when computing the hash code - but in this code, there's only one field to choose from - and it's a value type (a struct ). However, the moral of this story is: Never rely on the default GetHashCode() for value types! Addendum I thought that perhaps what was happening was related to Hans' answer in the thread I linked - maybe it was taking the value of the first field (the bool) in the Nullable<T> struct), and my experiments indicate that it may be related - but it's complicated: Consider this code and its output: using System;public class Program{ static void Main() { var a = new Test {A = 0, B = 0}; var b = new Test {A = 1, B = 0}; var c = new Test {A = 0, B = 1}; var d = new Test {A = 0, B = 2}; var e = new Test {A = 0, B = 3}; Console.WriteLine(a.GetHashCode()); Console.WriteLine(b.GetHashCode()); Console.WriteLine(c.GetHashCode()); Console.WriteLine(d.GetHashCode()); Console.WriteLine(e.GetHashCode()); }}public struct Test{ public int A; public int B;}Output:346948956346948957346948957346948958346948959 Note how the second and third hash codes (for 1/0 and 0/1) are the same, but the others are all different. I find this strange because clearly changing A changes the hash code, as does changing B, but given two values X and Y, the same hash code is generated for A=X, B=Y and A=Y, B=X. (That sounds like some XOR stuff is happening behind the scenes, but that's guess.) Incidentally, this behaviour where BOTH fields can be shown to contribute to the hash code proves that the comment in the reference source for ValueType.GetHashType() is inaccurate or wrong: Action: Our algorithm for returning the hashcode is a little bit complex. We look for the first non-static field and get it's hashcode. If the type has no non-static fields, we return the hashcode of the type. We can't take the hashcode of a static member because if that member is of the same type as the original type, we'll end up in an infinite loop. If that comment was true, then four of the five hash codes in the example above would be the same, since A has the same value, 0, for all those. (That assumes A is the first field, but you get the same results if you swap the values around: Both fields clearly contribute to the hash code.) Then I tried changing the first field to be a bool: using System;public class Program{ static void Main() { var a = new Test {A = false, B = 0}; var b = new Test {A = true, B = 0}; var c = new Test {A = false, B = 1}; var d = new Test {A = false, B = 2}; var e = new Test {A = false, B = 3}; Console.WriteLine(a.GetHashCode()); Console.WriteLine(b.GetHashCode()); Console.WriteLine(c.GetHashCode()); Console.WriteLine(d.GetHashCode()); Console.WriteLine(e.GetHashCode()); }}public struct Test{ public bool A; public int B;}Output346948956346948956346948956346948956346948956 Wow! So making the first field a bool makes all the hash codes come out the same, regardless of the values of ANY of the fields! This still looks like some kind of bug to me. The bug has been fixed in .NET 4, but only for Nullable. Custom types still yield the bad behavior. source | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/39391107', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7586/']} | jdg_77304 |
stackexchange | llm_judgeable_groundtruth_similarity | 23644232 |
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 divs that expand and contract when clicked on. The Masonry library has worked great for initializing the page. The problem I am experiencing is that with the absolute positioning in place from Masonry and the directive below, when divs expand they overlap with the divs below. I need to have the divs below the expanding div move down to deal with the expansion. My sources are: http://masonry.desandro.com/ and https://github.com/passy/angular-masonry/blob/master/src/angular-masonry.js /*!* angular-masonry <%= pkg.version %>* Pascal Hartig, weluse GmbH, http://weluse.de/* License: MIT*/(function () { 'use strict';angular.module('wu.masonry', []).controller('MasonryCtrl', function controller($scope, $element, $timeout) { var bricks = {}; var schedule = []; var destroyed = false; var self = this; var timeout = null; this.preserveOrder = false; this.loadImages = true; this.scheduleMasonryOnce = function scheduleMasonryOnce() { var args = arguments; var found = schedule.filter(function filterFn(item) { return item[0] === args[0]; }).length > 0; if (!found) { this.scheduleMasonry.apply(null, arguments); } }; // Make sure it's only executed once within a reasonable time-frame in // case multiple elements are removed or added at once. this.scheduleMasonry = function scheduleMasonry() { if (timeout) { $timeout.cancel(timeout); } schedule.push([].slice.call(arguments)); timeout = $timeout(function runMasonry() { if (destroyed) { return; } schedule.forEach(function scheduleForEach(args) { $element.masonry.apply($element, args); }); schedule = []; }, 30); }; function defaultLoaded($element) { $element.addClass('loaded'); } this.appendBrick = function appendBrick(element, id) { if (destroyed) { return; } function _append() { if (Object.keys(bricks).length === 0) { $element.masonry('resize'); } if (bricks[id] === undefined) { // Keep track of added elements. bricks[id] = true; defaultLoaded(element); $element.masonry('appended', element, true); } } function _layout() { // I wanted to make this dynamic but ran into huuuge memory leaks // that I couldn't fix. If you know how to dynamically add a // callback so one could say <masonry loaded="callback($element)"> // please submit a pull request! self.scheduleMasonryOnce('layout'); } if (!self.loadImages){ _append(); _layout(); } else if (self.preserveOrder) { _append(); element.imagesLoaded(_layout); } else { element.imagesLoaded(function imagesLoaded() { _append(); _layout(); }); } }; this.removeBrick = function removeBrick(id, element) { if (destroyed) { return; } delete bricks[id]; $element.masonry('remove', element); this.scheduleMasonryOnce('layout'); }; this.destroy = function destroy() { destroyed = true; if ($element.data('masonry')) { // Gently uninitialize if still present $element.masonry('destroy'); } $scope.$emit('masonry.destroyed'); bricks = []; }; this.reload = function reload() { $element.masonry(); $scope.$emit('masonry.reloaded'); };}).directive('masonry', function masonryDirective() { return { restrict: 'AE', controller: 'MasonryCtrl', link: { pre: function preLink(scope, element, attrs, ctrl) { var attrOptions = scope.$eval(attrs.masonry || attrs.masonryOptions); var options = angular.extend({ itemSelector: attrs.itemSelector || '.masonry-brick', columnWidth: parseInt(attrs.columnWidth, 10) || attrs.columnWidth }, attrOptions || {}); element.masonry(options); var loadImages = scope.$eval(attrs.loadImages); ctrl.loadImages = loadImages !== false; var preserveOrder = scope.$eval(attrs.preserveOrder); ctrl.preserveOrder = (preserveOrder !== false && attrs.preserveOrder !== undefined); scope.$emit('masonry.created', element); scope.$on('$destroy', ctrl.destroy); } } };}).directive('masonryBrick', function masonryBrickDirective() { return { restrict: 'AC', require: '^masonry', scope: true, link: { pre: function preLink(scope, element, attrs, ctrl) { var id = scope.$id, index; ctrl.appendBrick(element, id); element.on('$destroy', function () { ctrl.removeBrick(id, element); }); scope.$on('masonry.reload', function () { ctrl.scheduleMasonryOnce('reloadItems'); ctrl.scheduleMasonryOnce('layout'); }); scope.$watch('$index', function () { if (index !== undefined && index !== scope.$index) { ctrl.scheduleMasonryOnce('reloadItems'); ctrl.scheduleMasonryOnce('layout'); } index = scope.$index; }); } } };});}());
Now provide the response and nothing else.
| NSURL supports the data:// URL-Scheme ( RFC 2397 ). This scheme allows you to build URLs in the form of data://data:MIME-Type;base64,<data> A working Cocoa example would be: NSImage* img = [NSImage imageNamed:@"img"];NSData* imgData = [img TIFFRepresentation];NSString* dataFormatString = @"data:image/png;base64,%@";NSString* dataString = [NSString stringWithFormat:dataFormatString, [imgData base64EncodedStringWithOptions:0]];NSURL* dataURL = [NSURL URLWithString:dataString]; Passing around large binary blobs with data URLs might be a bit inefficient due to the nature of base64 encoding. You could also implement a custom NSURLProtocol that specifically deals with your data.Apple has some sample code that uses a custom protocol to pass around image objects: https://developer.apple.com/library/mac/samplecode/SpecialPictureProtocol/Introduction/Intro.html#//apple_ref/doc/uid/DTS10003816 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23644232', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2113436/']} | jdg_77305 |
stackexchange | llm_judgeable_groundtruth_similarity | 22536448 |
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 searched various SO questions about adding table columns but not many on rows. Here's what I have so far: HTML <table> <thead> <tr> <th>MAX ATK</th> <th>MAX DEF</th> <th>MAX HP</th> <th>Overall</th> </tr> </thead> <tbody> <tr> <td class="combat">8170</td> <td class="combat">6504</td> <td class="combat">6050</td> <td class="total-combat"></td> </tr> <tr> <td class="combat">8500</td> <td class="combat">10200</td> <td class="combat">7650</td> <td class="total-combat"></td> </tr> <tr> <td class="combat">9185</td> <td class="combat">7515</td> <td class="combat">9185</td> <td class="total-combat"></td> </tr> </tbody></table> jQuery $(document).ready(function () { var sum = 0; $('tr').find('.combat').each(function () { var combat = $(this).text(); if (!isNaN(combat) && combat.length !== 0) { sum += parseFloat(combat); } }); $('.total-combat').html(sum); }); You can see my fiddle here . Problem: It's finding ALL occurrences of .combat and adding them up instead of only finding occurrences of .combat within the current row. So instead of: MAX ATK MAX DEF MAX HP Overall 8170 6504 6050 20724 8500 10200 7650 26350 9185 7515 9185 25885 I'm getting: MAX ATK MAX DEF MAX HP Overall 8170 6504 6050 72959 8500 10200 7650 72959 9185 7515 9185 72959 I tried using closest() thinking that would tell it to find the parent tr and only add tds within that tr, like so: $('.combat').closest('tr').each(function () { but that didn't work :( Any help would be greatly appreciated!
Now provide the response and nothing else.
| You need to use a each loop $(document).ready(function () { //iterate through each row in the table $('tr').each(function () { //the value of sum needs to be reset for each row, so it has to be set inside the row loop var sum = 0 //find the combat elements in the current row and sum it $(this).find('.combat').each(function () { var combat = $(this).text(); if (!isNaN(combat) && combat.length !== 0) { sum += parseFloat(combat); } }); //set the value of currents rows sum to the total-combat element in the current row $('.total-combat', this).html(sum); });}); Demo: Fiddle A shorter way to sum: Using unary plus - Demo | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22536448', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/821960/']} | jdg_77306 |
stackexchange | llm_judgeable_groundtruth_similarity | 161507 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
How does the Eckmann-Hilton argument show that higher homotopy groups are commutative? I can easily follow the proof on Wikipedia, but I have no good mental picture of the higher homotopy groups, and I can't see how to apply it. Wikipedia mentions this application in one sentence, with no explanation. (Motivation: I'm thinking of giving a talk on algebraic topology for a general audience of math majors. The purpose would be to try to explain how purely "algebraic" methods can be used to gain serious insight into purely "geometric" problems. This would be a great example, if I could do the proof!) Thanks in advance!
Now provide the response and nothing else.
| Recall that the Eckmann-Hilton argument says that if you have two different unital monoid structures on a set such that both are homomorphisms for the other and both have the same unit, then they're equal and commutative. We want to apply that to see that higher homotopy groups are commutative. The two different monoid structures we want to consider are 'vertical' and 'horizontal' concatenation of maps from $I^n$: if I have two maps $f,g:I^n\to X$ for some topological space $X$ so that $f(\partial I^n)=g(\partial I^n)=x_0$, then I can concatenate them in the following ways as long as $n>1$: $f\cdot g=\begin{cases}f(2x,y,\cdots) &\text{ for } 0\leq x\leq 1/2\\g(2x-1,y,\cdots) &\text{ for } 1/2\leq x\leq 1\end{cases}$ $f \star g= \begin{cases}f(x,2y,\cdots) &\text{ for } 0\leq y\leq 1/2\\g(x,2y-1,\cdots) &\text{ for } 1/2\leq y\leq 1\end{cases}$ Now, if I can show that these are homomorphisms for each other, then I'll have that $\pi_n$ is commutative for $n>1$. But this is easy: both $(f\cdot g)\star (h\cdot i)$ and $(f\star h)\cdot (g\star i)$ are the following map: $(x,y,...)\mapsto\begin{cases}f(2x,2y,\cdots) &\text{ for }(x,y)\in [0,1/2]\times [0,1/2]\\g(2x-1,2y,\cdots) &\text{ for } (x,y)\in [1/2,1]\times [0,1/2]\\h(2x,2y-1,\cdots) &\text{ for } (x,y)\in [0,1/2]\times [1/2,1]\\i(2x-1,2y-1,\cdots) &\text{ for } (x,y)\in [1/2,1]\times [1/2,1]\end{cases}$ Now, by the Eckmann-Hilton argument, these two sorts of composition are the same and are in fact commutative. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/161507', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/28111/']} | jdg_77307 |
stackexchange | llm_judgeable_groundtruth_similarity | 137951 |
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:
Does there exist some simple formulas for the characters $$\chi_{\Lambda^{k}V}~~~~\text{and}~~~\chi_{\text{Sym}^{k}V},$$ where $V$ is a representation of some finite group? Thanks.
Now provide the response and nothing else.
| Suppose $V$ is a vector space over an field $k.^\dagger$ If an $A\in\mathrm{GL}(V)$ is diagonalizable, it induces an eigenbasis $\{v_i\}$ for $V$ with associated eigenvalues $\{\lambda_i\}$. Consider the inherited action of $A$ on the exterior and symmetric powers $\Lambda^k(V)$ and $S^k(V)$ respectively. In particular, we can characterize the eigenpairs or $\Lambda^k(A)$ and $S^k(A)$ respectively as $$(\lambda_{i_1}\cdots\lambda_{i_k},~v_{i_1}\wedge\cdots\wedge v_{i_k});$$ $$(\lambda_{j_1}\cdots\lambda_{j_k},~v_{j_1}\cdots v_{j_k}),$$ where $(i_1,\cdots,i_k)$ and $(j_1,\cdots,j_k)$ are respectively strictly increasing and nondecreasing sequences of integers taken from the index set $\{1,\cdots,n\}$. We thereby obtain the trace formulas $$\mathrm{tr}\,\Lambda^k(A)=e_k(\lambda_1,\cdots,\lambda_n);$$$$\mathrm{tr}\,S^k(A)=h_k(\lambda_1,\cdots,\lambda_n),$$ where $e_k$ is the $k$th elementary symmetric polynomial and $h_k$ the $k$th complete homogeneous symmetric polynomial . Fortunately, the symmetric power sum polynomials $$p_k(x_1,\cdots,x_n)=x_1^k+\cdots+x_n^k$$ also form a basis for the symmetric polynomials $k[x_1,\cdots,x_n]^{S_n}$, and $\mathrm{tr}(A^k)=p_k(\lambda_1,\cdots,\lambda_k)$, so we may recursively write the traces on $\Lambda^k$ and $S^k$ as polynomials in the traces of powers of $A$, using generating functions. Helpfully, Qiaochu writes an explicit formula I was not previously aware of, for the particular case of $k=n$, the dimension of $V$, we have $$\mathrm{tr}\,\Lambda^n(A)=\frac{1}{n!}\sum_{\pi\in S_n}\mathrm{sgn}(\pi)\mathrm{tr}_\pi(A).$$ Note $\mathrm{sgn}(\pi)$ is the parity of the permutation $\pi$, and Qiaochu defines $\mathrm{tr}_\pi(A)$ to be $\mathrm{tr}(A^{f_1})\cdots\mathrm{tr}(A^{f_m})$, where $(f_1,\cdots,f_m)$ is the cycle type of $\pi$. See the references given in his answer for more info. Also, the symmetric trace $\mathrm{tr}\,S^k(A)$ has the same formula but without the $\mathrm{sgn}(\pi)$. (Representations act as invertible linear maps, so we may now choose to write $g$ instead of $A$. Assuming it isn't defective.) Otherwise, we may use the family of Newton-Girard-type identites in order to recursively define trace formulae, as given by draks' answer on the previously linked question; $$\mathrm{tr}\,\Lambda^k(g)=\frac{1}{k}\sum_{m=1}^k(-1)^{m-1}\mathrm{tr}(g^m)\mathrm{tr}\,\Lambda^{k-m}(g).$$ It's the same for $\mathrm{tr}\,S^k(g)$, except the summands are not alternating like above, i.e. no $(-1)^{m-1}$. $^\dagger$The characteristic should not divide $n!$, where $n=\dim V$. The conclusions here can be extended to defective $A$ by considering e.g. continuity after taking care of the case of diagonalizable $A$ on the assumption of an underlying topology. Explicitly, in addition to the $k=2$ case in rattle's answer, this gives us $$\begin{array}{c l} \chi_{\Lambda^2(V)},~\chi_{S^2(V)} & =\frac{\chi(g)^2\mp\chi(g^2)}{2}, \\\chi_{\Lambda^3(V)},~\chi_{S^3(V)} & =\frac{\chi(g)^3\mp 3\chi(g)\chi(g^2)+2\chi(g^3)}{6}, \\\chi_{\Lambda^4(V)},~\chi_{S^4(V)}& =\frac{\chi(g)^4\mp6\chi(g)^2\chi(g^2)+3\chi(g^2)^2+8\chi(g)\chi(g^3)\mp6\chi(g^4)}{24}\end{array}$$ $$\cdots \cdots \cdots \cdots$$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/137951', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/13228/']} | jdg_77308 |
stackexchange | llm_judgeable_groundtruth_similarity | 400293 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I have many Cisco / JunOS routers and switches that send logs to my Debian server, which uses rsyslogd . How can I configure rsyslogd to send these router / switch logs to a specific file, based on their source IP address? I do not want to pollute general system logs with these entries. For instance: all routers in Chicago (source ip block: 172.17.25.0/24) to only log to /var/log/net/chicago.log . all routers in Dallas (source ip block 172.17.27.0/24) to only log to /var/log/net/dallas.log . Delete all APF-3-RCV_UNSUPP_MSG messages without logging them Send logs for 172.17.4.4 to a file named /var/log/net/firewall.log Forward firewall logs to 10.14.12.12 using UDP port 514 Finally, these logs should be rotated daily for up to 30 days and compressed. NOTE: I am answering my own question
Now provide the response and nothing else.
| rsyslogd Configuration In /etc/rsyslogd.conf # provides remote UDP syslog reception$ModLoad imudp$UDPServerRun 514# If logging to an NFS mount, use these settings...# "OMFileFlushOnTXEnd off" avoids fsync on every write...# mount -o hard,rsize=32768,wsize=32768,noacl,noatime,nodiratime -t nfs$OMFileIOBufferSize 768k$OMFileAsyncWriting on$OMFileFlushOnTXEnd off$OMFileFlushInterval 10$MainMsgQueueSize 100000# kill all INTF-FLAP messages...if $msg contains 'INTF-FLAP' then /dev/null&~## Cisco ACS Accounting...if ($fromhost-ip=='172.17.16.20') and ($programname == 'CSCOacs_TACACS_Accounting') then /var/log/tacacs_acct.log&~## CiscoACS 5.4 TACACS Authenticationif ($fromhost-ip=='172.17.16.20') and ($programname == 'CSCOacs_Passed_Authentications') then /var/log/tacacs_auth.log&~# Logging for Chicago issues...if $fromhost-ip startswith '172.17.25' then /var/log/net/chicago.log& ~# Logging for Dallas issues...if $fromhost-ip startswith '172.17.27' then /var/log/net/dallas.log& ~# Logging for firewall...if $fromhost-ip=='172.17.4.4' then @10.14.12.12if $fromhost-ip=='172.17.4.4' then /var/log/net/firewall.log& ~ Each of the &~ entries prevents fall-through to the rest of the rsyslog.conf configuration; thus I won't see router syslog entries in /var/log/messages . Touch all syslog files: touch /var/log/net/chicago.log touch /var/log/net/dallas.log touch /var/log/net/firewall.log Restart rsyslogd with /etc/init.d/rsyslogd restart Log rotation In /etc/logrotate.d/rsyslog /var/log/net/*.log{ copytruncate rotate 30 daily missingok dateext notifempty delaycompress create root 664 root root compress maxage 31 sharedscripts lastaction # RHEL: Use "/sbin/service rsyslog restart" # Debian / Ubuntu: Use "invoke-rc.d rsyslog reload > /dev/null" invoke-rc.d rsyslog reload > /dev/null endscript} | {} | {'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/400293', 'https://serverfault.com', 'https://serverfault.com/users/78702/']} | jdg_77309 |
stackexchange | llm_judgeable_groundtruth_similarity | 5813752 |
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 write a method to return an instance of itself.The pseudo code is Func<T,Func<T>> MyFunc<T>(T input){ //do some work with input return MyFunc;} seems simple enough. But I am having problem defining the return type. The return type should be a delegate which takes T as parameter, then returns a function which takes T as parameter, then returns a function which takes T as parameter, then returns a function ...recursive definition I am sure there was some subtle thing that I didn't notice. Can someone point it out for me?Thank you.
Now provide the response and nothing else.
| You can do it like this: delegate F<T> F<T>(T obj);F<T> MyFunc<T>(T obj){ return MyFunc;} But it's pretty much useless. The only thing you can really do is something like this, which is weird: void Main(){ MyFunc(1)(2)(3)(4);}delegate F<T> F<T>(T obj);F<T> MyFunc<T>(T obj){ Console.WriteLine(obj); return MyFunc;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5813752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/139230/']} | jdg_77310 |
stackexchange | llm_judgeable_groundtruth_similarity | 41427048 |
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 use commands as php yii sync anyvar2=anValue anyVar1=anyValue In controller public function actionIndex(){ echo $anyVar1; echo $anyVar2; } I tried with php yii sync [--anyvar2=anValue ,--anyVar1=anyValue]
Now provide the response and nothing else.
| 1) If you want to set controller parameters: class SyncController extends \yii\console\Controller{ public $anyVar1; public $anyVar2; public function options($actionID) { return array_merge(parent::options($actionID), [ 'anyVar1', 'anyVar2' ]); }} Now you can set them like that: php yii sync --anyVar1=aaa --anyVar2=bbb 2) If you want to just pass variables as arguments: public function actionIndex($anyVar1, $anyVar2){ // ...} Now you can set them like that: php yii sync aaa bbb | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41427048', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4916039/']} | jdg_77311 |
stackexchange | llm_judgeable_groundtruth_similarity | 9354016 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I found a quite strange inconsistency between the behaviour of div and / . *ghci> :t 1 `div` 01 `div` 0 :: Integral a => a*ghci> :t 1 / 01 / 0 :: Fractional a => a*ghci> 1 / 0Infinity*ghci> 1 `div` 0*** Exception: divide by zero I was quite surprised to notice that the fractional division by zero leads to Infinity , whereas div correctly leads to an exception.A NaN could be acceptable too for / , but why Infinity ? There is no mathematical justification for such a result. Do you know the reason for this, please?
Now provide the response and nothing else.
| The reason that div does not return Infinity is simple--there is no representation for infinity in the Integer type. / returns Infinity because it follows the IEEE 754 standard (which describes floating point number representations) since the default Fractional type is Double . Other languages with floating point numbers (e.g. JavaScript) also exhibit this behavior. To make mathematicians cringe even more, you get a different result if you divide by negative 0, despite the fact that -0 == 0 for floats: Prelude> 1/(-0)-Infinity This is also behavior from the standard. If you use a different fractional type like Rational , you will get the behavior you expect: Prelude> 1 / (0 :: Rational)*** Exception: Ratio.%: zero denominator Coincidentally, if you're wondering about why Integer and Double are the types in question when your actual operation does not reference them, take a look at how Haskell handles defaulting types (especially numeric types) in the report . The short version is that if you have an ambiguous type from the Num class, Haskell will first try Integer and then Double for that type. You can change this with a default (Type1, Type2...) statement or turn it off with a default () statement at the module level. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9354016', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/898400/']} | jdg_77312 |
stackexchange | llm_judgeable_groundtruth_similarity | 51220616 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Error: Apache shutdown unexpectedly.11:58:07 [Apache] This may be due to a blocked port, missing dependencies, 11:58:07 [Apache] improper privileges, a crash, or a shutdown by another method.11:58:07 [Apache] Press the Logs button to view error logs and check11:58:07 [Apache] the Windows Event Viewer for more clues11:58:07 [Apache] If you need more help, copy and post this11:58:07 [Apache] entire log window on the forums I can't start the server, the errors above appear when I try to
Now provide the response and nothing else.
| This exception means that you're trying to construct a dict from an iterable, and that iterable's first element is not a sequence. As the docs explain, you can construct a dict two ways: From a mapping, or From an iterable of key-value pairs So, if you try to construct it from, say, a set of numbers: >>> dict({1, 2, 3})TypeError: cannot convert dictionary update sequence element #0 to a sequence … it's trying to use the first element as a key-value pair—that is, a sequence of 2 values—but there's no way to interpret the number 1 as a key-value pair, so it raises a TypeError . Meanwhile, I know absolutely nothing about Plotly streaming but what's on this page , but this code is clearly wrong: stream1.write({dateTime,tempt,humty}) I can't imagine why you'd want to stream a set. Plus, the examples all have either a dict, or a string that's a JSON-encoding of a dict. So, obviously, that API is expecting you to pass it either a dict or something you can feed to the dict constructor. But you're passing it a set. So, it feeds that set to the dict constructor, and gets this exception. Since I have no idea what you're actually trying to do here, I have no idea what dict you should be sending here. But you definitely should be passing a dict. Also, even if you fix this, based on the sign_in call, it looks like you're using Plotly Cloud. But, as the same page says: Streaming is no longer supported in Plotly Cloud. So, if you're trying to use streaming with Plotly Cloud, then, even if you fix your code to make sense, it's probably still going to fail, just with an error from Plotly rather than a TypeError about passing nonsense. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51220616', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10028273/']} | jdg_77313 |
stackexchange | llm_judgeable_groundtruth_similarity | 4517356 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have been reading from Lee's Introduction to Smooth Manifolds and I have gotten to the section on how an orientation on a manifold is defined. First Lee defines an orientation on a vector space $V$ by considering the set of all possible ordered bases for $V$ , call this set $B$ . Thus if $(v_1, \ldots v_n)\in B$ then $(v_1, \ldots, v_n)$ is an ordered set such that $V = \text{span}(v_1, \ldots ,v_n)$ and the vectors are linearly independent. We then consider two bases $(v_1, \ldots v_n)$ and $(w_1, \ldots, w_n)$ to be equivalent if there exists an invertible matrix $A$ such $v_i = (A)_i^j w_j$ and $\text{det}(A) > 0$ . This creates an equivalence on $B$ of which there are two equivalence classes and an orientation on $V$ is a choice of either of the two equivalence classes. Now for a manifold $M$ we defined a point wise orientation as follows. For all $p\in M$ , we can select an orientation on $T_pM$ since $T_pM$ is a vector space. Next on some open set $U\subset M$ , if we have a local frame $(E_1, \ldots E_n)$ so that $(\forall p\in U)\, \text{span}(E_1|_p, \ldots, E_n|_p) = T_pM$ such that $(E_1|_p, \ldots, E_n|_p)$ is positively oriented on $T_pM$ with respect to the point wise orientation on $M$ , then we say that $(E_1,\ldots, E_n)$ is positively oriented on $U$ . Finally we say $M$ is oriented if for all $p\in M$ we may find an open set $U$ containing $p$ and a positively oriented local frame on $U$ . Further the orientation is said to be continuous in this case. My question is about the last part. In what sense is the orientation continuous? I cannot see how the point wise orientation is a weaker assumption than the definition of a local frame being positively oriented. I understand that the vector fields in the local frame are continuous maps from $U\subset M$ to $TM$ , but I don't how this tells us anything about how the orientation evolves on $M$ . I saw the answer on Definition of pointwise continuous orientation of smooth manifolds which elaborates on how for each $p\in M$ we can find a map $f:U\to GL(n,\mathbb{R})$ where $f(p)$ is a transition matrix from our local frame to any fixed representative of the orientation. In the answer, the author posts that $f$ is a continuous map and I do not see how that parts follows either.
Now provide the response and nothing else.
| To see in what sense a continuous orientation for $M$ is continuous, first prove the following easy topological lemma. Lemma. If $f\colon X\to D$ is a function on a topological space $X$ valued in a discrete space $D$ , then the function $f$ is locally constant if and only if $f$ is continuous. We will use the lemma for $D = \{1,-1\}$ . Now, by the definition of a continuous orientation, first of all, we have a pointwise orientation $\mathcal O$ such that each point of the manifold $M$ is contained in some open subset $U$ on which we have a local frame $(E_1,\dots,E_n)$ satisfying $[(E_1,\dots,E_n)] = \mathcal O$ on $U$ . By considering the determinant $\det(E_1,\dots,E_n)\in\mathbb R\smallsetminus\{0\}$ of the matrix whose columns are the vectors $E_1,\dots,E_n$ , and recalling the continuity of the local frame $(E_1,\dots,E_n)$ , you should check that, possibly after shrinking $U$ , either for all $p\in U$ , $\det(E_1,\dots,E_n)<0$ or for all $p\in U$ , $\det(E_1,\dots,E_n)>0$ . Thus, we see that our orientation $\mathcal O$ may be regarded as a locally constant function $M\to \{1,-1\}$ according to the sign of $\det(E_1,\dots,E_n)$ for whatever our local frame $(E_1,\dots,E_n)$ is. Since $\mathcal O$ is locally constant, the orientation is continuous when regarded as a map $M\to\{1,-1\}$ , which justifies the terminology. Here is the conclusion, summarized. A pointwise orientation allows the orientation $\mathcal O$ to flip-flop arbitrarily between "nearby" tangent spaces, whereas a continuous orientation is a pointwise orientation that is also locally constant as a consequence of the continuity of the map $p\mapsto \det(E_1(p),\dots, E_n(p))$ . Added: To compute the determinants $\det(E_1,\dots,E_n)$ , you can shrink $U$ to be a coordinate patch, and then express $E_j = a^i_j\partial_i$ in terms of coordinate vector fields. Now, the functions $p\mapsto a^i_j(p)$ are continuous by the assumption that $(E_1,\dots,E_n)$ is a local frame , and we are concretely taking the determinant of the matrix $(a^i_j)$ . Note. We also recall here that a local frame $(E_1,\dots,E_n)$ in the author's convention is by definition an $n$ -tuple of continuous vector fields that span the tangent space at each point. Continuity can be understood in various equivalent senses, the most concrete of which probably being the one in terms of coordinates with respect to some coordinate vector fields. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4517356', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/566958/']} | jdg_77314 |
stackexchange | llm_judgeable_groundtruth_similarity | 73739 |
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:
How to find the (original) value of a burnt resistor? Let's suppose a condition in which initially I don't know the value of its resistance. Now because of its low watt, it burnt. So is there any method to find out the resistance?
Now provide the response and nothing else.
| A burnt out resistor can only be read one of two ways. The first is the color code on the resistor, if it is through hole, or the number code if it is a smd resistor with a a number code. If that is not available, the only other way is a circuit diagram, or a reference design around the IC it is supporting. Most manufacturers tend to stick with the manufacturer's reference design, rarely deviating unless they have a specific reason to, so if the reference design specifies a specific resistor, you have a very good chance that is it. Aside from that, no, if the resistor code is unreadable, and the reference design is not applicable, you cannot know the original resistor value once the resistor goes bad. There is no point in measuring a burnt out resistor, as if it actually measured the right ohm-age, it wouldn't be ""burnt out"". The other option is context . Sometimes, based on the circuit, you can simply assume what the resistor is. If it is a transistor base resistor, it might simple be a saturation value resistor. If it is a led resistor, it's value might allow for 20mA through the led. This is very contextual, and it depends on the IC, so it pretty much falls under the "manufacturer reference circuit" standard. Engr Kahn's answer below also seems to have a reasonable chance of working. As resistance in series is cumulative, if you can measure half the resistor (like you would the wiper of a pot) and then the other half, aside from the burnt section, you can get an approximate value then adjust upwards to standard values. And depending on the circuit, the exact value is not always necessary. A 1.2k resistor might work well enough in place of a 1k resistor. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/73739', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/25084/']} | jdg_77315 |
stackexchange | llm_judgeable_groundtruth_similarity | 6542036 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There are multiple ways to produce email address Strings that differ with straight String comparison (see below), but are logically equivalent (i.e. mail sent to both goes to same mail box).This often allows users to give seemingly unique email addresses, even if strict equality was disallowed. I was hoping to find a library that would try to do normalization, to allow for finding some of duplicates from large sets of email addresses. Goal here is to find as many duplicates as possible.Given how useful this is for multiple purposes (in my case it is simple abuse detection, as abuse accounts tend to (try to) just reuse certain accounts), I am thinking there might be existing solutions. So what kind of things can vary? I know of at least things like: domain name part is case-insensitive (as per DNS); but local part may or may not be, this depends on mail provider (for example, Gmail considers it case-insensitive) many domains have aliases (googlemail.com is equivalent to gmail.com) some email providers allow other variations that they ignore (gmail, for example, ignores any dots in email address!) Ideally this would be in Java, although scripting languages would also work (command-line tool)
Now provide the response and nothing else.
| I could find a few bits off code on Google by searching for " normalize email address ", but nothing nearly thorough enough. I'm afraid you would have to write your own tool. If I were to write such a tool, here are a few rules I think I would apply: First the tool would lower the case of the domain name (after the @). It shouldn't be too hard, unless you want to handle emails with international domain names . For example, JoE@caFÉ.fR (note the accent on the E) should first go through the Nameprep algorithm. This leads to [email protected]. I have never seen anyone with such an international email address, but I suspect you might find some in China or Japan, for example. RFC 5322 states that the local-part of the email (before the @) is case sensitive , but the de facto standard for virtually all providers is to ignore case (I have never seen a case-sensitive email address actually used by a human being, but I suppose there are still some sysadmins out there who use their Un*x email accounts, where case does matter). I think the tool should have an option to ignore case for a list of domain names (or on the contrary, to be case sensitive only for a list of domain names). So at this point, the email address JoE@caFÉ.fR is now normalized to [email protected]. Once again, the question of international (aka. non ASCII) email addresses pops up. What if the local-part is non-ASCII ? For example something like 甲斐@黒川.日本 (disclaimer: I don't speak Japanese). RFC 5322 forbids this, but more recent RFCs do support this (see this wikipedia article ). A lot of languages have no notion of lower or uppercase. When they do, if you want to change to the lower-case form, make sure to use the appropriate Unicode lower-case algorithms, it's not always trivial. For example, in German, the lower case of the word "Großes" may be either "grosses" or "großes" (disclaimer: I don't speak German either). So at this point, the email address "Großes@caFÉ.Fr" should have been normalized to "[email protected]". I haven't read RFC 5322 in detail but I think there's also a possibility to have comments in an email address , either at the beginning or at the end of the local part, such as (sir)[email protected] or john.lennon(ono)@beatles.com. These comments should be stripped (this would lead to [email protected]. Stripping the comments is not entirely trivial because I don't know what to do with the nested comments, and also comments enclosed in double-quotes should not be stripped, according to the RFC (unless I am mistaken). For example, the comment in the following email address should not be stripped, according to the RFC: "john.(ono).lennon"@beatles.com. Once the email is thus normalized, I would apply the "provider-specific" rules you suggest. For example stripping the dots in GMail addresses and mixing equivalent domain names (googlemail.com == gmail.com for example). I think I would keep this really separate from the previous normalization steps. Note that Gmail also ignores the plus sign (+) and everything after it, for example [email protected] is equivalent to [email protected]. I'm not aware of other provider rules. The thing is, these rules may change at any time, you would have to keep track of them all. I think that's about it. If you come up with some working code, I would be really interested to see it. Cheers! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6542036', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/59501/']} | jdg_77316 |
stackexchange | llm_judgeable_groundtruth_similarity | 34012063 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
class ViewController: UIViewController { let fortuneArray = ["You will find true love in the summer.", "Outlook not good", "You may find great success in business soon.", "Watch out for grey cats."]let randomIndex = Int(arc4random_uniform(fortuneArray.count))override func viewDidLoad() { super.viewDidLoad() let randomIndex = Int(arc4random_uniform(UInt32(fortuneArray.count))) print("random index: ") print(randomIndex) // Do any additional setup after loading the view, typically from a nib.}override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated.}// actions@IBAction func cookiePressed(sender: AnyObject) { fortune.text = fortuneArray[randomIndex]} I'm creating a very simple fortune telling app in Swift and I keep running into issues with arc4random_uniform . Currently I'm just trying to get the app to draw a string at random but I get an error saying: Instance member 'fortuneArray' cannot be used on type 'ViewController' on the line where I am declaring the variable randomIndex . I've been using google for awhile but haven't found a fix. Hopefully someone can help, thanks! * Update * Problem solved! Thanks.
Now provide the response and nothing else.
| If the code you pasted is not defined in a method like viewDidLoad , you cannot use a variable thats defined at the class level for another variable thats defined at the class level as well. These variables are determined at run time and the order they are determined is not known so fortuneArray may not exist before randomIndex is made (might not really work like this behind the scenes but you can think of it this way at least) you should compute these variables inside viewDidLoad or init or some other function instead | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34012063', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5508856/']} | jdg_77317 |
stackexchange | llm_judgeable_groundtruth_similarity | 48301920 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We're dealing with a very large project that needs to be migrated to Git. Unfortunately, it contains a large number of binaries as well, some of which are zip-s, dll-s and so on. At the moment, it's not possible to remove these binaries from the version control system. I would like to find out more about how Git keeps deltas for binary files and if, and for which ones it doesn't. I know this is configurable via the .gitattributes file, but do the file types need to be listed explicitly, or is there a pre-defined default set that it recognizes and handles automatically...?
Now provide the response and nothing else.
| First, let's get a bit of terminology out of the way. Files are stored as blob objects . These are one of four object types, the other three being commit , tree , and annotated tag . Git's model is that all objects are logically independent. Everything is stored by its hash ID key, in a database. To retrieve any object, you start by knowing its hash ID, which you get from something or someone else. 1 You feed that hash ID to an object-getter, and it either looks up the object where it is stored directly, with no chance at delta compression at all—this is what Git calls a loose object —or, failing that, Git looks inside pack files , which pack multiple separate objects together and provide the opportunity for delta compression. 2 What you're looking for, then, is information about which blob objects Git chooses to delta-compress against which other blob objects inside these pack files. The answer has evolved somewhat over time, so there is no single correct answer—but there are certain control knobs, including the .gitattributes one you mentioned. The actual delta format is a modification of xdelta . It can, literally, compress (or "deltify") any binary data against any other binary data—but the results will be poor unless the inputs are well-chosen. It's the input choices that are the real key here. Git also has a technical documentation file describing how objects are chosen for deltification . This takes file path names, and especially final path component names, into account. Note that if deltification fails to make the object smaller, the object is simply not delta-compressed. The object's original file size is also an input here, and core.bigFileThreshold (introduced in Git 1.7.6) sets a size value: files above this level are never deltified at all. Hence, you can prevent Git from considering a file (object, really) for deltification by either of two ways: set core.bigFileThreshold so that the object is too big, or make the object's path name match a .gitattributes line that has -delta specified. Note that when using Git-LFS, large files are not stored in Git at all. Instead, a large file (as defined by the Git-LFS settings) is replaced (at git add time) by an indirect name. Git then stores this indirect name as the blob object (using the original file's path). When Git extracts the object, Git-LFS inspects it before allowing it to go into your work-tree. Git-LFS detects that the object's data were replaced with an indirect name, and retrieves the "real" data from another (separate, not-Git-at-all) server using the indirect name. So Git never sees the large file's data at all: instead, it sees only these indirect names. 1 For instance, we might start with a branch name like master , which gets us the latest (or tip ) commit hash ID. That hash ID gives us access to the commit object. The commit lists the hash ID of a tree. The tree, once we obtain it, lists the hash ID of some blob, along with the file's name. So, now we know that the hash ID for the version of README in the tip commit of master , if that's what we're looking for. Or, we use the commit data to find an older commit, which we use to find another even-older commit, and so on, until we arrive at the commit we want; and then we use the tree to find the blob IDs (and names) of files. 2 Normally, an object can only be "deltified" against other objects in the same pack. For transport purposes, Git provides what it calls a thin pack in which objects can be delta-compressed against other objects that are omitted, but are assumed to be available on the other side of the transport mechanism. The other Git must "fatten up" the thin pack. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48301920', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/774183/']} | jdg_77318 |
stackexchange | llm_judgeable_groundtruth_similarity | 45130184 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Training a model with tf.nn.ctc_loss produces an error every time the train op is run: tensorflow/core/util/ctc/ctc_loss_calculator.cc:144] No valid path found. Unlike in previous questions about this function, this is not due to divergence. I have a low learning rate, and the error occurs on even the first train op. The model is a CNN -> LSTM -> CTC. Here is the model creation code: # Build Graphself.videoInput = tf.placeholder(shape=(None, self.maxVidLen, 50, 100, 3), dtype=tf.float32)self.videoLengths = tf.placeholder(shape=(None), dtype=tf.int32)self.keep_prob = tf.placeholder(dtype=tf.float32)self.targets = tf.sparse_placeholder(tf.int32)self.targetLengths = tf.placeholder(shape=(None), dtype=tf.int32)conv1 = tf.layers.conv3d(self.videoInput ...)pool1 = tf.layers.max_pooling3d(conv1 ...)conv2 = ...pool2 = ...conv3 = ...pool3 = ...cnn_out = tf.reshape(pool3, shape=(-1, self.maxVidLength, 4*7*96))fw_cell = tf.nn.rnn_cell.MultiRNNCell(self.cell(), for _ in range(3))bw_cell = tf.nn.rnn_cell.MultiRNNCell(self.cell(), for _ in range(3))outputs, _ = tf.nn.bidirectional_dynamic_rnn( fw_cell, bw_cell, cnn_out, sequence_length=self.videoLengths, dtype=tf.float32)outputs = tf.concat(outputs, 2)outputs = tf.reshape(outputs, [-1, self.hidden_size * 2])w = tf.Variable(tf.random_normal((self.hidden_size * 2, len(self.char2index) + 1), stddev=0.2))b = tf.Variable(tf.zeros(len(self.char2index) + 1))out = tf.matmul(outputs, w) + bout = tf.reshape(out, [-1, self.maxVidLen, len(self.char2index) + 1])out = tf.transpose(out, [1, 0, 2])cost = tf.reduce_mean(tf.nn.ctc_loss(self.targets, out, self.targetLengths))self.train_op = tf.train.AdamOptimizer(0.0001).minimize(cost) And here is the feed dict creation code: indices = []values = []shape = [len(vids) * 2, self.maxLabelLen]vidInput = np.zeros((len(vids) * 2, self.maxVidLen, 50, 100, 3), dtype=np.float32)# Actual video, then left-right flipfor j in range(len(vids) * 2): # K is video index k = j if j < len(vids) else j - len(vids) # convert video and label to input format vidInput[j, 0:len(vids[k])] = vids[k] if k == j else vids[k][:,::-1,:] indices.extend([j, i] for i in range(len(labelList[k]))) values.extend(self.char2index[c] for c in labelList[k])fd[self.targets] = (indices, values, shape)fd[self.videoInput] = vidInput# Collect video lengths and label lengthsvidLengths = [len(j) for j in vids] + [len(j) for j in vids]labelLens = [len(l) for l in labelList] + [len(l) for l in labelList]fd[self.videoLengths] = vidLengthsfd[self.targetLengths] = labelLens
Now provide the response and nothing else.
| It turns out that the ctc_loss requires that the label lengths be shorter than the input lengths. If the label lengths are too long, the loss calculator cannot unroll completely and therefore cannot compute the loss. For example, the label BIFI would require input length of at least 4 while the label BIIF would require input length of at least 5 due to a blank being inserted between the repeated symbols. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45130184', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1761970/']} | jdg_77319 |
stackexchange | llm_judgeable_groundtruth_similarity | 7123898 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Apologies if this question has been asked already, but suppose we have this code (I've run it with Mono 2.10.2 and compiled with gmcs 2.10.2.0): using System;public class App { public static void Main(string[] args) { Func<string> f = null; var strs = new string[]{ "foo", "bar", "zar" }; foreach (var str in strs) { if ("foo".Equals(str)) f = () => str; } Console.WriteLine(f()); // [1]: Prints 'zar' foreach (var str in strs) { var localStr = str; if ("foo".Equals(str)) f = () => localStr; } Console.WriteLine(f()); // [2]: Prints 'foo' { int i = 0; for (string str; i < strs.Length; ++i) { str = strs[i]; if ("foo".Equals(str)) f = () => str; }} Console.WriteLine(f()); // [3]: Prints 'zar' }} It seems logical that [1] print the same as [3] . But to be honest, I somehow expected it to print the same as [2] . I somehow believed the implementation of [1] would be closer to [2] . Question : Could anyone please provide a reference to the specification where it tells exactly how the str variable (or perhaps even the iterator) is captured by the lambda in [1] . I guess what I am looking for is the exact implementation of the foreach loop.
Now provide the response and nothing else.
| You asked for a reference to the specification; the relevant location is section 8.8.4, which states that a "foreach" loop is equivalent to: V v; while (e.MoveNext()) { v = (V)(T)e.Current; embedded-statement } Note that the value v is declared outside the while loop, and therefore there is a single loop variable. That is then closed over by the lambda. UPDATE Because so many people run into this problem the C# design and compiler team changed C# 5 to have these semantics : while (e.MoveNext()) { V v = (V)(T)e.Current; embedded-statement } Which then has the expected behaviour -- you close over a different variable every time. Technically that is a breaking change, but the number of people who depend on the weird behaviour you are experiencing is hopefully very small. Be aware that C# 2, 3, and 4 are now incompatible with C# 5 in this regard. Also note that the change only applies to foreach , not to for loops. See http://ericlippert.com/2009/11/12/closing-over-the-loop-variable-considered-harmful-part-one/ for details. Commenter abergmeier states: C# is the only language that has this strange behavior. This statement is categorically false . Consider the following JavaScript: var funcs = [];var results = [];for(prop in { a : 10, b : 20 }){ funcs.push(function() { return prop; }); results.push(funcs[0]());} abergmeier, would you care to take a guess as to what are the contents of results ? | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7123898', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/858113/']} | jdg_77320 |
stackexchange | llm_judgeable_groundtruth_similarity | 12471067 |
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 been a Joomla developer for almost an year now. I have been struggling to import jQuery into joomla everyday. Joomla comes with mootools. When I import jQuery it crashes. Also when I create modules I have to import jQuery into each module which makes to site slow. Sometimes it makes the whole site crashes. I want both mootools and jquery to work hand in hand so I can use both without any crashes. What's the best way to import jQuery into Joomla ? Is there a specific place where the import should be done to use one jquery library site-wide( both backend and frontend ) ? Thanks
Now provide the response and nothing else.
| This is the code we use to ensure only 1 copy of jQuery is imported. It simply checks to see if jQuery is already being imported and if not, then we import it :) Joomla 2.5 <?php $app = JFactory::getApplication(); if (!$app->get('jquery')) { $app->set('jquery', true); JFactory::getDocument()->addScript(JUri::root() . 'templates/template_name/js/jquery.js'); }?> Joomla 3.x (no conflict mode): JHtml::_('jquery.framework'); Joomla 3.x (normal mode): JHtml::_('jquery.framework', false); You need to insert this code into the index.php of your template, preferably near the top so you remember where it is. If you do not wish to override your template's index.php file, then you can also develop a small Plugin Update: As Bobby stated. A lot of extensions include their own copy of jQuery and a lot of them don't use this method and thus causes conflicts. All I know is that any good developer should know that multiple jQuery libraries causes conflicts and should use this code. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12471067', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1263783/']} | jdg_77321 |
stackexchange | llm_judgeable_groundtruth_similarity | 1642070 |
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 recently proved that the product of all primitive roots of an odd prime $p$ is $\pm 1$ as an exercise. As a result, I became interested in how few distinct primitive roots need to be multiplied to guarantee a non-primitive product. Testing some small numbers, I have the following claim: "If $n$ and $m$ are two distinct primitive roots of an odd prime $p$, then $nm \bmod p$ is not a primitive root." I've tried to make some progress by rewriting one of the primitive roots as a power of the other, but haven't been able to see any argument which helps me prove the result. Any help would be appreciated.
Now provide the response and nothing else.
| Take any generator $g$ of the multiplicative group $\Bbb F_p^\times$. If $r$ and $s$ are primitive roots then $r=g^u$ and $s=g^v$ where $u$ and $v$ are coprime with $p-1$, so $u$ and $v$ are odd. Then, $rs=g^{u+v}$ and $u+v$ is even, so $rs$ is not a primitive root. Esentially it is the same reasoning than André's. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1642070', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']} | jdg_77322 |
stackexchange | llm_judgeable_groundtruth_similarity | 4290089 |
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:[0,\infty)\to (0,\infty)$ be a uniformly continuous function with $\lim_{t\to\infty}f(t)=C.$ Prove that $\int_0^\infty f(t)dt=\infty$ $\Longleftrightarrow$ $\sum_{n=1}^\infty f(n)=\infty$ . My attempt For the case $C>0$ , I can prove that both $\int_0^\infty f(t)dt=\infty$ and $\sum_{n=1}^\infty f(n)=\infty$ hold. The difficulty is in the case that $C=0$ and I got stuck. Any helps would be highly appreciated!
Now provide the response and nothing else.
| I think the statement does not hold. Take $f(x)$ to be a piecewise linear "bump" function with $f(n) = \frac{1}{n^2}$ but $f(n+0.5) = \frac{1}{n}$ for all $n$ . Then $f$ vanishes at $\infty$ and is uniformly continuous as a continuous function that vanishes at $\infty$ . We get $$\sum_{n} f(n) = \sum_{n} \frac{1}{n^2}< \infty$$ But $$\int_{0}^{\infty} f(x)dx \ge \sum_{n} 0.5 \cdot f(n+0.5) = \sum_{n} 0.5 \cdot \frac{1}{n} = \infty$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4290089', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/578168/']} | jdg_77323 |
stackexchange | llm_judgeable_groundtruth_similarity | 49836166 |
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 develop a server-side validation of my users' in-app purchases and subscriptions as recommended , and I want to use Firebase Functions for that. Basically it has to be an HTTP trigger function that receives a purchase token, calls the Play Developer API to verify the purchase, and then does something with the result. However, calling many of the Google APIs (including Play Developer API ) requires non-trivial authorization. Here's how I understand the required setup: There has to be a GCP project with Google Play Developer API v2 enabled. It should be a separate project, since there can be only one linked to Play Store in the Google Play Console. My Firebase Functions project must somehow authenticate to that other project. I figured that using a Service Account is most suitable in this server-to-server scenario. Finally, my Firebase Functions code must somehow obtain authentication token (hopefully JWT?) and finally make an API call to get a subscription status. The problem is that absolutely no human-readable documentation or guidance on that is existent. Given that ingress traffic in Firebase is included in the free plan (so I assume they encourage using Google APIs from Firebase Functions), that fact is pretty disappointing. I've managed to find some bits of info here and there, but having too little experience with Google APIs (most of which required simply using an api key), I need help with putting it together. Here's what I figured out so far: I got a GCP project linked to the Play Store and with the API enabled. For some reason though, trying to test it in APIs Explorer results in an error "The project id used to call the Google Play Developer API has not been linked in the Google Play Developer Console". I made a Service Account and exported a JSON key, which contains the key to produce a JWT. I also set up read permissions for that Service Account in Play Console. I found a Node.JS client library for Google APIs, which is in alpha and has very sparse documentation (e.g. there's no obvious documentation on how to authenticate with JWT, and no samples on how to call the android publisher API). At the moment I'm struggling with that. Unfortunately I'm not super-comfortable with reading JS library code, especially when the editor doesn't provide the possibility to jump to highlighted functions' sources. I'm pretty surprised this hasn't been asked or documented, because verifying in-app purchases from Firebase Functions seems like a common task. Has anyone successfully done it before, or maybe the Firebase team will step in to answer?
Now provide the response and nothing else.
| I figured it out myself. I also ditched the heavyweight client library and just coded those few requests manually. Notes: The same applies to any Node.js server environment. You still need the key file of a separate service account to mint a JWT and the two steps to call the API, and Firebase is no different. The same applies to other APIs that require authentication as well — differing only in scope field of the JWT. There are a few APIs that don't need you to exchange the JWT for an access token — you can mint a JWT and provide it directly in Authentication: Bearer , without a round trip to OAuth backend. After you've got the JSON file with the private key for a Service Account that's linked to Play Store, the code to call the API is like this (adjust to your needs). Note: I used request-promise as a nicer way to do http.request . const functions = require('firebase-functions');const jwt = require('jsonwebtoken');const keyData = require('./key.json'); // Path to your JSON key fileconst request = require('request-promise');/** * Exchanges the private key file for a temporary access token, * which is valid for 1 hour and can be reused for multiple requests */function getAccessToken(keyData) { // Create a JSON Web Token for the Service Account linked to Play Store const token = jwt.sign( { scope: 'https://www.googleapis.com/auth/androidpublisher' }, keyData.private_key, { algorithm: 'RS256', expiresIn: '1h', issuer: keyData.client_email, subject: keyData.client_email, audience: 'https://www.googleapis.com/oauth2/v4/token' } ); // Make a request to Google APIs OAuth backend to exchange it for an access token // Returns a promise return request.post({ uri: 'https://www.googleapis.com/oauth2/v4/token', form: { 'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer', 'assertion': token }, transform: body => JSON.parse(body).access_token });}/** * Makes a GET request to given URL with the access token */function makeApiRequest(url, accessToken) { return request.get({ url: url, auth: { bearer: accessToken }, transform: body => JSON.parse(body) });}// Our test functionexports.testApi = functions.https.onRequest((req, res) => { // TODO: process the request, extract parameters, authenticate the user etc // The API url to call - edit this const url = `https://www.googleapis.com/androidpublisher/v2/applications/${packageName}/purchases/subscriptions/${subscriptionId}/tokens/${token}`; getAccessToken(keyData) .then(token => { return makeApiRequest(url, token); }) .then(response => { // TODO: process the response, e.g. validate the purchase, set access claims to the user etc. res.send(response); return; }) .catch(err => { res.status(500).send(err); });}); These are the docs I followed. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49836166', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2299005/']} | jdg_77324 |
stackexchange | llm_judgeable_groundtruth_similarity | 373385 |
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:
A regression of $y$ on $x$ need not be causal if there are omitted variables which influence both $x$ and $y$ . But if not for omitted variables and measurement error, is a regression causal? That is, if every possible variable is included in the regression?
Now provide the response and nothing else.
| No, it's not, I will show you some counterexamples. The first is reverse causation . Consider the causal model is $Y \rightarrow X$ , where $X$ and $Y$ are standard gaussian random variables. Then $E[Y|do(x)] = 0$ , since $X$ does not cause $Y$ , but $E[Y|x]$ will depend on $X$ . The second example is controlling for colliders (see here ). Consider the causal model $X \rightarrow Z \leftarrow Y$ , that is $X$ does not cause $Y$ and $Z$ is a common cause. But note that, if you run a regression including $Z$ , the regression coefficient of $X$ will not be zero, because conditioning on the common cause will induce association between $Y$ and $X$ (you may want to see here as well Path Analysis in the Presence of a Conditioned-Upon Collider ). More generally, the regression of $Y$ on $X$ will be causal if the variables included in the regression satisfy the backdoor criterion . | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/373385', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/224545/']} | jdg_77325 |
stackexchange | llm_judgeable_groundtruth_similarity | 18354 |
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm interested in studying how information spreads in a social network. The basic problem is as follows. Let's say we have a large graph of people, with directed edges connecting them. Let's also assume that based on the links, we can robustly identify influential people using something like Pagerank, etc. Within this setting, suppose we want to inform the people in the network of some important piece of news, and that we can only do so by face-to-face contact with individual people. Also, we have limited resources -- suppose, because of limited resources, we can only have face-to-face contact with n people, out of a total of N people in the whole graph. Question: how do we choose this subset of n people from the graph? One easy solution is to use Pagerank and identify the most influential people. However, this doesn't exploit the idea of redundancy: if the top 3 most influential people according to Pagerank have let's say 80% of their neighbors in common, then we're essentially wasting resources by marketing to each of these three people. Any insight on this problem would be helpful -- it seems that this situation would occur often enough that someone must have come up with a formal treatment with efficient algorithms, etc. I can think of a few ways to do this, but they involve inefficient traversals, etc.
Now provide the response and nothing else.
| This isn't a full answer, but a partial one since there's a lot of literature out there. To answer the question, we need some model of how information spreads in a social network. You seem to maybe be assuming that everyone we talk to tells their friends, but their friends don't tell anyone (so we just want to pick the set that maximizes the number of neighbors). But many other dynamics are possible. Usually, one thinks of the problem as finding an initial set of nodes to "infect", and assuming that all nodes have some rule for when they get infected as a function of the number of infected neighbors. For example, you could have a threshold which says that I get infected as soon as I have 3 or more infected neighbors; or that $i$ has a probability $p_{ij}$ of getting infected from $j$ in the timestep after $j$ is first infected. The original/classic paper for this problem is Maximizing the Spread of Influence Through a Social Network by Kempe, J. Kleinberg, and Tardos in 2003. 1 If you search it on Google Scholar you'll see something like 1500 citations, so there is a lot of work in this area. You can see some on Jon Kleinberg's homepage under "Information Flow and Cascading Behavior in Networks"; he gave a survey talk on the area at this year's EC, but I don't know if the slides are available anywhere. In 1 , the authors show that, under several models of influence like those mentioned above, the "influence" of a set of vertices is a submodular function ; this allows greedy algorithms to find a set of initial nodes that gives a $1-1/e$ approximation to the best total influence. (However, solving the problem exactly is NP-hard.) 1 http://www.cs.cornell.edu/home/kleinber/kdd03-inf.pdf | {} | {'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/18354', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/16935/']} | jdg_77326 |
stackexchange | llm_judgeable_groundtruth_similarity | 25138594 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
i am trying to use google maps in my app, i am using google play services in app MapViewActivity: public class MapsViewActivity extends FragmentActivity {// Google Mapprivate GoogleMap googleMap;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.maps); try { // Loading map initilizeMap(); } catch (Exception e) { e.printStackTrace(); }}/** * function to load map. If map is not created it will create it for you * */private void initilizeMap() { if (googleMap == null) { googleMap = ((MapFragment) getFragmentManager().findFragmentById( R.id.map)).getMap(); // check if map is created successfully or not if (googleMap == null) { Toast.makeText(getApplicationContext(), "Sorry! unable to create maps", Toast.LENGTH_SHORT) .show(); } }} XMl: <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent" ><fragment android:id="@+id/map" android:name="com.google.android.gms.maps.MapFragment" android:layout_width="match_parent" android:layout_height="match_parent" /> and getting the following errors : 08-05 16:41:54.384: E/dalvikvm(24979): Could not find class 'gpq', referenced from method gpr.a08-05 16:41:54.384: W/dalvikvm(24979): VFY: unable to resolve new-instance 4090 (Lgpq;) in Lgpr;08-05 16:41:54.384: D/dalvikvm(24979): VFY: replacing opcode 0x22 at 0x000008-05 16:41:54.404: W/dalvikvm(24979): VFY: unable to resolve static field 20875 (t) in Lyo;08-05 16:41:54.404: D/dalvikvm(24979): VFY: replacing opcode 0x62 at 0x000e08-05 16:41:54.404: W/dalvikvm(24979): VFY: unable to resolve static field 20875 (t) in Lyo;08-05 16:41:54.484: E/AndroidRuntime(24979): FATAL EXCEPTION: main08-05 16:41:54.484: E/AndroidRuntime(24979): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.careandcure/com.example.careandcure.MapsViewActivity}: android.view.InflateException: Binary XML file line #6: Error inflating class fragment08-05 16:41:54.484: E/AndroidRuntime(24979): at com.example.careandcure.MapsViewActivity.onCreate(MapsViewActivity.java:16)08-05 16:41:54.484: E/AndroidRuntime(24979): at android.app.Activity.performCreate(Activity.java:4538)08-05 16:41:54.484: E/AndroidRuntime(24979): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1071)08-05 16:41:54.484: E/AndroidRuntime(24979): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2161)08-05 16:41:54.484: E/AndroidRuntime(24979): Caused by: java.lang.RuntimeException: API key not found. Check that <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="your API key"/> is in the <application> element of AndroidManifest.xml08-05 16:41:54.484: E/AndroidRuntime(24979): at com.google.android.gms.maps.internal.IMapFragmentDelegate$a$a.onCreateView(Unknown Source) manifest: <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.careandcure"android:versionCode="1"android:versionName="1.0" ><uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /><permission android:name="info.androidhive.googlemapsv2.permission.MAPS_RECEIVE" android:protectionLevel="signature" /><uses-permission android:name="info.androidhive.googlemapsv2.permission.MAPS_RECEIVE" /><uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /><uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /><uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /><uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /><!-- Required OpenGL ES 2.0. for Maps V2 --><uses-feature android:glEsVersion="0x00020000" android:required="true" /><application android:allowBackup="true" android:icon="@drawable/logo" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="com.example.careandcure.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="com.example.careandcure.MapsViewActivity" > </activity> <!-- Goolge Maps API Key --> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="api_key" /></application></manifest> I am not getting where I am getting wrong or missing anything andhow to remove please help me in solving this issue.
Now provide the response and nothing else.
| Case 1: String str = "Good";str = str + " Morning"; In the above code you create 3 String Objects. "Good" it goes into the String Pool . " Morning" it goes into the String Pool as well. "Good Morning" created by concatenating "Good" and " Morning". This guy goes on the Heap . Note: Strings are always immutable . There is no, such thing as a mutable String . str is just a reference which eventually points to "Good Morning". You are actually, not working on 1 object. you have 3 distinct String Objects. Case 2: StringBuffer str = new StringBuffer("Good"); str.append(" Morning"); StringBuffer contains an array of characters. It is not same as a String .The above code adds characters to the existing array. Effectively, StringBuffer is mutable, its String representation isn't. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/25138594', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3671508/']} | jdg_77327 |
stackexchange | llm_judgeable_groundtruth_similarity | 7503944 |
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 shared path (like //servername/c$/batches/) where all my batch files are located now I am writing an web application in C# to run .bat files from that application. I know way to do it when I have a physical path.But here I dont have a physical path. Is it possible to do it. EDIT# 1 I execute my bat files just by double clicking on them or open the cmd progam on the physical server and then navigate to the drive and execute the bat file. EDIT #2 when I put UNC path the get the following error I getting an error myprogram.exe is not recognized as an internal or external command operable program or batch file. 9009
Now provide the response and nothing else.
| Batch files don't support UNC paths as their "current directory". There's a hackish work around of doing: pushd "%~dp0"your batch stuffpopd %~dp0 expands to the current (d)rive/(p)ath/(0)batchfilename example: ok. a Simple batch file: pushd %~dp0echo "Hello from batch land"echo %~dp0popd put that on a server somewhere, and try to run it via a unc path: C:\> \\server\share\test.bat You'll get as output: C:\>pushd \\server\share\Z:\>echo Hello from batch landHello from batch landZ:\>echo \\server\share\\\server\share\Z:\>popdC:\> Weird, but it works. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7503944', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/336767/']} | jdg_77328 |
stackexchange | llm_judgeable_groundtruth_similarity | 10263505 |
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 print a list or something in haskell at every call for example : funct a list = funct (a + 1) (a : list) print list here ??????? but how ?
Now provide the response and nothing else.
| For debugging, there's import Debug.Tracefunct :: Integer -> [Integer] -> Bool funct a list = trace (show list) $ funct (a + 1) (a : list) where trace :: String -> a -> a . It uses unsafePerformIO under the hood, so it's evil and only for debugging. Be aware that due to lazy evaluation, the debugging output may appear in surprising order and interleaved with the output the program would normally generate. With module TraceIt whereimport Debug.Tracefunct :: Integer -> [Integer] -> Boolfunct 10 list = null listfunct a list = trace (show list) $ funct (a + 1) (a : list) I get *TraceIt> funct 1 [][][1][2,1][3,2,1][4,3,2,1][5,4,3,2,1][6,5,4,3,2,1][7,6,5,4,3,2,1][8,7,6,5,4,3,2,1]False as expected. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10263505', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1117857/']} | jdg_77329 |
stackexchange | llm_judgeable_groundtruth_similarity | 9619 |
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:
In the documentation for fold, it says Fold[f,x,list] gives the last element of FoldList[f,x,list]. But this is surely not the way it is implemented, right? In those cases where each step of the Fold returns a large object, it would be a huge waste of memory to actually store the whole list and then just pick the last element at the end. How can I test this? Does Trace work as advertised, or does it skip printing intermediate steps sometimes?
Now provide the response and nothing else.
| It's quite easy to show that Fold doesn't use the memory that would be required to store intermediate results. $HistoryLength = 0;big = Range[1*^7];ByteCount[big]MaxMemoryUsed[] //N 40000124 5.49458*10^ 7 Fold[# + 1 &, big, Range@100];MaxMemoryUsed[] //N 1.34909*10^ 8 FoldList by comparison (with a much shorter Range ): FoldList[# + 1 &, big, Range@30];MaxMemoryUsed[] //N 2.49489*10^ 9 | {} | {'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/9619', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1167/']} | jdg_77330 |
stackexchange | llm_judgeable_groundtruth_similarity | 368742 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose I have a method that takes an object of some kind as an argument. Now say that if this method is passed a null argument, it's a fatal error and an exception should be thrown. Is it worth it for me to code something like this (keeping in mind this is a trivial example): void someMethod(SomeClass x){ if (x == null){ throw new ArgumentNullException("someMethod received a null argument!"); } x.doSomething();} Or is it safe for me to just rely on it throwing NullException when it calls x.doSomething()? Secondly, suppose that someMethod is a constructor and x won't be used until another method is called. Should I throw the exception immediately or wait until x is needed and throw the exception then?
Now provide the response and nothing else.
| I prefer the ArgumentNullException over the NullReferenceException that not checking the argument would provide. In general, my preference is to always check for nullity before trying to invoke a method on a potentially null object. If the method is a constructor, then it would depend on a couple of different factors: is there also a public setter for the property and how likely is it that the object will actually be used. If there is a public setter, then not providing a valid instance via the constructor would be reasonable and should not result in an exception. If there is no public setter and it is possible to use the containing object without referencing the injected object, you may want to defer the checking/exception until its use is attempted. I would think that the general case, though, would be that injected object is essential to the functioning of the instance and thus an ArgumentNull exception is perfectly reasonable since the instance can't function without it. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/368742', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2147/']} | jdg_77331 |
stackexchange | llm_judgeable_groundtruth_similarity | 7212 |
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:
I am wondering why the following does not plot the way it's written and exactly how does the Do[] function operate? I think I could be using it incorrectly. In[1]:= u[x_, t_] := (1/2) (Exp[-(x + t)^2] + Exp[-(x - t)^2]) Do[ Plot[u[x, k], {x, -5, 5}, AxesLabel -> {x, u}, PlotRange -> {0, 1}], {k, 0, 3} ] EDIT Clear["Global`*"]a = 1;b = 1;ϕ[ξ_, ν_, t_] := Sum[(((5*(-1 + (-1)^j)*(-1 + (-1)^i))/(j*i*Pi^2))* Cos[(1/Pi^4)*Sqrt[i^4*Pi^4 + j^4*Pi^4]*t])*Sin[i*Pi*ξ]*Sin[j*Pi*ν], {i, 1, 10}, {j, 1, 10}];Do[Print[Plot3D[ϕ[ξ, ν, m], {ξ, 0, a}, {ν, 0, b}, Mesh :> Automatic, PlotLabel :> StringJoin["Surface Plot of Solution at t = ", ToString[m]], ColorFunction :> {"BlueGreenYellow"}]], {m, 0, 10, 2}]
Now provide the response and nothing else.
| The reason is that since version 6 of Mathematica, the Plot returns its output just like any other function. It does not print is as a side effect . Do is meant to be used with operations that have side effects and simply discards the output, so you never see the plot. You can either use Table , which collects the values in a list: Note how you get a list of graphics objects. Graphics are expressions like any other, they're simply shown using a special formatting. You can always see their internal structure by using InputForm on them or pressing Ctrl - Shift - I on the containing cell. Or you can use Print explicitly: Do[Print@Plot[u[x, k], {x, -5, 5}, AxesLabel -> {x, u}, PlotRange -> {0, 1}], {k, 0, 3}] Note: If as @JM noted, you are trying to animate the plot, use Animate : Animate[Plot[u[x, k], {x, -5, 5}, AxesLabel -> {x, u}, PlotRange -> {0, 1}], {k, 0, 3, 1}] | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/7212', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/116/']} | jdg_77332 |
stackexchange | llm_judgeable_groundtruth_similarity | 9050263 |
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 develop a social networking site and I decide that I want the core of the application to be completely REST'ed. A user logs in with a password. Now, my question is does every request require password and login pairs (assuming that you need to provide your identity) at the end of URL like www.site.com/index.php?p=pass&l=login ? I would be a little nervous about asking for that at every request. I know that I am missing something… it can't be like that because anyone could snoop into packets and capture the password and login easily. I don't think having all requests done in HTTPS would make sense (I read it's taxing on resources). So please fill in the missing part that I need to understand.
Now provide the response and nothing else.
| First off, unless you know that using SSL is too expensive for you, use SSL. Security comes before performance optimizations. Now, about passing usernames and passwords: usually you have an "API access token" or the like. It's not actually the username/password, but when someone has it they're granted the ability to make API requests. These can have limited or unlimited validity as you like. You can even make the token a signature - the user signs the request with some key, and you validate the signature. But yes, since each API request is independent of the last, you're going to either have to use HTTP Basic authentication or its equivalent, or pass the API token (or other signatory device) with every request. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9050263', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/155366/']} | jdg_77333 |
stackexchange | llm_judgeable_groundtruth_similarity | 5520418 |
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 set up my domain and the LINQ statement so I can delete a record from a database? public class Category { public int CategoryId { get; set; } public string Name { get; set; } public List<Product> Products{ get; set; }}public class Product { public int ProductId { get; set; } public string Name { get; set; } public int CategoryId {get; set; } public Category Category{ get; set; }} What I'd like to do is delete Category and be able to cascade the delete to all the child products. Is there any other additional attributes needed in my domain? What is the LINQ statement to delete objects without doing a round trip? (I do not want to select, just a direct delete). Is this the only way to do this? Category category = new Category() { CategoryId = 1 } ; context.AttachTo("Category", category);context.DeleteObject(category);context.Savechanges();
Now provide the response and nothing else.
| You mentioned EF code first which means EF 4.1 but you have shown example of deleting object in EF 4. Correct approach to delete object in EF 4.1 without loading it from database is: var category = new Category() { CategoryId = 1 };context.Categories.Attach(category);context.Categories.Remove(category);context.SaveChanges(); If you didn't change anything in configuration of defalut conventions it will also delete all related products because OneToManyCascadeDeleteConventions ensures that all one-to-many relations are created with ON CASCADE DELETE . There will be no additional roundtrips to database - only single DELETE statement for Category with Id = 1. The different situation can occure if you want to delete fully loaded Category (with loaded Products navigation property) in such case EF will create separate delete statement for each Product so you will have N+1 roundtrips to database where N is number of products in category. Here is how cascade delete works in EF. It is related to entity designer but described principles are the same. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5520418', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/400861/']} | jdg_77334 |
stackexchange | llm_judgeable_groundtruth_similarity | 121168 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
How much has been the group of diffeomorphisms of a manifold " been studied.I got this information from wiki." Quite a lot is known about the group of diffeomorphisms of the circle. Its Lie algebra is (more or less) the Witt algebra, which has a central extension called the Virasoro algebra, used in string theory and conformal field theory. Very little is known about the diffeomorphism groups of manifolds of larger dimension. The diffeomorphism group of spacetime sometimes appears in attempts to quantize gravity." .What more is known about this?Has this group been calculated for the standard manifolds.Since this group is a big group,so what are the better ways of studying this object.
Now provide the response and nothing else.
| One can approach the study of diffeomorphism groups from many perspectives: topology, geometry, differential equations, and dynamics. I'll mention a few results that I'm aware of, giving links to literature surveys on different topics. There is a short exact sequence $$Diff_0(M)\to Diff(M)\to MCG(M),$$ where $Diff_0(M)$ is the subgroup of diffeomorphisms isotopic to the identity. One can regard $MCG(M)=\pi_0(Diff(M))$ .There is a huge literature studying $MCG(M)$ , especially when $M$ is a surface. One question that has been answered for closed surfaces is that there is no section $Diff(M)\leftarrow MCG(M)$ . I'm not sure what's known about the higher-dimensional version of this question. Topologists study the homotopy type of $Diff(M)$ , which breaks down into computing $MCG(M)$ and the homotopy type of $Diff_0(M)$ . Hatcher has a survey on the homotopy type of $Diff(M)$ . This has more-or-less been completely resolved in dimensions $\leq 3$ , but is quite complex for general higher dimensional manifolds. It is known that $Diff_0(M)$ is simple for closed manifolds by a result of Thurston.A general strategy then for understanding the group structure of $Diff_0(M)$ is to understand its subgroups. One aspect of this is the Zimmer program , to understand homomorphisms $\Lambda\to Diff_0(M)$ , where $\Lambda$ is a higher rank lattice. Another aspect is to consider homomorphisms between diffeomorphism groups for different manifolds. There are some results on dynamics of diffeomorphisms with relation to the diffeomorphism group. There is a huge literature on the dynamics of individual diffeomorphisms, but I think this is orthogonal to your question. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/121168', 'https://mathoverflow.net', 'https://mathoverflow.net/users/30081/']} | jdg_77335 |
stackexchange | llm_judgeable_groundtruth_similarity | 27415935 |
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 read many articles in order to know what is the maximum number of the Unicode code points, but I did not find a final answer. I understood that the Unicode code points were minimized to make all of the UTF-8 UTF-16 and UTF-32 encodings able to handle the same number of code points. But what is this number of code points? The most frequent answer I encountered is that Unicode code points are in the range of 0x000000 to 0x10FFFF (1,114,112 code points) but I have also read in other places that it is 1,112,114 code points. So is there a one number to be given or is the issue more complicated than that?
Now provide the response and nothing else.
| The maximum valid code point in Unicode is U+10FFFF, which makes it a 21-bit code set (but not all 21-bit integers are valid Unicode code points; specifically the values from 0x110000 to 0x1FFFFF are not valid Unicode code points). This is where the number 1,114,112 comes from: U+0000 .. U+10FFFF is 1,114,112 values. However, there are also a set of code points that are the surrogates for UTF-16. These are in the range U+D800 .. U+DFFF. This is 2048 code points that are reserved for UTF-16. 1,114,112 - 2,048 = 1,112,064 There are also 66 non-characters. These are defined in part in Corrigendum #9 : 34 values of the form U+nFFFE and U+nFFFF (where n is a value 0x00000, 0x10000, … 0xF0000, 0x100000), and 32 values U+FDD0 - U+FDEF. Subtracting those too yields 1,111,998 allocatable characters. There are three ranges reserved for 'private use': U+E000 .. U+F8FF, U+F0000 .. U+FFFFD, and U+100000 .. U+10FFFD. And the number of values actually assigned depends on the version of Unicode you're looking at. You can find information about the latest version at the Unicode Consortium . Amongst other things, the Introduction there says: The Unicode Standard, Version 7.0, contains 112,956 characters So only about 10% of the available code points have been allocated. I can't account for why you found 1,112,114 as the number of code points. Incidentally, the upper limit U+10FFFF is chosen so that all the values in Unicode can be represented in one or two 2-byte coding units in UTF-16, using one high surrogate and one low surrogate to represent values outside the BMP or Basic Multilingual Plane, which is the range U+0000 .. U+FFFF. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/27415935', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_77336 |
stackexchange | llm_judgeable_groundtruth_similarity | 279487 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In bash, I notice that if a command using redirection would fail, any programs which run prior to that are not run. For example, this program opens the file "a" and writes 50 bytes to file "a". However, running this command with redirection to a file with insufficient permissions (~root/log), yields no change in file size of "a". $ ./write_file.py >> ~root/log-bash: /var/root/log: Permission deniedcdal at Mac in ~/experimental/unix_write$ ls -lttotal 16-rw-rw-r-- 1 cdal staff 0 Apr 27 08:54 a <-- SHOULD BE 50 BYTES One would think the program would run, capture any output (but also write to the file "a"), and then fail to write any output to ~root/log. Instead the program is never run. Why is this, and how does bash choose the order of the "checks" it performs prior to executing a program? Are other checks performed as well? p.s. I'm trying to determine whether a program run under cron actually ran when redirected to a "permission denied" file.
Now provide the response and nothing else.
| It's not really a question of ordering checks, simply the order in which the shell sets things up. Redirections are set up before the command is run; so in your example, the shell tries to open ~root/log for appending before trying to do anything involving ./write_file.py . Since the log file can't be opened, the redirection fails and the shell stops processing the command line at that point. One way to demonstrate this is to take a non-executable file and attempt to run it: $ touch demo$ ./demozsh: permission denied: ./demo$ ./demo > ~root/logzsh: permission denied: /root/log This shows that the shell doesn't even look at ./demo when the redirection can't be set up. | {} | {'log_upvote_score': 5, 'links': ['https://unix.stackexchange.com/questions/279487', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/167848/']} | jdg_77337 |
stackexchange | llm_judgeable_groundtruth_similarity | 13723790 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have this code, when I try to get not existed culture I get exception. Is there exists method like TryGetCultureInfo , which return bool value? I don't want to use try-catch statement CultureInfo culture = CultureInfo.GetCultureInfo(cultureCode);if (culture == null){ culture = CultureInfo.GetCultureInfo(DefaultCultureCode);}
Now provide the response and nothing else.
| I think there's no such method. So you could just try-catch or check all installed cultures: string cultureCode = "de-DE";CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.AllCultures & ~CultureTypes.NeutralCultures);var culture = cultures.FirstOrDefault(c => c.Name.Equals(cultureCode, StringComparison.OrdinalIgnoreCase));if (culture == null){ culture = cultures.FirstOrDefault(c => c.Name.Equals(DefaultCultureCode, StringComparison.OrdinalIgnoreCase)); if (culture == null) culture = CultureInfo.CurrentCulture;} But i would prefer the try-catch , i'm sure it is more efficient. public bool TryGetCultureInfo(string cultureCode, string DefaultCultureCode, out CultureInfo culture){ try { culture = CultureInfo.GetCultureInfo(cultureCode); return true; } catch(CultureNotFoundException) { if (DefaultCultureCode == null) culture = CultureInfo.CurrentCulture; else { try { culture = CultureInfo.GetCultureInfo(DefaultCultureCode); } catch (CultureNotFoundException) { culture = CultureInfo.CurrentCulture; } } } return false;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13723790', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/650148/']} | jdg_77338 |
stackexchange | llm_judgeable_groundtruth_similarity | 1846647 |
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 change the content of the main surface (the stuff below the ribbon itself)in a WPF application when a ribbon tab is clicked. I'm using the office ribbon, not that is matters much. So which WPF container control should I use, and how would I do it? Should I just have various controls with visibility hidden, or what. I'm not a WPF expert so I need a little inspiration.
Now provide the response and nothing else.
| Ill preface by saying I doubt this is the best way to do this. This is my style for RibbonTab notice IsSelected is bound to IsSelected in The view model <!-- RibbonTab --> <Style TargetType="{x:Type ribbon:RibbonTab}"> <Setter Property="ContextualTabGroupHeader" Value="{Binding ContextualTabGroupHeader}" /> <Setter Property="Header" Value="{Binding Header}" /> <Setter Property="ItemsSource" Value="{Binding GroupDataCollection}" /> <Setter Property="IsSelected" Value="{Binding IsSelected}" /> </Style> This is view model code public bool IsSelected { get { return _isSelected; } set { if (_isSelected != value) { _isSelected = value; OnPropertyChanged(new PropertyChangedEventArgs("IsSelected")); } } } private bool _isSelected; In the constructor for the TabViewModel I take a parameter for the ViewModel of the content public TabData(ISelectedContentTab content) : this(content.DisplayName) { _selectedContent = content; } private ISelectedContentTab _selectedContent; Then I used an ItemsControl to display the selected content in my xaml <ItemsControl Grid.Row="1" VerticalContentAlignment="Stretch" VerticalAlignment="Stretch" ItemsSource="{Binding ElementName=ribbon,Path=SelectedItems}" ItemTemplate="{StaticResource ContentControlTemplate}" /> And the ContentControlTemplate I have is <DataTemplate x:Key="ContentControlTemplate"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> </Grid.RowDefinitions> <ContentControl Grid.Row="0" VerticalAlignment="Stretch" Height="Auto" VerticalContentAlignment="Stretch" Content="{Binding SelectedContent}" /> </Grid> </DataTemplate> Also make sure you have a datatemplate pointing your content to a view Hope this helps. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1846647', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/218589/']} | jdg_77339 |
stackexchange | llm_judgeable_groundtruth_similarity | 337937 |
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:
Can you please explain why$$\sum_{k=1}^{\infty} \dfrac{k}{2^k} =\dfrac{1}{2} +\dfrac{ 2}{4} + \dfrac{3}{8}+ \dfrac{4}{16} +\dfrac{5}{32} + \dots =2$$ I know $1 + 2 + 3 + ... + n = \dfrac{n(n+1)}{2}$
Now provide the response and nothing else.
| \begin{gather*}|x|<1:\quad f(x)=\sum_{n=1}^{\infty} x^n=\frac{x}{1-x} \\xf'(x)=\sum_{n=1}^{\infty} nx^n=\frac{x}{(1-x)^2}\end{gather*} Let $x=\frac{1}{2}$ | {} | {'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/337937', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/68022/']} | jdg_77340 |
Subsets and Splits