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 | 808176 |
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 to show that the Volterra operator: $$V:L_2(0,1)\rightarrow L_2(0,1): x\mapsto \int^t_0 x(s) \, ds$$ is not normal. $t\in (0,1)$ Could you please help with this question.
Now provide the response and nothing else.
| From this answer we know that$$V^*(x)(t)=\int_t^1 x(s)\,ds$$Using Fubini theorem you can chek that$$VV^*(x)(t)=\int_0^t\int_s^1x(\tau)\,d\tau \,ds=\int_0^t\int_0^\tau x(\tau) \,ds\,d\tau=\int_0^t x(\tau)\int_0^\tau \, ds\,d\tau=\int_0^t \tau x(\tau)\,d\tau$$$$V^*V(x)(t)=\int_t^1\int_0^s x(\tau)\,d\tau \,ds=\int_0^t\int_t^1 x(\tau) \,ds \,d\tau + \int_t^1\int_\tau^1 x(\tau) \,ds \,d\tau\\=(1-t)\int_0^t x(\tau) \,d\tau + \int_t^1(1-\tau) x(\tau) \,d\tau$$So $VV^*\neq V^*V$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/808176', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/104078/']} | jdg_381241 |
stackexchange | llm_judgeable_groundtruth_similarity | 44739 |
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Here's the reaction: $\ce{H2SO4(aq) + CaCO3(s) -> CaSO4(s) + H2O(l) + CO2(g)}$ I don't understand why calcium carbonate decomposes in sulphuric acid. It's not soluble in water. I could understand the hydrogen ions oxidizing the calcium, yet the reaction isn't a redox reaction; the oxidation states remain the same!
Now provide the response and nothing else.
| I don't understand why calcium carbonate decomposes... It's not soluble in water. It's more soluble in water than you might think. If it weren't soluble, we wouldn't have awesome things such as stalagmites in caves. Calcium sulfate is more soluble in water than the carbonate, but that isn't saying much. It's solubility is only about $\pu{2 g/L}$. So writing the product as $\ce{CaSO4(s)}$ is only correct if you are talking about dilute solutions. Anything too concentrated would decompose to form precipitated calcium sulfate. I could understand the hydrogen ions oxidizing the calcium... Now that would be a very curious reaction. The calcium in calcium carbonate is already in the +2 oxidation state. Calcium has only two valence electrons and further oxidation would require disrupting an intact octet. It would be very unfavorable. $\ce{Ca^{2+} -> Ca^{3+} + e-}$ would be far too unfavorable a reaction for protons to carry out. $\ce{Ca^{3+}}$ would be a much stronger oxidant than aqueous protons. Why does calcium carbonate decompose in sulphuric acid? The decomposition can still happen even with insoluble, solid-phase calcium carbonate because reactions can happen at surfaces. An acidic proton could be attacked by a solid-phase carbonate ion at the crystal surface, forming bicarbonate. The bicarbonate could attack another acidic proton, forming a surface-bound $\ce{H2CO3}$ molecule, which could spontaneously transform into $\ce{CO2}$ and water, which would be very loosely bound to the surface, allowing them to escape and exposing fresh not-yet-reacted calcium carbonate molecules to the aqueous surface, and the process begins anew... | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/44739', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/25053/']} | jdg_381242 |
stackexchange | llm_judgeable_groundtruth_similarity | 5437723 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here's an issue with IIS 7.5 and ASP.NET that I've been researching and getting nowhere with. Any help would be greatly appreciated. My question is: using ASP.NET in IIS 7.5, how does IIS and/or the operating system allow the web application to write to a folder like C:\dump when running under full trust? How is it that I don't have to explicitly add write access for the application pool user (in this case ApplicationPoolIdentity )? This much I know: In IIS 7.5, the default Identity for an Application Pool is ApplicationPoolIdentity . ApplicationPoolIdentity represents a Windows user account called "IIS APPPOOL\AppPoolName", which is created when the Application Pool is created, where AppPoolName is the name of the Application Pool. The "IIS APPPOOL\AppPoolName" user is by default a member of the IIS_IUSRS group. If you are running under Full Trust, your web application can write to many areas of the file system (excluding folders like C:\Users , C:\Windows , etc). For example, your application will have access to write to some folders, like, C:\dump . By default, the IIS_IUSRS group is not given read or write access to C:\dump (at least not access that is visible through the "Security" tab in Windows Explorer). If you deny write access to IIS_IUSRS , you will get a SecurityException when trying to write to the folder (as expected). So, taking all of that into account, how is write access granted to the "IIS APPPOOL\AppPoolName" user? The w3wp.exe process runs as this user, so what allows this user to write to a folder it doesn't seem to have explicit access to? Please note that I understand this was probably done for the sake of convenience, since it would be a pain to grant a user access to every folder it needs to write to if you are running under Full Trust. If you want to limit this access, you can always run the application under Medium Trust. I am interested in finding out about the way the operating system and/or IIS allows these writes to take place, even though there appears to be no explicit file system access granted.
Now provide the response and nothing else.
| The ApplicationPoolIdentity is assigned membership of the Users group as well as the IIS_IUSRS group. On first glance this may look somewhat worrying, however the Users group has somewhat limited NTFS rights. For example, if you try and create a folder in the C:\Windows folder then you'll find that you can't. The ApplicationPoolIdentity still needs to be able to read files from the windows system folders (otherwise how else would the worker process be able to dynamically load essential DLL's). With regard to your observations about being able to write to your c:\dump folder. If you take a look at the permissions in the Advanced Security Settings, you'll see the following: See that Special permission being inherited from c:\ : That's the reason your site's ApplicationPoolIdentity can read and write to that folder. That right is being inherited from the c:\ drive. In a shared environment where you possibly have several hundred sites, each with their own application pool and Application Pool Identity, you would store the site folders in a folder or volume that has had the Users group removed and the permissions set such that only Administrators and the SYSTEM account have access (with inheritance). You would then individually assign the requisite permissions each IIS AppPool\[name] requires on it's site root folder. You should also ensure that any folders you create where you store potentially sensitive files or data have the Users group removed. You should also make sure that any applications that you install don't store sensitive data in their c:\program files\[app name] folders and that they use the user profile folders instead. So yes, on first glance it looks like the ApplicationPoolIdentity has more rights than it should, but it actually has no more rights than it's group membership dictates. An ApplicationPoolIdentity 's group membership can be examined using the SysInternals Process Explorer tool . Find the worker process that is running with the Application Pool Identity you're interested in (you will have to add the User Name column to the list of columns to display: For example, I have a pool here named 900300 which has an Application Pool Identity of IIS APPPOOL\900300 . Right clicking on properties for the process and selecting the Security tab we see: As we can see IIS APPPOOL\900300 is a member of the Users group. | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/5437723', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/342113/']} | jdg_381243 |
stackexchange | llm_judgeable_groundtruth_similarity | 12359 |
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Given $k$ numbers $A_1 \leq A_2 \leq ... \leq A_k$ such that $\sum\limits_{i=1}^k A_i = k(2k + 1)$ is there an assignment of numbers $i_1, i_2, ... , i_{2k}$ which is a permutation of $1, 2, ... , 2k$ such that $i_1 + i_2 \leq A_1\\ i_3 + i_4 \leq A_2\\ .\\.\\.\\ i_{2k-1} + i_{2k} \leq A_k$ ? I cannot find an efficient algorithm and that solves this problem. It seems to be a combinatorial problem. I was unable to find a similar NP-Complete problem. Does this problem look like a known NP-Complete problem or can it be solved with a polynomial algorithm?
Now provide the response and nothing else.
| This problem is strongly NP-complete. Suppose all the $A_j$ are odd. Then we know that since $i_{2j-1} + i_{2j} = A_j$ is odd, one of $i_{2j-1}$ and $i_{2j}$ is even and the other is odd. We can assume that $i_{2j-1}$ is odd and $i_{2j}$ is even. By letting $\pi_j = \frac{1}{2}(i_{2j-1}+1)$ and $\sigma_j = \frac{1}{2}(i_{2j})$, we can show that this is equivalent to asking for two permutations, $\pi$ and $\sigma$, of the numbers $1 \ldots n$ such that $\pi_j + \sigma_j = \frac{1}{2}(A_j+1)$. This problem is known to be NP-complete; see this cstheory.se problem and this paper of W. Yu, H. Hoogeveen, and J. K. Lenstra referenced in the answer. | {} | {'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/12359', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/512/']} | jdg_381244 |
stackexchange | llm_judgeable_groundtruth_similarity | 31423462 |
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 wondering if it is possible to do something like this with css gradients: I have searched a lot and all the gradients are either "Linear" or "Radial". My desired gradient is linear in a circular way!
Now provide the response and nothing else.
| -- Updated with information from early 2022 -- It's doable now - at least with most browsers. The CSS property conic-gradient can easily achieve this: html, body { margin: 0; padding: 0; }.box { position: absolute; width: 200px; height: 200px; left: 100px;}.colorwheel { background: conic-gradient(red, yellow, lime, aqua, blue, magenta, red); border-radius:50%;}.fallback { text-align: center; padding: 50px 0;} <div class="fallback box"> If you can read<br>this, your browser<br>doesn't support<br>conic-gradient yet.</div><div class="colorwheel box"></div> This CSS function is specified in an editor's draft of CSS Images Module Level 4 and is currently implement by most browsers including many mobile browsers. Check Can I use for current support. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31423462', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5118146/']} | jdg_381245 |
stackexchange | llm_judgeable_groundtruth_similarity | 2873254 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was studying the legacy API's in the Java's Collection Framework and I learnt that classes such as Vector and HashTable have been superseded by ArrayList and HashMap . However still they are NOT deprecated, and deemed as legacy when essentially, deprecation is applied to software features that are superseded and should be avoided, so, I am not sure when is a API deemed legacy and when it is deprecated.
Now provide the response and nothing else.
| From the official Sun glossary: deprecation : Refers to a class, interface, constructor, method or field that is no longer recommended, and may cease to exist in a future version. From the how-and-when to deprecate guide: You may have heard the term, "self-deprecating humor," or humor that minimizes the speaker's importance. A deprecated class or method is like that. It is no longer important. It is so unimportant, in fact, that you should no longer use it, since it has been superseded and may cease to exist in the future. The @Deprecated annotation went a step further and warn of danger: A program element annotated @Deprecated is one that programmers are discouraged from using, typically because it is dangerous , or because a better alternative exists. References java.sun.com Glossary Language guide/How and When to Deprecate APIs Annotation Type Deprecated API Note that the official glossary does not define what "legacy" means. In all likelihood, it may be a term that Josh Bloch used without an exact definition. The implication, though, is always that a legacy class should never be used in new code, and better replacement exists. Perhaps an old code using legacy but non-deprecated class requires no action, since for now at least, they aren't in danger of ceasing to exist in future version. In contrast, deprecation explicitly warns that they may cease to exist, so action should be taken to migrate to the replacement. Quotes from Effective Java 2nd Edition For comparison on how these terms are used in context, these are quotes from the book where the word "deprecated" appears: Item 7: Avoid finalizers : The only methods that claim to guarantee finalization are System.runFinalizersOnExit and its evil twin Runtime.runFinalizersOnExit . These methods are fatally flawed and have been deprecated. Item 66: Synchronize access to shared mutable data : The libraries provide the Thread.stop method, but this method was deprecated long ago because it's inherently unsafe -- its use can result in data corruption. Item 70: Document thread safety : The System.runFinalizersOnExit method is thread-hostile and has been deprecated. Item 73: Avoid thread groups : They allow you to apply certain Thread primitives to a bunch of threads at once. Several of these primitives have been deprecated, and the remainder are infrequently used. [...] thread groups are obsolete. By contrast, these are the quotes where the word "legacy" appears: Item 23: Don't use raw types in new code : They are provided for compatibility and interoperability with legacy code that predates the introduction of generics. Item 25: Prefer lists to arrays : Erasure is what allows generic types to interoperate freely with legacy code that does not use generics. Item 29: Consider typesafe heterogeneous containers : These wrappers are useful for tracking down who adds an incorrectly typed element to a collection in an application that mixes generic and legacy code. Item 54: Use native methods judiciously : They provide access to libraries of legacy code, which could in turn provide access to legacy data. [...] It is also legitimate to use native methods to access legacy code. [...] If you must use native methods to access low-level resources or legacy libraries, use as little native code as possible and test it thoroughly. Item 69: Prefer concurrency utilities to wait and notify : While you should always use the concurrency utilities in preference to wait and notify , you might have to maintain legacy code that uses wait and notify . These quotes were not carefully selected: they're ALL instances where the word "deprecated" and "legacy" appear in the book. Bloch's message is clear here: Deprecated methods, e.g. Thread.stop , are dangerous, and should never be used at all. On the other hand, e.g. wait/notify can stay in legacy code, but should not be used in new code. My own subjective opinion My interpretation is that deprecating something is admitting that it is a mistake, and was never good to begin with. On the other hand, classifying that something is a legacy is admitting that it was good enough in the past, but it has served its purpose and is no longer good enough for the present and the future. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2873254', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1140524/']} | jdg_381246 |
stackexchange | llm_judgeable_groundtruth_similarity | 368267 |
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:
Find all functions satisfying $f(2x)=2f'(x)f(x)$ Under given condition, can't we find explicit solutions?
Now provide the response and nothing else.
| If one restrict oneself to functions which admit a power series expansion at $x = 0$,following is the list of solutions I found: $$f(x) = \begin{cases}0, & f(0) = 0, f'(0) = 0,\\k \sin(x/k), & f(0) = 0, f'(0) = 1, f'''(0) < 0\\x, & f(0) = 0, f'(0) = 1, f'''(0) = 0\\k \sinh(x/k), & f(0) = 0, f'(0) = 1, f'''(0) > 0\\k \exp(x/2k), & f(0) \ne 0, f'(0) = \frac12\\\end{cases}$$ where $k$ is a non-zero constant. Let $f(x) = a_0 + a_1 x + a_2 x^2 + a_3 x^3 + \cdots$. In terms of $a_n$, the function equation becomes: $$\begin{align}a_0 &= 2 ( a_1 a_0 )\tag{*0}\\2\,a_1 &= 2 ( 2 a_2 a_0 + a_1 a_1 )\tag{*1}\\2^2 a_2 &= 2 ( 3 a_3 a_0 + 2 a_2 a_1 + a_1 a_2 )\\2^3 a_3 &= 2 ( 4 a_4 a_0 + 3 a_3 a_1 + 2 a_2 a_2 + a_1 a_3 )\\2^4 a_4 &= 2 ( 5 a_5 a_0 + 4 a_4 a_1 + 3 a_3 a_2 + 2 a_2 a_3 + a_1 a_4)\\2^5 a_5 &= 2 ( 6 a_6 a_0 + 5 a_5 a_1 + 4 a_4 a_2 + 3 a_3 a_3 + 2 a_2 a_4 + a_1 a_5 )\\&\;\vdots\end{align}$$ The first thing we notice is $(*0)$ implies: $$a_0 (1 - 2a_1) = 0 \implies a_0 = 0 \quad\text{ or }\quad a_1 = \frac12$$ If $a_0 = 0$, then $(*1)$ implies $a_1 = 0$ or $1$. It is easy to see $a_1 = 0$ will lead us to $f(x) \equiv 0$. So let us assume $a_1 = 1$. The set of equations become:$$\begin{align}( 2^1 - 3 ) a_2 &= 0\\( 2^2 - 4 ) a_3 &= 2 a_2 a_2 \iff 0 = 0 \text{ ( i.e. } a_3\;\text{ is arbitrary )}\\( 2^3 - 5 ) a_4 &= 3 a_3 a_2 + 2 a_2 a_3\\( 2^4 - 6 ) a_5 &= 4 a_4 a_2 + 3 a_3 a_3 + 2 a_2 a_4\\&\;\vdots\end{align}$$It is then easy to see: $a_n = 0$ for all even $n$. $a_3$ is arbitrary. once $a_3$ is fixed, $a_n$ is recursively fixed for all odd $n > 3$. Depends on the sign of $a_3$, it leads us to solutions of the form $k \sin(x/k), x $ or k sinh(x/k)$. If $a_0 \ne 0$, then $a_1 = \frac12$ and the set of equations becomes: $$\begin{align}2 a_2 a_0 &= 2^0\,a_1 - ( a_1 a_1 )\tag{*1}\\3 a_3 a_0 &= 2^1 a_2 - ( 2 a_2 a_1 + a_1 a_2 )\\4 a_4 a_0 &= 2^2 a_3 - ( 3 a_3 a_1 + 2 a_2 a_2 + a_1 a_3 )\\5 a_5 a_0 &= 2^3 a_4 - ( 4 a_4 a_1 + 3 a_3 a_2 + 2 a_2 a_3 + a_1 a_4)\\&\;\vdots\end{align}$$It is easy to see these will recursively fix the values of $a_n$ for all $n > 1$. This lead us to the $k \exp(x/2k)$ solution. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/368267', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/45070/']} | jdg_381247 |
stackexchange | llm_judgeable_groundtruth_similarity | 7300072 |
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 seen two basic ways of setting up a tkinter program. Is there any reason to prefer one to the other? from Tkinter import *class Application(): def __init__(self, root, title): self.root = root self.root.title(title) self.label = Label(self.root, text='Hello') self.label.grid(row=0, column=0) root = Tk()app = Application(root, 'Sample App')root.mainloop() and from Tkinter import *class Application(Frame): def __init__(self, title, master=None): Frame.__init__(self, master) self.grid() self.master.title(title) self.label = Label(self, text='Hello') self.label.grid(row=0, column=0) app = Application('Sample App')app.mainloop()
Now provide the response and nothing else.
| The option I prefer* is to inherit from the class Tk. I think it is the more reasonable choice since the window is, in effect, your application. Inheriting from Frame doesn't make any more sense to me then inheriting from Button or Canvas or Label . Since you can only have a single root, it makes sense that that is what you inherit from. I also think it makes the code more readable if you do the import as import Tkinter as tk rather than from Tkinter import * . All of your calls then explicitly mention the tk module. I don't recommend this for all modules, but to me it makes sense with Tkinter. For example: import Tkinter as tkclass SampleApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.label = tk.Label(text="Hello, world") self.label.pack(padx=10, pady=10)app = SampleApp()app.mainloop() * Note: since originally writing this answer I have changed my position. I now prefer to inherit from Frame rather than Tk . There's no real advantage one way or the other, it's more of a philosophical choice than anything else. Regardless, I believe that whether you inherit from Frame or Tk , I think either choice is better than the first example in the code that inherits from nothing. The one slight advantage inheriting from Frame has over Tk is in the case where you want your application to support multiple identical windows. In that case, inheriting from Frame lets you create the first window as a child of root, and additional windows as children of instances of Toplevel . However, I've seen very few programs that ever have a need to do this. For more information about how I think Tkinter programs should be structured, see my answer to the question Python Tkinter program structure . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7300072', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/173922/']} | jdg_381248 |
stackexchange | llm_judgeable_groundtruth_similarity | 7920128 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Given an example like this: class MyForm(forms.Form): name = forms.CharField() I'm trying to grasp what the difference between the following two snippets is: "Bound Data" style: my_form = MyForm({'name': request.user.first_name}) "Initial data" style: my_form = MyForm(initial={'name': request.user.first_name}) The documentation seems to suggest than "initial is for dynamic initial values", and yet being able to pass "bound data" to the constructor accomplishes exactly the same thing. I've used initial data in the past for dynamic values, but I'm tempted to use the more straightforward "bound data" style, but would like some insights about what the real difference between these two styles is.
Now provide the response and nothing else.
| Here's the key part from the django docs on bound and unbound forms . A Form instance is either bound to a set of data, or unbound : If it’s bound to a set of data, it’s capable of validating that data and rendering the form as HTML with the data displayed in the HTML. If it’s unbound , it cannot do validation (because there’s no data to validate!), but it can still render the blank form as HTML. You can't really see the difference for the example form you gave, because the form is valid in the "bound data" style. Let's extend the form by adding an age field, then the difference will be more obvious. class MyForm(forms.Form): name = forms.CharField() age = forms.IntegerField() Bound form my_form = MyForm({'name': request.user.first_name}) This form is invalid, because age is not specified. When you render the form in the template, you will see validation errors for the age field. Unbound form with dynamic initial data my_form = MyForm(initial={'name':request.user.first_name}) This form is unbound. Validation is not triggered, so there will not be any errors displayed when you render the template. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7920128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/66289/']} | jdg_381249 |
stackexchange | llm_judgeable_groundtruth_similarity | 20428709 |
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 set my own custom similarity in my solr schema.xml but i have a few problems with understanding this feature.I want to completely deactivate solr scoring (tf,idf,coord and fieldNorm). I dont know where to start. Things i know I have to write my own DefaultSimilarity implementation. Override the (tf,idf,coord and fieldNorm) - methods. Load the class in schem.xml Where to store the class ?Are there any working examples in the web ? I cant find one! THANKS
Now provide the response and nothing else.
| I figured it out on my own. I have stored my own implementation of DefaultSimilarity under /dist/ folder in solr. Then i add <lib dir="../../../dist/org/apache/lucene/search/similarities/" regex=".*\.jar"/> to my solrconfig.xml and everything works fine. package org.apache.lucene.search.similarities;import org.apache.lucene.index.FieldInvertState;import org.apache.lucene.search.similarities.DefaultSimilarity;public class MyNewSimilarityClass extends DefaultSimilarity {@Overridepublic float coord(int overlap, int maxOverlap) { return 1.0f;}@Overridepublic float idf(long docFreq, long numDocs) { return 1.0f;}@Overridepublic float lengthNorm(FieldInvertState arg0) { return 1.0f;}@Overridepublic float tf(float freq) { return 1.0f;}} Gist: https://gist.github.com/FabianKoestring/7846845 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20428709', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/625681/']} | jdg_381250 |
stackexchange | llm_judgeable_groundtruth_similarity | 4132829 |
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 have a WPF DataGrid with a horizontal orientation, does anyone know a solution?
Now provide the response and nothing else.
| I've done this earlier since we wanted to be able to use the same control for a DataGrid and a PropertyGrid . Alot of things have to be changed (like alignment, scrolling, positioning of sort-arrows etc.). There is way to much code to post the whole solution but this should get you started. This is an example with Autogenerated TextColumns but you can easily modify it to use other column types. <ScrollViewer Name="c_dataGridScrollViewer" Loaded="c_dataGridScrollViewer_Loaded" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"> <DataGrid x:Name="c_dataGrid" HorizontalAlignment="Left" VerticalAlignment="Top" AutoGeneratedColumns="c_dataGrid_AutoGeneratedColumns" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"> <DataGrid.ColumnHeaderStyle> <Style TargetType="{x:Type DataGridColumnHeader}"> <Setter Property="LayoutTransform"> <Setter.Value> <TransformGroup> <RotateTransform Angle="90"/> </TransformGroup> </Setter.Value> </Setter> </Style> </DataGrid.ColumnHeaderStyle> <DataGrid.LayoutTransform> <TransformGroup> <RotateTransform Angle="-90"/> </TransformGroup> </DataGrid.LayoutTransform> </DataGrid></ScrollViewer> And when the Columns are generated, we reverse their positions and rotates the TextBlocks and TextBoxes (This is better than rotating the DataGridCell in terms of alignment, blur etc.) private void c_dataGridScrollViewer_Loaded(object sender, RoutedEventArgs e){ // Add MouseWheel support for the datagrid scrollviewer. c_dataGrid.AddHandler(MouseWheelEvent, new RoutedEventHandler(DataGridMouseWheelHorizontal), true);}private void DataGridMouseWheelHorizontal(object sender, RoutedEventArgs e){ MouseWheelEventArgs eargs = (MouseWheelEventArgs)e; double x = (double)eargs.Delta; double y = c_dataGridScrollViewer.VerticalOffset; c_dataGridScrollViewer.ScrollToVerticalOffset(y - x);}private void c_dataGrid_AutoGeneratedColumns(object sender, EventArgs e){ TransformGroup transformGroup = new TransformGroup(); transformGroup.Children.Add(new RotateTransform(90)); foreach (DataGridColumn dataGridColumn in c_dataGrid.Columns) { if (dataGridColumn is DataGridTextColumn) { DataGridTextColumn dataGridTextColumn = dataGridColumn as DataGridTextColumn; Style style = new Style(dataGridTextColumn.ElementStyle.TargetType, dataGridTextColumn.ElementStyle.BasedOn); style.Setters.Add(new Setter(TextBlock.MarginProperty, new Thickness(0, 2, 0, 2))); style.Setters.Add(new Setter(TextBlock.LayoutTransformProperty, transformGroup)); style.Setters.Add(new Setter(TextBlock.HorizontalAlignmentProperty, HorizontalAlignment.Center)); Style editingStyle = new Style(dataGridTextColumn.EditingElementStyle.TargetType, dataGridTextColumn.EditingElementStyle.BasedOn); editingStyle.Setters.Add(new Setter(TextBox.MarginProperty, new Thickness(0, 2, 0, 2))); editingStyle.Setters.Add(new Setter(TextBox.LayoutTransformProperty, transformGroup)); editingStyle.Setters.Add(new Setter(TextBox.HorizontalAlignmentProperty, HorizontalAlignment.Center)); dataGridTextColumn.ElementStyle = style; dataGridTextColumn.EditingElementStyle = editingStyle; } } List<DataGridColumn> dataGridColumns = new List<DataGridColumn>(); foreach (DataGridColumn dataGridColumn in c_dataGrid.Columns) { dataGridColumns.Add(dataGridColumn); } c_dataGrid.Columns.Clear(); dataGridColumns.Reverse(); foreach (DataGridColumn dataGridColumn in dataGridColumns) { c_dataGrid.Columns.Add(dataGridColumn); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4132829', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/121122/']} | jdg_381251 |
stackexchange | llm_judgeable_groundtruth_similarity | 902407 |
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:
Exercise Let $f:G \to G'$ be an isomorphism and let $H\unlhd G$. If $H'=f(H)$, prove that $G/H \cong G'/H'$. As I've shown that $H'\unlhd G'$, I thought of defining $$\phi(Ha)=H'f(a)$$I was trying to show that this function is well defined and that it is an isomorphism. I'll work with right cosets (which, since $H$ and $H'$ are normal, it's the same as working with left cosets). I need to know if what I did is correct and I would appreciate some help to show injectivity (maybe the $\phi$ I've defined is not the correct one). So, what I mean by well-defined is that if $Ha=Ha'$, then $H'f(a)=H'f(a')$. It will be sufficient to show that $f(a)f(a')^{-1} \in H'$; by hypothesis, we have $aa'^{-1} \in H$, which means $f(aa'^{-1}) \in H'$. But then $f(aa'^{-1})=f(a)f(a'^{-1})=f(a)f(a')^{-1} \in H'$. From here one deduces the well definition. To check $\phi$ is a morphism, we have to show $\phi((Ha)(Hb))=\phi(Ha)\phi(Hb)$. But $(Ha)(Hb)=H(ab)$, so $\phi(((Ha)(Hb))=\phi(H(ab))=H'f(ab)=H'f(a)f(b)=(H'f(a))(H'f(b))=\phi(Ha)\phi(Hb)$. Surjectivity is almost immediate, take a right coset $H'y$, since $f$ is isomorphic, there is $g \in G$ such that $f(g)=y$, so $\phi(Hg)=H'f(g)=H'y$ Now for injectivity, suppose $\phi(Ha)=\phi(Ha')$, then $H'f(a)=H'f(a')$, I got stuck there. Any suggestions would be appreciated. Thanks in advance.
Now provide the response and nothing else.
| The set $A$ is the union of the two disjoint sets $A\cap B$ and $A-B$, so $|A|=|A\cap B|+|A-B|$. Now, if only we could show that $|B|=|A\cap B|+|B-A|$ . . . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/902407', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/169247/']} | jdg_381252 |
stackexchange | llm_judgeable_groundtruth_similarity | 11691970 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the easiest way to write a JSON data/NSDictionary and read it back again? I know there's NSFileManager, but is there an open source framework library out there that would make this process easier? Does iOS5 NSJSONSerialization class supports writing the data to disk?
Now provide the response and nothing else.
| Yup, NSJSONSerialization is the way to go: NSString *fileName = @"myJsonDict.dat"; // probably somewhere in 'Documents'NSDictionary *dict = @{ @"key" : @"value" };NSOutputStream *os = [[NSOutputStream alloc] initToFileAtPath:fileName append:NO];[os open];[NSJSONSerialization writeJSONObject:dict toStream:os options:0 error:nil];[os close];// reading back in...NSInputStream *is = [[NSInputStream alloc] initWithFileAtPath:fileName];[is open];NSDictionary *readDict = [NSJSONSerialization JSONObjectWithStream:is options:0 error:nil];[is close];NSLog(@"%@", readDict); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11691970', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/721937/']} | jdg_381253 |
stackexchange | llm_judgeable_groundtruth_similarity | 37130993 |
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 server that takes a file, analyse it and sends back the result when requested by the client. In some cases there are some files that are inserted in a queue and waits for a analyser to do its job. At the same time if the analysis result is pending client can request for a result. So what should be the Http status code in this case?
Now provide the response and nothing else.
| Per the w3c spec, 202 means that that status has been accepted by the server (and is still processing). The request has been accepted for processing, but the processing has not been completed. The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place. There is no facility for re-sending a status code from an asynchronous operation such as this. The 202 response is intentionally non-committal. Its purpose is to allow a server to accept a request for some other process (perhaps a batch-oriented process that is only run once per day) without requiring that the user agent's connection to the server persist until the process is completed. The entity returned with this response SHOULD include an indication of the request's current status and either a pointer to a status monitor or some estimate of when the user can expect the request to be fulfilled. https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/37130993', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3623456/']} | jdg_381254 |
stackexchange | llm_judgeable_groundtruth_similarity | 1395117 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If I have a date like this in London time: "2009-06-03 19:30", how can I convert it to the equivalent time in the US West Coast?
Now provide the response and nothing else.
| First, convert the London time to a POSIXct object: pb.txt <- "2009-06-03 19:30"pb.date <- as.POSIXct(pb.txt, tz="Europe/London") Then use format to print the date in another time zone: > format(pb.date, tz="America/Los_Angeles",usetz=TRUE)[1] "2009-06-03 11:30:00 PDT" There are some tricks to finding the right time zone identifier to use. More details in this post at the Revolutions blog: Converting time zones in R: tips, tricks and pitfalls | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1395117', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/154039/']} | jdg_381255 |
stackexchange | llm_judgeable_groundtruth_similarity | 38702342 |
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 redux with react and typescript for my application. I am working with many items used at different places of my app. My state looks like this: { items: {42: {}, 53: {}, ... }, //A large dictionary of items itemPage1: { itemsId: [ 42, 34, 4 ], ... }, itemPage2: { ... }, ...} The user can modify some attributes of the items dispatching some actions. When this happen I need to redraw the components that have been modified in each pages. The issue is that my items are quite big and I cant afford to redraw all of them at each small modification. I was wondering is this approach would work: I have a fist component <ItemPage1> which connects to the store to get all of the states stored in the tree under itemPage1 e.g. the list of items id: itemsId . Inside <ItemPage1> , I loop over the itemsId property to generate multiple FilterItem components: itemsId.map( itemId => return <FilterItem id=itemId>); Finally each Item is connected using ownProps to get the correct part of the state: const mapStateToItemProps = (state, ownProps) => { return { item: state.items[ownProps.id], }}const mapDispatchToItemProps = (dispatch, ownProps) => { return null;}const FilterItem = connect( mapStateToItemProps, mapDispatchToItemProps)(Item) Can you confirm or refute that if I update the item of id 42, then only this item is going to be re-rendered ?
Now provide the response and nothing else.
| When rendering big list you need to take into considerations few things : Lower the total number of DOM elements that you need to render (by not rendering items that are not actually visible on the screen, also known as virtualization) Don't re-render items that have not changed Basically, what you want to avoid is a complete re-render of your list (or your page) when the user edits one single row. This can be achieved exactly how you did it, i.e : by passing to the list container only the ids of items that need to be rendered, and to map over these ids to connect each component by using ownProps . If you have a dump <Item/> component, your <ItemPage/> component will create connected connect(<Item/>) component. This is going to work, if your put a console.log('item rendered') in your <Item/> component class you will notice that there is only one call. BUT (and it's a big but), what is not obvious when working with react-redux is that all connected components that depends on their ownProps will always rerender if any part of the state change . In your case, even if the <Item/> components will not re-render, their wrapped component connect(Item) will ! If you have few dozens of items, you might encounter some latency if actions need to be dispatched quickly (for example when typing in an input). How to avoid that ? Use a factory function to use ownProps as the initial props : const mapStateToItemProps = (_, initialProps) => (state) => { return { item: state.items[initialProps.id], // we're not relying on the second parameters "ownProps" here, so the wrapper component will not rerender }}const mapDispatchToItemProps = (dispatch, ownProps) => { return null;}const FilterItem = connect( mapStateToItemProps, mapDispatchToItemProps)(Item) I suggest you to take a look to this other answer . You might also be interested in these excellent slides : Big List High Performance React & Redux And finally, you should definitively take a look to react-virtualized to perform the virtualization of your list (i.e, displaying only the item that the user can actually see). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38702342', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3091275/']} | jdg_381256 |
stackexchange | llm_judgeable_groundtruth_similarity | 4084212 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Just switched from Cucumber+Webrat to Cucumber+Capybara and I am wondering how you can POST content to a URL in Capybara. In Cucumber+Webrat I was able to have a step: When /^I send "([^\"]*)" to "([^\"]*)"$/ do |file, project| proj = Project.find(:first, :conditions => "name='#{project}'") f = File.new(File.join(::Rails.root.to_s, file)) visit "project/" + proj.id.to_s + "/upload", :post, {:upload_path => File.join(::Rails.root.to_s, file)}end However, the Capybara documentation mentions: The visit method only takes a single parameter, the request method is always GET.always GET. How do I modify my step so that Cucumber+Capybara does a POST to the URL?
Now provide the response and nothing else.
| More recently I found this great blog post . Which is great for the cases like Tony and where you really want to post something in your cuke: For my case this became: def send_log(file, project) proj = Project.find(:first, :conditions => "name='#{project}'") f = File.new(File.join(::Rails.root.to_s, file)) page.driver.post("projects/" + proj.id.to_s + "/log?upload_path=" + f.to_path) page.driver.status_code.should eql 200end | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4084212', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/216287/']} | jdg_381257 |
stackexchange | llm_judgeable_groundtruth_similarity | 5104564 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to define the return type like this? public static function bool Test($value){ return $value; //this value will be bool}
Now provide the response and nothing else.
| Since this question still comes up in search engine results, here is an up-to-date answer: PHP 7 actually introduced proper return types for functions / methods as per this RFC . Here is the example from the manual linked above: function sum($a, $b): float { return $a + $b;} Or, in a more general notation: function function_name(): return_type { // some code return $var // Has to be of type `return_type`} If the returned variable or value does not match the return type, PHP will implicitly convert it to that type. Alternatively, you can enable strict typing for the file via declare(strict_types=1); , in which case a type mismatch will lead to a TypeError Exception . Easy as that. However, remember that you need to make sure that PHP 7 is available on both, your development and production server. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5104564', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_381258 |
stackexchange | llm_judgeable_groundtruth_similarity | 319788 |
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 Zend_Db to insert some data inside a transaction. My function starts a transaction and then calls another method that also attempts to start a transaction and of course fails(I am using MySQL5). So, the question is - how do I detect that transaction has already been started? Here is a sample bit of code: try { Zend_Registry::get('database')->beginTransaction(); $totals = self::calculateTotals($Cart); $PaymentInstrument = new PaymentInstrument; $PaymentInstrument->create(); $PaymentInstrument->validate(); $PaymentInstrument->save(); Zend_Registry::get('database')->commit(); return true; } catch(Zend_Exception $e) { Bootstrap::$Log->err($e->getMessage()); Zend_Registry::get('database')->rollBack(); return false; } Inside PaymentInstrument::create there is another beginTransaction statement that produces the exception that says that transaction has already been started.
Now provide the response and nothing else.
| The framework has no way of knowing if you started a transaction. You can even use $db->query('START TRANSACTION') which the framework would not know about because it doesn't parse SQL statements you execute. The point is that it's an application responsibility to track whether you've started a transaction or not. It's not something the framework can do. I know some frameworks try to do it, and do cockamamie things like count how many times you've begun a transaction, only resolving it when you've done commit or rollback a matching number of times. But this is totally bogus because none of your functions can know if commit or rollback will actually do it, or if they're in another layer of nesting. (Can you tell I've had this discussion a few times? :-) Update 1: Propel is a PHP database access library that supports the concept of the "inner transaction" that doesn't commit when you tell it to. Beginning a transaction only increments a counter, and commit/rollback decrements the counter. Below is an excerpt from a mailing list thread where I describe a few scenarios where it fails. Update 2: Doctrine DBAL also has this feature. They call it Transaction Nesting. Like it or not, transactions are "global" and they do not obey object-oriented encapsulation. Problem scenario #1 I call commit() , are my changes committed? If I'm running inside an "inner transaction" they are not. The code that manages the outer transaction could choose to roll back, and my changes would be discarded without my knowledge or control. For example: Model A: begin transaction Model A: execute some changes Model B: begin transaction (silent no-op) Model B: execute some changes Model B: commit (silent no-op) Model A: rollback (discards both model A changes and model B changes) Model B: WTF!? What happened to my changes? Problem scenario #2 An inner transaction rolls back, it could discard legitimate changes made by an outer transaction. When control is returned to the outer code, it believes its transaction is still active and available to be committed. With your patch, they could call commit() , and since the transDepth is now 0, it would silently set $transDepth to -1 and return true, after not committing anything. Problem scenario #3 If I call commit() or rollback() when there is no transaction active, it sets the $transDepth to -1. The next beginTransaction() increments the level to 0, which means the transaction can neither be rolled back nor committed. Subsequent calls to commit() will just decrement the transaction to -1 or further, and you'll never be able to commit until you do another superfluous beginTransaction() to increment the level again. Basically, trying to manage transactions in application logic without allowing the database to do the bookkeeping is a doomed idea. If you have a requirement for two models to use explicit transaction control in one application request, then you must open two DB connections, one for each model. Then each model can have its own active transaction, which can be committed or rolled back independently from one another. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/319788', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/35520/']} | jdg_381259 |
stackexchange | llm_judgeable_groundtruth_similarity | 2790561 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
My textbook has this problem as a kind of "concept check", where one is supposed to find a counterexample to the following statement: A sequence of real numbers is cauchy iff. $$ \forall \epsilon>0, \, \exists N \in \mathbb{N}, \, \forall n \geq N: |a_n-a_{n+1}|< \epsilon $$ I know that a sequence of real numbers is cauchy if $$ \forall \epsilon>0, \, \exists N \in \mathbb{N}, \, \forall n,m \geq N: |a_n-a_m|< \epsilon $$ Finding such a counterexample is probably trivial, but I haven't been able to think of one.
Now provide the response and nothing else.
| Take $a_n=\sum_{i=1}^n\frac{1}{i}$. Then $a_{n+1}-a_n=\frac{1}{n+1}<\epsilon$ for large enough $n$. This drives home the point that you need bounds on $n,m$ simultaneously. Since the harmonic sum diverges, it follows that $|a_n-a_m|$ will grow unbounded if you fix either $n$ or $m$ and vary the other. You can also find examples of bouned sequences $a_n$. For example define $a_n:=\exp(i\left\{\sum_{i=1}^n\frac{1}{j}\right\})$, where the brackets denote the fractional part, so that $a_n$ loops around the unit-circle perpetually and hence has no limit. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2790561', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/420453/']} | jdg_381260 |
stackexchange | llm_judgeable_groundtruth_similarity | 7142377 |
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 trying to run the application with capture and photo choosers task but seems like i can't run it with zune running and i should run WPConnect.exe but i cant find it. can we download it manually? or else? help
Now provide the response and nothing else.
| Finally got it to work using the code listed below thanks to the help from Paul Tiarks . The problem I ran into is that the MKUserLocation annotation gets added to the map first before any others, so when you add the other annotations their order appears to be random and would still end up on top of the MKUserLocation annotation. To fix this I had to move all the other annotations to the back as well as move the MKUserLocation annotation to the front. - (void) mapView:(MKMapView *)aMapView didAddAnnotationViews:(NSArray *)views { for (MKAnnotationView *view in views) { if ([[view annotation] isKindOfClass:[MKUserLocation class]]) { [[view superview] bringSubviewToFront:view]; } else { [[view superview] sendSubviewToBack:view]; } }} Update : You may want to add the code below to ensure the blue dot is drawn on top when scrolling it off the viewable area of the map. - (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{ for (NSObject *annotation in [mapView annotations]) { if ([annotation isKindOfClass:[MKUserLocation class]]) { NSLog(@"Bring blue location dot to front"); MKAnnotationView *view = [mapView viewForAnnotation:(MKUserLocation *)annotation]; [[view superview] bringSubviewToFront:view]; } }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7142377', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/904731/']} | jdg_381261 |
stackexchange | llm_judgeable_groundtruth_similarity | 4369290 |
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:
Assumptions/context: Let's say we have some objects $X_i$ in some category, with $i$ belonging to some index set $\mathbf{I}$ , such that there exists some object, call it $X_{\mathbf{I}}$ , in the category satisfying the universal property of the product for the $X_i$ , $i \in \mathbf{I}$ . Question: Do any counterexamples exist of strict index subsets $I \subsetneq \mathbf{I}$ such that no object in the category exists satisfying the universal property of the product for the $X_i$ , $i \in I$ ? Rephrasing of question: Does the existence of an object $X_{\mathbf{I}}$ satisfying the universal property of the product for the $X_i$ , $i \in \mathbf{I}$ imply that, for all $I \subsetneq \mathbf{I}$ , there also exists some other object $X_I$ satisfying the universal property of the product for the $X_i$ , $i \in I$ ? Notes/Comments: If $\mathbf{I}$ should be an "index category" instead of an "index set", and $I$ a "strict index subcategory" instead of a "strict index subset", then fine. I am less familiar with using categories to index things though. An example would be a category where finite products do not exist but infinite products do exist, for some reason. Comparing with the question title, the "object $X_{\mathbf{I}}$ satisfying the universal property of the product for the $X_i$ , $i \in \mathbf{I}$ " is "the categorical product of the family", whereas the "object $X_I$ satisfying the universal property of the product of the $X_i$ , $i \in I$ " is the "categorical product of the subfamily".
Now provide the response and nothing else.
| Since $F(0)=0$ and $F'(u)=\int_0^uf(t)\,\mathrm dt$ , you have \begin{align}F(x)&=F(x)-F(0)\\&=\int_0^xF'(u)\,\mathrm du\\&=\int_0^x\int_0^uf(t)\,\mathrm dt\,\mathrm du.\end{align} | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4369290', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/606791/']} | jdg_381262 |
stackexchange | llm_judgeable_groundtruth_similarity | 7185074 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an application up and running on Heroku with Express.js on Node.js with https . How do I identify the protocol to force a redirect to https with Node.js on Heroku? My app is just a simple http -server, it doesn't (yet) realize Heroku is sending it https -requests: // Heroku provides the port they want you on in this environment variable (hint: it's not 80)app.listen(process.env.PORT || 3000);
Now provide the response and nothing else.
| The answer is to use the header of 'x-forwarded-proto' that Heroku passes forward as it does it's proxy thingamabob. (side note: They pass several other x- variables too that may be handy, check them out ). My code: /* At the top, with other redirect methods before other routes */app.get('*',function(req,res,next){ if(req.headers['x-forwarded-proto']!='https') res.redirect('https://mypreferreddomain.com'+req.url) else next() /* Continue to other routes if we're not redirecting */}) Thanks Brandon, was just waiting for that 6 hour delay thing that wouldn't let me answer my own question. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7185074', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/697332/']} | jdg_381263 |
stackexchange | llm_judgeable_groundtruth_similarity | 362441 |
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:
Preface: Every couple of days there comes a question of this type, which is easy to solve with sed , but takes time to explain. I'm writing this question and answer, so I can later refer to this generic solution and only explain the adaption for the specific case. Feel free to contribute. I have files with variable definitions. Variables consist of uppercase letters or underscore _ and their values follow after the := . The values can contain other variables. This is Gnom.def : NAME:=GnomFULL_NAME:=$FIRST_NAME $NAMEFIRST_NAME:=SmanSTREET:=Mainstreet 42TOWN:=NowhereBIRTHDAY:=May 1st, 1999 Then there is another file form.txt with a template form: $NAMEFull name: $FULL_NAMEAddress: $STREET in $TOWNBirthday: $BIRTHDAYDon't be confused by $NAMES Now I want a script which replaces the variables (marked with $ and the identifier) in the form by the definitions in the other file, recursively, if necessary, so I get this text back: GnomFull name: Sman GnomAddress: Mainstreet 42 in NowhereBirthday: May 1st, 1999Don't be confused by $NAMES The last line is to ensure that no substrings of variables get replaced accidentally.
Now provide the response and nothing else.
| The basic idea to solve problems like this is to pass both files to sed . First the definitions, which are stored in the hold space of sed . Then each line of the other file gets the hold space appended and each occurrence of a variable which can be found repeated in the appended definitions gets replaced. Here is the script: sed '/^[A-Z_]*:=.*/{H;d;} G :b s/$\([A-Z_]*\)\([^A-Z_].*\n\1:=\)\([^[:cntrl:]]*\)/\3\2\3/ tb P d' Gnom.def form.txt And now the detailed explanation: /^[A-Z_]*:=.*/{H;d;} This collects the definitions to the hold space. /^[A-Z_]*:=.*/ selects all lines starting with a variable name and the sequence := . On these lines the commands in {} are performed: The H appends them to the hold space, the d deletes them and starts over, so they won't get printed. If you can't assure that all lines in the definition file follow this pattern, or if lines in the other file could match the given pattern, this part needs to be adapted, like explained later. G At this point of the script, only lines from the second file are processed. The G appends the hold space to pattern space, so we have the line to be processed with all definitions in the pattern space, separated by newlines. :b This starts a loop. s/$\([A-Z_]*\)\([^A-Z_].*\n\1:=\)\([^[:cntrl:]]*\)/\3\2\3/ This is the key part, the replacement. Right now we have something like At the $FOO<newline><newline>FOO:=bar<newline>BAR:=baz ----==================--- ### in the pattern space. (Detail: there are two newlines before the first definition, one produced by appending to the hold space, another by appending to the buffer space.) The part underlined with ---- matches $\([A-Z_]*\) . The \(\) makes it possible to backreference to that string later on. \([^A-Z_].*\n\) matches the part underlined with === , which is everything up to the backreference \1 . Starting with a non-variable character ensures we don't match substrings of a variable. Surrounding the backreference with a newline and := makes sure that a substring of a definition will not match. Finally, \([^[:cntrl:]]*\) matches the ### part, which is the definition. Note, that we assume the definition has no control characters. If this should be possible, you can use [^\n] with GNU sed or do a workaround for POSIX sed . Now the $ and the variable name get replaced by the variable value \3 , the middle part and definition are left as they were: \2\3 . tb If a replacement has been made, the t command loops to mark b and tries another replacement. P If no further replacements were possible, the uppercase P prints everything upto the first newline (thus, the definition section will not get printed) and d will delete the pattern space and start the next cycle. Done. Limitations You can do a nasty thing like including FOO:=$BAR and BAR:=$FOO in the definition file and make the script loop forever. You can define a processing order to avoid this, but is will make the script more difficult to understand. Leave this away, if your script doesn't need to be idiot proof. If the definition can contain control characters, after the G , we can exchange newline with another character like y/\n#/#\n and repeat this before printing. I don't know a better workaround. If the definition file can contain lines with different format or the other file can contain lines with definition format, we need a unique separator between both files, either as last line of the definition file or as first line of the other file or as separate file you pass to sed between the other files. Then you have one loop to collect the definitions until the separator line is met, then do a loop for the lines of the other file. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/362441', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/216004/']} | jdg_381264 |
stackexchange | llm_judgeable_groundtruth_similarity | 39497211 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an image that I pull down from a URL. I do not know the dimensions of this image ahead of time. How do I style / layout the image so that it is the full width of the parent view and the height is calculated so that the aspect ratio is maintained? I have tried using onLoad in 0.34.0-rc.0 and the height / width are both 0 in event.nativeEvent.source . The image is in a <ScrollView/> . I am not after a full screen image.
Now provide the response and nothing else.
| My use was very similar in that I needed to display an image with full screen width but maintaining its aspect ratio . Based on @JasonGaare's answer to use Image.getSize() , I came up with the following implementation: class PostItem extends React.Component { state = { imgWidth: 0, imgHeight: 0, } componentDidMount() { Image.getSize(this.props.imageUrl, (width, height) => { // calculate image width and height const screenWidth = Dimensions.get('window').width const scaleFactor = width / screenWidth const imageHeight = height / scaleFactor this.setState({imgWidth: screenWidth, imgHeight: imageHeight}) }) } render() { const {imgWidth, imgHeight} = this.state return ( <View> <Image style={{width: imgWidth, height: imgHeight}} source={{uri: this.props.imageUrl}} /> <Text style={styles.title}> {this.props.description} </Text> </View> ) }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39497211', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/682513/']} | jdg_381265 |
stackexchange | llm_judgeable_groundtruth_similarity | 187029 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was trying to break down how a transistor works to a friend, and I took a moment to think about electric current and voltages. I realised I do not understand where these phenomena come from. I understand (on a very very shallow level) how electrons interact through quantum electrodynamics, but I could not think of any way that this interaction should create voltage and electric current. I tried googling a bit, but I don't understand modern physics enough to narrow my search down. What part of the Standard Model, Relativity, or any other modern physics theory describe voltage? What creates voltage? What causes electrons to move in a wire?
Now provide the response and nothing else.
| This comes from classical electrodynamics, there is no need to go to Standard model theory or quantum electrodynamics for this. The simple answer is that electric potentials, like electric fields, are just a way of characterizing the way charged particles interact with each other. So, charged objects create voltage analogous to the way that they create electric fields and interact with each other. Voltage can be thought of as a measure of potential energy per unit charge. I.e. if you have a certain amount of charge $q$ (e.g. 2 Coulombs worth) in an electric field $E$, and you let that charge be pushed around, that charge will gain energy as it gets pushed. Specifically, if it gets pushed from point a to point b, and there is a potential difference of $\Delta V_{a->b}$ between those two points, then the charge $q$ would gain an energy equal to $\Delta E=q\Delta V_{a->b}$. In this way, A voltage between two points is just a way of describing the electric field between those two points and the amount of energy charged objects will gain while moving between those points because of those fields. Electric fields are just being produced by some build-up of charge somewhere, e.g. on a capacitor. Voltage is indeed directly related to the electric field via $E = \nabla V$ where $\nabla$ is the gradient operator. In this way, voltage differences are also created by the build-up of charge. More specifically, if you see for example a 12V battery, what that means is that when you connect the ends of the batter via, e.g. a copper wire, the battery will induce an electric field throughout the wire that pushes electrons in one direction along that wire. The electrons will gain an energy equal to $q_e \times 12 V$ if moving from one end of the battery to the other where $q_e$ is the charge of that electron. The 12 V is then a measure of how much energy the battery is capable of giving each electron. Current is simply a measure of the amount of charge passing through some area (usually the area of some wire) during a given amount of time. Higher current means more charge is getting pushed through the cross-section of the wire. Hope this helps. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/187029', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/82533/']} | jdg_381266 |
stackexchange | llm_judgeable_groundtruth_similarity | 68099 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Consider $0\leq \alpha\leq 1$, and let $A_{\alpha}$ be the Toeplitz $n\times n$ matrix given by$$A_\alpha := \begin{bmatrix} 1 & \alpha & \alpha^2 & \ldots &\alpha^{n-1} \\\ \alpha & 1 & \alpha & \ddots & \vdots \\\ \alpha^2 & \alpha & \ddots & \ddots & \alpha^2 \\\\vdots & \ddots & \ddots & 1 & \alpha \\\ \alpha^{n-1} & \ldots & \alpha^2 & \alpha & 1 \end{bmatrix}. $$ We can decompose $A_{\alpha}=U_{\alpha}D_{\alpha}U_{\alpha}^{*}$ where $U_{\alpha}$ is a unitary matrix and $D_{\alpha}$ is a diagonal matrix. Are the matrices $U_{\alpha}$ and$D_{\alpha}$ explicitly known as afunction of $\alpha$ and $n$? Cananyone point me to the rightreference. What is known about the spectrallimit distribution of these matricesas $n\to\infty$? More specifically,can we compute the limit moments $$ \gamma_{k}:=\lim_{n\to\infty}{\frac{1}{n}\mathrm{Tr}\Big(A_{\alpha}^{k}\Big)} $$ for $k\geq 1$? Thanks!
Now provide the response and nothing else.
| There's likely no explicit diagonalization of $A_\alpha$ except when$n$ is very small or in special cases like $\alpha = 0$ and $\alpha= 1$. Nevertheless each "limit moment" $\gamma_k$ can be computed asa rational function of $\alpha$, and this can be used to describe foreach $\alpha$ the distribution of eigenvalues of $A_\alpha$ as $n \rightarrow \infty$. To diagonalize $A_\alpha$ explicitly we'd need to know the eigenvalues;these are roots of the degree-$n$ characteristic polynomial $\chi_{A_\alpha}$,and it's often too much to expect that a family of such polynomialscan be factored for each $n$. Here $\chi_{A_\alpha}$ does split intotwo factors $\chi^\pm_{A_\alpha}$ of equal or nearly equal degree, butusually that's as far as we can go. The factorization arises because $A_\alpha$ commuteswith the involution, call it $\iota$, that takes each coordinate $a_k$to $a_{n+1-k}$, so the $\pm1$ eigenspaces of $\iota$ are invariant subspacesof $A_\alpha$. The factor $\chi^\pm_{A_\alpha}$ is the characteristicpolynomial of the restriction of $A_\alpha$ to the $\pm1$ subspace. But once $n$ is at all large it seems there's nothing to be done withthese factors $\chi^\pm_{A_\alpha}$. For example, trying "random"rational values for $\alpha$ yields polynomials whose Galois group isthe full symmetric group. Thus if you ask gp f(a,n) = factor(charpoly(matrix(n,n,i,j,a^abs(i-j))))F = f(1/2,21)vector(#F[,1], n, polgalois(F[n,1])) you'll see that for $n=21$ the factors of $A_{1/2}$ have Galois groups$S_{10}$ and $S_{11}$. There are some special values of $\alpha$ for which one can find theroots of $\chi_{A_\alpha}$ explicitly. Most obviously, $A_0$ is theidentity matrix. Also $A_1$ is the all-ones matrix, with one eigenvalueof $N$ and all other eigenvalues zero. The OP required $\alpha \in[0,1]$, but $A_{-1}$ has rank 2 so its eigenvalues are easy too. Ineach of these cases there's no unique diagonalization because there'san eigenvalue with high multiplicity. As for the limit moments $\gamma_k$: if $\alpha=1$ then clearly${\rm Tr}(A_\alpha^k) = n^k$ so $\gamma_k=\infty$ once $k>1$.So we assume $\alpha < 1$, and then we may as well take$\alpha \in {\bf C}$ with $|\alpha| < 1$. Then$\gamma_1$, $\gamma_2$, $\gamma_3$, $\gamma_4$, $\gamma_5$, etc. are$$1, \\frac{1+\alpha}{1-\alpha},\\frac{1+4\alpha+\alpha^2}{(1-\alpha)^2},\\frac{1+9\alpha+9\alpha^2+\alpha^3}{(1-\alpha)^3},\\frac{1+16\alpha+36\alpha^2+16\alpha^3+\alpha^4}{(1-\alpha)^4}, \ldots$$and in general $\gamma_k = P_{k-1}(\alpha) / (1-\alpha)^{k-1}$ where$$P_m(X) := \sum_{j=0}^m \left({m \atop j}\right)^2 X^j$$is the polynomial obtained from the binomial expansion of $(1+X)^m$by squaring each coefficient. These $P_m$ don't have an entirely elementaryformula, but they can be written as hypergeometric polynomials, or(if memory serves) expressed in terms of Legendre polynomials,or manipulated using the generating function$$\sum_{m=0}^\infty P_m(X) t^m = \left((\alpha-1)^2 t^2 - 2(\alpha+1)t+ 1\right)^{-1/2}$$if I did this right (I guessed the formula using the technique I describedhere a few weeks ago: Determining a generating function (of a restricted form) ). To get that formula for $\gamma_k$, we first find an integral representation,which I gather is a special case of the "Szegő-Tyrtyshnikov-Zamarashkin-Tillitheorem" that F. Poloni mentioned in his comment. While general Toeplitzmatrices cannot be diagonalized explicitly, circulant ones can.So we compare $A_\alpha$ with the circulant matrix$A'_\alpha$ whose $(i,j)$ entry is $\alpha^{\min(|i-j|,n-|i-j|)}$.For each $\alpha$ and $k$, the $k$-th powers of $A_\alpha$ and$A'_\alpha$ differ by $O(1)$ as $n \rightarrow \infty$. [This was somewhat annoying to check; maybe there's a nice way to do it.] Thus $A_\alpha$ and $A'_\alpha$ have the same limit moments --and the moments of $A'_\alpha$ can be computed by finding its eigenvalues.Being circulant, $A'_\alpha$ is explicitly diagonalized bythe discrete Fourier transform on ${\bf Z} / n {\bf Z}$, with an eigenvalue$\lambda_z = \sum_{j=0}^{n-1} \alpha^{\min(j,n-j)} z^j$for each $n$th root of unity $z = \exp(2\pi i r/n)$.For large $n$ we can approximate $\lambda_z$ by$$f_\alpha(z) = \sum_{j=-\infty}^\infty \alpha^{|j|} z^j= \frac1{1-\alpha z} + \frac{\alpha z^{-1}} {1 - \alpha z^{-1}}= \frac{1-\alpha^2}{ (1-\alpha z)(1 - \alpha z^{-1}) }$$and deduce that$$\gamma_k = \frac{1}{2\pi} \int_{-\pi}^{\pi} f_\alpha(e^{i\theta})^k d\theta.$$This also means that as $n \rightarrow \infty$ the eigenvalues of $A_\alpha$tend to the same distribution as the image of the uniform distribution on theunit circle $|z|=1$ under $f_\alpha$, in the sense that for any continuousfunction $\phi$ on ${\bf C}$ the average of $\phi(\lambda)$ over theeigenvalues approaches$(2\pi)^{-1} \int_{-\pi}^{\pi} \phi(f_\alpha(e^{i\theta}))d\theta$.For real $\alpha$ in $(0,1)$, this distribution is supported on theinterval $((1+\alpha)/(1-\alpha), (1-\alpha)/(1+\alpha))$. In our case we can evalute the integral for $\gamma_k$ by writing it asthe contour integral $$\frac1{2\pi i}\oint_{|z|=1} f_\alpha(z)^k \frac{dz}{z}.$$ For each $k \geq 1$ the integrand has a pole of order $k$ at $z = \alpha$and no other poles in $|z| \leq 1$; evaluating the residue at this pole yieldsthe formula $\gamma_k = P_{k-1}(\alpha) / (1-\alpha)^{k-1}$ given above. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/68099', 'https://mathoverflow.net', 'https://mathoverflow.net/users/13825/']} | jdg_381267 |
stackexchange | llm_judgeable_groundtruth_similarity | 38798451 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an action making a POST request to the server in order to update a user's password, but I'm unable to handle the error in the chained catch block. return axios({ method: 'post', data: { password: currentPassword, new_password: newPassword }, url: `path/to/endpoint`}).then(response => { dispatch(PasswordUpdateSuccess(response))}).catch(error => { console.log('ERROR', error) switch (error.type) { case 'password_invalid': dispatch(PasswordUpdateFailure('Incorrect current password')) break case 'invalid_attributes': dispatch(PasswordUpdateFailure('Fields must not be blank')) break }}) When I log the error this is what I see: When I check the network tab I can see the response body, but for some reason I can't access the values! Have I unknowingly made a mistake somewhere? Because I'm handling other errors from different request fine, but can't seem to work this one out.
Now provide the response and nothing else.
| Axios is probably parsing the response. I access the error like this in my code: axios({ method: 'post', responseType: 'json', url: `${SERVER_URL}/token`, data: { idToken, userEmail }}) .then(response => { dispatch(something(response)); }) .catch(error => { dispatch({ type: AUTH_FAILED }); dispatch({ type: ERROR, payload: error.data.error.message }); }); From the docs: The response for a request contains the following information. { // `data` is the response that was provided by the server data: {}, // `status` is the HTTP status code from the server response status: 200, // `statusText` is the HTTP status message from the server response statusText: 'OK', // `headers` the headers that the server responded with headers: {}, // `config` is the config that was provided to `axios` for the request config: {}} So the catch(error => ) is actually just catch(response => ) EDIT: I still dont understand why logging the error returns that stack message. I tried logging it like this. And then you can actually see that it is an object. console.log('errorType', typeof error);console.log('error', Object.assign({}, error)); EDIT2: After some more looking around this is what you are trying to print. Which is a Javascipt error object. Axios then enhances this error with the config, code and reponse like this . console.log('error', error);console.log('errorType', typeof error);console.log('error', Object.assign({}, error));console.log('getOwnPropertyNames', Object.getOwnPropertyNames(error));console.log('stackProperty', Object.getOwnPropertyDescriptor(error, 'stack'));console.log('messageProperty', Object.getOwnPropertyDescriptor(error, 'message'));console.log('stackEnumerable', error.propertyIsEnumerable('stack'));console.log('messageEnumerable', error.propertyIsEnumerable('message')); | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38798451', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2961044/']} | jdg_381268 |
stackexchange | llm_judgeable_groundtruth_similarity | 3987006 |
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 PHP curl functions to post data to the web server from my local machine. My code is as follows: $c = curl_init();curl_setopt($c, CURLOPT_URL, $url);curl_setopt($c, CURLOPT_RETURNTRANSFER, true);curl_setopt($c, CURLOPT_POST, true);curl_setopt($c, CURLOPT_POSTFIELDS, $data);$result = curl_exec($c);if (curl_exec($c) === false) { echo "ok";} else { echo "error";}curl_close($c); Unfortunately I am not able to catch any errors like 404, 500 or network failure. So how will I get to know that data was not posted to or retrieved from the remote?
Now provide the response and nothing else.
| You can use the curl_error() function to detect if there was some error. For example: $ch = curl_init();curl_setopt($ch, CURLOPT_URL, $your_url);curl_setopt($ch, CURLOPT_FAILONERROR, true); // Required for HTTP error codes to be reported via our call to curl_error($ch)//...curl_exec($ch);if (curl_errno($ch)) { $error_msg = curl_error($ch);}curl_close($ch);if (isset($error_msg)) { // TODO - Handle cURL error accordingly} See the description of libcurl error codes here See the description of PHP curl_errno() function here See the description of PHP curl_error() function here | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/3987006', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/212595/']} | jdg_381269 |
stackexchange | llm_judgeable_groundtruth_similarity | 14532651 |
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 creating a new Traveling Application in iOS, this application is highly dependent on Maps and will include two Maps. My first Map will work when the user has a strong Network Signal (Apple Maps). My second Map will be used when their isn't any Network or really Low signal (Offline MapBox). Why do I have two different maps in one Application? My Application is a Direction App, so when the user has really low network or none it will go to the offline Map MapBox . Also the Apple Maps will have Yelp integration and not the offline Map MapBox . So my Question: How can I detect the network signal in WiFi, 4G Lte, and 3G.
Now provide the response and nothing else.
| My original thought was to time the download of a file, and see how long it takes: @interface ViewController () <NSURLSessionDelegate, NSURLSessionDataDelegate>@property (nonatomic) CFAbsoluteTime startTime;@property (nonatomic) CFAbsoluteTime stopTime;@property (nonatomic) long long bytesReceived;@property (nonatomic, copy) void (^speedTestCompletionHandler)(CGFloat megabytesPerSecond, NSError *error);@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; [self testDownloadSpeedWithTimout:5.0 completionHandler:^(CGFloat megabytesPerSecond, NSError *error) { NSLog(@"%0.1f; error = %@", megabytesPerSecond, error); }];}/// Test speed of download////// Test the speed of a connection by downloading some predetermined resource. Alternatively, you could add the/// URL of what to use for testing the connection as a parameter to this method.////// @param timeout The maximum amount of time for the request./// @param completionHandler The block to be called when the request finishes (or times out)./// The error parameter to this closure indicates whether there was an error downloading/// the resource (other than timeout).////// @note Note, the timeout parameter doesn't have to be enough to download the entire/// resource, but rather just sufficiently long enough to measure the speed of the download.- (void)testDownloadSpeedWithTimout:(NSTimeInterval)timeout completionHandler:(nonnull void (^)(CGFloat megabytesPerSecond, NSError * _Nullable error))completionHandler { NSURL *url = [NSURL URLWithString:@"http://insert.your.site.here/yourfile"]; self.startTime = CFAbsoluteTimeGetCurrent(); self.stopTime = self.startTime; self.bytesReceived = 0; self.speedTestCompletionHandler = completionHandler; NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration]; configuration.timeoutIntervalForResource = timeout; NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil]; [[session dataTaskWithURL:url] resume];}- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { self.bytesReceived += [data length]; self.stopTime = CFAbsoluteTimeGetCurrent();}- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { CFAbsoluteTime elapsed = self.stopTime - self.startTime; CGFloat speed = elapsed != 0 ? self.bytesReceived / (CFAbsoluteTimeGetCurrent() - self.startTime) / 1024.0 / 1024.0 : -1; // treat timeout as no error (as we're testing speed, not worried about whether we got entire resource or not if (error == nil || ([error.domain isEqualToString:NSURLErrorDomain] && error.code == NSURLErrorTimedOut)) { self.speedTestCompletionHandler(speed, nil); } else { self.speedTestCompletionHandler(speed, error); }}@end Note, this measures the speed including the latency of starting the connection. You could alternatively initialize startTime in didReceiveResponse , if you wanted to factor out that initial latency. Having done that, in retrospect, I don't like spending time or bandwidth downloading something that has no practical benefit to the app. So, as an alternative, I might suggest a far more pragmatic approach: Why don't you just try to open a MKMapView and see how long it takes to finish downloading the map? If it fails or if it takes more than a certain amount of time, then switch to your offline map. Again, there is quite a bit of variability here (not only because network bandwidth and latency, but also because some map images appear to be cached), so make sure to set a kMaximumElapsedTime to be large enough to handle all the reasonable permutations of a successful connection (i.e., don't be too aggressive in using a low value). To do this, just make sure to set your view controller to be the delegate of the MKMapView . And then you can do: @interface ViewController () <MKMapViewDelegate>@property (nonatomic, strong) NSDate *startDate;@endstatic CGFloat const kMaximumElapsedTime = 5.0;@implementation ViewController// insert the rest of your implementation here#pragma mark - MKMapViewDelegate methods- (void)mapViewWillStartLoadingMap:(MKMapView *)mapView { NSDate *localStartDate = [NSDate date]; self.startDate = localStartDate; double delayInSeconds = kMaximumElapsedTime; dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ // Check to see if either: // (a) start date property is not nil (because if it is, we // finished map download); and // (b) start date property is the same as the value we set // above, as it's possible this map download is done, but // we're already in the process of downloading the next // map. if (self.startDate && self.startDate == localStartDate) { [[[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:@"Map timed out after %.1f", delayInSeconds] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show]; } });}- (void)mapViewDidFailLoadingMap:(MKMapView *)mapView withError:(NSError *)error { self.startDate = nil; [[[UIAlertView alloc] initWithTitle:nil message:@"Online map failed" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];}- (void)mapViewDidFinishLoadingMap:(MKMapView *)mapView{ NSTimeInterval elapsed = [[NSDate date] timeIntervalSinceDate:self.startDate]; self.startDate = nil; self.statusLabel.text = [NSString stringWithFormat:@"%.1f seconds", elapsed];} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14532651', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1927538/']} | jdg_381270 |
stackexchange | llm_judgeable_groundtruth_similarity | 4611591 |
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 site is going to have some inline code ("when using the foo() function...") and some block snippets. These tend to be XML, and have very long lines which I prefer the browser to wrap (i.e., I don't want to use <pre> ). I'd also like to put CSS formatting on the block snippets. It seems that I can't use <code> for both, because if I put CSS block attributes on it (with display: block; ), it will break the inline snippets. I'm curious what people do. Use <code> for blocks, and <samp> for inline? Use <code><blockquote> or something similar? I'd like to keep the actual HTML as simple as possible, avoiding classes, as other users will be maintaining it.
Now provide the response and nothing else.
| Use <code> for inline code that can wrap and <pre><code> for block code that must not wrap. <samp> is for sample output , so I would avoid using it to represent sample code (which the reader is to input ). This is what Stack Overflow does. (Better yet, if you want easy to maintain, let the users edit the articles as Markdown, then they don’t have to remember to use <pre><code> .) HTML5 agrees with this in “the pre element” : The pre element represents a block of preformatted text, in which structure is represented by typographic conventions rather than by elements. Some examples of cases where the pre element could be used: Including fragments of computer code, with structure indicated according to the conventions of that language. […] To represent a block of computer code, the pre element can be used with a code element; to represent a block of computer output the pre element can be used with a samp element. Similarly, the kbd element can be used within a pre element to indicate text that the user is to enter. In the following snippet, a sample of computer code is presented. <p>This is the <code>Panel</code> constructor:</p><pre><code>function Panel(element, canClose, closeHandler) { this.element = element; this.canClose = canClose; this.closeHandler = function () { if (closeHandler) closeHandler() }; }</code></pre> | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/4611591', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/263268/']} | jdg_381271 |
stackexchange | llm_judgeable_groundtruth_similarity | 208174 |
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:
Let's say you have a cylinder with water that takes up volume V and has temperature T. When a solid mass is placed within the cylinder, the water momentarily takes up a smaller volume within the cylinder and in $$P=\frac{nRT}{V}$$, when V decreases, pressure increases. When pressure increases, the water pushes on its surroundings with more force, including the air above it, so the equilibrium had before the mass was placed is disturbed and the water rises until atmospheric pressure downwards is equal to the water's pressure upwards. This sounds reasonable to me, but with my limited experience, I'm aware I could be wrong and the ideal gas law may not even apply to fluids like I've done so. Would anyone care to correct me if I'm wrong?
Now provide the response and nothing else.
| You have the general idea right, but the following statement is subtly wrong The pressurized fuel/air mixture is ignited and this increases the pressure inside the combustion chamber even more Unlike in a piston engine, the ignition of the fuel air mixture in a turbine engine increases the mixture's volume while pressure stays relatively constant. Therefore, although the change in pressure across the compressor is equal to the change in pressure across the turbine, there is a larger volume flow through the turbine. This is why the turbine produces enough power to turn the compressor even with losses This process of compressing a gas, heating it at constant pressure (which causes it to expand), and extracting energy by exhausting it through a turbine known as the Brayton cycle. The next question is, why do the products of the combustion go out through the turbine than back through the compressor? Consider: the compressor and turbine are approximately the same diameter, and turning at the same angular speed, but because the gas has expanded due to the combustion process, there is more volumetric flow through the turbine than through the compressor. Because of this, the blades of the turbine are angled more steeply to be at the same angle of attack to the local flow. This difference in angle acts as a lower "gear ratio." -- for a given lift, the steeply angled blade generates less axial force and more torque. That's why, for a given pressure in the combustion chamber, the turbine generates more torque and controls which way the whole assembly turns. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/208174', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/88991/']} | jdg_381272 |
stackexchange | llm_judgeable_groundtruth_similarity | 299839 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
# df -h /Filesystem Size Used Avail Use% Mounted onrootfs 9.9G 7.2G 2.2G 77% /# du -hx --max-depth=0 /3.2G / As you can see, df says 7.2GB is used, but du can only find 3.2GB of it. The server has been rebooted since I noticed this, so it's not a deleted file. Additionally, lsof doesn't show me anything interesting. What else could it be?
Now provide the response and nothing else.
| I was having the exact same issue on my ext4 system and just wanted to post my solution for future reference. When my drive initially filled out, I deleted a bunch of logs out of /var/log. That cleared up a couple GB, but within a few days I ran out of space again, and du -h and "mount --bind / /mnt" did not point to the culprit. What finally got it was when I ran lsof. lsof...rsyslogd 1766 root 2w REG 9,1 12672375940 264014 /var/log/messages (deleted)... When I had deleted the messages log file, the rsyslog service still kept it open, but hidden. Running a "touch /var/log/messages;service rsyslog restart" cleared up the problem and my disk space was reclaimed. The lsof output can be a bit overwhelming, especially if you have a busy system (it was over 1000 lines long on mine). If you grep for "deleted" in the lsof output, it should help to pinpoint the problem process. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/299839', 'https://serverfault.com', 'https://serverfault.com/users/91238/']} | jdg_381273 |
stackexchange | llm_judgeable_groundtruth_similarity | 126286 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
In thinking about a MathOverflow question pertaining to numbers whose decimal and binary digit sums are equal, I found myself asking: Are there any solutions in non-negative integers $(a,b,c,d)$ to the equation $$2^a + 2^b = 10^c + 10^d$$ aside from the trivial solution $(0,0,0,0)$ and the nontrivial solutions $(2,4,1,1)$ and $(4,2,1,1)$? (This is, in effect, the case $s=2$ to the other MO question regarding which numbers $s$ can be a simultaneous binary and decimal digit sum and if so, how often. It seems likely that 20 is the only number whose digit sums are both 2, but that's basically what I'm asking here.) In searching for other solutions, we may as well assume, for the sake of simplicity, that $a\le b$ and $c\le d$. It's quickly clear that we can restrict to looking for positive solutions, and we can also dismiss the possibility that $a=b$. That is, we can assume $0\lt a\lt b$ and $0\lt c \le d$. The possibility that $c=d\ne 1$ is ruled out by Mihăilescu's proof of Catalan's conjecture: If $2^a + 2^b = 2\cdot10^c = 2^{c+1}\cdot5^c$ (with $a\lt b$) we necessarily have $a=c+1$, leaving the equation $1 = 5^c - 2^n$, where $n=b-a$, whose only solution is $c=1$, $n=2$. (Aside: We don't actually need to invoke Catalan's conjecture. See below.) If now we restrict to $c\lt d$, it's immediately clear that we must have $a=c$. After writing $n=b-a$ (as before) and $m=d-c$ and doing a little factoring, the problem reduces to what I take to be the core question: Does the equation $$1+2^n = 5^a(1+10^m)$$ have any solutions in positive integers $(a,m,n)$? This is as far as I've gotten in any meaningful sense. The question is obviously related to the Cunningham project. It's easy to see that $a>0$ implies $n\equiv2\mod4$, so the aurifeuillian factorization $$2^{4k+2}+1 = (2^{2k+1}-2^{k+1}+1)(2^{2k+1}+2^{k+1}+1)$$ may or may not help. (It does help avoid the use of invocation of Catalan's conjecture above: Only one aurifeuillian factor is divisible by 5.) It's also easy to see that $$n\log2 + \log(1+1/2^n) = a\log5 + m\log10 + \log(1+1/10^m)$$ implies $$(a+m)\log5 \approx (n-m)\log2$$ if $m$ and $n$ are large. Finally, writing $5^a = (1+4)^a = 1+4a+16{a\choose2}+\cdots$, it may be possible to say something useful about the relationship of $a$ to $n$, but I don't see what.
Now provide the response and nothing else.
| There's an elementary way of solving this (and similar equations). Let's start with$$ 1+2^n=5^a(1+10^m)$$which you want to solve in positive integers $n$, $a$, $m$. Clearly $m < n$ and $a < n$. As wccanard points out, $2$ is a primitive root modulo $5^a$ and so we obtain that $n$ is divisible by $2 \cdot 5^{a-1}$. In particular,$$2 \cdot 5^{a-1} \le n.$$Now let's use the fact that $m < n$ are reduce the equation modulo $2^m$. We obtain,$$5^a \equiv 1 \pmod{2^m}. $$As in your question you write this as$$4a + 16 \binom{a}{2}+\cdots \equiv 0 \pmod{2^m}.$$This implies that $2^{m-2} \mid a$, and so $$2^{m-2} \le a.$$The inequalities we now have show that the left-hand side of the equation is much bigger than the right-hand side as soon as the $n$ is large! Appended by the OP : With apologies to Samir if he had something slicker in mind, I thought I'd add my own elaboration on when $(1+2^n)$ becomes bigger than $5^a(1+10^m)$. The first displayed inequality implies $5^a \le (5/2)n$ and the second, combined with $a \lt n$, gives $2^m \le 4a < 4n.$ Clearly, $1+10^m \lt 16^m = (2^m)^4\lt (4n)^4$. This all gives $$2^n \lt 1+2^n = 5^a(1+10^m) \lt (5/2)n(4n)^4 = 640n^5,$$ and it's easy to check that this implies $n\lt 35$. Knowing also that $n$ must be congruent to 2 mod 4 means we can finish the problem off by checking the factorizations of $1+2^n$ for $n=2,6,10,14,18,22,26,30,$ and $34$, which is easy enough to do. A less crude estimate than $1+10^m \lt 16^m$ might shave off a few of the larger values of $n$, but it doesn't seem worth the effort. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/126286', 'https://mathoverflow.net', 'https://mathoverflow.net/users/15837/']} | jdg_381274 |
stackexchange | llm_judgeable_groundtruth_similarity | 16193331 |
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 not sure when but I read an article on this which indicates that the usage of Skip(1).Any() is better than Count() compassion when using Entity Framework (I may remember wrong). I'm not sure about this after I saw the generated T-SQL code. Here is the first option: int userConnectionCount = _dbContext.HubConnections.Count(conn => conn.UserId == user.Id);bool isAtSingleConnection = (userConnectionCount == 1); This generates the following T-SQL code which is reasonable: SELECT [GroupBy1].[A1] AS [C1]FROM ( SELECT COUNT(1) AS [A1] FROM [dbo].[HubConnections] AS [Extent1] WHERE [Extent1].[UserId] = @p__linq__0) AS [GroupBy1] Here is the other option which is the suggested query as far as I remember: bool isAtSingleConnection = !_dbContext .HubConnections.OrderBy(conn => conn.Id) .Skip(1).Any(conn => conn.UserId == user.Id); Here is the generated T-SQL for the above LINQ query: SELECT CASE WHEN ( EXISTS (SELECT 1 AS [C1] FROM ( SELECT [Extent1].[Id] AS [Id], [Extent1].[UserId] AS [UserId] FROM ( SELECT [Extent1].[Id] AS [Id], [Extent1].[UserId] AS [UserId], row_number() OVER (ORDER BY [Extent1].[Id] ASC) AS [row_number] FROM [dbo].[HubConnections] AS [Extent1] ) AS [Extent1] WHERE [Extent1].[row_number] > 1 ) AS [Skip1] WHERE [Skip1].[UserId] = @p__linq__0)) THEN cast(1 as bit) WHEN ( NOT EXISTS (SELECT 1 AS [C1] FROM ( SELECT [Extent2].[Id] AS [Id], [Extent2].[UserId] AS [UserId] FROM ( SELECT [Extent2].[Id] AS [Id], [Extent2].[UserId] AS [UserId], row_number() OVER (ORDER BY [Extent2].[Id] ASC) AS [row_number] FROM [dbo].[HubConnections] AS [Extent2] ) AS [Extent2] WHERE [Extent2].[row_number] > 1 ) AS [Skip2] WHERE [Skip2].[UserId] = @p__linq__0)) THEN cast(0 as bit) END AS [C1]FROM ( SELECT 1 AS X ) AS [SingleRowTable1]; Which one is the proper way here? Is there a big performance difference between these two?
Now provide the response and nothing else.
| Query performance depends on a lot of things, like the indexes that are present, the actual data, how stale the statistics about the data present are etc. SQL query plan optimizer looks at these different metrics to come up with an efficient query plan. So, any straightforward answer that says query 1 is always better than query 2 or the opposite would be incorrect. That said, my answer below tries to explain the articles stance and how Skip(1).Any() could be better(marginally) than doing a Count() > 1 . The second query though being bigger in size and mostly unreadable looks like it could be interpreted in an efficient fashion. Again, this depends on things aforementioned. The idea is that the number of rows that the database has to look into to figure out the result is more in case of Count() . In the count case, assuming that the required indexes are there (a clustered index on Id to make the OrderBy in second case efficient), the db has to go through count number of rows. In the second case, it has to go through a maximum of two rows to arrive at the answer. Lets get more scientific in our analysis and see if my above theory holds any ground. For this, I am creating a dummy database of customers. The Customer type looks like this, public class Customer{ public int ID { get; set; } public string Name { get; set; } public int Age { get; set; }} I am seeding the database with some 100K random rows(I really have to prove this) using this code, for (int j = 0; j < 100; j++) { using (CustomersContext db = new CustomersContext()) { Random r = new Random(); for (int i = 0; i < 1000; i++) { Customer c = new Customer { Name = Guid.NewGuid().ToString(), Age = r.Next(0, 100) }; db.Customers.Add(c); } db.SaveChanges(); } } Sample code here . Now, the queries that I am going to use are as follows, db.Customers.Where(c => c.Age == 26).Count() > 1; // scenario 1db.Customers.Where(c => c.Age == 26).OrderBy(c => c.ID).Skip(1).Any() // scenario 2 I have started SQL profiler to catch the query plans. The captured plans look as follows, Scenario 1: Check out the estimated cost and actual row count for scenario 1 in the above images. Scenario 2: Check out the estimated cost and actual row count for scenario 2 in the below images. As per the initial guess, the estimated cost and the number of rows is lesser in the Skip and any case as compared to Count case. Conclusion: All this analysis aside, as many others have commented earlier, these are not the kind of performance optimizations you should try to do in your code. Things like these hurt readability with very minimal(I would say non-existent) perf benefit. I just did this analysis for fun and would never use this as a basis for choosing scenario 2. I would measure and see if doing a Count() is actually hurting to change the code to use Skip().Any() . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16193331', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/463785/']} | jdg_381275 |
stackexchange | llm_judgeable_groundtruth_similarity | 49766 |
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
$$\frac{-\Delta G}{T}=\Delta S_{universe}$$ (This equation applies under isobaric and isothermal conditions.) I understand that if $\Delta G$ is positive, the reaction is nonspontaneous, and adding that amount of energy to a system can drive that reaction to occur. However, if you’re increasing the Gibbs free energy of the system, then by that equation, the entropy of the universe would be decreasing, which would violate the Second Law of Thermodynamics. Can anyone explain this?
Now provide the response and nothing else.
| When you add energy from somewhere, let's say a battery, you are creating a greater amount of entropy there (in the battery or whatever). That's all there is to it. The Second Law is not violated. The electrolysis process is not non-spontaneous. Yes, it would not occur in the absence of the battery. But the fact that it does occur with the battery there must tell you that overall it is spontaneous. The fact that you are coupling a strongly spontaneous reaction (discharge of the batter) with a non-spontaneous reaction (the electrolysis) means that overall, the electrolytic process is spontaneous. It's incorrect to treat the electrolysis as if it occurs without the battery. | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/49766', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/15465/']} | jdg_381276 |
stackexchange | llm_judgeable_groundtruth_similarity | 163559 |
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was looking at the contents of the Pioneer Plaque and I pretty much understood everything that was there, but not the so-called "Hyperfine transition of neutral hydrogen". Looking mostly at Wikipedia articles, I could understand that what is depicted there is the frequency (in centimeters) of the electromagnetic radiation of the spin up-spin down transition, and, crudely, this is what 'hyperfine transition' means. But, what I don't understand is how do the spectral line enters in all this. Do the photons emitted generate both emission and absorption lines? Or certain particles generate emission lines and other generate absorption? And how is this related to the 'hyperfine transition'? Does the spectral line has a period/frequency?
Now provide the response and nothing else.
| If you want to write a super-operator representing left- or right-multiplication, there is a distinct method which is simpler and more elegant. Let us define the left-multiplication superoperator by$$ \mathcal{L}(A)[\rho] = A\rho,$$and the right-multiplication superoperator by$$ \mathcal{R}(A)[\rho] = \rho A.$$It should be clear that these operations commute, i.e. $\mathcal{L}(A)\mathcal{R}(B) = \mathcal{R}(B)\mathcal{L}(A)$. Many common superoperators can be represented as a sum of these elementary components, for example the commutator: $$ [H,\rho] = \mathcal{L}(H)[\rho] - \mathcal{R}(H)[\rho].$$ Actually I believe all superoperators can be represented in terms of these elementary operations, although I have never proven it: it seems rather obvious. Now, in order to represent these operations as matrices, you need to flatten your target operator into a vector. One way of performing this mapping is the following$$ \tag{1}\rho = \sum_{i,j} \rho_{ij}\;\lvert i\rangle\langle j\rvert \to \sum_{i,j} \rho_{ij}\;\lvert i\rangle\otimes\lvert j \rangle . $$ In this flattened representation we find$$\mathcal{L}(A)[\rho] = \sum_{i,j} \rho_{ij}\;A\lvert i\rangle\langle j\rvert \to \sum_{i,j} \rho_{ij}\;(A\lvert i\rangle)\otimes\lvert j \rangle = \sum_{i,j} \rho_{ij}\;(A\otimes \mathbb{1})\lvert i\rangle\otimes\lvert j \rangle. $$Therefore the left-multiplication superoperator is represented by the matrix $\mathcal{L}(A)= (A\otimes\mathbb{1})$. Similarly, you should be able to show that $\mathcal{R}(A) = (\mathbb{1}\otimes A^T)$. Be warned: many standard computer linear algebra packages do not automatically perform the flattening map according to Eq. (1). For example, the MATLAB reshape() function uses a different convention, meaning that these formulas must be adapted. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/163559', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/72476/']} | jdg_381277 |
stackexchange | llm_judgeable_groundtruth_similarity | 742594 |
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 map network drive, but get error 1219 on Windows XP: net use z: \\serverA\tests password /user:serverA\alex I have tried net use * /del /yes But it has no effect, and the net use shows empty list. \\serverA\tests is a valid path, as I can open it in Explorer. What can be done? EDIT: After reboot it works. But any ideas are still very welcome.
Now provide the response and nothing else.
| This will usually be caused by a handle left open. Download Process Explorer to find it, and try to close the program that has it open (don't close the handle itself). If it turns out to be explorer.exe , it's probably a buggy preview handler/shell extension. If you can't find the handle, you can always try using the IP address of ServerA to create a new connection with different credentials, e.g. net use z: \\10.1.2.3\tests password /user:serverA\alex Yes, sorry - use Find Handle or DLL with \\ServerA to find the program. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/742594', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/62192/']} | jdg_381278 |
stackexchange | llm_judgeable_groundtruth_similarity | 593609 |
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:
In the Flow of dry water chapter of Feynman lecture, this following point is written (see here) : The law of hydrostatics, therefore, is that the stresses are always normal to any surface inside the fluid. The normal force per unit area is called pressure. From the fact that there is no shear in a static fluid, it follows that the pressure stress is the same in all directions (Fig. 40-1). We will let you entertain yourself by proving that if there is no shear on any plane in a fluid, the pressure must be the same in any direction. I am trying to figure out how to prove the statement "if there is no shear on any plane in a fluid, the pressure must be the same in any direction." What I've found so far: The premise he puts itself is confusing for me because according to Wikipedia, the pressure is a scalar field rather than a vector field and hence it should have no associated direction. Anyways, I assumed maybe that since pressure’s direction is determined by the area which it may act on and hence any area element below a given height from the top of the container would have the same pressure acting throughout it. After some searching on stack exchange, I found that the explanation of pressure being the same in all direction is given by Pascal's law ( See Here ), but on seeing the Wikipedia page for pascal's law (here) , I formed the impression that Pascal's law may be related to pressure transmission rather than what direction pressure acts in. This led me to search for proof for pascals law. I found this answer in which the author proves that pressure change in any point in a fluid is transmitted throughout the whole fluid undiminished(pascal's law) but I think that the statement doesn't really explain the isotropic nature of pressure. Hence this leads me to two main questions: How is pascal's law related to the isotropic nature of pressure? How do you prove the isotropic nature of pressure using pascal's law or however another way?
Now provide the response and nothing else.
| The stress tensor is the physical quantity which has units of pressure and describes the force per unit area in different directions. It is a tensor which you can think of as a matrix. When you multiply a matrix by a vector you get another vector. In the case of the stress tensor you multiply the stress by an area vector and you get a force vector, the force acting on that area. This allows us to look at the force in all directions. Since the stress tensor is a symmetric tensor it has three real eigenvalues: $\sigma_1$ , $\sigma_2$ , $\sigma_3$ . These are the diagonal elements of the tensor in coordinates rotated so that all of the off diagonal elements are 0. These are called the principal stresses and the axes are called the principal axes. In these coordinates the stress tensor is: $$ \left(\begin{array}{ccc} \sigma_1 & 0 & 0 \\ 0 & \sigma_2 & 0 \\ 0 & 0 & \sigma_3 \\\end{array}\right) $$ Let us order the eigenvalues from largest to smallest so $\sigma_1 \ge \sigma_2 \ge \sigma_3$ . The maximum normal stress (pressure in a direction) is equal the largest principle stress, $\sigma_1$ , and the minimum normal stress is equal to the smallest principle stress, $\sigma_3$ . Pressure being the same in all directions implies that the normal stress is the same in all directions, which is true if and only if the maximum normal stress is equal to the minimum normal stress. So the proof reduces to proving that $\sigma_1=\sigma_3$ In a coordinate system aligned with the principal axes, the shear stress, $\sigma_s$ , on a plane defined by its unit normal vector, $ \hat n=(n_1,n_2,n_3) $ , where $ \hat n \cdot \hat n = 1$ , is given by $$\sigma_s^2=(\sigma_1^2 n_1^2+\sigma_2^2 n_2^2+\sigma_3^2 n_3^2)-(\sigma_1 n_1^2+\sigma_2 n_2^2+\sigma_3 n_3^2)^2$$ We can find the extrema by solving $$\frac{\partial(\sigma_s^2)}{\partial n_i}=0$$ This has local minima of $\sigma_s^2=0$ for $\hat n=(\pm 1,0,0)$ , $\hat n=(0,\pm 1,0)$ , $\hat n=(0,0,\pm 1)$ . This has local maxima of $\sigma_s^2=\frac{1}{4}(\sigma_1-\sigma_2)^2$ for $\hat n = (\pm 1/\sqrt{2},\pm 1/\sqrt{2},0)$ $\sigma_s^2=\frac{1}{4}(\sigma_2-\sigma_3)^2$ for $\hat n = (0,\pm 1/\sqrt{2},\pm 1/\sqrt{2})$ $\sigma_s^2=\frac{1}{4}(\sigma_1-\sigma_3)^2$ for $\hat n = (\pm 1/\sqrt{2},0,\pm 1/\sqrt{2})$ Out of these the global maximum is the last one $\sigma_s^2=\frac{1}{4}(\sigma_1-\sigma_3)^2$ . Since a fluid in equilibrium has no shear stress we know that the maximum is zero (as is the minimum) so we have $\sigma_s^2=\frac{1}{4}(\sigma_1-\sigma_3)^2=0$ which implies $\sigma_1=\sigma_3$ which proves that the pressure is isotropic. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/593609', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/236734/']} | jdg_381279 |
stackexchange | llm_judgeable_groundtruth_similarity | 25647454 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to pass and receive two parameters to the state I want to transit to using ui-sref of ui-router. Something like using the link below for transitioning the state to home with foo and bar parameters: <a ui-sref="home({foo: 'fooVal', bar: 'barVal'})">Go to home state with foo and bar parameters </a> Receiving foo and bar values in a controller: app.controller('SomeController', function($scope, $stateParam) { //.. var foo = $stateParam.foo; //getting fooVal var bar = $stateParam.bar; //getting barVal //..}); I get undefined for $stateParam in the controller. Could somebody help me understand how to get it done? Edit: .state('home', { url: '/', views: { '': { templateUrl: 'home.html', controller: 'MainRootCtrl' }, 'A@home': { templateUrl: 'a.html', controller: 'MainCtrl' }, 'B@home': { templateUrl: 'b.html', controller: 'SomeController' } }});
Now provide the response and nothing else.
| I've created an example to show how to. Updated state definition would be: $stateProvider .state('home', { url: '/:foo?bar', views: { '': { templateUrl: 'tpl.home.html', controller: 'MainRootCtrl' }, ... } And this would be the controller: .controller('MainRootCtrl', function($scope, $state, $stateParams) { //.. var foo = $stateParams.foo; //getting fooVal var bar = $stateParams.bar; //getting barVal //.. $scope.state = $state.current $scope.params = $stateParams; }) What we can see is that the state home now has url defined as: url: '/:foo?bar', which means, that the params in url are expected as /fooVal?bar=barValue These two links will correctly pass arguments into the controller: <a ui-sref="home({foo: 'fooVal1', bar: 'barVal1'})"><a ui-sref="home({foo: 'fooVal2', bar: 'barVal2'})"> Also, the controller does consume $stateParams instead of $stateParam . Link to doc: URL Parameters You can check it here params : {} There is also new , more granular setting params : {} . As we've already seen, we can declare parameters as part of url . But with params : {} configuration - we can extend this definition or even introduce paramters which are not part of the url: .state('other', { url: '/other/:foo?bar', params: { // here we define default value for foo // we also set squash to false, to force injecting // even the default value into url foo: { value: 'defaultValue', squash: false, }, // this parameter is now array // we can pass more items, and expect them as [] bar : { array : true, }, // this param is not part of url // it could be passed with $state.go or ui-sref hiddenParam: 'YES', }, ... Settings available for params are described in the documentation of the $stateProvider Below is just an extract value - {object|function=} : specifies the default value for this parameter. This implicitly sets this parameter as optional... array - {boolean=}: (default: false) If true, the param value will be treated as an array of values. squash - {bool|string=}: squash configures how a default parameter value is represented in the URL when the current parameter value is the same as the default value. We can call these params this way: // hidden param cannot be passed via url<a href="#/other/fooVal?bar=1&bar=2">// default foo is skipped<a ui-sref="other({bar: [4,5]})"> Check it in action here | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/25647454', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/411449/']} | jdg_381280 |
stackexchange | llm_judgeable_groundtruth_similarity | 85087 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
We have ~50 machines which connect via a 3G modem from Option (either the Globesurfer Icon , Icon 401 or Icon 7.2 ) to the network, for some reason from the telco they will be dropped (signal issue, tower, butterfly flapping it's wings - the telco is not much help here). After the drop, the machines fail to reconnect. The error message that comes up is Cannot load phonebook. Error 1722 RPC is unavailable and checking the event log the following issue us listed there: Event Type: Error Event Source: MSDTC Client Event Category: (10) Event ID: 4427 Date: 2009/11/12 Time: 02:31:02 PM User: N/A Computer: TERMINAL Description: Failed to initialize the needed name objects. Error Specifics: d:\xpsp\com\com1x\dtc\dtc\msdtcprx\src\dtcinit.cpp:215, Pid: 3500 No Callstack, CmdLine: C:\WINDOWS\system32\dllhost.exe /Processid:{02D4B3F1-FD88-11D1-960D-00805FC79235} Data: 0000: 05 40 00 80 .@. The same issue will appear in the event log occur when trying to access the COM+ snap-in in the control panel. The solution is to reinstall MSDTC by doing the following: net stop msdtc msdtc -uninstall Delete the msdtc registry key msdtc -resetlogs msdtc -install net start msdtc This is on Windows XP Embedded SP 3. What I am trying to find is the cause of the corruption of msdtc, but I am not sure where to start. Updates (17/11) The solution above, which reinstalls MSDTC, works in so that MSDTC is no longer corrupted and the machines can reconnect - however it does not correct the reconnection issue permanently. The machines can reconnect for a while (yet to determine how long or what changes) and then will fail - however without the MSDTC corruption this time. (18/11) Testing the machines with a network connection, there issue never occurs. It would seem to indicate that the cause is something in the 3G modem. (19/11) Tried upgrading the drivers to the latest versions with no change. Was also recommended to change the MTU to 1354, which has also not helped.
Now provide the response and nothing else.
| If you don't want to create another IP, then all you can do is install a reverse http proxy on the main IP and a name based virtual host to route the traffic using mod_proxy. Here is how you can do it with apache, almost any http server can do it, other popular alternatives are squid, nginx, lighthttpd, etc. Listen IP_ADDR:80NameVirtualHost IP_ADDR:80<VirtualHost IP_ADDR:80> ServerName yourname.yourdomain ProxyPass / http://localhost:10000/ ProxyPassReverse / http://localhost:10000/</VirtualHost> | {} | {'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/85087', 'https://serverfault.com', 'https://serverfault.com/users/103/']} | jdg_381281 |
stackexchange | llm_judgeable_groundtruth_similarity | 3887460 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a high-level overview of HLA versus DIS simulation frameworks? Can one host the other and vice-versa?
Now provide the response and nothing else.
| I currently (though only for another week or so) work in the simulation industry - I apologize in advance for any errors, I will correct them if I am remembering incorrect information. DIS The standard specifies the layout of data on the wire, i.e. your packets/data PDUs are laid out exactly as defined in the DIS specifications Relies on best-effort networking (i.e. UDP protocol, broadcasting) Entities have to heartbeat at certain intervals (default: 5 seconds) to notify everyone else that it is still part of the exercise No central server managing the various applications joined to the exercise Simulation applications can join the simulation at any time, leave at any time HLA Uses a central manager, called the RTI (Run Time Infrastructure), that receives data from various applications and sends them to other applications in the simulation (in the context of HLA, these are called Federates and a set of Federates is a Federation) All federates must join and leave the simulation by going through the RTI Unlike DIS, HLA specification does not specify the layout of data packets, but instead defines a set of API functionality that applications use. The RTI is what implements the API. HLA federates publish data according to a FOM (Federation Object Model) which defines what the data in a simulation represents. This allows people to create new FOMs that define new object and interaction types, unlike in DIS, where adding new types of data PDUs goes through a committee (SISO). For example, most simulations running under HLA utilize the RPR FOM, which pretty much mirrors the DIS standard entities and interactions. HLA adds additional features DIS does not support, such as Data Distribution Management (DDM), wherein federates notify the RTI that they are only interested in certain types of data. Supports subscription services, wherein federates notify the RTI that they are only interested in receiving certain object or interaction data (i.e. an application only wants data about ships) Supports the feature of ownership transfer, where objects under the control of one federate are given to another federate to manage. Can DIS host HLA and Vice Versa? Due to these fundamental differences, it should be clear that DIS and HLA can not host each other. However, what this really means is that for simulations in DIS to interact with simulations in HLA is that you need some type of network broker that acts as an adapter between the two protocols. Examples of such brokers are MAK VR-Exchange or GMU Gateway . For even further reading: http://www.mak.com/products/standards.php http://www.siaa.asn.au/get/2395379411.pdf http://dss.ll.mit.edu/dss.web/96.14.103.RTI.Introduction.html | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3887460', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/31295/']} | jdg_381282 |
stackexchange | llm_judgeable_groundtruth_similarity | 5377782 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The following regular expression will match "Saturday" or "Sunday" : (?:(Sat)ur|(Sun))day But in one case backreference 1 is filled while backreference 2 is empty and in the other case vice-versa. PHP (pcre) provides a nice operator "?|" that circumvents this problem. The previous regex would become (?|(Sat)ur|(Sun))day . So there will not be empty backreferences. Is there an equivalent in C# or some workaround ?
Now provide the response and nothing else.
| .NET doesn't support the branch-reset operator, but it does support named groups, and it lets you reuse group names without restriction (something no other flavor does, AFAIK). So you could use this: (?:(?<abbr>Sat)ur|(?<abbr>Sun))day ...and the abbreviated name will be stored in Match.Groups["abbr"] . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5377782', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/363573/']} | jdg_381283 |
stackexchange | llm_judgeable_groundtruth_similarity | 16777456 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Summary: I'm looking for the fastest way to calculate (int) x / (int) y without getting an exception for y==0 . Instead I just want an arbitrary result. Background: When coding image processing algorithms I often need to divide by an (accumulated) alpha value. The most simple variant is plain C code with integer arithmetic. My problem is that I typically get a division by zero error for result pixels with alpha==0 . However this are exactly the pixels where the result doesn't matter at all: I don't care about color values of pixels with alpha==0 . Details: I'm looking for something like: result = (y==0)? 0 : x/y; or result = x / MAX( y, 1 ); x and y are positive integers. The code is executed a huge number of times in a nested loop, so I'm looking for a way to get rid of the conditional branching. When y does not exceed the byte range, I'm happy with the solution unsigned char kill_zero_table[256] = { 1, 1, 2, 3, 4, 5, 6, 7, [...] 255 };[...]result = x / kill_zero_table[y]; But this obviously does not work well for bigger ranges. I guess the final question is: Whats the fastest bit twiddling hack changing 0 to any other integer value, while leaving all other values unchanged? Clarifications I'm not 100% sure that branching is too expensive. However, different compilers are used, so I prefer benchmarking with little optimizations (which is indeed questionable). For sure, compilers are great when it comes to bit twiddling, but I can't express the "don't care" result in C, so the compiler will never be able to use the full range of optimizations. Code should be fully C compatible, main platforms are Linux 64 Bit with gcc & clang and MacOS.
Now provide the response and nothing else.
| Inspired by some of the comments I got rid of the branch on my Pentium and gcc compiler using int f (int x, int y){ y += y == 0; return x/y;} The compiler basically recognizes that it can use a condition flag of the test in the addition. As per request the assembly: .globl f .type f, @functionf: pushl %ebp xorl %eax, %eax movl %esp, %ebp movl 12(%ebp), %edx testl %edx, %edx sete %al addl %edx, %eax movl 8(%ebp), %edx movl %eax, %ecx popl %ebp movl %edx, %eax sarl $31, %edx idivl %ecx ret As this turned out to be such a popular question and answer, I'll elaborate a bit more. The above example is based on programming idiom that a compiler recognizes. In the above case a boolean expression is used in integral arithmetic and the use of condition flags are invented in hardware for this purpose. In general condition flags are only accessible in C through using idiom. That is why it so hard to make a portable multiple precision integer library in C without resorting to (inline) assembly. My guess is that most decent compilers will understand the above idiom. Another way of avoiding branches, as also remarked in some of the above comments, is predicated execution. I therefore took philipp's first code and my code and ran it through the compiler from ARM and the GCC compiler for the ARM architecture, which features predicated execution. Both compilers avoid the branch in both samples of code: Philipp's version with the ARM compiler: f PROC CMP r1,#0 BNE __aeabi_idivmod MOVEQ r0,#0 BX lr Philipp's version with GCC: f: subs r3, r1, #0 str lr, [sp, #-4]! moveq r0, r3 ldreq pc, [sp], #4 bl __divsi3 ldr pc, [sp], #4 My code with the ARM compiler: f PROC RSBS r2,r1,#1 MOVCC r2,#0 ADD r1,r1,r2 B __aeabi_idivmod My code with GCC: f: str lr, [sp, #-4]! cmp r1, #0 addeq r1, r1, #1 bl __divsi3 ldr pc, [sp], #4 All versions still need a branch to the division routine, because this version of the ARM doesn't have hardware for a division, but the test for y == 0 is fully implemented through predicated execution. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/16777456', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/664204/']} | jdg_381284 |
stackexchange | llm_judgeable_groundtruth_similarity | 6353149 |
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 vector of pointers to objects. I need to remove an element from the vector and place that element in another list. I read that erase can be used to remove the object from the vector, but I also read that it calls the objects destructor before doing so. I need to know whether or not erasing the object will destroy it as well.
Now provide the response and nothing else.
| vector::erase Removes from the vector container and calls its destructor but If the contained object is a pointer it doesnt take ownership of destroying it. You will have to explicitly call delete on each contained pointer to delete the content it is pointing to, for example: void clearVectorContents( std::vector <YourClass*> & a ) { for ( int i = 0; i < a.size(); i++ ) { delete a[i]; } a.clear(); } Storing raw pointers in standard containers is not a good idea. If you really need to store resources that have to be allocated by new , then you should use boost::shared_ptr . Check out the Boost documentation . An more generic & elegant solution: This solution makes use of for_each & templates as @Billy pointed out in comments: // Functor for deleting pointers in vector.template<class T> class DeleteVector{ public: // Overloaded () operator. // This will be called by for_each() function. bool operator()(T x) const { // Delete pointer. delete x; return true; }}; And this can be called as: for_each( myclassVector.begin(),myclassVector.end(), DeleteVector<myclass*>()); where, myclassVector is your vector containing pointers to myclass class objects. Usage Example: #include "functional"#include "vector"#include "algorithm"#include "iostream"//Your classclass myclass{ public: int i; myclass():i(10){}};// Functor for deleting pointers in vector.template<class T> class DeleteVector{ public: // Overloaded () operator. // This will be called by for_each() function. bool operator()(T x) const { // Delete pointer. delete x; return true; }};int main(){ // Add 10 objects to the vector. std::vector<myclass*> myclassVector; for( int Index = 0; Index < 10; ++Index ) { myclassVector.push_back( new myclass); } for (int i=0; i<myclassVector.size(); i++) { std::cout << " " << (myclassVector[i])->i; } // Now delete the vector contents in a single line. for_each( myclassVector.begin(), myclassVector.end(), DeleteVector<myclass*>()); //Clear the vector myclassVector.clear(); std::cout<<"\n"<<myclassVector.size(); return 0;} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/6353149', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/152993/']} | jdg_381285 |
stackexchange | llm_judgeable_groundtruth_similarity | 6856028 |
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 execute an external command from java code, but there's a difference I've noticed between Runtime.getRuntime().exec(...) and new ProcessBuilder(...).start() . When using Runtime : Process p = Runtime.getRuntime().exec(installation_path + uninstall_path + uninstall_command + uninstall_arguments);p.waitFor(); the exitValue is 0 and the command is terminated ok. However, with ProcessBuilder : Process p = (new ProcessBuilder(installation_path + uninstall_path + uninstall_command, uninstall_arguments)).start();p.waitFor(); the exit value is 1001 and the command terminates in the middle, although waitFor returns. What should I do to fix the problem with ProcessBuilder ?
Now provide the response and nothing else.
| The various overloads of Runtime.getRuntime().exec(...) take either an array of strings or a single string. The single-string overloads of exec() will tokenise the string into an array of arguments, before passing the string array onto one of the exec() overloads that takes a string array. The ProcessBuilder constructors, on the other hand, only take a varargs array of strings or a List of strings, where each string in the array or list is assumed to be an individual argument. Either way, the arguments obtained are then joined up into a string that is passed to the OS to execute. So, for example, on Windows, Runtime.getRuntime().exec("C:\DoStuff.exe -arg1 -arg2"); will run a DoStuff.exe program with the two given arguments. In this case, the command-line gets tokenised and put back together. However, ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe -arg1 -arg2"); will fail, unless there happens to be a program whose name is DoStuff.exe -arg1 -arg2 in C:\ . This is because there's no tokenisation: the command to run is assumed to have already been tokenised. Instead, you should use ProcessBuilder b = new ProcessBuilder("C:\DoStuff.exe", "-arg1", "-arg2"); or alternatively List<String> params = java.util.Arrays.asList("C:\DoStuff.exe", "-arg1", "-arg2");ProcessBuilder b = new ProcessBuilder(params); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6856028', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/867030/']} | jdg_381286 |
stackexchange | llm_judgeable_groundtruth_similarity | 340865 |
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 a situation where I want to connect to a Linux machine running VNC (lets call it VNCServer) which is behind two consecutive Linux machines i.e., to ssh into the VNCServer, I have to ssh into Gateway1 from my laptop, then from Gateway1 shell I ssh into the Gateway2 and then from that shell I finally ssh into VNCServer. I cannot change the network design and access flow Laptop-->Gateway1-->Gateway2-->Server. I have no root privileges on Gateway1 and all ports except 22 and 5901 are closed. Is there a way by which I can launch a VNC viewer on my laptop and access the VNCServer? I understand that it might be done using ssh tunneling features and I have putty on my Windows laptop (sorry, no Linux or Cygwin etc. can be installed on the work laptop). Any help will be greatly appreciated as this would make my life so easier!
Now provide the response and nothing else.
| Putty does support ssh tunnels, if you expand the Connection, SSH tree, you'll see an entry for tunnels. Local tunnels produce a localhost port opening on your windows machine that remotes to the ip address and port you specify. For instance, when I'm trying to RDP to a desktop at my house, I'll generally choose a random local port, something like 7789, then put the local ip address of the desktop (1.2.3.4:3389) as the remote host. Be sure to click "Add", then "Apply." At this point, when you rdp to 127.0.0.1:7789, you'll then connect to 1.2.3.4:3389 over the putty session. This is where the fun comes in. If you then setup a port tunnel on your intermediate box, setting up the local port you specified as the remote port in putty, you can then bounce through your putty, through the intermediate box your final destination. You'll still need to do a few ssh connects, but you'll be able to cross vnc or rdp directly from the windows system once you're set, which is what I believe you're looking to do. EXAMPLE Head over to the tunnels panel in Putty (Connections->SSH->Tunnels accessed either from the context menu if the ssh session is already active, or in the beginning connection screen when just starting putty) Create a tunnel with local source 15900, and remote source 127.0.0.1:15900 Connect (if not already connected) to Gateway1. On Gateway1, ssh -L 127.0.0.1:15900:VNCServerIP:5900 user@Gateway2 Once the ssh to Gateway2 is up, attempt to vnc to 127.0.0.1:15900 -- you should now see the VNC screen on the far side! ADDED BONUS -- not many people know this, but this process can also be used to proxy IPv6/IPv4 traffic as well. SSH doesn't care what protocol it uses for the tunnels, so you can theoretically access IPv6 only hosts from an IPv4 only system, given that the ssh server is dual stack (has both IPv4 and IPv6 addresses.) | {} | {'log_upvote_score': 6, 'links': ['https://serverfault.com/questions/340865', 'https://serverfault.com', 'https://serverfault.com/users/104112/']} | jdg_381287 |
stackexchange | llm_judgeable_groundtruth_similarity | 18630937 |
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 restore a vim file from the undo file without hitting undo ? I had a vim file that I saved while adding text. Then I ran a python command that emptied the file's contents, and I can see some of the words the file contained in the file's .un~ file. When I try to undo in the file, it says Already at latest change . I can't find the swap file in my swap files directory.
Now provide the response and nothing else.
| You can't. The undo information is linked to Vim's last knowledge of the file's contents; when they don't correspond any more, Vim cannot re-apply the changes. This is documented at :help undo-persistence : Vim will detect if an undo file is no longer synchronized with the file it was written for (with a hash of the file contents) and ignore it when the file was changed after the undo file was written, to prevent corruption. Best you can do is try to manually salvage recognizable bits in the undo file, e.g. with a hex editor, or Vim's binary mode. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18630937', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/365298/']} | jdg_381288 |
stackexchange | llm_judgeable_groundtruth_similarity | 2349211 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been trying to optimize some extremely performance-critical code (a quick sort algorithm that's being called millions and millions of times inside a monte carlo simulation) by loop unrolling. Here's the inner loop I'm trying to speed up: // Search for elements to swap.while(myArray[++index1] < pivot) {}while(pivot < myArray[--index2]) {} I tried unrolling to something like: while(true) { if(myArray[++index1] < pivot) break; if(myArray[++index1] < pivot) break; // More unrolling}while(true) { if(pivot < myArray[--index2]) break; if(pivot < myArray[--index2]) break; // More unrolling} This made absolutely no difference so I changed it back to the more readable form. I've had similar experiences other times I've tried loop unrolling. Given the quality of branch predictors on modern hardware, when, if ever, is loop unrolling still a useful optimization?
Now provide the response and nothing else.
| Loop unrolling makes sense if you can break dependency chains. This gives a out of order or super-scalar CPU the possibility to schedule things better and thus run faster. A simple example: for (int i=0; i<n; i++){ sum += data[i];} Here the dependency chain of the arguments is very short. If you get a stall because you have a cache-miss on the data-array the cpu cannot do anything but to wait. On the other hand this code: for (int i=0; i<n-3; i+=4) // note the n-3 bound for starting i + 0..3{ sum1 += data[i+0]; sum2 += data[i+1]; sum3 += data[i+2]; sum4 += data[i+3];}sum = sum1 + sum2 + sum3 + sum4;// if n%4 != 0, handle final 0..3 elements with a rolled up loop or whatever could run faster. If you get a cache miss or other stall in one calculation there are still three other dependency chains that don't depend on the stall. A out of order CPU can execute these in parallel. (See Why does mulss take only 3 cycles on Haswell, different from Agner's instruction tables? (Unrolling FP loops with multiple accumulators) for an in-depth look at how register-renaming helps CPUs find that parallelism, and an in depth look at the details for FP dot-product on modern x86-64 CPUs with their throughput vs. latency characteristics for pipelined floating-point SIMD FMA ALUs. Hiding latency of FP addition or FMA is a major benefit to multiple accumulators, since latencies are longer than integer but SIMD throughput is often similar.) | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2349211', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/23903/']} | jdg_381289 |
stackexchange | llm_judgeable_groundtruth_similarity | 52069813 |
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 created a PHP login form where I want to add ajax code in which it helps me to successfully login without loading windows bit during the ajax code are adding .This code is not working. Please help me fix this issue and it is possible that I dont want to show login after page in Jquery . What I mean is that after the login page i dont want dashboard.php to show the user. But my main issue is that my code is not working.Please help and fix my issue. Thanks in advance. $.ajax({ method: "POST", url: "loginpage.php", dataType: "json", data: { email: email, password: pass},success:function(data){if(data.type=='success') window.location = 'welcomepage_hideme.php';else//server side error from php but now alert("Incorrect email or and password");}}); <?php $msg = ""; if (isset($_POST['submit'])) { $con = new mysqli('localhost', 'research_emailC', 'test123', 'research_phpEmailConfirmation'); $email = $con->real_escape_string($_POST['email']); $password = $con->real_escape_string($_POST['pass']); if ($email == "" || $password == "") $msg = "Please check your inputs!"; else { $sql = $con->query("SELECT id, password, isEmailConfirmed FROM users WHERE email='$email'"); if ($sql->num_rows > 0) { $data = $sql->fetch_array(); if (password_verify($password, $data['password'])) { if ($data['isEmailConfirmed'] == 0) $msg = "Please verify your email!"; else { $msg = "You have been logged in"; header("location: welcomepage_hideme.php"); } } else $msg = "Please check your inputs!"; } else { $msg = "Please check your inputs!"; } } }?><!doctype html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Log In</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous"></head><body> <div class="container" style="margin-top: 100px;"> <div class="row justify-content-center"> <div class="col-md-6 col-md-offset-3" align="center"> <img src="images/logo.png"><br><br> <?php if ($msg != "") echo $msg . "<br><br>" ?> <form method="post" action="loginpage.php"> <input class="form-control" name="email" type="email" placeholder="Email..."><br> <input class="form-control" name="password" type="password" placeholder="Password..."><br> <input class="btn btn-primary" type="submit" name="submit" value="Log In"> </form> </div> </div> </div></body></html>
Now provide the response and nothing else.
| ++cnt and cnt.fetch_add(1) are truly atomic operations. One thread is blocked while the other thread reads, increments, and updates the value. As such, the two threads cannot step on each other's toes. Access to cnt is fully serialized, and the final result is as you would expect. cnt = cnt+1; is not fully atomic. It involves three separate operations, only two of which are atomic, but one is not. By the time a thread has atomically read the current value of cnt and made a copy of it locally, the other thread is no longer blocked and can freely modify cnt at will while that copy is being incremented. Then, the assignment of the incremented copy back to cnt is done atomically, but will be assigning a stale value if cnt has already been modified by the other thread. So the final result is random and not what you would expect. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/52069813', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10264068/']} | jdg_381290 |
stackexchange | llm_judgeable_groundtruth_similarity | 2853673 |
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 came across this as one of the shortcuts in my textbook without any proof. When $b\gt a$, $$\int\limits_a^b \dfrac{dx}{\sqrt{(x-a)(b-x)}}=\pi$$ My attempt : I notice that the the denominator is $0$ at both the bounds. I thought of substituting $x=a+(b-a)t$ so that the integral becomes$$\int\limits_0^1 \dfrac{dt}{\sqrt{t(1-t)}}$$ This doesn't look simple, but I'm wondering if the answer can be seen using symmetry/geometry ?
Now provide the response and nothing else.
| Other way is substitution $t=\sin^2\theta$ so$$\int\limits_0^1 \dfrac{dt}{\sqrt{t(1-t)}}=\int\limits_0^\frac{\pi}{2} 2dt=\pi$$ | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/2853673', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/168854/']} | jdg_381291 |
stackexchange | llm_judgeable_groundtruth_similarity | 57144905 |
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 table with few columns including 2 varchar2(200) columns. In this columns we basically store serial numbers which can be numeric or alpha-numeric. Alpha-numeric values always both serials are same in those 2 columns. However for number serials it is a range like (first column value = 511368000004001226 and second column value = 511368000004001425 with 200 different (Qty)). Maximum length of the serial is 20 digits. I have indexed both the columns.Now I want to sear a serial in-between the above range. (lets say 511368000004001227). I use following query. SELECT * FROM Table_Namr dWHERE d.FROM_SN <= '511368000004001227' AND d.TO_SN >= '511368000004001227' Is it a valid query? Can I use <=> operators for numbers in a varchar column?
Now provide the response and nothing else.
| This error shows up in Android 10 with androidx.core (or core-ktx) version 1.2.0 and higher when you try to register multiple fonts with the same style and weight into the same font family. Although your example is creating the font family programmatically, most developers will run into this error when using the font XML, so let's start with that. In the font XML, we can't have more than one font element with the same fontStyle and fontWeight attributes. For example, the following XML would cause this error, because both font elements have the same values for the style and weight: <?xml version="1.0" encoding="utf-8"?><font-family xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <font android:font="@font/gibson_regular" android:fontStyle="normal" android:fontWeight="400" /> <font android:font="@font/gibson_bold" android:fontStyle="normal" android:fontWeight="400" /></font-family> Even though the value of font is different ( @font/gibson_regular vs @font/gibson_bold ), the fontStyle and fontWeight are the same, so this causes the error. Also, note that if you do not provide the fontStyle or fontWeight attributes, they default to normal and 400 respectively, so this next example also fails: <?xml version="1.0" encoding="utf-8"?><font-family xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <font android:font="@font/gibson_regular" android:fontStyle="normal" android:fontWeight="400" /> <font android:font="@font/gibson_bold" /></font-family> To fix the issue, make sure that the combination of fontStyle and fontWeight for each font element is unique. For example, if we properly set the fontWeight for the gibson_bold font, we will avoid the error: <?xml version="1.0" encoding="utf-8"?><font-family xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <font android:font="@font/gibson_regular" android:fontStyle="normal" android:fontWeight="400" /> <font android:font="@font/gibson_bold" android:fontStyle="normal" android:fontWeight="700" /></font-family> Now, when building this out programmatically, as you are above, the same rules apply. It looks like the API docs that you're referencing haven't been updated to match what the source code is actually doing. Here's how your example should look now: val regularFont: Font = Font.Builder(resources.assets,"regular.ttf").build()val boldFont: Font = Font.Builder(resources.assets, "bold.ttf").build()val family: FontFamily = FontFamily.Builder(regularFont).addFont(boldFont).build()val typeface: Typeface = CustomFallbackBuilder(family) .setStyle(FontStyle(FONT_WEIGHT_BOLD, FONT_SLANT_UPRIGHT)) .build() When writing it programmatically like this, it appears that Android properly notes the weight and style of the fonts when loading them in via the Font.Builder , so as long as regular.ttf and bold.ttf differ in their weight and style, this code will work fine. But you can still get this exception if the two fonts have the same weight and style, or if you manually specify the font and style to be the same, such as if you were to call setWeight(400) on the bold font. In summary, when using the font XML, always specify the fontStyle and fontWeight for each font. And regardless of whether you're writing things with XML or building them out programmatically, make sure that the combination of weight and style is unique for each font in a font family. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/57144905', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11818788/']} | jdg_381292 |
stackexchange | llm_judgeable_groundtruth_similarity | 3986067 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Im looking for a delphi component that looks and functions like the Windows 7 control panel buttons when you "view by category". Anybody know if something like this already exists?
Now provide the response and nothing else.
| I just created a small component that looks sort of what you want. It is double-buffered, and hence completely flicker-free, and works both with visual themes enabled and disabled. unit TaskButton;interfaceuses SysUtils, Forms, Messages, Windows, Graphics, Classes, Controls, UxTheme, ImgList, PNGImage;type TIconSource = (isImageList, isPNGImage); TTaskButtonLinkClickEvent = procedure(Sender: TObject; LinkIndex: integer) of object; TTaskButton = class(TCustomControl) private { Private declarations } FCaption: TCaption; FHeaderRect: TRect; FImageSpacing: integer; FLinks: TStrings; FHeaderHeight: integer; FLinkHeight: integer; FLinkSpacing: integer; FHeaderSpacing: integer; FLinkRects: array of TRect; FPrevMouseHoverIndex: integer; FMouseHoverIndex: integer; FImages: TImageList; FImageIndex: TImageIndex; FIconSource: TIconSource; FImage: TPngImage; FBuffer: TBitmap; FOnLinkClick: TTaskButtonLinkClickEvent; procedure UpdateMetrics; procedure SetCaption(const Caption: TCaption); procedure SetImageSpacing(ImageSpacing: integer); procedure SetLinkSpacing(LinkSpacing: integer); procedure SetHeaderSpacing(HeaderSpacing: integer); procedure SetLinks(Links: TStrings); procedure SetImages(Images: TImageList); procedure SetImageIndex(ImageIndex: TImageIndex); procedure SetIconSource(IconSource: TIconSource); procedure SetImage(Image: TPngImage); procedure SwapBuffers; function ImageWidth: integer; function ImageHeight: integer; procedure SetNonThemedHeaderFont; procedure SetNonThemedLinkFont(Hovering: boolean = false); protected { Protected declarations } procedure Paint; override; procedure WndProc(var Message: TMessage); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override; procedure MouseMove(Shift: TShiftState; X: Integer; Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X: Integer; Y: Integer); override; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; published { Published declarations } property Caption: TCaption read FCaption write SetCaption; property Links: TStrings read FLinks write SetLinks; property ImageSpacing: integer read FImageSpacing write SetImageSpacing default 16; property HeaderSpacing: integer read FHeaderSpacing write SetHeaderSpacing default 2; property LinkSpacing: integer read FLinkSpacing write SetLinkSpacing default 2; property Images: TImageList read FImages write SetImages; property ImageIndex: TImageIndex read FImageIndex write SetImageIndex; property Image: TPngImage read FImage write SetImage; property IconSource: TIconSource read FIconSource write SetIconSource default isPNGImage; property OnLinkClick: TTaskButtonLinkClickEvent read FOnLinkClick write FOnLinkClick; end;procedure Register;implementationuses Math;procedure Register;begin RegisterComponents('Rejbrand 2009', [TTaskButton]);end;function IsIntInInterval(x, xmin, xmax: integer): boolean; inline;begin IsIntInInterval := (xmin <= x) and (x <= xmax);end;function PointInRect(const Point: TPoint; const Rect: TRect): boolean; inline;begin PointInRect := IsIntInInterval(Point.X, Rect.Left, Rect.Right) and IsIntInInterval(Point.Y, Rect.Top, Rect.Bottom);end;{ TTaskButton }constructor TTaskButton.Create(AOwner: TComponent);begin inherited; InitThemeLibrary; FBuffer := TBitmap.Create; FLinks := TStringList.Create; FImage := TPngImage.Create; FImageSpacing := 16; FHeaderSpacing := 2; FLinkSpacing := 2; FPrevMouseHoverIndex := -1; FMouseHoverIndex := -1; FIconSource := isPNGImage;end;destructor TTaskButton.Destroy;begin FLinkRects := nil; FImage.Free; FLinks.Free; FBuffer.Free; inherited;end;function TTaskButton.ImageHeight: integer;begin result := 0; case FIconSource of isImageList: if Assigned(FImages) then result := FImages.Height; isPNGImage: if Assigned(FImage) then result := FImage.Height; end;end;function TTaskButton.ImageWidth: integer;begin result := 0; case FIconSource of isImageList: if Assigned(FImages) then result := FImages.Width; isPNGImage: if Assigned(FImage) then result := FImage.Width; end;end;procedure TTaskButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);begin inherited; Paint;end;procedure TTaskButton.MouseMove(Shift: TShiftState; X, Y: Integer);var i: Integer;begin inherited; FMouseHoverIndex := -1; for i := 0 to high(FLinkRects) do if PointInRect(point(X, Y), FLinkRects[i]) then begin FMouseHoverIndex := i; break; end; if FMouseHoverIndex <> FPrevMouseHoverIndex then begin Cursor := IfThen(FMouseHoverIndex <> -1, crHandPoint, crDefault); Paint; end; FPrevMouseHoverIndex := FMouseHoverIndex;end;procedure TTaskButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);begin inherited; Paint; if (FMouseHoverIndex <> -1) and Assigned(FOnLinkClick) then FOnLinkClick(Self, FMouseHoverIndex);end;procedure TTaskButton.Paint;var theme: HTHEME; i: Integer; pnt: TPoint; r: PRect;begin inherited; if FLinks.Count <> length(FLinkRects) then UpdateMetrics; FBuffer.Canvas.Brush.Color := Color; FBuffer.Canvas.FillRect(ClientRect); if GetCursorPos(pnt) then if PointInRect(Self.ScreenToClient(pnt), ClientRect) then begin if UxTheme.UseThemes then begin theme := OpenThemeData(Handle, 'BUTTON'); if theme <> 0 then try DrawThemeBackground(theme, FBuffer.Canvas.Handle, BP_COMMANDLINK, CMDLS_HOT, ClientRect, nil); finally CloseThemeData(theme); end; end else begin New(r); try r^ := ClientRect; DrawEdge(FBuffer.Canvas.Handle, r^, EDGE_RAISED, BF_RECT); finally Dispose(r); end; end; end; case FIconSource of isImageList: if Assigned(FImages) then FImages.Draw(FBuffer.Canvas, 14, 16, FImageIndex); isPNGImage: if Assigned(FImage) then FBuffer.Canvas.Draw(14, 16, FImage); end; if UxTheme.UseThemes then begin theme := OpenThemeData(Handle, 'CONTROLPANEL'); if theme <> 0 then try DrawThemeText(theme, FBuffer.Canvas.Handle, CPANEL_SECTIONTITLELINK, CPSTL_NORMAL, PChar(Caption), length(Caption), DT_LEFT or DT_END_ELLIPSIS or DT_TOP or DT_SINGLELINE, 0, FHeaderRect); for i := 0 to FLinks.Count - 1 do DrawThemeText(theme, FBuffer.Canvas.Handle, CPANEL_CONTENTLINK, IfThen(FMouseHoverIndex = i, IfThen(csLButtonDown in ControlState, CPCL_PRESSED, CPCL_HOT), CPCL_NORMAL), PChar(FLinks[i]), length(FLinks[i]), DT_LEFT or DT_END_ELLIPSIS or DT_TOP or DT_SINGLELINE, 0, FLinkRects[i] ); finally CloseThemeData(theme); end; end else begin SetNonThemedHeaderFont; DrawText(FBuffer.Canvas.Handle, PChar(Caption), -1, FHeaderRect, DT_LEFT or DT_END_ELLIPSIS or DT_TOP or DT_SINGLELINE); for i := 0 to FLinks.Count - 1 do begin SetNonThemedLinkFont(FMouseHoverIndex = i); DrawText(FBuffer.Canvas.Handle, PChar(FLinks[i]), -1, FLinkRects[i], DT_LEFT or DT_END_ELLIPSIS or DT_TOP or DT_SINGLELINE); end; end; SwapBuffers;end;procedure TTaskButton.SetCaption(const Caption: TCaption);begin if not SameStr(FCaption, Caption) then begin FCaption := Caption; UpdateMetrics; Paint; end;end;procedure TTaskButton.SetHeaderSpacing(HeaderSpacing: integer);begin if FHeaderSpacing <> HeaderSpacing then begin FHeaderSpacing := HeaderSpacing; UpdateMetrics; Paint; end;end;procedure TTaskButton.SetIconSource(IconSource: TIconSource);begin if FIconSource <> IconSource then begin FIconSource := IconSource; UpdateMetrics; Paint; end;end;procedure TTaskButton.SetImage(Image: TPngImage);begin FImage.Assign(Image); UpdateMetrics; Paint;end;procedure TTaskButton.SetImageIndex(ImageIndex: TImageIndex);begin if FImageIndex <> ImageIndex then begin FImageIndex := ImageIndex; UpdateMetrics; Paint; end;end;procedure TTaskButton.SetImages(Images: TImageList);begin FImages := Images; UpdateMetrics; Paint;end;procedure TTaskButton.SetImageSpacing(ImageSpacing: integer);begin if FImageSpacing <> ImageSpacing then begin FImageSpacing := ImageSpacing; UpdateMetrics; Paint; end;end;procedure TTaskButton.SetLinks(Links: TStrings);begin FLinks.Assign(Links); UpdateMetrics; Paint;end;procedure TTaskButton.SetLinkSpacing(LinkSpacing: integer);begin if FLinkSpacing <> LinkSpacing then begin FLinkSpacing := LinkSpacing; UpdateMetrics; Paint; end;end;procedure TTaskButton.SwapBuffers;begin BitBlt(Canvas.Handle, 0, 0, Width, Height, FBuffer.Canvas.Handle, 0, 0, SRCCOPY);end;procedure TTaskButton.WndProc(var Message: TMessage);begin inherited; case Message.Msg of WM_SIZE: UpdateMetrics; CM_MOUSEENTER: Paint; CM_MOUSELEAVE: Paint; WM_ERASEBKGND: Message.Result := 1; end;end;procedure TTaskButton.UpdateMetrics;var theme: HTHEME; cr, r: TRect; i, y: Integer;begin FBuffer.SetSize(Width, Height); SetLength(FLinkRects, FLinks.Count); if UxTheme.UseThemes then begin theme := OpenThemeData(Handle, 'CONTROLPANEL'); if theme <> 0 then try with cr do begin Top := 10; Left := ImageWidth + FImageSpacing; Right := Width - 4; Bottom := Self.Height; end; GetThemeTextExtent(theme, FBuffer.Canvas.Handle, CPANEL_SECTIONTITLELINK, CPSTL_NORMAL, PChar(Caption), -1, DT_LEFT or DT_END_ELLIPSIS or DT_TOP or DT_SINGLELINE, @cr, r); FHeaderHeight := r.Bottom - r.Top; with FHeaderRect do begin Top := 10; Left := 14 + ImageWidth + FImageSpacing; Right := Width - 4; Bottom := Top + FHeaderHeight; end; with cr do begin Top := 4; Left := 14 + ImageWidth + FImageSpacing; Right := Width - 4; Bottom := Self.Height; end; y := FHeaderRect.Bottom + FHeaderSpacing; for i := 0 to high(FLinkRects) do begin GetThemeTextExtent(theme, FBuffer.Canvas.Handle, CPANEL_CONTENTLINK, CPCL_NORMAL, PChar(FLinks[i]), -1, DT_LEFT or DT_END_ELLIPSIS or DT_TOP or DT_SINGLELINE, @cr, r); FLinkHeight := r.Bottom - r.Top; FLinkRects[i].Left := FHeaderRect.Left; FLinkRects[i].Top := y; FLinkRects[i].Right := FLinkRects[i].Left + r.Right - r.Left; FLinkRects[i].Bottom := FLinkRects[i].Top + FLinkHeight + FLinkSpacing; inc(y, FLinkHeight + FLinkSpacing); end; finally CloseThemeData(theme); end; end else begin SetNonThemedHeaderFont; FHeaderHeight := FBuffer.Canvas.TextHeight(FCaption); with FHeaderRect do begin Top := 10; Left := 14 + ImageWidth + FImageSpacing; Right := Width - 4; Bottom := Top + FHeaderHeight; end; SetNonThemedLinkFont; y := FHeaderRect.Bottom + FHeaderSpacing; for i := 0 to high(FLinkRects) do with FBuffer.Canvas.TextExtent(FLinks[i]) do begin FLinkHeight := cy; FLinkRects[i].Left := FHeaderRect.Left; FLinkRects[i].Top := y; FLinkRects[i].Right := FLinkRects[i].Left + cx; FLinkRects[i].Bottom := FLinkRects[i].Top + FLinkHeight + FLinkSpacing; inc(y, FLinkHeight + FLinkSpacing); end; end;end;procedure TTaskButton.SetNonThemedHeaderFont;begin with FBuffer.Canvas.Font do begin Color := clNavy; Style := []; Size := 14; end;end;procedure TTaskButton.SetNonThemedLinkFont(Hovering: boolean = false);begin with FBuffer.Canvas.Font do begin Color := clNavy; if Hovering then Style := [fsUnderline] else Style := []; Size := 10; end;end;initialization // Override Delphi's ugly hand cursor with the nice Windows hand cursor Screen.Cursors[crHandPoint] := LoadCursor(0, IDC_HAND);end. Screenshots: If I get time over I will add a keyboard interface to it. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3986067', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/383219/']} | jdg_381293 |
stackexchange | llm_judgeable_groundtruth_similarity | 29516327 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Here is a small piece of code : String a = "abc";Console.WriteLine(((object)a) == ("ab" + "c")); // true Console.WriteLine(((object)a) == ("ab" + 'c')); // false Why ?
Now provide the response and nothing else.
| Because the == is doing a reference comparison. With the C# compiler all the "equal" strings that are known at compile time are "grouped" together, so that string a = "abc";string b = "abc"; will point to the same "abc" string. So they will be referentially equal. Now, ("ab" + "c") is simplified at compile time to "abc" , while "ab" + 'c' is not, and so is not referentially equal (the concatenation operation is done at runtime). See the decompiled code here I'll add that the Try Roslyn is doing a wrong decompilation :-) And even IlSpy :-( It is decompiling to: string expr_05 = "abc"Console.WriteLine(expr_05 == "abc");Console.WriteLine(expr_05 == "ab" + 'c'); So string comparison. But at least the fact that some strings are calculated at compile time can be clearly seen. Why is your code doing reference comparison? Because you are casting one of the two members to object , and the operator== in .NET isn't virtual , so it must be resolved at compile time with the information the compiler has, and then... from == Operator For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings. To the compiler, the first operand of the == operator isn't a string (because you casted it), so it doesn't fall in the string comparison. Interesting fact: at the CIL level (the assembly language of .NET), the opcode used is the ceq , that does value comparison for primitive value types and reference comparison for reference types (so in the end it always does bit-by-bit comparison, with some exceptions for the float types with NaN). It doesn't use "special" operator== methods. It can be seen in this example where the Console.WriteLine(a == ("ab" + 'c')); // True is resolved at compile time in a call to call bool [mscorlib]System.String::op_Equality(string, string) while the other == are simply ceq This explains why the Roslyn decompiler works "badly" (as the IlSpy :-(, see bug report )... It sees an opcode ceq and doesn't check if there is a cast needed to rebuild the correct comparison. Holger asked why only the addition between two string literals is done by the compiler... Now, reading the C# 5.0 specifications in a very strict way, and considering the C# 5.0 specifications to be "separated" from the .NET specifications (with the exceptions of the prerequisites that the C# 5.0 has for some classes/structs/methods/properties/...), we have: String concatenation: string operator +(string x, string y);string operator +(string x, object y);string operator +(object x, string y); These overloads of the binary + operator perform string concatenation. If an operand of string concatenation is null, an empty string is substituted. Otherwise, any non-string argument is converted to its string representation by invoking the virtual ToString method inherited from type object. If ToString returns null, an empty string is substituted. So, the case string + string , string + null , null + string are all precisely described, and their result can be "calculated" by using only the rules of the C# specifications. For every other type, the virtual ToString method must be called. The result of the virtual ToString method isn't defined for any type in the C# specifications, so if the compiler "presumed" its result it would do a wrong "thing". For example a .NET version that had System.Boolean.ToString() that returned Yes / No instead of True / False would still be OK for the C# specifications. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/29516327', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3775807/']} | jdg_381294 |
stackexchange | llm_judgeable_groundtruth_similarity | 354747 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is the statement $$(p\rightarrow q) \longleftrightarrow (!q \rightarrow \mathord!p) $$ always true? If it is not, provide a counterexample. Till now I cannot find a counterexample nor prove that the statement is always true. $!x$ is the negation of $x$.
Now provide the response and nothing else.
| Let us think about when implication has to be true? Or, equivalently, when it has to be false? $p\implies q$ is false if and only if $p$ is true and $q$ is false. $\neg q \implies \neg p$ is false if and only if $\neg q$ is true and $\neg p$ is false, i.e. when $q$ is false and $p$ is true. We've shown that whenever one of the statements does not hold, then the other also has to be false. It means exactly that these statements are equivalent. We cannot find any counterexample. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/354747', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/63095/']} | jdg_381295 |
stackexchange | llm_judgeable_groundtruth_similarity | 51299555 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
ReturnType<T> extracts return type of a function. Is there a way to define ArgumentsType<T> that extracts parameter types of a function in tuple format? For example, ArgumentsType<(a: number, b: string) => boolean> will be [number, string] .
Now provide the response and nothing else.
| Edit Since writing the original answer, typescript now has a built-in type (defined in lib.d.ts ) to get the type of the parameters called Parameters type argsEmpty = Parameters<() => void> // []type args = Parameters<(x: number, y: string, z: boolean) => void> // [number, string, boolean]type argsOpt = Parameters<(x: number, y?: string, z?: boolean) => void> // [number, (string | undefined)?, (boolean | undefined)?] Edit Typescript 3.0 has been relesed the code below works as expected. While this is not possible in the current version of typescript (2.9) without spelling out all parameters. It will become possible in the next version of typescript (3.0) which will be released in the next few days: type ArgumentsType<T> = T extends (...args: infer U) => any ? U: never;type argsEmpty = ArgumentsType<() => void> // []type args = ArgumentsType<(x: number, y: string, z: boolean) => void> // [number, string, boolean]type argsOpt = ArgumentsType<(x: number, y?: string, z?: boolean) => void> // [number, (string | undefined)?, (boolean | undefined)?] If you install npm install typescript@next you can already play with this, it should be available sometime this month. Note We can also spread a tuple into arguments with this new feature: type Spread<T extends any[]> = (...args: T)=> void;type Func = Spread<args> //(x: number, y: string, z: boolean) => void You can read more about this feature here | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/51299555', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/692528/']} | jdg_381296 |
stackexchange | llm_judgeable_groundtruth_similarity | 238639 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a files named with YYYYMMDD in the file name, such as file-name-20151002.txt I want to determine if this file was modified after 2015-10-02. Notes: I can do this by looking at the output of ls , but I know that parsing the output of ls is a bad idea. I don't need to find all files dated after a specific date, just need to test one specific file at a time. I am not concerned about the file being modified on the same date after I created it. That is, I just want to know if this file with 20151002 in the name was modified on Oct 03, 2015 or later. I am on MacOs 10.9.5.
Now provide the response and nothing else.
| Here are some possible ways with : OSX stat : newer () {tstamp=${1:${#1}-12:8}mtime=$(stat -f "%Sm" -t "%Y%m%d" "$1")[[ ${mtime} -le ${tstamp} ]] && printf '%s\n' "$1 : NO: mtime is ${mtime}" || printf '%s\n' "$1 : YES: mtime is ${mtime}"} GNU date : newer () {tstamp=${1:${#1}-12:8}mtime=$(date '+%Y%m%d' -r "$1")[[ ${mtime} -le ${tstamp} ]] && printf '%s\n' "$1 : NO: mtime is ${mtime}" || printf '%s\n' "$1 : YES: mtime is ${mtime}"} zsh only: zmodload zsh/statnewer () {tstamp=${1:${#1}-12:8}mtime=$(zstat -F '%Y%m%d' +mtime -- $1)[[ ${mtime} -le ${tstamp} ]] && printf '%s\n' "$1 : NO: mtime is ${mtime}" || printf '%s\n' "$1 : YES: mtime is ${mtime}"} Usage: newer FILE Example output: file-name-20150909.txt : YES: mtime is 20151026 or file-name-20151126.txt : NO: mtime is 20151026 | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/238639', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/7723/']} | jdg_381297 |
stackexchange | llm_judgeable_groundtruth_similarity | 47583 |
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
CNN reports that a Frenchman named Amirouche Hammar had Covid-19 in December in Paris. This was supposedly discovered after old samples were re-checked for the Covid-19 virus. Alas there's hardly any detail in that news report besides the fact that Hammar went to a hospital with a dry cough and (eventually?) coughing blood. There's nothing said about his travel history for example. Insofar, I think the first (previously) confirmed case outside China was one in Thailand on Jan 13, according to the WHO : 13 January 2020: Officials confirm a case of COVID-19 in Thailand, the first recorded case outside of China. So is there anything that can corroborate the scant account from the CNN report? Did Hammar have a travel history? Is the virus sampled from him close enough to the original Wuhan samples (vast phylogenetic trees of Covid-19 have assembled by now). Alternatively Hammar's sample(s) could have been contaminated later... (E.g., even the CDC had a notorious problem with something like that.)
Now provide the response and nothing else.
| This has been all over the breaking news, although none of the news stories I found link to the actual study, so here's Reuters' take : The Italian National Institute of Health looked at 40 sewage samples collected from wastewater treatment plants in northern Italy between October 2019 and February 2020. An analysis released late on Thursday said samples taken in Milan and Turin on Dec. 18 showed the presence of the SARS-Cov-2 virus. [...] “That COVID-19 could have been circulating in Italy is possible,” said Rowland Kao, a veterinary epidemiology and data science professor at Scotland’s Edinburgh University. “(This finding) does not on its own, however, tell us if that early detection was the source of the very large epidemic in Italy, or if that was due to a later introduction into the country.” [...] Samples positive for traces of the virus that causes COVID-19 were also found in sewage from Bologna, Milan and Turin in January and February 2020. Samples taken in October and November 2019 tested negative. So it is corroborating evidence that the virus may have been circulating in Europe somewhat earlier (December 18 in Italy) than the confirmed (individual) cases. It seems that study has been published in a peer reviewed venue. They mention Milan and Turin in the abstract and find Dec 18 as the first positive sample, so it's almost certainly the same study that was discussed in the press. Furthermore the CDC has published a paper from Italian authors finding a similar case to the French one, but in Italy, i.e. a Dec 2019 retrospective detection: We identified severe acute respiratory syndrome coronavirus 2 RNA in an oropharyngeal swab specimen collected from a child with suspected measles in early December 2019, ≈3 months before the first identified coronavirus disease case in Italy. [...] The sequence (SARS-CoV-2_Milan_Dec2019 [GenBank accession no. MW303957]) was identified in a specimen collected from a 4-year-old boy who lived in the surrounding area of Milan and had no reported travel history. On November 21, the child had cough and rhinitis; about a week later (November 30), he was taken to the emergency department with respiratory symptoms and vomiting. On December 1, he had onset of a measles-like rash; on December 5 (14 days after symptom onset), the oropharyngeal swab specimen was obtained for clinical diagnosis of suspected measles. This patient’s clinical course, which included late skin manifestations, resembles what has been reported by other authors; maculopapular lesions have been among the most prevalent cutaneous manifestations observed during the COVID-19 pandemic, and several studies have noticed a later onset in younger patients (7). | {} | {'log_upvote_score': 4, 'links': ['https://skeptics.stackexchange.com/questions/47583', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/29579/']} | jdg_381298 |
stackexchange | llm_judgeable_groundtruth_similarity | 49544 |
Below is a question asked on the forum astronomy.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been trying to see planets using my 114 mm (aperture) f=900 mm telescope. For the moon, I got very good quality pictures, but when I try to see planets they just appear to be as if I'm looking at a star with my naked eye; it's just a point of light. I tried looking at Saturn, and it appeared the same. I couldn't even get a light blur or suggestion of its rings. I tried looking at Jupiter which is quite bright with the naked eye, but couldn't see any of its moons and neither got any indication of its disk. It's like as if I'm looking at it with the naked eye only. I used both a 25 mm and 10 mm eyepiece, but both went in vain. I used the Stellarium app to make sure I'm pointing at correct object.
Now provide the response and nothing else.
| I'm a VERY amateur observer myself and my telescope has the exact same aperture as yours. I can all but guarantee that you should definitely be able to see Saturn rings and Jupiter moons (and even some planet bands) through your scope. It's virtually impossible NOT to see those features, actually. The only "diagnosis" I can think of, barring a hardware defect, is that you're not really looking at the planets. Are you 100% sure you're aiming the telescope exactly where the planets are? Planets are surprisingly difficult to target, due to the small FOV you get when using a telescope. (This, BTW, is why many enthusiasts give up on their telescopes after a few unsuccessful attempts at seeing a planet). If your telescope doesn't have a guidance system, I'd recommend using a laser pointer (and a good friend) to point at the planet while you look through the eyepiece, tracking the laser trail until you find the planet. If your telescope does have guidance, then perhaps it needs to be (re)calibrated. Also as @MikeG suggests , if you telescope has a finder scope , it's really worth your while to take some time to align the finder to the main telescope, perhaps using an object on the horizon during the day, or the Moon. But don't use a star or planet. Then using the finder scope first to point directly at the planet you are much more likely to have the planet already within your 36x field of view, or worst case need only a very small, much more restricted search. Please try again and let me know if you need any more help. Don't give up. It will be worth it when you get to see the planets. Example of what using an object near the horizon during the day to align the finder scope to the main telescope might be like: Source: Wikimedia | {} | {'log_upvote_score': 5, 'links': ['https://astronomy.stackexchange.com/questions/49544', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/46399/']} | jdg_381299 |
stackexchange | llm_judgeable_groundtruth_similarity | 3903537 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
See the code snippets below: Code 1 public class A { static int add(int i, int j) { return(i + j); }}public class B extends A { public static void main(String args[]) { short s = 9; System.out.println(add(s, 6)); }} Code 2 public class A { int add(int i, int j) { return(i + j); }}public class B extends A { public static void main(String args[]) { A a = new A(); short s = 9; System.out.println(a.add(s, 6)); }} What is the difference between these code snippets? Both output 15 as an answer.
Now provide the response and nothing else.
| A static method belongs to the class itself and a non-static (aka instance) method belongs to each object that is generated from that class. If your method does something that doesn't depend on the individual characteristics of its class, make it static (it will make the program's footprint smaller). Otherwise, it should be non-static. Example: class Foo { int i; public Foo(int i) { this.i = i; } public static String method1() { return "An example string that doesn't depend on i (an instance variable)"; } public int method2() { return this.i + 1; // Depends on i }} You can call static methods like this: Foo.method1() . If you try that with method2, it will fail. But this will work: Foo bar = new Foo(1); bar.method2(); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3903537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/471927/']} | jdg_381300 |
stackexchange | llm_judgeable_groundtruth_similarity | 41869606 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
This is my database: { "UID1" : { "KEY" : { "Name" : "name1", "Email" : "[email protected]", "userid" : "UID1" } }, "UID2" : { "KEY2" : { "Name" : "name1", "Email" : "[email protected]", "userid" : "UID2" }, "KEY3" : { "Name" : "name2", "Email" : "[email protected]", "userid" : "UID2" }, "KEY4" : { "Name" : "name3", "Email" : "[email protected]", "userid" : "UID2" }} I would like to update and delete data which for example would be at the position of "KEY2". How can I achieve this? I have not yet tried any code in Android.
Now provide the response and nothing else.
| To write single data you can use the setValue() method on your DatabaseReference with your child Id's: private void writeNewData(String userId, String name, String email) { User user = new User(name, email); mDatabase.child("users").child(userId).setValue(user);} In your case you can do something like: mDatabase.child("UID2").child("KEY2").setValue(yourNewValueOrObject); If you want to update a specific value, you should be more concise: mDatabase.child("UID2").child("KEY2").child("email").setValue(newEmail); Anyway I recomend you to use custom classes as POJO's(Plain Old Java Object) with the values of each of your items in database. For example: public class User { public String username; public String email; public User() { // Default constructor required for calls to DataSnapshot.getValue(User.class) } public User(String username, String email) { this.username = username; this.email = email; }} Finally to remove data you should use the removeValue() method in the same way. private void deleteUserData(String userId) { mDatabase.child("users").child(userId).removeValue(); } This method will remove the whole reference from your Database, so be care with it. In the case that you wanted to remove a specific field, you should add another .child() call to the tree. For example, let's say that we want to remove the email value from "KEY2" node: mDatabase.child("users").child(userId).child("email").removeValue(); Finally, there's the case that maybe we want to update multiple fields in different database nodes. In that case we should use the updateChildren() method with a map of references and values. private void writeNewPost(String userId, String username, String title, String body) { // Create new post at /user-posts/$userid/$postid and at // /posts/$postid simultaneously String key = mDatabase.child("posts").push().getKey(); Post post = new Post(userId, username, title, body); Map<String, Object> postValues = post.toMap(); Map<String, Object> childUpdates = new HashMap<>(); childUpdates.put("/posts/" + key, postValues); childUpdates.put("/user-posts/" + userId + "/" + key, postValues); mDatabase.updateChildren(childUpdates);} What updateChildren method do. Is a setValue () call over each row in the given Map<String, Object> being the key the full reference of the node and the Object the value. You can read more update and delete data in the official Firebase documentation | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41869606', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7472834/']} | jdg_381301 |
stackexchange | llm_judgeable_groundtruth_similarity | 430184 |
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:
What are their benefits? I know sparse parameters are a different story than sparse representations, but I want to know how each of these can benefit us and which one is more important than the other one.
Now provide the response and nothing else.
| The citation is true. When you plug $x=0$ to the PDF function, you do NOT get the probability of taking this particular value. The resulting number is probability density which is not a probability. The probability of taking exactly $x=0$ is zero (consider the infinite number of similarly-likely values in the tiny interval $x\in[0,10^{-100}]$ ). To further convince yourself that this $\varphi(x)$ cannot be a probability, consider decreasing the standard deviation of your normal distribution from $\sigma = 1$ to $\sigma = \frac{1}{100}$ . Now, $\varphi(0)=\frac{100}{\sqrt{2\pi}}$ - much more than one. Not a probability. | {} | {'log_upvote_score': 6, 'links': ['https://stats.stackexchange.com/questions/430184', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/14306/']} | jdg_381302 |
stackexchange | llm_judgeable_groundtruth_similarity | 7188563 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to use certain jQuery plugins in my Django admin site. Django admin sets the jQuery namespace to django.jQuery (to avoid conflicts) If I don't have the default $ namespace for jQuery, the plugins won't work, will they ? Do I have to do something like window.$ = django.jQuery ? How & where can I change this namespace for the whole admin site ?
Now provide the response and nothing else.
| Actually, most plugins will require "jQuery" - not $ - to be available, and then provide $ themselves as in dmidz's answer. Therefore, insert var jQuery = django.jQuery; before your external references. If you're loading a bunch of thirdparty jQuery plugins, put the above line in a script tag that preceeds the plugins. See also my question five months ago How to provide $ to third-party, external jQuery plugins in Django admin | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7188563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/305189/']} | jdg_381303 |
stackexchange | llm_judgeable_groundtruth_similarity | 1092262 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let $a(n)$ be the number of sequences with length $n$ which consists the digits $0,1,2$ such that between every two occurrences of $2$ there is an occurrence of $0$ (not necessarily next to the $2$ 's). An example for good sequence is $0102102$ . An example for bad sequence is $01212$ . A. Find a recursion formula for $a(n)$ B. Find an explicit expression for $a(n)$ . My try: let $x(n)$ be the number of sequences with length $n$ that if we add $2$ at the end of sequence it is still a good sequence with length $n+1$ . Now, if the last digit in the sequence was $0$ , then we have to look on the number of good sequences with length $n-1$ , hence $\displaystyle a(n-1)$ . If the last digit was $1$ , then we now need to look on $x(n-1)$ and work with the same manipulation. This way we get the recursion $x(n)=a(n-1)+x(n-1)$ . By induction I can get a recursion formula for $x(n)$ , but I don't know how to find a formula for $a(n)$ or find an explicit expression for $a(n)$ . Any help will be appreciated, thank you!
Now provide the response and nothing else.
| $x(n) = x(n-1) + x(n-1) + \sum_{i=1}^{n-1}x(n-1 -i) + x(0), n\ge 2 $ $x(0)=1$ $, x(1)=3$. Any valid string either start with $0$ (number of such strings are $x(n-1)$) or $1$ (number of such strings are $x(n-1))$ or $2$.If it starts with $2$ then it must have only $1's$ before first occurrence of $0$. Condition on the position of first $0$ after the $2$. It can be next to it, or one $1$ followed by $0$ an so on and the case that occurrence of $2$ is followed by only $1's$ (number of such strings are $x(0))$. Edit More Simpler Recurrence Using the recurrence above subtract $x(n-1)$ from $x(n)$ to get this simpler recurrence,$$x(n)= 3x(n-1)-x(n-2), n \ge 2 $$ You can use this formula to compute the closed formula easily. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1092262', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/111334/']} | jdg_381304 |
stackexchange | llm_judgeable_groundtruth_similarity | 63533648 |
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 the default grouping function in the vuetify datatable. It works fine, but I want to change the default button style for grouping and replace it with an icon. Is that possible? If I inspect the button in the dev tools, it just shows <span>group</span> . Found only this in the docs: https://vuetifyjs.com/en/components/data-tables/#grouped-rows Edit: By now I know what I would like. I am looking for the default template for the v-slot:header . This is where the button I mentioned above is generated that starts the grouping.
Now provide the response and nothing else.
| You can use the group.header slot and provide your own template for the group header including the toggle button and use the toggle method from the props like : <template v-slot:group.header="{ group, headers, toggle, isOpen }"> <td :colspan="headers.length"> <v-btn @click="toggle" x-small icon :ref="group"> <v-icon v-if="isOpen">mdi-plus</v-icon> <v-icon v-else>mdi-minus</v-icon> </v-btn> <span class="mx-5 font-weight-bold">{{ group }}</span> </td></template> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63533648', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7625095/']} | jdg_381305 |
stackexchange | llm_judgeable_groundtruth_similarity | 60205552 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Problem: I'm creating an API Application with NET Core 3.1.I'd like to avoid to set route attribute over every ApiControllers and Actions. I tryed a lot of combinations over UseEndpoints to set a conventional route, but i'm failing. With some configuration I can't get the Api working, with some others I get this exception during startup: InvalidOperationException: Action 'ApiIsWorking' does not have an attribute route. Action methods on controllers annotated with ApiControllerAttribute must be attribute routed. How can i set the startup.cs to auto map controllers with their class name and actions with their method name? Thank you! Some code: startup.cs ...services.AddControllers()...app.UseHttpsRedirection() .UseRouting() .UseAuthentication() .UseEndpoints(endpoints => ?? ) .UseCoreHttpContext() .UseServerConfiguration(); controller.cs [ApiController]public class BaseAPI : ControllerBase { [HttpGet] public string ApiIsWorking() { return "API is working!"; }} Solution: As Reza Aghaei says in the solution , the error was to add the ApiController attribute. After I removed it, the command UseEndpoints start to work. My mistake was to add the attribute to be able to recognize which classes should be exposed via API. It wasn't necessary because UseEndpoints maps only the classes that inherit from ControllerBase. Warning: 1) Conventional Routing require [FromBody] attribute in actions params. 2) I highlight Zinov's response about conventional routing problems with Swashbuckle in .NET Core
Now provide the response and nothing else.
| To have conventional routing for your controllers and action, you need to remove [ApiController] attribute and [Route] attribute from your controller and actions and setup route in UseEndpoints . It's already mentioned in the documentations : The [ApiController] attribute makes attribute routing a requirement. Actions are inaccessible via conventional routes defined by UseEndpoints , UseMvc , or UseMvcWithDefaultRoute in Startup.Configure . Example This is the working setup that I have for Startup: public class Startup{ public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }} And a sample API controller: public class ValuesController : ControllerBase{ // values/getall [HttpGet] public IEnumerable<string> GetAll() { return new string[] { "value1", "value2" }; } // values/getitem/1 [HttpGet] public string GetItem(int id) { return "value"; }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60205552', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2693640/']} | jdg_381306 |
stackexchange | llm_judgeable_groundtruth_similarity | 1006531 |
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 was given a task to prove the following inequality equation:$$\frac{a}{b}+\frac{b}{c}+\frac{c}{a} \geq 3 \quad,\quad \text{for $a,b,c \gt 0$}$$A hint was also given: The Inequality of arithmetic and geometric means equations should be used to help to prove the task. I've tried several methods with using the AM-GM means, but to no avail. For example, I reached the equation:$$6 \leq \frac{a+c}{b} + \frac{b+c}{a} + \frac{a+b}{c}$$Which translates also to:$$6abc \leq a^2c + ac^2 + b^2c + bc^2 +a^2b + ab^2$$ When trying with a different method, I concluded that:$$27 \leq \frac{1}{a^2bc} + \frac{1}{ab^2c} + \frac{1}{abc^2}$$ I don't know what am I missing.I could use your advice/hint with this task. Thank you.
Now provide the response and nothing else.
| Let our three numbers be $x$, $y$, and $z$. Note that $xyz=1$. By AM-GM we have $$\frac{x+y+z}{3}\ge 1^{1/3}.$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1006531', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/189966/']} | jdg_381307 |
stackexchange | llm_judgeable_groundtruth_similarity | 45752601 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following dataframe: key1 key20 a one1 a two2 b one3 b two4 a one5 c two Now, I want to group the dataframe by the key1 and count the column key2 with the value "one" to get this result: key1 0 a 21 b 12 c 0 I just get the usual count with: df.groupby(['key1']).size() But I don't know how to insert the condition. I tried things like this: df.groupby(['key1']).apply(df[df['key2'] == 'one']) But I can't get any further. How can I do this?
Now provide the response and nothing else.
| I think you need add condition first: #if need also category c with no values of 'one'df11=df.groupby('key1')['key2'].apply(lambda x: (x=='one').sum()).reset_index(name='count')print (df11) key1 count0 a 21 b 12 c 0 Or use categorical with key1 , then missing value is added by size : df['key1'] = df['key1'].astype('category')df1 = df[df['key2'] == 'one'].groupby(['key1']).size().reset_index(name='count') print (df1) key1 count0 a 21 b 12 c 0 If need all combinations: df2 = df.groupby(['key1', 'key2']).size().reset_index(name='count') print (df2) key1 key2 count0 a one 21 a two 12 b one 13 b two 14 c two 1df3 = df.groupby(['key1', 'key2']).size().unstack(fill_value=0)print (df3)key2 one twokey1 a 2 1b 1 1c 0 1 | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/45752601', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7605513/']} | jdg_381308 |
stackexchange | llm_judgeable_groundtruth_similarity | 6545858 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to add/remove/change an embedded resource in a .NET DLL after it has been compiled? If so, how is this done, and are there any gotchas? Edit: I would like to do this manually, but eventually automatically through a script in the post-build event.
Now provide the response and nothing else.
| There's no way to do this in managed code . Once a resource has been embedded it becomes part of the assembly just like the compiled MSIL code is. However, you could do this manually , like suggested by Lucero , by disassembling the DLL into a text file using ildasm , removing the resource using a text editor, and finally reassembling the DLL using ilasm . Here's an example using a DLL with a single embedded text file: 1) Decompile the DLL into MSIL: ildasm MyLibrary.dll /out=MyLibrary.il 2) Open the resulting MyLibrary.il file and remove the .mresource section: .mresource public MyLibrary.MyResource.txt{ // Offset: 0x00000000 Length: 0x0000000F // WARNING: managed resource file MyLibrary.MyResource.txt created} 3) Reassemble the DLL from the modified MyLibrary.il file: ilasm MyLibrary.il /dll | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6545858', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/197911/']} | jdg_381309 |
stackexchange | llm_judgeable_groundtruth_similarity | 29011851 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the HTML control below and want a delay after it is clicked so users cannot accidentally or intentionally click it again- UPDATE SYNCHRONIZED VALUES <a href="Javascript:main.ManualCommand.perform( 'command here' )"><FONT size=3 COLOR = White> UPDATE SYNCHRONIZED VALUES</FONT></A>
Now provide the response and nothing else.
| Create a table that has a structure like create table ResetTickets( username varchar(200), tokenHash varbinary(16), expirationDate datetime, tokenUsed bit) Then in your code when the user clicks the reset password button you will generate a random token then put a entry in that table with the hashed value of that token and a expiration date of something like DATEADD(day, 1, GETDATE()) and appends that token value on the url you email to the user for the password reset page. www.example.com/passwordReset?username=Karan&token=ZB71yObR On the password reset page you take the username and token passed in, hash the token again then compare that with the ResetTickets table, and if the expiration date has not passed yet and the token has not been used yet then take the user to a page that lets them enter a new password. Things to be careful about : Make sure to expire the token , don't let a email from two years ago reset the password. Make sure to mark the token as used , don't let other users of the computer use the browser's history to reset other users passwords. Make sure you generate the random token safely . Don't use Rand and use it to generate the token, two users who reset at the same time would get the same token (I could reset my password and your password at the same time then use my token to reset your account). Instead make a static RNGCryptoServiceProvider and use the GetBytes method from that, the class is thread safe so you don't need to worry about two threads using the same instance. Be sure to parameterize your queries . In your current code if I typed in the userid '; delete dbo.[USERS] -- it would delete all the users in your database. See the linked SO post for more info on how to fix it. Be sure you hash the token, your passwordReset page only accepts the unhashed version, and you never store the unhashed version anywhere (including email logs of outgoing messages to users). This prevents an attacker who has read access to the database from making a token for some other user, reading the value that was sent in the email, then sending the same value himself (and perhaps getting access to an administrator user who can do more stuff than just read values). | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/29011851', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4663181/']} | jdg_381310 |
stackexchange | llm_judgeable_groundtruth_similarity | 300829 |
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:
Consider standard quantum harmonic oscillator, $H = \frac{1}{2m}P^2 + \frac{1}{2}m\omega^2Q^2$. We can solve this problem by defining the ladder operators $a$ and $a^{\dagger}$. One can show that there is a unique "ground state" eigenvector $\psi_0$ with $H\psi_0 = \frac{1}{2}\hbar\omega\psi_0$ and furthermore that given any eigenvector $\psi$ of $H$ with eigenvalue $E$, the vector $a^{\dagger}\psi$ is also an eigenvector of $H$ with eigenvalue $E + \hbar\omega$. However, it is usually stated that we now have all eigenvectors of $H$ by considering all vectors of the form $(a^{\dagger})^n\psi_0$. How do we know that we have not missed any eigenvectors by this process? e.g. how do we know that eigenvalues are only of the form $E_n = (n+\frac{1}{2})\hbar\omega$? Also a slightly more technical question, how do we know that the continuous spectrum of $H$ is empty? The technical details I am operating with are that $\mathcal{H} = L^2(\mathbb{R})$ and all operators ($H, P, Q$) are defined on Schwartz space, so that they are essentially self-adjoint with their unique self-adjoint extensions corresponding to the actual observables.
Now provide the response and nothing else.
| It is sufficient to prove that the vectors $|n\rangle$ form a Hilbert basis of $L^2(\mathbb R)$. This fact cannot be completely established by using the ladder operators. To prove that the span of the afore-mentioned vectors is dense in the Hilbert space, one should write down the explicit expression of the wavefunctions of the said vectors recognizing that they are the well-known Hilbert basis of Hermite functions.Since the vectors $|n\rangle$ are a Hilbert basis, from standard results of spectral theory, the operator $$\sum_n \hbar \omega(n +1/2 ) |n\rangle \langle n | \tag{1}$$(using the strong operator topology which defines the domain of this operator implicitly)is self-adjoint and its spectrum is a pure point spectrum made of the numbers $\hbar \omega(n +1/2 ) $ with $n$ natural. This fact proves that the initial symmetric Hamiltonian operator you described in your post and defined on the Schwartz space admits at least one self-adjoint extension with the said spectrum (in particular no continuous spectrum takes place). To prove that it is the unique self-adjoint extesion, i.e., that the initial symmetric operator is essentially self-adjoint, the shortest way is to observe that the vectors $|n\rangle$ are necessarily analytic vectors of the initial Hamiltonian (notice that all the afore-mentioned vectors stay in the Schwartz space which is the initial domain) because they are eigenvectors. Since they are a Hilbert basis, their span is dense. Under these hypotheses, a celebrated theorem by Nelson implies that the initial symmetric Hamiltonian operator is essentially self-adjoint and thus (1) is the only self-adjoint extension of the initial symmetric Hamiltonian operator. As a final comment, it is interesting to remark that (1) is not a differential operator differently from the naive initial Hamiltonian which is a differential operator but it is not self-adjoint. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/300829', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/140223/']} | jdg_381311 |
stackexchange | llm_judgeable_groundtruth_similarity | 4757565 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
At this link, the following was mentioned: add.cpp: int add(int x, int y){ return x + y;} main.cpp: #include <iostream> int add(int x, int y); // forward declaration using function prototype int main(){ using namespace std; cout << "The sum of 3 and 4 is " << add(3, 4) << endl; return 0;} We used a forward declaration so that the compiler would know what " add " was when compiling main.cpp . As previously mentioned, writing forward declarations for every function you want to use that lives in another file can get tedious quickly. Can you explain " forward declaration " further? What is the problem if we use it in the main function?
Now provide the response and nothing else.
| Why forward-declare is necessary in C++ The compiler wants to ensure you haven't made spelling mistakes or passed the wrong number of arguments to the function. So, it insists that it first sees a declaration of 'add' (or any other types, classes, or functions) before it is used. This really just allows the compiler to do a better job of validating the code and allows it to tidy up loose ends so it can produce a neat-looking object file. If you didn't have to forward declare things, the compiler would produce an object file that would have to contain information about all the possible guesses as to what the function add might be. And the linker would have to contain very clever logic to try and work out which add you actually intended to call, when the add function may live in a different object file the linker is joining with the one that uses add to produce a dll or exe . It's possible that the linker may get the wrong add . Say you wanted to use int add(int a, float b) , but accidentally forgot to write it, but the linker found an already existing int add(int a, int b) and thought that was the right one and used that instead. Your code would compile, but wouldn't be doing what you expected. So, just to keep things explicit and avoid guessing, etc, the compiler insists you declare everything before it is used. Difference between declaration and definition As an aside, it's important to know the difference between a declaration and a definition. A declaration just gives enough code to show what something looks like, so for a function, this is the return type, calling convention, method name, arguments, and their types. However, the code for the method isn't required. For a definition, you need the declaration and then also the code for the function too. How forward-declarations can significantly reduce build times You can get the declaration of a function into your current .cpp or .h file by #includ'ing the header that already contains a declaration of the function. However, this can slow down your compile, especially if you #include a header into a .h instead of .cpp of your program, as everything that #includes the .h you're writing would end up #include'ing all the headers you wrote #includes for too. Suddenly, the compiler has #included pages and pages of code that it needs to compile even when you only wanted to use one or two functions. To avoid this, you can use a forward-declaration and just type the declaration of the function yourself at the top of the file. If you're only using a few functions, this can really make your compiles quicker compared to always #including the header. For really large projects, the difference could be an hour or more of compile time bought down to a few minutes. Break cyclic references where two definitions both use each other Additionally, forward-declarations can help you break cycles. This is where two functions both try to use each other. When this happens (and it is a perfectly valid thing to do), you may #include one header file, but that header file tries to #include the header file you're currently writing... which then #includes the other header, which #includes the one you're writing. You're stuck in a chicken and egg situation with each header file trying to re #include the other. To solve this, you can forward-declare the parts you need in one of the files and leave the #include out of that file. Eg: File Car.h #include "Wheel.h" // Include Wheel's definition so it can be used in Car.#include <vector>class Car{ std::vector<Wheel> wheels;}; File Wheel.h Hmm... the declaration of Car is required here as Wheel has a pointer to a Car , but Car.h can't be included here as it would result in a compiler error. If Car.h was included, that would then try to include Wheel.h which would include Car.h which would include Wheel.h and this would go on forever, so instead the compiler raises an error. The solution is to forward declare Car instead: class Car; // forward declarationclass Wheel{ Car* car;}; If class Wheel had methods which need to call methods of Car , those methods could be defined in Wheel.cpp and Wheel.cpp is now able to include Car.h without causing a cycle. | {} | {'log_upvote_score': 10, 'links': ['https://Stackoverflow.com/questions/4757565', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/588855/']} | jdg_381312 |
stackexchange | llm_judgeable_groundtruth_similarity | 782105 |
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 $p_1<p_2<\cdots<p_{31}$ be prime numbers such that $30$ divides $p_1^4 + p_2^4 + \cdots + p_{31}^4$. Prove that $p_1=2$, $p_2=3$ and $p_3=5$. No clue how to start..Hints are welcomed.
Now provide the response and nothing else.
| Not quite, but almost. Note that $(A\times B)^n$ is a set of $n$-tuples of ordered pairs, whereas $A^n\times B^n$ is a set of ordered pairs made of $n$-tuples. However, there is a very natural bijection between $(A\times B)^n$ and $A^n\times B^n$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/782105', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/143010/']} | jdg_381313 |
stackexchange | llm_judgeable_groundtruth_similarity | 4354261 |
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 start reading Lift framework source code, I find that there're so many methods are defined using a name like methodName_? , is there a convention that _? has some special meaning? def empty_? : Boolean = {}
Now provide the response and nothing else.
| The ? denotes that this is a predicate, a function returning Boolean . This convention goes back to Lisp, where ? (Scheme), p or -p (other Lisps, simulating the question mark with a "similar" letter) also denote predicates. Think of it as asking a question, "is the object empty?" Scala will only allow mixed identifier names (containing alphanumerics and punctuation) if you separate them by _ . E.g., scala> def iszero?(x : Int) = x == 0 <console>:1: error: '=' expected but identifier found. def iszero?(x : Int) = x == 0 ^ doesn't work, but scala> def iszero_?(x : Int) = x == 0 iszero_$qmark: (x: Int)Boolean does. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4354261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/241824/']} | jdg_381314 |
stackexchange | llm_judgeable_groundtruth_similarity | 460729 |
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:
Try to solve this puzzle: The first expedition to Mars found only the ruins of a civilization. From the artifacts and pictures, the explorers deduced that the creatures who produced this civilization were four-legged beings with a tentatcle that branched out at the end with a number of grasping "fingers". After much study, the explorers were able to translate Martian mathematics. They found the following equation: $$5x^2 - 50x + 125 = 0$$ with the indicated solutions $x=5$ and $x=8$. The value $x=5$ seemed legitimate enough, but $x=8$ required some explanation. Then the explorers reflected on the way in which Earth's number system developed, and found evidence that the Martian system had a similar history. How many fingers would you say the Martians had? $(a)\;10$ $(b)\;13$ $(c)\;40$ $(d)\;25$ P.S. This is not a home work. It's a question asked in an interview.
Now provide the response and nothing else.
| Many people believe that since humans have $10$ fingers, we use base $10$. Let's assume that the Martians have $b$ fingers and thus use a base $b$ numbering system, where $b \neq 10$ (note that we can't have $b=10$, since in base $10$, $x=8$ shouldn't be a solution). Then since the $50$ and $125$ in the equation are actually in base $b$, converting them to base $10$ yields $5b+0$ and $1b^2 + 2b + 5$, so we now have:$$5x^2-(5b)x + (b^2+2b+5)=0$$Since $x=5$ is a solution, substitution yields:$$ \begin{align*}5(5)^2-(5b)(5) + (b^2+2b+5) &= 0 \\b^2-23b+130 &= 0 \\(b-10)(b-13) &= 0 \\b&=10,13\end{align*} $$Since we know that $b\neq10$, we conclude that the Martians must have $13$ fingers. Indeed, this makes sense, because if $50$ and $125$ are in base $13$, then converting them to base $10$ yields $5(13)=65$ and $1(13)^2+2(13)+5=200$, so our equation becomes:$$ \begin{align*}5x^2-65x+200 &= 0 \\x^2-13x+40&= 0 \\(x-5)(x-8)&= 0 \\x&= 5,8 \\\end{align*} $$as desired. | {} | {'log_upvote_score': 7, 'links': ['https://math.stackexchange.com/questions/460729', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/49700/']} | jdg_381315 |
stackexchange | llm_judgeable_groundtruth_similarity | 36965948 |
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 create a live clock with php that gets time from server not users pc time [not javascript] i used the below code but time stops when using php variable <form name="Tick"><input type="text" size="12" name="Clock"></form><script type="text/javascript">function show(){ var hours="<?php echo $myhour; ?>" var minutes="<?php echo $mymin; ?>" var seconds="<?php echo $mysec; ?>" var dn="AM" if (hours>12){ dn="PM" hours=hours-12 //this is so the hours written out is in 12-hour format, instead of the default //24-hour format. } if (hours==0) hours=12 //this is so the hours written out when hours=0 (meaning 12a.m) is 12 if (minutes<=9) minutes="0"+minutes if (seconds<=9) seconds="0"+seconds document.Tick.Clock.value= hours+":"+minutes+":"+seconds+" "+dn setTimeout("show()",1000)} show()</script>
Now provide the response and nothing else.
| You can use ajax . timestamp.php <?php date_default_timezone_set('YOUR TIMEZONE'); echo $timestamp = date('H:i:s'); jQuery $(document).ready(function() { setInterval(timestamp, 1000);});function timestamp() { $.ajax({ url: 'http://localhost/timestamp.php', success: function(data) { $('#timestamp').html(data); }, });} HTML <div id="timestamp"></div> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36965948', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6277427/']} | jdg_381316 |
stackexchange | llm_judgeable_groundtruth_similarity | 13814704 |
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 change jdesktoppane background image in MDI (Multiple Documents interface) using java netbeans? Means I added the jdesktoppane to java MDI so now I want to change default background image of that jdesktoppane which I'm using in java MDI. Any easy way? Check attached snapshot link may be you will better understand my question what I want. http://i50.tinypic.com/iml1e9.jpg
Now provide the response and nothing else.
| +1 to MadProgrammers comment. Simply override JDesktopPane paintComponent(..) and call drawImage(Image img,int x,int y,ImageObserver io) to draw an image. Dont forget to honor the paint chain and call super.paintComponent(g) as first call in overridden paintComponent(..) method Here is an example: import java.awt.*;import java.awt.event.*;import java.awt.image.BufferedImage;import java.net.URL;import javax.imageio.ImageIO;import javax.swing.JDesktopPane;import javax.swing.JFrame;import javax.swing.JInternalFrame;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.SwingUtilities;public class JInternalFrameDemo { private JDesktopPane jdpDesktop; private static int openFrameCount = 0; private BufferedImage img; public JInternalFrameDemo() { JFrame frame = new JFrame("JInternalFrame Usage Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); try { img = ImageIO.read(new URL("http://images1.wikia.nocookie.net/__cb20120817224359/villains/images/6/6a/Nine-Tailed_Fox_(Naruto).jpg")); } catch (Exception ex) { ex.printStackTrace(); } // A specialized layered pane to be used with JInternalFrames jdpDesktop = new JDesktopPane() { @Override protected void paintComponent(Graphics grphcs) { super.paintComponent(grphcs); grphcs.drawImage(img, 0, 0, null); } @Override public Dimension getPreferredSize() { return new Dimension(img.getWidth(), img.getHeight()); } }; createFrame(); // Create first window frame.setContentPane(jdpDesktop); frame.setJMenuBar(createMenuBar()); // Make dragging faster by setting drag mode to Outline jdpDesktop.putClientProperty("JDesktopPane.dragMode", "outline"); frame.pack(); frame.setVisible(true); } protected JMenuBar createMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu("Frame"); menu.setMnemonic(KeyEvent.VK_N); JMenuItem menuItem = new JMenuItem("New IFrame"); menuItem.setMnemonic(KeyEvent.VK_N); menuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { createFrame(); } }); menu.add(menuItem); menuBar.add(menu); return menuBar; } protected void createFrame() { MyInternalFrame frame = new MyInternalFrame(); frame.setVisible(true); // Every JInternalFrame must be added to content pane using JDesktopPane jdpDesktop.add(frame); try { frame.setSelected(true); } catch (java.beans.PropertyVetoException e) { } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new JInternalFrameDemo(); } }); } class MyInternalFrame extends JInternalFrame { static final int xPosition = 30, yPosition = 30; public MyInternalFrame() { super("IFrame #" + (++openFrameCount), true, // resizable true, // closable true, // maximizable true);// iconifiable setSize(300, 300); // Set the window's location. setLocation(xPosition * openFrameCount, yPosition * openFrameCount); } }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13814704', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1124285/']} | jdg_381317 |
stackexchange | llm_judgeable_groundtruth_similarity | 3209899 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Does anyone have an algorithm to determine the direction from one lat/lon to another (pseudo-code): CalculateHeading( lat1, lon1, lat2, long2 ) returns string heading Where heading is e.g. NW, SW, E, etc. Basically, I have two points on a map and I want to get a general idea of the direction taking into account that 50 miles East and one mile North is simply East and not Northeast.
Now provide the response and nothing else.
| This site has the basic algorithm: // in javascript, not hard to translate...var y = Math.sin(dLon) * Math.cos(lat2);var x = Math.cos(lat1)*Math.sin(lat2) - Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);var brng = Math.atan2(y, x).toDeg(); UPDATED: See here for complete algorith Mapping Math and Javascript That'll give you a number between 0 and 360 then it's just a matter of having a simple lookup: var bearings = ["NE", "E", "SE", "S", "SW", "W", "NW", "N"];var index = brng - 22.5;if (index < 0) index += 360;index = parseInt(index / 45);return(bearings[index]); It's important to note that your bearing actually changes as you move around the earth. The algorithm above shows you initial bearing, but if you're traveling a long distance, your bearing to be significantly different when you reach the destination (if you're only traveling a short distance [< a few hundred kms] then it probably won't change enough to be a concern). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3209899', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/135952/']} | jdg_381318 |
stackexchange | llm_judgeable_groundtruth_similarity | 408214 |
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:
This is from a past qualifying exam. Here is the question: If $\alpha= (1+\sqrt{-19})/2$ then any ring homomorphism $f : \mathbb{Z}[\alpha] \rightarrow \mathbb{Z}_3$ is the zero map. Here is what I thought of: $\mathbb{Z}_3$ is a field. So I was thinking of using something like $ \mathbb{Z}[\alpha]/(f(\alpha))$ is isomorphic to the field $\mathbb{Z}_3$. If I can somehow show that $f(\alpha)$ is the root of some irreducible polynomial over $\mathbb{Z_3}$ then I will have what I want? I also have that $\alpha(1-\alpha)=5$. So If I apply $f$ to this relation and then using the fact that $f$ is ring homomorphism I get $f(\alpha)\cdot (f(1)-f(\alpha))=f(5)$. I also know that $f(1)=1$. How do I proceed from here? Am I on the right track? Can anybody please help me on this? Your time and answers are always appreciated. Thanks.
Now provide the response and nothing else.
| Using @Lubin's hint.Discuss what $f(\alpha)$ would be? If $f(1)=1$,then $f(\alpha)=0$? then $f(\alpha)(f(1)-f(\alpha))=f(5)$, so $0\cdot(1-0)=5=2$ !? $f(\alpha)=1$? then $1\cdot(1-1)=5$ !? $f(\alpha)=2$? then $2\cdot(1-2)=5$ !? | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/408214', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/54755/']} | jdg_381319 |
stackexchange | llm_judgeable_groundtruth_similarity | 3038392 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is there a limit to the number of elements a Java array can contain? If so, what is it?
Now provide the response and nothing else.
| Using OpenJDK 64-Bit Server VM (build 15.0.2+7, mixed mode, sharing) ... on MacOS, the answer seems to be Integer.MAX_VALUE - 2 . Once you go beyond that: cat > Foo.java << "END"public class Foo { public static void main(String[] args) { boolean[] array = new boolean[Integer.MAX_VALUE - 1]; // too big }}ENDjava -Xmx4g Foo.java ... you get: Exception in thread "main" java.lang.OutOfMemoryError: Requested array size exceeds VM limit | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/3038392', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/123140/']} | jdg_381320 |
stackexchange | llm_judgeable_groundtruth_similarity | 22497165 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
With Java 8, executing gradle sonarRunner shows this error message. (sonarQube version : 4.2.1) java.lang.ArrayIndexOutOfBoundsException: 26721 at org.objectweb.asm.ClassReader.readClass(Unknown Source) [asm-all-3.2.jar:5.0_BETA] at org.objectweb.asm.ClassReader.accept(Unknown Source) [asm-all-3.2.jar:5.0_BETA] at org.objectweb.asm.ClassReader.accept(Unknown Source) [asm-all-3.2.jar:5.0_BETA] at org.sonar.java.bytecode.asm.AsmClassProviderImpl.decoracteAsmClassFromBytecode(AsmClassProviderImpl.java:76) [java-squid-2.0.jar:na] at org.sonar.java.bytecode.asm.AsmClassProviderImpl.getClass(AsmClassProviderImpl.java:55) [java-squid-2.0.jar:na] at org.sonar.java.bytecode.asm.AsmClassVisitor.visit(AsmClassVisitor.java:52) [java-squid-2.0.jar:na] at org.objectweb.asm.ClassReader.accept(Unknown Source) [asm-all-3.2.jar:5.0_BETA] at org.objectweb.asm.ClassReader.accept(Unknown Source) [asm-all-3.2.jar:5.0_BETA]``` Does SonarQube not support Java 8 yet? I would like to know when support is available. Thank you.
Now provide the response and nothing else.
| SonarQube supports Java 8 since end of March 2014 (with some hickups at first, which were fixed in version 2.2 of its Java plugin). I had to uninstall the PMD and Checkstyle plugins in Sonar's update center as those are not ready for Java 8. Sonar's own rule engine Squid should make those plugins redundant anyway. If you are using Gradle 1.11 to call Sonar and want Jacoco to calculate code coverage, you'll have to specify the latest Jacoco version in order to analyze Java 8 bytecode. Here's my script that does that when called with gradle test jacocoTestReport sonarRunner : /** This script is responsible for unit testing and static analysis of the project source code*/apply plugin: "jacoco"apply plugin: "sonar-runner"// Location of the XML unit test and code coverage reports def testResultsDir = "$buildDir/test-results/" // Use double quotes. Otherwise the $ won't workjacoco{ // Gradle 1.11 ships with a Jacoco version that doesn't support Java 8 toolVersion = "0.7.0.201403182114"}// Call "gradle test jacocoTestReport" to produce a code coverage report at "build/reports/jacoco/test/html/index.html"test { jacoco { def coverageReport = new File(testResultsDir, "jacocoTest.exec") destinationFile = file(coverageReport) }}// Let SonarQube analyze the projectsonarRunner { sonarProperties { property "sonar.projectKey", projectId property "sonar.projectName", projectName property "sonar.junit.reportsPath", testResultsDir // Address of SonarQube server property "sonar.host.url", "http://localhost:9000" // SonarQube stores the test results in this database property "sonar.jdbc.url", "jdbc:mysql://localhost:3306/sonar?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true" property "sonar.jdbc.driverClassName", "com.mysql.jdbc.Driver" property "sonar.jdbc.username", "root" property "sonar.jdbc.password", sonarDBpassword }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22497165', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1943160/']} | jdg_381321 |
stackexchange | llm_judgeable_groundtruth_similarity | 70062750 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For my research I need to cURL the fqdns and get their status codes. (For Http, Https services) But some http urls open as https although it returns 200 with cURL. (successful request, no redirect) curl -I http://example.example.com/HTTP/1.1 200 OKServer: nginxDate: Mon, 22 Nov 2021 10:43:32 GMTContent-Type: text/html; charset=UTF-8Content-Length: 64991Connection: keep-aliveKeep-Alive: timeout=20Vary: Accept-EncodingExpires: Thu, 19 Nov 1981 08:52:00 GMTPragma: no-cacheLink: <https://example.example.com/>; rel=shortlinkX-Powered-By: WP EngineX-Cacheable: SHORTVary: Accept-Encoding,CookieCache-Control: max-age=600, must-revalidateX-Cache: HIT: 10X-Cache-Group: normalAccept-Ranges: bytes As seen above I get 200 response with curl request. But I can see the 307 code in my browser. (available in the picture below) Request URL: http://example.example.com/Request Method: GETStatus Code: 307 Internal RedirectReferrer Policy: strict-origin-when-cross-origin Can I detect 307 code with curl? (-L parameter doesn't work) Any suggestions?
Now provide the response and nothing else.
| curl -w '%{response_code}\n' -so /dev/null $URL It can be tested out like this: curl -w '%{response_code}\n' -so /dev/null httpbin.org/status/307 so what is the 307 in the question? As Stefan explains here in a separate answer: that's an internal message from Chrome that informs you that it uses HSTS. It is not an actual response code. Which is why curl can't show it. Chrome should make that clearer. HSTS HSTS is a way for a HTTPS server to ask clients to not contact them over clear text HTTP again. curl also supports HSTS but then you need to use --hsts - and curl will still not confusingly claim any 307 response codes. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/70062750', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17476759/']} | jdg_381322 |
stackexchange | llm_judgeable_groundtruth_similarity | 561816 |
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 invoking PHP cURL method on a server and the response is XML type. cURL is saving the output (after removing the tags) in a scalar type variable. Is there a way to store it in an object/hash/array so that it's easy to parse?
Now provide the response and nothing else.
| <?phpfunction download_page($path){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$path); curl_setopt($ch, CURLOPT_FAILONERROR,1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_TIMEOUT, 15); $retValue = curl_exec($ch); curl_close($ch); return $retValue;}$sXML = download_page('http://alanstorm.com/atom');$oXML = new SimpleXMLElement($sXML);foreach($oXML->entry as $oEntry){ echo $oEntry->title . "\n";} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/561816', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/50851/']} | jdg_381323 |
stackexchange | llm_judgeable_groundtruth_similarity | 14868406 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have some data in a list that I need to look for continuous runs of integers (My brain think rle but don't know how to use it here). It's easier to look at the data set and explain what I'm after. Here's the data view: $greg [1] 7 8 9 10 11 20 21 22 23 24 30 31 32 33 49$researcher[1] 42 43 44 45 46 47 48$sally [1] 25 26 27 28 29 37 38 39 40 41$sam [1] 1 2 3 4 5 6 16 17 18 19 34 35 36$teacher[1] 12 13 14 15 Desired output: $greg [1] 7:11, 20:24, 30:33, 49$researcher [1] 42:48$sally [1] 25:29, 37:41$sam [1] 1:6, 16:19 34:36$teacher [1] 12:15 Use base packages how can I replace continuous span with a colon between highest and lowest and commas in between non the non continuous parts? Note that the data goes from a list of integer vectors to a list of character vectors. MWE data: z <- structure(list(greg = c(7L, 8L, 9L, 10L, 11L, 20L, 21L, 22L, 23L, 24L, 30L, 31L, 32L, 33L, 49L), researcher = 42:48, sally = c(25L, 26L, 27L, 28L, 29L, 37L, 38L, 39L, 40L, 41L), sam = c(1L, 2L, 3L, 4L, 5L, 6L, 16L, 17L, 18L, 19L, 34L, 35L, 36L), teacher = 12:15), .Names = c("greg", "researcher", "sally", "sam", "teacher"))
Now provide the response and nothing else.
| I think diff is the solution. You might need some additional fiddling to deal with the singletons, but: lapply(z, function(x) { diffs <- c(1, diff(x)) start_indexes <- c(1, which(diffs > 1)) end_indexes <- c(start_indexes - 1, length(x)) coloned <- paste(x[start_indexes], x[end_indexes], sep=":") paste0(coloned, collapse=", ")})$greg[1] "7:11, 20:24, 30:33, 49:49"$researcher[1] "42:48"$sally[1] "25:29, 37:41"$sam[1] "1:6, 16:19, 34:36"$teacher[1] "12:15" | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14868406', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1000343/']} | jdg_381324 |
stackexchange | llm_judgeable_groundtruth_similarity | 266786 |
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:
Please walk through how an attacker can intercept Chrome's connection to 127.0.0.1:999, as suggested by the warning below. This warning is consitently displayed across many versions of Chrome in many OSes. When I click the "learn more" link in the message, it says that SSL would be more secure, implying that an attacker can intercept Chrome's connection to 127.0.0.1:999. It is established that any user can open a port on 127.0.0.1 . However, according to w3.org, only root can open port numbers below 1024 . In light of this, how does the attacker pull off the interception in this case?
Now provide the response and nothing else.
| There are a number of different points here: only root can open port numbers below 1024 : that is true on most Unix-like OSes such as Linux. But any user can open any port on a Microsoft system, or macOS since version 10.14 an attacker can intercept Chrome's connection to 127.0.0.1:999 : well 127.0.0.x is the loopback address. That means that for the attacker to intercept the connection it has to be already active on the local machine. Said differently, the interception could be a way to gather information to prepare a privilege elevation, but in any case for the attack to start, the local machine has to be already compromised Google Chrome was written from the beginning as a browser and assumes that the client and the server could be on different systems. For that reason, it always throws warnings when it sees the raw HTTP protocol (in fact, any time there is no HTTPS certificate ). But only you can say whether you actually trust your local network or your local machine. What I mean here is that IMHO using https on a local machine adds little to no security: if the machine is compromised you should not trust anything because both the client and server side are compromised, and if it is not, no interception is possible... | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/266786', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/286296/']} | jdg_381325 |
stackexchange | llm_judgeable_groundtruth_similarity | 20412379 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
i have a problem that i have been struggling with for the past 2 days. I am building an app that uses ActionBar, ViewPager & FragmentPagerAdapter.The code for the Activity, Fragments & FragmentPagerAdapter are exactly as the ones stated in the android example on http://developer.android.com/reference/android/support/v4/view/ViewPager.html The problem i am facing is -- assuming i have only 2 fragments in the viewPager. when switching/swiping between the two, the fragments are not getting updated. onResume does not get called because the viewPager caches a minimum of 1 fragment to either side of the displayed fragment. I tried using the onTabSelected to detect when a fragment is selected and then start a method from that fragment with the help of an interface (code below). public void onTabSelected(Tab tab, FragmentTransaction ft) { TabInfo tag = (TabInfo)tab.getTag(); for (int i=0; i<mTabs.size(); i++) { if (mTabs.get(i) == tag) { mViewPager.setCurrentItem(i); } } ((IStartStop)getItem(tab.getPosition())).Start();} However, when the Start method is used a NullPointerException is fired when trying to update a textview. The start method's code is: public void Start() { TextView tv = _view.findViewById(R.id.text); tv.setText("test");} The exception is thrown at line: TextView tv = _view.findViewById(R.id.text); The IStartStop interface is quite simple: public interface IStartStop { public void Start(); public void Stop();} I don't want to use notifyDataSetChanged(); with POSITION_NONE because every time I swipe to a new fragment, it takes a few seconds to load the fragments At this time, the fragments only include a textview, in the future they will have an animation and so it is important to: 1- Only run an animation when the fragment is selected and not when the fragment next to it is selected (the way ViewPager caches and resumes fragments). 2- Stop the animation when the fragment is no longer selected to avoid wasting device resources. Yes, i already checked everything available on the internet but nothing seems to work with me. Thank you very much for your help!
Now provide the response and nothing else.
| Surprisingly the ViewPager doesn't do this "natively" (among other things). But not all is lost. First you have to modify your fragments so they only run the animation when you tell them that it's ok and not when they are instantiated. This way you can play with the viewpager offset (default = 3) and have 2-3 fragments preloaded but not animated. Second step is to create an interface or similar that defines when the "fragment has become visible". Third step would be to attach a new OnPageScrollListener to your viewpager. Code follows (in semi-untested-code): 1) Attach the Listener: mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(final int i, final float v, final int i2) { } @Override public void onPageSelected(final int i) { YourFragmentInterface fragment = (YourFragmentInterface) mPagerAdapter.instantiateItem(mViewPager, i); if (fragment != null) { fragment.fragmentBecameVisible(); } } @Override public void onPageScrollStateChanged(final int i) { } }); 2) This is your Interface: public interface YourFragmentInterface { void fragmentBecameVisible();} 3) Change your fragments so they implement this: public class YourLovelyFragment extends Fragment implements YourFragmentInterface { 4) Implement the interface in the fragment @Overridepublic void fragmentBecameVisible() { // You can do your animation here because we are visible! (make sure onViewCreated has been called too and the Layout has been laid. Source for another question but you get the idea.} Where to go from here? You might want to implement a method/listener to notify the "other" fragments that they are no longer visible (i.e. when one is visible, the others are not). But that may not be needed. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/20412379', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3072237/']} | jdg_381326 |
stackexchange | llm_judgeable_groundtruth_similarity | 15637556 |
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 new to c++ and I'm having difficulties with constructor and classes. So, here is my header file: #pragma once#include <string>using namespace std;class test{ private: string name; int number;public: test(); test(string i,int b);}; This is cpp file: #include "test.h"#include <string>using namespace std;test::test(){}test::test(string i,int b){ this->name=i; this->number=b;} now, when I try to call test t=new test("rrr",8); I get: 1 IntelliSense: no suitable constructor exists to convert from "test *" to "test" So, whats the thing with classes having * in their name ( for instance, classes without .cpp file don't have asterix, all others do)? And what do I do wrong?
Now provide the response and nothing else.
| I imagine you're coming from a Java/C# background. t is not a reference type here, it's a value type. new returns a pointer to an object. So you need any of the following: test t = test("rrr", 8);test t("rrr", 8);test *t = new test("rrr", 8); If you're not yet familiar with pointers, then definitely don't use the last one! But understanding the semantics of pointers is fairly critical; I recommend reading the relevant chapter(s) in your textbook... | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/15637556', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1515865/']} | jdg_381327 |
stackexchange | llm_judgeable_groundtruth_similarity | 3147992 |
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 be able to change my webpage background image according to the screen resolution the user uses so: if screen resolution is greater than or equal to 1200*600 then background = mybackground.jpg no-repeat or else. How can I do this?
Now provide the response and nothing else.
| Pure CSS approaches that work very well are discussed here . Two techniques are examined in particular and I personally prefer the second as it not CSS3 dependent, which suits my own needs better. If most/all of your traffic has a CSS3 capable browser, the first method is quicker and cleaner to implement (copy/pasted by Mr. Zoidberg in another answer here for convenience, though I'd visit the source for further background on why it works). An alternative method to CSS is to use the JavaScript library jQuery to detect resolution changes and adjust the image size accordingly. This article covers the jQuery technique and provides a live demo. Supersized is a dedicated JavaScript library designed for static full screen images as well as full sized slideshows. A good tip for full-screen images is to scale them with a correct ratio beforehand. I normally aim for a size of 1500x1000 when using supersized.js or 1680x1050 for other methods, setting the jpg quality for photographs to between 60-80% resulting in a file size in the region of 100kb or less if possible without compromising quality too much. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3147992', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/352833/']} | jdg_381328 |
stackexchange | llm_judgeable_groundtruth_similarity | 48130461 |
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 a newbie to coding, and I am making a game, but I do not know how to simulate gravity to make my character jump. I have tried many different things, and turned up with disastrous results. This is my code: #canvas { border: 1px solid #d3d3d3; background-color: #f1f1f1;} <body> <canvas id='canvas' width='512px' height='300px'></canvas> <script> let canvas = document.getElementById('canvas'); let ctx = canvas.getContext('2d'); let charX = 20; let charY = 130; let charSide = 20; let velocity = 0; let resistance = 0; let rightPressed = false; let leftPressed = false; let upPressed = false; let aPressed = false; let dPressed = false; function drawRect(x, y, width, height, color) { ctx.beginPath(); ctx.rect(x, y, width, height); ctx.fillStyle = color; ctx.fill(); ctx.closePath(); } function drawGround(x, y, count) { if (count === undefined) { count = 1; } drawRect(x, y, 32 * count, canvas.height - y, '#684027'); drawRect(x, y, 32 * count, 10, 'green'); } function draw() { //Updates Game ctx.clearRect(0, 0, canvas.width, canvas.height); //Draws Character drawRect(charX, charY, charSide, charSide, 'lime'); //Draws Ground drawGround(0, 150, 16); //Moves Character if (charY = 130) { speed = 0; accelerate = 0; } if (rightPressed && charX < canvas.width - charSide) { charX += 2; } else if (leftPressed && charX > 0) { charX -= 2; } else if (upPressed && charY > 0 && charY < 131) { velocity = 0; velocity += 50; resistance++; velocity -= resistance; charY -= velocity; } else if (upPressed === false && charY > 129) { resistance = 0; velocity = 0; } } //Character Movement Logic document.addEventListener("keydown", keyDownHandler, false); document.addEventListener("keyup", keyUpHandler, false); function keyDownHandler(e) { if (e.keyCode == 39) { rightPressed = true; } else if (e.keyCode == 37) { leftPressed = true; } else if (e.keyCode == 38) { upPressed = true; } else if (e.keyCode == 65) { aPressed = true; } else if (e.keyCode == 68) { dPressed = true; } } function keyUpHandler(e) { if (e.keyCode == 39) { rightPressed = false; } else if (e.keyCode == 37) { leftPressed = false; } else if (e.keyCode == 38) { upPressed = false; } else if (e.keyCode == 65) { aPressed = false; } else if (e.keyCode == 68) { dPressed = false; } } //Animates Game setInterval(draw, 10); </script></body> I have tried to make different variable, like velocity and resistance, and apply them to the y-position of my character when jumping, but it did not work.
Now provide the response and nothing else.
| Simple game physics First of when animating use requestAnimationFrame to time the animation. Example below shows how. Gravity The simplest gravity can be applied assuming a constant frame rate. An object has a y position and a y speed (delta y). Gravity is a constant force that increases the delta y each frame obj = { y : 0, // position dy : 0, // speed size : 20, // height onGround : false, // true if on the ground drag : 0.99, // the drag is 0.01 }const grav = 0.1; Each frame (animation tick) apply gravity and update the position obj.dy += grav;obj.y += obj.dy; If the object hits the ground you zero the delta y if(obj.y + obj.size >= 150){ // has hit ground obj.y = 150 - obj.size; // place on ground obj.dy = 0; // stop delta y obj.onGround = true;}else{ obj.onGround = false;} Then draw the character Jump To make the character jump just set the delta y to a negative value. Only set it when the character is on the ground. The above code will bring the character back down in time. if(keyboard.up && obj.onGround){ obj.dy = -5;} Drag To add some resistance or drag which is proportional to the speed. The faster you go the more drag there is you create a drag coefficient. You multiply the delta y by this value each frame after you add the gravity force. obj.dy *= obj.drag; // reduce speed due to drag The example below shows a player that can jump from the ground and move left and right. There is a little drag in the jump and when the player is on the ground there is a lot of drag for left and right movement. Demo const ctx = canvas.getContext('2d');// Simple keyboard handlerconst keyboard = (() => { document.addEventListener("keydown", keyHandler); document.addEventListener("keyup", keyHandler); const keyboard = { right: false, left: false, up: false, any : false, }; function keyHandler(e) { const state = e.type === "keydown" if (e.keyCode == 39) { keyboard.right = state; } else if (e.keyCode == 37) { keyboard.left = state; } else if (e.keyCode == 38) { keyboard.up = state; e.preventDefault(); } if(state) { keyboard.any = true } // must reset when used } return keyboard;})();// define the player.// update() updates position and response to keyboard// draw() draws the player// start() sets start position and stateconst player = { x: 0, y: 0, dx: 0, // delta x and y dy: 0, size: 20, color: 'lime', onGround: false, jumpPower: -5, // power of jump smaller jumps higher eg -10 smaller than -5 moveSpeed: 2, update() { // react to keyboard state if (keyboard.up && this.onGround) { this.dy = this.jumpPower } if (keyboard.left) { this.dx = -this.moveSpeed } if (keyboard.right) { this.dx = this.moveSpeed } // apply gravity drag and move player this.dy += world.gravity; this.dy *= world.drag; this.dx *= this.onGround ? world.groundDrag : world.drag; this.x += this.dx; this.y += this.dy; // test ground contact and left and right limits if (this.y + this.size >= world.ground) { this.y = world.ground - this.size; this.dy = 0; this.onGround = true; } else { this.onGround = false; } if (this.x > ctx.canvas.width) { this.x -= ctx.canvas.width; } else if (this.x + this.size < 0) { this.x += ctx.canvas.width; } }, draw() { drawRect(this.x, this.y, this.size, this.size, this.color); }, start() { this.x = ctx.canvas.width / 2 - this.size / 2; this.y = world.ground - this.size; this.onGround = true; this.dx = 0; this.dy = 0; }}// define worldconst world = { gravity: 0.2, // strength per frame of gravity drag: 0.999, // play with this value to change drag groundDrag: 0.9, // play with this value to change ground movement ground: 150,}// set startplayer.start();// call first frame. This will run after all the rest of the code has runrequestAnimationFrame(mainLoop); // start when ready// From OPfunction drawRect(x, y, width, height, color) { ctx.beginPath(); ctx.rect(x, y, width, height); ctx.fillStyle = color; ctx.fill(); ctx.closePath();}function drawGround(x, y, count = 1) { drawRect(x, y, 32 * count, canvas.height - y, '#684027'); drawRect(x, y, 32 * count, 10, 'green');}// show instructvar showI = true;// main animation loopfunction mainLoop(time) { // time passed by requestAnimationFrame ctx.clearRect(0, 0, canvas.width, canvas.height); drawGround(0, world.ground, 16); player.update(); player.draw(); if(showI){ if(keyboard.any){ keyboard.any = false; showI = false; } ctx.textAlign = "center"; ctx.font = "24px arial"; ctx.fillStyle = "#000"; ctx.fillText("Up arrow to jump. Left right to move",ctx.canvas.width / 2, 80); } requestAnimationFrame(mainLoop);}// make sure window has focus for keyboard input.window.focus(); #canvas { border: 1px solid #d3d3d3; background-color: #f1f1f1;} <canvas id='canvas' width='512px' height='300px'></canvas> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48130461', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8997493/']} | jdg_381329 |
stackexchange | llm_judgeable_groundtruth_similarity | 10379261 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to override a getFilter() method from the class ArrayAdapter and i found the source code from here in the github //package nameimport java.util.ArrayList;import java.util.Arrays;import java.util.List;import android.content.Context;import android.util.Log;import android.widget.ArrayAdapter;import android.widget.Filter;import android.widget.Filterable;public class CustomAdapter<T> extends ArrayAdapter<T> implements Filterable{ private ArrayList<T> mOriginalValues; private List<T> mObjects; private CustomFilter mFilter; private final Object mLock = new Object(); public CustomAdapter(Context context, int textViewResourceId, T[] objects) { super(context, textViewResourceId, objects); mObjects = Arrays.asList(objects); // TODO Auto-generated constructor stub } @Override public Filter getFilter() { // TODO Auto-generated method stub if (mFilter == null) { mFilter = new CustomFilter(); } return mFilter; } private class CustomFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence prefix) { FilterResults results = new FilterResults(); Log.d("bajji", "its ---> " + prefix); if (mOriginalValues == null) { synchronized (mLock) { mOriginalValues = new ArrayList<T>(mObjects); } } if (prefix == null || prefix.length() == 0) { ArrayList<T> list; synchronized (mLock) { list = new ArrayList<T>(mOriginalValues); } results.values = list; results.count = list.size(); } else { String prefixString = prefix.toString().toLowerCase(); ArrayList<T> values; synchronized (mLock) { values = new ArrayList<T>(mOriginalValues); } final int count = values.size(); final ArrayList<T> newValues = new ArrayList<T>(); final ArrayList<T> approxValues = new ArrayList<T>(); final ArrayList<T> secondApproxValues = new ArrayList<T>(); for (int i = 0; i < count; i++) { final T value = values.get(i); final String valueText = value.toString().toLowerCase(); boolean flag = true; // First match against the whole, non-splitted value if (valueText.startsWith(prefixString)) { newValues.add(value); flag = false; } else { final String[] words = valueText.split(" "); final int wordCount = words.length; // Start at index 0, in case valueText starts with space(s) for (int k = 0; k < wordCount; k++) { if (words[k].startsWith(prefixString)) { newValues.add(value); flag = false; break; } } } if(flag) { if(approxMatch(valueText, prefixString) <= 3) { //change the stuff and do a levi work approxValues.add(value); } else { final String[] words = valueText.split(" "); final int wordCount = words.length; // Start at index 0, in case valueText starts with space(s) for (int k = 0; k < wordCount; k++) { if(approxMatch(words[k], prefixString) <= 3) { //leve work secondApproxValues.add(value); break; } } } } } newValues.addAll(approxValues); newValues.addAll(secondApproxValues); results.values = newValues; results.count = newValues.size(); } return results; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { //noinspection unchecked mObjects = (List<T>) results.values; if (results.count > 0) { notifyDataSetChanged(); } else { notifyDataSetInvalidated(); } } } private int approxMatch (String s, String t) { // an approxmimate string matching algo return p; }} The problem is the getFilter method has a object of a private inner class ArrayFilter which has a method peformFiltering and i need to put a different code there so i have to overide the class. And i get an exception in the method. In the derived class which extends ArrayAdapter i created a private inner class which is similar to ArrayFilter and called it MyFilter and i get the same exception again in the method performFiltering . I found a solution to solve my problem. I copied all the code in ArrayAdapter class and created a new class called MyAdapter and i altered some code inside the inner class ArrayFilter and the app works the way i wanted it to. But i feel its not the best solution. Android has various api levels so if the array adapter is changed in different api level then i have to add those changes in my codes to. So i feel the best way is to extend the class ArrayAdapter to create MyAdapter rather than just copying and pasting the code from the ArrayAdapter How can i override the inner private class of a parent class..? Edit: The exception i get.. Edit2: Now i added the full code in the question. and it works perfectly if i copy and edit the array adapter.. the problem is only when i extend..!! now the code and search is working perfectly. I checked it with Log.i .. but the drop down list for auto complete suggestion in UI is not working.. i only get for the first character i type the next character filtering takes place but UI update is not taking place.
Now provide the response and nothing else.
| After some help from stackoverflow community i removed the exception and later i found out that the suggestions that are returned doesn't really change because the mObjects was returned from the super class or base class. The problem was the there were two public methods getCount() and getItem(int position) which gets the count and fetches the list from mObjects from the base class. So i just have to add those two methods in my class.. public int getCount() { return mObjects.size();}public T getItem(int position) { return mObjects.get(position);} Now mObjects of the derived class will be returned. Which are the updated in the dropdown list in the UI. I am not a java expert, but this solves my problem. If you have any suggestions to make the code better please add it in comments or feel free to edit the answer.! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/10379261', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/896872/']} | jdg_381330 |
stackexchange | llm_judgeable_groundtruth_similarity | 491286 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I’m wondering if I’m making the right approach when I’m trying to calculate the power consumed by the diode in the circuit. Here is the problem: So my approach is: Power loss by diode $$V_f \times I_f$$ where \$V_f\$ = Diode forward voltage drop. \$I_f\$ = The current flowing through the diode. So the first thing I did was to calculate the current $$I = V/R = 5/1000 = 5 mA$$ And then I use $$ V_f \times I_f= 2 \times 0.005 = 10 mW $$ Is this correct? I feel like there is more to the problem with the fact that it states ”red color light”. Should I check on a sheet or similar?
Now provide the response and nothing else.
| I think that you have neglected the voltage drop across the diode which limits the current. My solution is : $$\because V_{R_1}=V_0-V_f=5-2=3\,\text{V}$$ $$\therefore I_f=I_{R_1}=V_{R_1}/R_1=3/1000=3\,\text{mA}$$ $$Power Loss =V_f\times I_f=2 \times0.003=6\,\text{mW} $$ | {} | {'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/491286', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/105597/']} | jdg_381331 |
stackexchange | llm_judgeable_groundtruth_similarity | 213684 |
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:
It bothers me to see commented out code and it seems often-times a symptom of developers not being proficient in advanced source control features, but on the other hand source control does not really go all the way in solving the problem that commenting out is intended for. I've occasionally seen requirements flip-flop in such a way that code that would have been deleted suddenly is needed again. If the code is really deleted, there doesn't seem to be a clear procedure for locating exactly where to find that deleted code in source control. Is there a better way out there to save developer work that may be needed again besides the tried-and-true "commenting out"?
Now provide the response and nothing else.
| We're pretty rigorous about this, and the guideline is that commented-out code shouldn't be checked in. The rationale behind this is that you can never really know whether the engineer forgot to uncomment it before checking it in. Even with a comment explaining why the code is commented out, there's still an element of doubt. If you need it back, you can get it back from source control. In my opinion, the danger of changing requirements is less than the danger (and probable uncertainty) of seeing a block of checked in commented out code (particularly at some point far in the future) and wondering whether it should be there or not. At the end of the day, even with specifications, user stories, Jira tickets and all that jazz, "the code is the documentation" - it's the only definitive reference as to what something actually does . Of course it's just a guideline; I'm sure you're going to get some really great answers to this -- I'm looking forward to reading them! Succinctly: don't check in the commented code, instead leave yourself a note in your issue tracker. Write in the revision number and location of the alternate implementation. The code remains clean, and you help your future self. If/when the requirements change, the implementation ticket will (should) get reopened, and you can use your breadcrumb to find the previous version. Some issue trackers automatically track the change in source control directly on the ticket - that's another aid to you. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/213684', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/4526/']} | jdg_381332 |
stackexchange | llm_judgeable_groundtruth_similarity | 39277321 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
For instance, I want to do something like the following: char output = 'A' + 1; getting output of 'B' However, simply trying what I have above gives a casting error.
Now provide the response and nothing else.
| Yes, the binary + operator isn't defined on char , so you end up with implicit conversions to int . You can use a pre/post-increment operator: char x = 'A';x++; ... because the ++ operator is defined for char . But otherwise, you need a cast: char x = 'A';x = (char) (x + 1); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39277321', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6758106/']} | jdg_381333 |
stackexchange | llm_judgeable_groundtruth_similarity | 2604428 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
They said this expression is valid in C, and that it means calling a function: (*(void(*)())0)(); Can someone clearly explain what this expression means? I tried to compile this and was surprised that it didn't result in an error.
Now provide the response and nothing else.
| Step by step: void(*)() // a pointer-to-function type, taking unspecified parameters // and returning nothing. (void(*)())0 // a null pointer of that pointer-to-function type(*(void(*)())0) // dereference that pointer(*(void(*)())0)(); // and call it with no parameters The code has undefined behaviour, it'll probably crash with some kind of illegal access / segfault. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2604428', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3941732/']} | jdg_381334 |
stackexchange | llm_judgeable_groundtruth_similarity | 44748 |
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am presented with a comparison network. How can I determine if the comparison network is a sorting network? In the image below there is an example of a selection sort and insertion sort network. The intent is to have a comparison network and sort numeric values. If I test 2^n values in this case 2^8. This is a lot of work|non-efficient way to test it. I'm looking for a mathematical model/proof to verify this is a valid sorting network.
Now provide the response and nothing else.
| In general, verifying whether a particular comparison network is indeed a correct sorting network is a Co-NP complete problem. If you want to check by testing, then you need to try exponentially many tests. In particular, there exist sorting networks that sort all but a single value correctly, so you can't hope to test whether the network is correct or not simply by feeding it a few inputs. One standard method is to test whether it correctly sorts all $2^n$ inputs that are composed solely of zeros and ones. If it does, then it turns out that it will sort all inputs (even ones that aren't limited to zeros and ones). However, this requires exponentially many tests. Moreover, the number of tests cannot be reduced significantly: for zero-one inputs, it is possible to prove that at least $2^n-n-1$ tests are needed, in order to verify that the sorting network is correct. Alternatively, one can use tests where the inputs are permutations of $1,2,\dots,n$ . This reduces the number of tests needed somewhat, but you still need exponentially many tests. In particular, $C(n, \lfloor n/2 \rfloor)-1$ tests are necessary and sufficient. For proofs of these facts, see the following papers: On the Computational Complexity of Optimal Sorting Network Verification . Ian Parberry. Parle'91 Parallel Architectures and Languages Europe, 1991. Bounds on the size of test sets for sorting and related networks . Moon Jung Chung and B. Ravikumar. Discrete Mathematics, vol 81, pp.1--9, April 1990. | {} | {'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/44748', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/35856/']} | jdg_381335 |
stackexchange | llm_judgeable_groundtruth_similarity | 48333 |
Below is a question asked on the forum skeptics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was reading Stuart Stevens' interview on Politico , and came across this claim: more Americans have died from a disease [referring to Covid-19] in the last four months than have ever died of anything in America Mutatis mutandis , is that true, or just something he threw out on the spur of the moment? I doubt that "than have ever died of anything in America" is the case, so let's adjust it and confine it to any given 4 month period. I am scratching my head and trying to come up with other major mass killers: cancer wars "Spanish" flu traffic accidents heart disease guns violence I don't imagine that any of those killed as many in 4 months (the qualification is mine). If we allow that qualification, which I believe can be fairly implied, is he correct?
Now provide the response and nothing else.
| No, but it's close, ranking between #4 and #6 depending on how you count. As of August 20, 2020, the US death toll from COVID-19 is roughly 175,000 (source: the New York Times, the CDC, and Worldometers all agree to within about 2%). The death toll started rising in late March, for a duration of slightly over five months, not the four months mentioned in the question. Compare that to other death tolls (all numbers rounded to the nearest thousand): American Civil War, total military deaths: 593,000, including disease, over four years . World War II: 419,000 total, including civilian deaths, over four years . American Civil War, Union deaths: 335,000 total, including disease, over four years . 1918 flu pandemic, second wave: 292,000 over four months . Heart disease (#1 cause of ongoing deaths): 270,000 per five months in 2017 . Cancer (#2 cause of ongoing deaths): 250,000 per five months in 2017 . COVID-19 is here right now, at 175,000 deaths. <From here on down, only some causes of death have been listed> World War I: 117,000 total, including disease, over roughly a year and a half . Accidental injuries (#3 cause of ongoing deaths): 71,000 per five months in 2017 . Influenza: 61,000 in the 2017-2018 flu season, the worst in the past decade . Vietnam War: 58,000 total, over roughly nine years . American Civil War, Overland Campaign: 12,000 over two months . Sorted by percent of the population killed, using the population numbers from the nearest census. The relative rankings of some things change, but COVID-19 remains in the #6 spot American Civil War, total military: 1.8% American Civil War, Union military: 1.5% World War II: 0.32% 1918 flu pandemic, second wave: 0.28% Heart disease, five-month average in 2017: 0.082% Cancer, five-month average in 2017: 0.076% COVID-19, March 1-August 21: 0.054% <From here on down, only some causes of death have been listed> American Civil War, Overland Campaign: 0.038% Vietnam War: 0.028% Accidental injuries, five-month average in 2017: 0.022% Influenza, 2017-2018 season: 0.018% COVID-19 isn't the biggest killer of Americans in history, but it's well up there. Compared to other disease outbreaks, it's ahead of everything except the 1918 flu pandemic. Compared to non-contagious causes of death, it's ahead of everything except heart disease and cancer. And compared to mass-casualty events such as wars, it's ahead of everything except World War II and the American Civil War -- and it's ahead of any five-month slice of either of those wars. More people dying from COVID-19 won't change the relative ordering, barring a disastrous third wave -- the COVID-19 rate is currently lower than that for cancer or heart disease (so it won't pass them), the COVID-19 total is already ahead of the annual total for accidents (so it can't fall behind it), and the 1918 pandemic is far enough ahead of COVID-19 that it isn't likely to be surpassed, particularly as a percentage of population killed. | {} | {'log_upvote_score': 6, 'links': ['https://skeptics.stackexchange.com/questions/48333', 'https://skeptics.stackexchange.com', 'https://skeptics.stackexchange.com/users/6956/']} | jdg_381336 |
stackexchange | llm_judgeable_groundtruth_similarity | 427744 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
For any odd positive integer $k\geq1$, the sum $1^k+2^k + \dots + n^k$ is divisible by $n(n+1)\over 2$. I used induction principle for the solution but cannot prove it. I took $P(k) = 1^k+2^k+\dots+n^k$. For $P(1)$ it is true. For $P(n)$ let it be true. But for $P(n+1)$ I cannot solve it.
Now provide the response and nothing else.
| For odd $k$ we have that$$a^k+b^k=(a+b)(a^{k-1}-a^{k-2}b+a^{k-3}b^2-\dots+b^{k-1})$$Thus, each column of$$\begin{align}&0^k+\hphantom{(n-\ )}1^k+\hphantom{(n-\,\,)}2^k+\dots+n^k\\&n^k+(n-1)^k+(n-2)^k+\cdots+0^k\end{align}$$is divisible by $n$ and each column of$$\begin{align}&1^k+\hphantom{(n-\ )}2^k+\hphantom{(n-\,\,)}3^k+\dots+n^k\\&n^k+(n-1)^k+(n-2)^k+\cdots+1^k\end{align}$$is divisible by $n+1$. Since $(n,n+1)=1$ we get that$$n(n+1)\,|\,2(1^k+2^k+3^k+\dots+n^k)$$and therefore, since $n(n+1)$ is even,$$\left.\frac{n(n+1)}{2}\middle|1^k+2^k+3^k+\dots+n^k\right.$$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/427744', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/81622/']} | jdg_381337 |
stackexchange | llm_judgeable_groundtruth_similarity | 1397827 |
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 read from stdin five numbers entered as follows: 3, 4, 5, 1, 8 into seperate variables a,b,c,d & e. How do I do this in python? I tried this: import stringa=input()b=a.split(', ') for two integers, but it does not work. I get: Traceback (most recent call last): File "C:\Users\Desktop\comb.py", line 3, in <module> b=a.split(', ')AttributeError: 'tuple' object has no attribute 'split' How to do this? and suppose I have not a fixed but a variable number n integers. Then?
Now provide the response and nothing else.
| Use raw_input() instead of input() . # Python 2.5.4>>> a = raw_input()3, 4, 5>>> a'3, 4, 5'>>> b = a.split(', ')>>> b['3', '4', '5']>>> [s.strip() for s in raw_input().split(",")] # one liner3, 4, 5['3', '4', '5'] The misleadingly names input function does not do what you'd expect it to. It actually evaluates the input from stdin as python code. In your case it turns out that what you then have is a tuple of numbers in a , all parsed and ready for work, but generally you don't really want to use this curious side effect. Other inputs can cause any number of things to happen. Incidentally, in Python 3 they fixed this, and now the input function does what you'd expect. Two more things: You don't need to import string to do simple string manipulations. Like mjv said , to split a tuple or a list into several variables, you can 'unpack' it. This will not be feasible if you don't know how long the list will be, though. Unpacking: >>> l = (1,2,3,4,5)>>> a,b,c,d,e = l>>> e5 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1397827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/113124/']} | jdg_381338 |
stackexchange | llm_judgeable_groundtruth_similarity | 2310 |
Below is a question asked on the forum quantumcomputing.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Given a $2$ qubit-system and thus $4$ possible measurements results in the basis $\{|00\rangle$, $|01\rangle$, $|10\rangle$, $|11\rangle\}$, how can I prepare the state, where: only $3$ of these $4$ measurement results are possible (say, $|00\rangle$, $|01\rangle$, $|10\rangle$)? these measurements are equally likely? (like Bell state but for $3$ outcomes)
Now provide the response and nothing else.
| Break the problem in parts. Say we have already sent $\mid 00 \rangle$ to $\frac{1}{\sqrt{3}} \mid 00 \rangle + \frac{\sqrt{2}}{\sqrt{3}}\mid 01 \rangle$. We can send that to $\frac{1}{\sqrt{3}} \mid 00 \rangle + (\frac{1}{2} (1+i))\frac{\sqrt{2}}{\sqrt{3}}\mid 01 \rangle + (\frac{1}{2} (1-i))\frac{\sqrt{2}}{\sqrt{3}}\mid 10 \rangle$ by a $\sqrt{SWAP}$. That satisfies you're requirements with all probabilities $\frac{1}{3}$ but with different phases. If you want use phase shift gates on each to get the phases you want like if you want to make them all equal. Now how do we get from $\mid 00 \rangle$ to $\frac{1}{\sqrt{3}} \mid 00 \rangle + \frac{\sqrt{2}}{\sqrt{3}}\mid 01 \rangle$? If it was $\frac{1}{\sqrt{2}} \mid 00 \rangle + \frac{1}{\sqrt{2}}\mid 01 \rangle$, we could do a Hadamard on the second qubit. It is not a easy with this but we can still use a unitary only on the second qubit. That is done by a rotation operator purely on the second qubit by factoring as $$Id \otimes U : \; \mid 0 \rangle \otimes (\mid 0 \rangle) \to \mid 0 \rangle \otimes (\frac{1}{\sqrt{3}} \mid 0 \rangle + \frac{\sqrt{2}}{\sqrt{3}} \mid 1 \rangle)$$ $$U = \begin{pmatrix}\frac{1}{\sqrt{3}} & \frac{\sqrt{2}}{\sqrt{3}} & \\\frac{\sqrt{2}}{\sqrt{3}} & -\frac{1}{\sqrt{3}} & \\\end{pmatrix}$$ works. Decompose this into more basic gates if you need to. In total we have: $$\mid 00 \rangle \to \frac{1}{\sqrt{3}} \mid 00 \rangle + \frac{\sqrt{2}}{\sqrt{3}}\mid 01 \rangle\\\to \frac{1}{\sqrt{3}} \mid 00 \rangle + (\frac{1}{2} (1+i))\frac{\sqrt{2}}{\sqrt{3}}\mid 01 \rangle + (\frac{1}{2} (1-i))\frac{\sqrt{2}}{\sqrt{3}}\mid 10 \rangle\\\to \frac{1}{\sqrt{3}} \mid 00 \rangle + \frac{e^{i \theta_1}}{\sqrt{3}}\mid 01 \rangle + \frac{e^{i \theta_2}}{\sqrt{3}}\mid 10 \rangle$$ | {} | {'log_upvote_score': 5, 'links': ['https://quantumcomputing.stackexchange.com/questions/2310', 'https://quantumcomputing.stackexchange.com', 'https://quantumcomputing.stackexchange.com/users/2624/']} | jdg_381339 |
stackexchange | llm_judgeable_groundtruth_similarity | 59631118 |
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 Laravel in Ubuntu 19.10. The problem is when I try to reach project_name/login, it says that the request url was not found on the server. I've tried to change apache2.conf and change .htaccess inside public folder of my laravel's project. But it doesn't worked.. This is apache2.conf in /etc/apache2/ # This is the main Apache server configuration file. It contains the# configuration directives that give the server its instructions.# See http://httpd.apache.org/docs/2.4/ for detailed information about# the directives and /usr/share/doc/apache2/README.Debian about Debian specific# hints.### Summary of how the Apache 2 configuration works in Debian:# The Apache 2 web server configuration in Debian is quite different to# upstream's suggested way to configure the web server. This is because Debian's# default Apache2 installation attempts to make adding and removing modules,# virtual hosts, and extra configuration directives as flexible as possible, in# order to make automating the changes and administering the server as easy as# possible.# It is split into several files forming the configuration hierarchy outlined# below, all located in the /etc/apache2/ directory:## /etc/apache2/# |-- apache2.conf# | `-- ports.conf# |-- mods-enabled# | |-- *.load# | `-- *.conf# |-- conf-enabled# | `-- *.conf# `-- sites-enabled# `-- *.conf### * apache2.conf is the main configuration file (this file). It puts the pieces# together by including all remaining configuration files when starting up the# web server.## * ports.conf is always included from the main configuration file. It is# supposed to determine listening ports for incoming connections which can be# customized anytime.## * Configuration files in the mods-enabled/, conf-enabled/ and sites-enabled/# directories contain particular configuration snippets which manage modules,# global configuration fragments, or virtual host configurations,# respectively.## They are activated by symlinking available configuration files from their# respective *-available/ counterparts. These should be managed by using our# helpers a2enmod/a2dismod, a2ensite/a2dissite and a2enconf/a2disconf. See# their respective man pages for detailed information.## * The binary is called apache2. Due to the use of environment variables, in# the default configuration, apache2 needs to be started/stopped with# /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not# work with the default configuration.# Global configuration### ServerRoot: The top of the directory tree under which the server's# configuration, error, and log files are kept.## NOTE! If you intend to place this on an NFS (or otherwise network)# mounted filesystem then please read the Mutex documentation (available# at <URL:http://httpd.apache.org/docs/2.4/mod/core.html#mutex>);# you will save yourself a lot of trouble.## Do NOT add a slash at the end of the directory path.##ServerRoot "/etc/apache2"## The accept serialization lock file MUST BE STORED ON A LOCAL DISK.##Mutex file:${APACHE_LOCK_DIR} default## The directory where shm and other runtime files will be stored.#DefaultRuntimeDir ${APACHE_RUN_DIR}## PidFile: The file in which the server should record its process# identification number when it starts.# This needs to be set in /etc/apache2/envvars#PidFile ${APACHE_PID_FILE}## Timeout: The number of seconds before receives and sends time out.#Timeout 300## KeepAlive: Whether or not to allow persistent connections (more than# one request per connection). Set to "Off" to deactivate.#KeepAlive On## MaxKeepAliveRequests: The maximum number of requests to allow# during a persistent connection. Set to 0 to allow an unlimited amount.# We recommend you leave this number high, for maximum performance.#MaxKeepAliveRequests 100## KeepAliveTimeout: Number of seconds to wait for the next request from the# same client on the same connection.#KeepAliveTimeout 5# These need to be set in /etc/apache2/envvarsUser ${APACHE_RUN_USER}Group ${APACHE_RUN_GROUP}## HostnameLookups: Log the names of clients or just their IP addresses# e.g., www.apache.org (on) or 204.62.129.132 (off).# The default is off because it'd be overall better for the net if people# had to knowingly turn this feature on, since enabling it means that# each client request will result in AT LEAST one lookup request to the# nameserver.#HostnameLookups Off# ErrorLog: The location of the error log file.# If you do not specify an ErrorLog directive within a <VirtualHost># container, error messages relating to that virtual host will be# logged here. If you *do* define an error logfile for a <VirtualHost># container, that host's errors will be logged there and not here.#ErrorLog ${APACHE_LOG_DIR}/error.log## LogLevel: Control the severity of messages logged to the error_log.# Available values: trace8, ..., trace1, debug, info, notice, warn,# error, crit, alert, emerg.# It is also possible to configure the log level for particular modules, e.g.# "LogLevel info ssl:warn"#LogLevel warn# Include module configuration:IncludeOptional mods-enabled/*.loadIncludeOptional mods-enabled/*.conf# Include list of ports to listen onInclude ports.conf# Sets the default security model of the Apache2 HTTPD server. It does# not allow access to the root filesystem outside of /usr/share and /var/www.# The former is used by web applications packaged in Debian,# the latter may be used for local directories served by the web server. If# your system is serving content from a sub-directory in /srv you must allow# access here, or in any related virtual host.<Directory /> Options FollowSymLinks AllowOverride None Require all denied</Directory><Directory /usr/share> AllowOverride None Require all granted</Directory><Directory /var/www> Options Indexes FollowSymLinks AllowOverride All Require all granted</Directory>#<Directory /srv/># Options Indexes FollowSymLinks# AllowOverride None# Require all granted#</Directory># AccessFileName: The name of the file to look for in each directory# for additional configuration directives. See also the AllowOverride# directive.#AccessFileName .htaccess## The following lines prevent .htaccess and .htpasswd files from being# viewed by Web clients.#<FilesMatch "^\.ht"> Require all denied</FilesMatch>## The following directives define some format nicknames for use with# a CustomLog directive.## These deviate from the Common Log Format definitions in that they use %O# (the actual bytes sent including headers) instead of %b (the size of the# requested file), because the latter makes it impossible to detect partial# requests.## Note that the use of %{X-Forwarded-For}i instead of %h is not recommended.# Use mod_remoteip instead.#LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combinedLogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combinedLogFormat "%h %l %u %t \"%r\" %>s %O" commonLogFormat "%{Referer}i -> %U" refererLogFormat "%{User-agent}i" agent# Include of directories ignores editors' and dpkg's backup files,# see README.Debian for details.# Include generic snippets of statementsIncludeOptional conf-enabled/*.conf# Include the virtual host configurations:IncludeOptional sites-enabled/*.conf# vim: syntax=apache ts=4 sw=4 sts=4 sr noet and this is .htaccess inside public folder of my project <IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews -Indexes </IfModule> RewriteEngine On # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L]</IfModule> And I've enabled a2enmod rewrite with command like this sudo a2enmod rewrite !the results after I run that command !This is the screenshoot of my web https://i.stack.imgur.com/rcvEd.png Specification:Ubuntu 19.10PHP 7.3.11Laravel 5.8
Now provide the response and nothing else.
| Since PairGrid automatically passes a color attribute to the plotting function, one way to get a different color per plot is to create your own plotting function that ignores the color passed by PairGrid (note that you loose the possibility to color code by hues obviously) colors = iter(['xkcd:red purple', 'xkcd:pale teal', 'xkcd:warm purple', 'xkcd:light forest green', 'xkcd:blue with a hint of purple', 'xkcd:light peach', 'xkcd:dusky purple', 'xkcd:pale mauve', 'xkcd:bright sky blue', 'xkcd:baby poop green', 'xkcd:brownish', 'xkcd:moss green', 'xkcd:deep blue', 'xkcd:melon', 'xkcd:faded green', 'xkcd:cyan', 'xkcd:brown green', 'xkcd:purple blue', 'xkcd:baby shit green', 'xkcd:greyish blue'])def my_scatter(x,y, **kwargs): kwargs['color'] = next(colors) plt.scatter(x,y, **kwargs)def my_hist(x, **kwargs): kwargs['color'] = next(colors) plt.hist(x, **kwargs)iris = sns.load_dataset("iris")g = sns.PairGrid(iris)g.map_diag(my_hist)g.map_offdiag(my_scatter) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/59631118', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9012788/']} | jdg_381340 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.