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 | 4690904 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Basically, I have an asp.net ajax enabled usercontrol, and now I'd like to just return a simple string value, to be used in some js I'm firing after the ajax request is done. I've been fiddling around with the endrequest method, which I already set up to use for exception handling, which works fine. But is there no way to simply return a string value? First I thought I could do this through Response.Write(); but args.get_response() doesn't like when you do that apparantly - can anyone point me in the right direction? Thanks!
Now provide the response and nothing else.
| You can use the ScriptManager.RegisterDataItem method with the Sys.WebForms.PageRequestManager. Consider the following test page which when you click the button it registers data item with the script manager and at the client side it handles the endrequest and get that data item, <%@ Page Language="C#" AutoEventWireup="true" Inherits="WebApplication1._Default" %><script runat="server"> protected void btTest_Click(object sender, EventArgs e) { ScriptManager1.RegisterDataItem(btTest, "Your value to pass to the client"); }</script><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title></title></head><body> <form id="form1" runat="server"> <div> <asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:UpdatePanel ID="upTest" runat="server"> <ContentTemplate> <asp:Button ID="btTest" runat="server" Text="Click Me" OnClick="btTest_Click" /> </ContentTemplate> </asp:UpdatePanel> </div> </form></body><script language="javascript" type="text/javascript"> Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler); function endRequestHandler(sender, args) { var dataItems = args.get_dataItems()['<%= btTest.ClientID %>']; if (dataItems != null) alert(dataItems); }</script></html> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4690904', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/295540/']} | jdg_72241 |
stackexchange | llm_judgeable_groundtruth_similarity | 1516795 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I don't know if that is something obvious or if it is a dumb question. But it seems to be true. Consider the non-theorem $\forall x. x < 1$. Its negation is $\exists x. x \geq 1$ and is a theorem.Is this always true? I couldn't find a counterexample. If this is true I would like to know a good explanation why.
Now provide the response and nothing else.
| It's neither obvious nor a dumb question. But it is, perhaps surprisingly, sensitive to what theory, or at least what language, you're proving things in. I assume you intend the example you gave, $(\exists x)\,x\ge1$, as a sentence about the real numbers. The reals are a real closed field , and the theory of real closed fields is complete: every sentence or its negation is a theorem. So this really is a special case: as fate would have it, for this theory, the negation of every non-theorem actually is a theorem, so you'll search in vain for a counterexample. However, the same cannot be said for arithmetic, as formalized by Peano arithmetic (PA): there are sentences $S$ in the language of arithmetic such that neither $S$ nor $\neg S$ is a theorem of PA (assuming, of course, that PA is consistent). Examples include Gödel sentences (true sentences asserting their own unprovability within the system), as well as more natural sentences: Goodstein's theorem , which Kirby and Paris showed is unprovable in PA, and a true sentence about finite Ramsey theory which Paris and Harrington showed is independent of PA. Set theory offers further examples. For our purposes, it's safe to say that ZFC is the system in which contemporary mathematical practice takes place. ZFC has its own Gödel sentences (assuming it's consistent), but it turns out that many natural mathematical questions — sentences $S$ — are simply independent of the ZFC axioms: ZFC proves neither $S$ nor $\neg S$. One famous example is the Continuum Hypothesis, but the list of interesting statements independent of ZFC is substantial. The Axiom of Choice, AC, provides the "C" in ZFC. AC says:for every set $X$ of nonempty sets, there is a function $f$ with domain $X$ such that $f(x)\in x$ for all $x\in X$ ($f$ is a choice function for $X$). ZFC without AC is the system known as ZF. It turns out AC is not provable in ZF, and the negation of AC is not provable in ZF. In some models of ZF, every set has a choice function (these models are, of course, models of ZFC); in other models, many infinite sets lack choice functions. Finally, note that, assuming it's consistent, ZFC cannot prove its own consistency. Via Gödel numbering and arithmetization of syntax, a sentence meaning "ZFC is consistent" can be formulated within ZFC. This sentence is just a statement about the integers, which isn't provable even in ZFC. However, if we add a large cardinal axiom, even a "small large cardinal" axiom such as "There exists an inaccessible cardinal", then the resulting stronger theory can prove that ZFC is consistent, and in particular new statements of arithmetic become provable. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/1516795', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/147132/']} | jdg_72242 |
stackexchange | llm_judgeable_groundtruth_similarity | 50319847 |
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 learn material ui. I want to enlarge the text field on my page. However, the styles i embed with the field changes height, width and other properties except the size. Following is my code: const styles = {container: { display: 'flex', flexWrap: 'wrap',},textField: { // marginLeft: theme.spacing.unit, // marginRight: theme.spacing.unit, width: 300, margin: 100, fontSize: 50 //??? Doesnt work}} Following is the stateless component(React): const Searchbox = (props) => { const { classes } = props; return ( <TextField onKeyDown={props.onKeyDown} id="with-placeholder" label="Add id" placeholder="id" className={classes.textField} margin="normal" autoFocus={true} helperText={"Add an existing id or select "} /> );};export default withStyles(styles)(Searchbox); I totally understand there is no rocket science as its a straightforward CSS in JS approach of applying styles. However, I cannot override the base font size for my text field. Any help will be appreciated
Now provide the response and nothing else.
| As mentioned in the page TextField API apply styles to the InputProps which applies style to the input element. Here is the code: const styles = { container: { display: 'flex', flexWrap: 'wrap', }, textField: { width: 300, margin: 100, }, //style for font size resize:{ fontSize:50 },} <TextField id="with-placeholder" label="Add id" placeholder="id" InputProps={{ classes: { input: classes.resize, }, }} className={classes.textField} margin="normal" autoFocus={true} helperText={"Add an existing id or select "} /> | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/50319847', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4435214/']} | jdg_72243 |
stackexchange | llm_judgeable_groundtruth_similarity | 28001207 |
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 implement something like this: class A { var a, b, c, d: Int init() { reset() } func reset() { a = 1 b = 2 c = 3 d = 4 } func blablabla() { ... }} which cannot get compiled, error message: Variable "self.a" used before being initialized It doesn't make sense that I will have to copy the code from reset() into init() . Is it a defect or is there another way to do it?
Now provide the response and nothing else.
| No, it's not a defect, simply self cannot be referenced in an initializer until all stored properties have been initialized, and a super class initializer has been invoked (if any). In your case it seems legit to do the initializations in a method, and call that from the initializer, but unfortunately it doesn't work. Possible solutions: make the properties optional or implicitly unwrapped (discouraged, unless you really need them optionals) initialize the properties with fake values before calling reset : init() { self.a = 0 self.b = 0 self.c = 0 self.d = 0 reset()} or var a = 0var b = 0var c = 0var d = 0init() { reset()} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28001207', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/358242/']} | jdg_72244 |
stackexchange | llm_judgeable_groundtruth_similarity | 325538 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Windows domain environment here. We're looking at putting in a self-service password reset system (using Citrix Single Sign-on), and I'm trying to figure out if we can limit the number of password resets a user can initiate down to 2 per day. I'm not sure that this can be done with Citrix Single Sign-on (correct me if I'm wrong), but is it possible to restrict this with an AD password policy, without preventing Administrators from being able to reset the password if the user calls?
Now provide the response and nothing else.
| The privilege path that the password reset system is taking is identical to what happens when an administrator resets the password; the service account that the self service software is using will be assigned the same rights. It's a simple privilege against the user account, which overrides the password change rate-limiting restrictions in the password policy, as well as other aspects like password history restrictions. So, no, a limit on resets per day would unfortunately need to be implemented and enforced in the self service tool. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/325538', 'https://serverfault.com', 'https://serverfault.com/users/3150/']} | jdg_72245 |
stackexchange | llm_judgeable_groundtruth_similarity | 44574679 |
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 came across a problem with comparing the predictions of my model with the labels of training set. The arrays I'm using have shapes: Training set (200000, 28, 28) (200000,) Validation set (10000, 28, 28) (10000,) Test set (10000, 28, 28) (10000,) However, when checking the accuracy with the function: def accuracy(predictions, labels): return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) / predictions.shape[0]) It's giving me: C:\Users\Arslan\Anaconda3\lib\site-packages\ipykernel_launcher.py:5: DeprecationWarning: elementwise == comparison failed; this will raise an error in the future.""" And it gives the accuracy as 0% for all datasets. I think we cannot compare the arrays using '==' . How could I compare the arrays in the right way instead?
Now provide the response and nothing else.
| I assume the error occurs in this expression: np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1)) can you tell us something about the 2 arrays, predictions , labels ? The usual stuff - dtype, shape, some sample values. Maybe go the extra step and show the np.argmax(...) for each. In numpy you can compare arrays of the same size, but it has become pickier about comparing arrays that don't match in size: In [522]: np.arange(10)==np.arange(5,15)Out[522]: array([False, False, False, False, False, False, False, False, False, False], dtype=bool)In [523]: np.arange(10)==np.arange(5,14)/usr/local/bin/ipython3:1: DeprecationWarning: elementwise == comparison failed; this will raise an error in the future. #!/usr/bin/python3Out[523]: False | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44574679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8167812/']} | jdg_72246 |
stackexchange | llm_judgeable_groundtruth_similarity | 31839032 |
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 calculate the length of a range, but ideally without creating the range, (hopefully will be faster and use less memory. This is important, because this function will be called a lot). The length is used to set an extended slice. Right now I have tried: int_div = lambda n, d: (n + d // 2) // ddef range_len(start, stop, step): return int_div(stop - start, step) But on some cases, such as range_len(9, 100, 3) it gives 30 when the correct answer is 31. I feel like this should be simple, what am I doing wrong?
Now provide the response and nothing else.
| You can use this formula: (end - start - 1) // step + 1 def calc_length(start, end, step): return (end - start - 1) // step + 1for i in range(start, end): calculated = calc_length(start, i, step) empirical = len(range(start, i, step)) assert calculated == empirical, "{} {}".format(calculated, empirical) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31839032', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1498618/']} | jdg_72247 |
stackexchange | llm_judgeable_groundtruth_similarity | 319189 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
So I have written a Quaternion based 3D Camera oriented toward new programmers so it is ultra easy for them to integrate and begin using. While I was developing it, at first I would take user input as Euler angles, then generate a Quaternion based off of the input for that frame. I would then take the Camera's Quaternion and multiply it by the one we generated for the input, and in theory that should simply add the input rotation to the current state of the camera's rotation, and things would be all fat and happy. Lets call this: Accumulating Quaternions, because we are storing and adding Quaternions only. But I noticed that there was a problem with this method. The more I used it, even if I was only rotating on one Euler angle, say Yaw, it would, over some iterations, begin bleeding over into another, say Pitch. It was slight, but fairly unacceptable. So I did some more research and found an article stating it was better to accumulate Euler angles, so the camera stores it's current rotation as Euler angles, and input is simply added to them each frame. Then I generate a Quaternion from them each frame, which is in turn used to generate my rotation matrix. And this fixed the issue of rotation bleeding into improper axes. So do any Stackoverflow members have any insight into this problem? Is that a proper way of doing things?
Now provide the response and nothing else.
| Multiplying quaternions is going to suffer from accumulation of floating-point roundoff issues (even simple angles like 45 degrees won't be exact). It's a great way to composite rotations, but the precision of each of your quaternion components is going to drop-off over time. The bleed-through is one side-effect, a visually worse one though is your quaternion could start incorporating a scale factor - to recover that, you'd have to renormalize back to Euler angles in any case. A fixed-point Euler angle isn't going to accumulate roundoff. Recalculating the quaternion per-frame is minimal. I wouldn't bother trying to optimize it out. You could probably allow a few quaternions to accumulate before you renormalized to get the accuracy back, but it really isn't worth the effort. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/319189', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1366/']} | jdg_72248 |
stackexchange | llm_judgeable_groundtruth_similarity | 5119190 |
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 run a subquery in Oracle SQL and it will not let me order the subquery columns. Ordering the subquery is important as Oracle seems to choose at will which of the returned columns to return to the main query. select ps.id, ps.created_date, pst.last_updated, pst.from_state, pst.to_state, (select last_updated from mwcrm.process_state_transition subpst where subpst.last_updated > pst.last_updated and subpst.process_state = ps.id and rownum = 1) as next_response from mwcrm.process_state ps, mwcrm.process_state_transition pst where ps.created_date > sysdate - 1/24 and ps.id=pst.process_state order by ps.id asc Really should be: select ps.id, ps.created_date, pst.last_updated, pst.from_state, pst.to_state, (select last_updated from mwcrm.process_state_transition subpst where subpst.last_updated > pst.last_updated and subpst.process_state = ps.id and rownum = 1 order by subpst.last_updated asc) as next_response from mwcrm.process_state ps, mwcrm.process_state_transition pst where ps.created_date > sysdate - 1/24 and ps.id=pst.process_state order by ps.id asc
Now provide the response and nothing else.
| Actually "ordering" only makes sense on the outermost query -- if you order in a subquery, the outer query is permitted to scramble the results at will, so the subquery ordering does essentially nothing. It looks like you just want to get the minimum last_updated that is greater than pst.last_updated -- its easier when you look at it as the minimum (an aggregate), rather than a first row (which brings about other problems, like what if there are two rows tied for next_response?) Give this a shot. Fair warning, been a few years since I've had Oracle in front of me, and I'm not used to the subquery-as-a-column syntax; if this blows up I'll make a version with it in the from clause. select ps.id, ps.created_date, pst.last_updated, pst.from_state, pst.to_state, ( select min(last_updated) from mwcrm.process_state_transition subpst where subpst.last_updated > pst.last_updated and subpst.process_state = ps.id) as next_responsefrom <the rest> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5119190', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/568508/']} | jdg_72249 |
stackexchange | llm_judgeable_groundtruth_similarity | 2668618 |
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 created a simple window GUI in Glade 3.6.7 and I am trying to import it into Python. Every time I try to do so I get the following error: (queryrelevanceevaluation.py:8804): libglade-WARNING **: Expected <glade-interface>. Got <interface>.(queryrelevanceevaluation.py:8804): libglade-WARNING **: did not finish in PARSER_FINISH stateTraceback (most recent call last): File "queryrelevanceevaluation.py", line 17, in <module> app = QueryRelevanceEvaluationApp() File "queryrelevanceevaluation.py", line 10, in __init__ self.widgets = gtk.glade.XML(gladefile)RuntimeError: could not create GladeXML object My Python Code: #!/usr/bin/env pythonimport gtkimport gtk.gladeclass QueryRelevanceEvaluationApp:def __init__(self): gladefile = "foo.glade" self.widgets = gtk.glade.XML(gladefile) dic = {"on_buttonGenerate_clicked" : self.on_buttonGenerate_clicked} self.widgets.signal_autoconnect(dic)def on_buttonGenerate_clicked(self, widget): print "You clicked the button"app = QueryRelevanceEvaluationApp()gtk.main() And the foo.glade file: <?xml version="1.0"?><interface><requires lib="gtk+" version="2.16"/><!-- interface-naming-policy project-wide --><object class="GtkWindow" id="windowRelevanceEvaluation"><property name="visible">True</property><property name="title" translatable="yes">Query Result Relevance Evaluation</property><child> <object class="GtkVBox" id="vbox1"> <property name="visible">True</property> <property name="orientation">vertical</property> <child> <object class="GtkHBox" id="hbox2"> <property name="visible">True</property> <child> <object class="GtkLabel" id="labelQuery"> <property name="visible">True</property> <property name="label" translatable="yes">Query:</property> </object> <packing> <property name="expand">False</property> <property name="padding">4</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkEntry" id="entry1"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">●</property> </object> <packing> <property name="padding">4</property> <property name="position">1</property> </packing> </child> </object> <packing> <property name="position">0</property> </packing> </child> <child> <object class="GtkFrame" id="frameSource"> <property name="visible">True</property> <property name="label_xalign">0</property> <child> <object class="GtkAlignment" id="alignment1"> <property name="visible">True</property> <property name="left_padding">12</property> <child> <object class="GtkHButtonBox" id="hbuttonbox1"> <property name="visible">True</property> <child> <object class="GtkRadioButton" id="radiobuttonGoogle"> <property name="label" translatable="yes">Google</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkRadioButton" id="radiobuttonBing"> <property name="label" translatable="yes">Bing</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">1</property> </packing> </child> <child> <object class="GtkRadioButton" id="radiobuttonBoden"> <property name="label" translatable="yes">Boden</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">2</property> </packing> </child> <child> <object class="GtkRadioButton" id="radiobuttonCSV"> <property name="label" translatable="yes">CSV</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">False</property> <property name="active">True</property> <property name="draw_indicator">True</property> </object> <packing> <property name="expand">False</property> <property name="fill">False</property> <property name="position">3</property> </packing> </child> </object> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="labelFrameSource"> <property name="visible">True</property> <property name="label" translatable="yes"><b>Source</b></property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="position">1</property> </packing> </child> <child> <object class="GtkFrame" id="frame1"> <property name="visible">True</property> <property name="label_xalign">0</property> <child> <object class="GtkHBox" id="hbox3"> <property name="visible">True</property> <child> <object class="GtkLabel" id="labelResults"> <property name="visible">True</property> <property name="label" translatable="yes">Number Results:</property> </object> <packing> <property name="expand">False</property> <property name="position">0</property> </packing> </child> <child> <object class="GtkSpinButton" id="spinbuttonResults"> <property name="visible">True</property> <property name="can_focus">True</property> <property name="invisible_char">●</property> </object> <packing> <property name="padding">4</property> <property name="position">1</property> </packing> </child> </object> </child> <child type="label"> <object class="GtkLabel" id="labelFrameResults"> <property name="visible">True</property> <property name="label" translatable="yes"><b>Results</b></property> <property name="use_markup">True</property> </object> </child> </object> <packing> <property name="padding">2</property> <property name="position">2</property> </packing> </child> <child> <object class="GtkButton" id="buttonGenerateResults"> <property name="label" translatable="yes">Generate!</property> <property name="visible">True</property> <property name="can_focus">True</property> <property name="receives_default">True</property> </object> <packing> <property name="position">3</property> </packing> </child> </object></child></object></interface> foo.glade and the above python script are in the same directory, and I have tried using a fully-qualified path but still get the same error (I am certain that the path is correct!). Any ideas? Cheers, Pete
Now provide the response and nothing else.
| You have created a GtkBuilder file instead of Glade file. You can use GtkBuilder as follow: builder = gtk.Builder()builder.add_from_string(string, len(string))builder.connect_signals(anobject)builder.get_object(name) EDIT : When you start a new project in glade it asks you if you want create a glade file or a GtkBuilder file, which is new and more flexible.Try the builder file with the following code: #!/usr/bin/env pythonimport gtkclass QueryRelevanceEvaluationApp: def __init__(self): filename = "foo.glade" builder = gtk.Builder() builder.add_from_file(filename) builder.connect_signals(self) def on_buttonGenerate_clicked(self, widget): print "You clicked the button"app = QueryRelevanceEvaluationApp()gtk.main() EDIT2: Beware that i cannot see any handler in your GtkBuilder file | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2668618', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_72250 |
stackexchange | llm_judgeable_groundtruth_similarity | 12723 |
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:
From my understanding, a ring can form around a planet when a moon gets too close to its Roche limit, and gets ripped appart by the planet's gravity pull. That makes sense to me, but I don't understand why Saturn has both moons and rings at the same place. I know the F ring is supposedly created by Enceladus' rejections, but I don't get why Pandora and Prometheus are not ripped appart as well as the ancient objects that formed the ring they are in. I couldn't find specific explanations for this. Does it have any link to the moon's density?
Now provide the response and nothing else.
| You're right that density is the important thing here. The Roche limit is the distance from the main body $d$ such that$$d=1.26R_M\left(\frac{\rho_M}{\rho_m}\right)^{\frac{1}{3}}$$where $_M$ denotes the main body and $_m$ denotes the satellite. As you can see from the chart on the Wikipedia page, Pandora and Prometheus are both at least one and a half times the Roche limit from Saturn. Therefore, they're in no danger of being ripped apart any time soon. | {} | {'log_upvote_score': 4, 'links': ['https://astronomy.stackexchange.com/questions/12723', 'https://astronomy.stackexchange.com', 'https://astronomy.stackexchange.com/users/9679/']} | jdg_72251 |
stackexchange | llm_judgeable_groundtruth_similarity | 52355 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I use the PwdHash service ( http://crypto.stanford.edu/PwdHash/ ) and plugins for pretty much all of my passwords. I believe this is safer because: No service gets the same password as another, so if one account is comprised my other ones shouldn't be. The hashed passwords should be more secure than unique passwords I can realistically remember myself. However, I am concerned that I could be exposing myself to risk by having a master password that, if comprised, can be used to gain access to all my services via PwdHash. If an attacker has the hash, and knows that it was generated with PwdHash and knows the domain that it was generated for, how feasible would it be for them to determine the original password from that?
Now provide the response and nothing else.
| Having unique passwords entered to every site IS safer than giving each site the same password, for exactly the independent-compromise reason you suggested. If an attacker has the hash, and knows that it was generated with PwdHash and knows the domain that it was generated for, how feasible would it be for them to determine the original password from that? Well, let's do some investigation and some math! PwdHash appears to be using effectively GoofyStuff(Base64(HMAC-MD5())), so we're at the usual MD5(MD5()) guessing game speeds. Per oclHashcat , "PC5 (8x AMD R9 290Xstock core clock)" can crack ~81 Billion MD5's per second, so ~40 billion tries as PwdHash per second, which gives us the more practical 1E17 (somewhat over 2^56) tries per 30 days. I base the above on this snippet from a quick glance at the PwdHash page source: var hash = b64_hmac_md5(password, realm); This is in the range of an exhaustive keyspace search of 62^9 to 62^10 in those 30 days, where 62 is the keyspace of upper case, lower case, and numbers (or upper case, lower case, and the symbols above numbers, whichever you like), and 9 or 10 is the length. Thus, a fully random upper case, lower case, numeric password encoded with HMAC-MD5 will be found in less than about 30 days (unless you and the attacker are using different character sets (i.e. Cryllic vs. English)). You'll need something with a larger total keyspace than this for your master password, and that's if it's a truly random password! You don't even want to think about what a rules based dictionary attack can come up with at this speed, if your password is not, in fact, fully random. My most comprehensive wordlist set is over 40GB of unique passwords; if we assume an average word length of 9 plus a LF separator, that's 4E9 words, meaning that if an attacker with that PC spent 30 days on your password, they'd be able to try roughly 2.5E7, i.e. 25 million different variations (rules) for each password. Note that this wordlist is too slow and cumbersome to bother with... unless the target can be attacked at insane speeds, like a single HMAC-MD5 can. If you do use PwdHash with a master password, have a really, really good one - 15 character or better, cryptographically random, with a large character set (upper, lower, number, symbols above numbers, symbols not above numbers). Other considerations You should think about how you're going to change your master password after it leaks; perhaps you're up late and are trying to hurry and you type the master password into a web site directly instead of into PwdHash, just by habit, caffeine deprivation, hurry, and carelessness. Now you need to change it! Personally, I like offline password storage like KeePass , but I'd much rather use even basic OpenSSL than PwdHash - AS PATHETICALLY INSUFFICIENT AS IT IS, I'll put HMAC-SHA-512 up against HMAC-MD5 any day of the week. echo example.com2014 | openssl dgst -sha512 -hmac MyPassword -binary | openssl enc -base64 As always, you're better off using something truly random and storing it, or, if you insist on a deterministic generation routine, something really, really slow - particularly since this is just for you, so PBKDF2/BCrypt/Scrypt with enough iterations/work factor that takes even a second or two or five on your machine would be just fine, and would slow down an attacker to a crawl. Shameless plug: I'm working on collecting a variety of PBKDF2 (and hopefully later BCrypt and Scrypt) code examples at my Anti-weakpasswords github page , some of which compile so you can run them at the command line of Windows or Linux, and use them exactly the way you're using PwdHash now, but with a higher iteration count than almost any website could use, if you're willing to wait a couple seconds. As of today, there's only a Python version that Mitsuhiko wrote and Warner fixed for high iteration counts, not yet updated with better hashes, but that'll improve. | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/52355', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/39565/']} | jdg_72252 |
stackexchange | llm_judgeable_groundtruth_similarity | 34319 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's say I have the following logistic regression models: df=data.frame(income=c(5,5,3,3,6,5), won=c(0,0,1,1,1,0), age=c(18,18,23,50,19,39), home=c(0,0,1,0,0,1))> md1 = glm(factor(won) ~ income + age + home, + data=df, family=binomial(link="logit"))> md2 = glm(factor(won) ~ factor(income) + factor(age) + factor(home), + data=df, family=binomial(link="logit"))> summary(md1)Call:glm(formula = factor(won) ~ income + age + home, family = binomial(link = "logit"), data = df)Deviance Residuals: 1 2 3 4 5 6 -1.0845 -1.0845 0.8017 0.4901 1.7298 -0.8017 Coefficients: Estimate Std. Error z value Pr(>|z|)(Intercept) 4.784832 6.326264 0.756 0.449income -1.027049 1.056031 -0.973 0.331age 0.007102 0.097759 0.073 0.942home -0.896802 2.252894 -0.398 0.691(Dispersion parameter for binomial family taken to be 1) Null deviance: 8.3178 on 5 degrees of freedomResidual deviance: 6.8700 on 2 degrees of freedomAIC: 14.87Number of Fisher Scoring iterations: 4> summary(md2)Call:glm(formula = factor(won) ~ factor(income) + factor(age) + factor(home), family = binomial(link = "logit"), data = df)Deviance Residuals: 1 2 3 4 5 6 -6.547e-06 -6.547e-06 6.547e-06 6.547e-06 6.547e-06 -6.547e-06 Coefficients: (3 not defined because of singularities) Estimate Std. Error z value Pr(>|z|)(Intercept) 2.457e+01 1.310e+05 0 1factor(income)5 -4.913e+01 1.605e+05 0 1factor(income)6 -2.573e-30 1.853e+05 0 1factor(age)19 NA NA NA NAfactor(age)23 -1.383e-30 1.853e+05 0 1factor(age)39 -3.479e-14 1.605e+05 0 1factor(age)50 NA NA NA NAfactor(home)1 NA NA NA NA(Dispersion parameter for binomial family taken to be 1) Null deviance: 8.3178e+00 on 5 degrees of freedomResidual deviance: 2.5720e-10 on 1 degrees of freedomAIC: 10 So depending on the mode of the predictors, R produced different outputs. For factors, R splits out the coefficients into separate categories for the levels, but not for the model with numeric predictors. I'm wondering about a couple things. Is it ever useful to have the response categories expressed as individual rows? To express the general regression equation, how does one go from a model with the categories expressed in an individual equation to an equation with a single B_i. So, for example, if gender has two coefficients, 3.5 for Male and 2.3 for Female, how does one use that in an equation such that (besides converting them into numeric values): Y = B0 + B1 (Gender)
Now provide the response and nothing else.
| I don't entirely understand question 1. Are you asking when to use numeric versus factor values? Factor values should be used for categorical data (discrete units that are not in any specific order), numeric should be used for continuous, ratio, or (some) interval level data. In the equation above, age should be numeric, home (if dichotomous) won't matter if it is factor or not, and income would likely be factor (though you could make a reasonable interpretation with numeric if the factors are equally spaced and distributed). To know if you should be using factors, consider the following question: does a partial count (e.g. 0 < x < 1) make sense as a result? Treating non-numeric data as numeric is what gives us our famous 2.4 children. For question 2, if you have a sample that is limited to the two genders (e.g. all respondents are male or female) you'll shouldn't be able to get a coefficient for male and female from the equation. One of them will be the reference variable, meaning that it is represented as part of the constant. So, the effect of being male in your equation would be: y=bx(male) + BX(other covariates) + a(constant) + e. The result for male should be the effect of being male controlling for other covariates. If you take male out and put in female, the number should be of the same magnitude but in the other direction (assuming your model does not allow for any interaction between the covariates). c.f. http://www.ats.ucla.edu/stat/mult_pkg/whatstat/nominal_ordinal_interval.htm | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/34319', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/3310/']} | jdg_72253 |
stackexchange | llm_judgeable_groundtruth_similarity | 14346 |
Below is a question asked on the forum arduino.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have an Arduino Uno (a SainSmart model, actually) . I intend to power it with three 1.5V batteries. I measured them and they yield 4.67V in total. The Arduino requires 5V. The question is, if the arduino will work this way. I'm not powering complicated microcontroller components here. These components are used: A buzzer An LED A unit of 4 seven segment displays A couple of buttons as input elements If the volume or brightness of these components is slightly decreased, it doesn't matter at all. But I would like to know if it will work in the first place. And also... Where exactly do I plug the power source in? The power jack, the USB jack, pins, somewhere else? The schematic looks like this , just to illustrate it. I'm not a good drawer, but you'll get the idea...
Now provide the response and nothing else.
| The Arduino doesn't require 5V. The Atmel chip on the board requires somewhere between 1.8V and 5.5V, the Arduino just happens to have chosen 5V as a good common widely used voltage to run at. If you provide a voltage within that range to the +5V pin the board will operate. There's a couple of caveats though: Anything below about 4V will mean the 3.3V regulator won't be working right, so the 3.3V pin won't be functioning properly At lower voltages the Atmel chip can't operate reliably at higher frequencies, which is why 3.3V Arduino boards operate at 8MHz instead of 16Mhz. So 3 x AA batteries is a perfect power source for running the Arduino, direct into the 5V pin. Just make sure that you don't power it any other way at the same time or you'll be pumping 5V into your batteries. You may want to add a Schottky diode in series with your battery + (between battery + and the 5V pin) to stop that ever causing a problem. Choose one with a very low forward voltage drop though, otherwise you could end up dropping too much of your precious voltage over the diode. By the way, when you're powering it from USB the 5V could be anywhere between 4.75V and 5.25V. | {} | {'log_upvote_score': 5, 'links': ['https://arduino.stackexchange.com/questions/14346', 'https://arduino.stackexchange.com', 'https://arduino.stackexchange.com/users/8762/']} | jdg_72254 |
stackexchange | llm_judgeable_groundtruth_similarity | 12235110 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
we know that (A + B) % P = (A % P + B % P) % P(A * B) % P = (A % P * B % P) % P where P is a prime . I need to calculate (A / B) % P where A,B can be very large and can overflow . Does such kind of formula for modular arithmetic holds for (A / B) % P and (A - B) % P . If not then please explain what the correct answer is. I.e is it true that (A / B) % P = ((A % P) / (B % P)) % P ? I WAS TRYING TO CALULATE (N*(N^2+5)/6)%P where N can be as large as 10^15 here A=n*(n^2+5) can surely overflow for n=10^15
Now provide the response and nothing else.
| Yes, but it's different: (a - b) mod p = ((a mod p - b mod p) + p) mod p(a / b) mod p = ((a mod p) * (b^(-1) mod p)) mod p Where b^(-1) mod p is the modular inverse of b mod p . For p = prime , b^(-1) mod p = b^(p - 2) mod p . Edit: (N*(N^2+5)/6)%P You don't need any modular inverses from this. Just simplify the fraction: N or N^2+5 will be divisible by 2 and 3 . So divide them and then you have (a*b) mod P . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/12235110', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1488299/']} | jdg_72255 |
stackexchange | llm_judgeable_groundtruth_similarity | 58093386 |
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 still struggling to understand the difference between ASP.NET Core Hosted and Server-side Blazor. I know same question already exists , but it's not satisfying. In fact, I couldn't find the satisfying answer anywhere - the answers were more or less the same. If hosted option uses server (IIS, Kestrel), then why server-side ? Confusing... It's a shame that official documentation didn't shed the light either... UPDATE The confusion stems from the fact that we have THREE options to create Blazor application. After executing dotnew new --list I get: dotnet new blazorserver (Blazor Server App) dotnet blazorwasm (Blazor WebAssembly App) However, there's a third option: dotnet blazorwasm --hosted (or dotnet blazor --hosted ) It's the same as check box in Visual Studio when creating application: The documentation says: you have the option of configuring the app to use an ASP.NET Corebackend by selecting the ASP.NET Core hosted check box But no explanation was provided what does it mean...
Now provide the response and nothing else.
| Re this part of your question: However, there's a third option: dotnet blazorwasm --hosted (or dotnet blazor --hosted ) It's the same as check box in Visual Studio when creating application: The documentation says: you have the option of configuring the app to use an ASP.NET Corebackend by selecting the ASP.NET Core hosted check box But no explanation was provided what does it mean... TL;DR 'Hosted' is used where you want the back-end of your site and the Blazor client using that back-end to both be hosted on the same website. In Detail I agree, the documentation really isn't terribly clear about all of this, but the explanation is actually simpler than it seems: The Blazor app has to be 'hosted' somewhere The first thing to remember is that the Blazor WebAssembly 'app' is not a standalone website , it's an app that's embedded in a website. In a lot of cases it will behave like a website, because it will be used as a Single Page Application, but that is by no means required. Essentially the Blazor WebAssembly app is a series of files and a JavaScript file that are created by compiling/publishing your Blazor project. Those files then need to be put on a website somewhere and the combination of the name of a div tag and the Blazor JS file produced for your site deals with wiring your app files into the WebAssembly part of the browser so that it's then rendered on the page. The key here is that the website 'hosting' your Blazor app does not have to be an ASP.NET Core site . It could be any site, pure HTML, Drupal, whatever, it just needs to be shown on a browser that handles WebAssembly and JavaScript correctly. However, if you're also writing the backend of your site in ASP.NET Core, you can reuse that site So, your Blazor project doesn't have to be hosted in a website written in ASP.NET Core, but it does have to be hosted somewhere (so the user can see it). If you're also writing the back-end of the site at the same time, e.g. if you're writing an API or SignalR hub to send and receive data from your Blazor client, and if you're writing that back-end in ASP.NET Core, then you can reuse that same site to also host your Blazor client. This scenario is what the 'Hosted' option is for. If you create a project using the template in the screenshot above, with the 'hosted' option ticked, you'll see that the [YourProjectName].Server project that's created is the Start Up project, but the index.html page that's shown when you run that project has come from the [YourProjectName].Client project. This approach means you only have one site running on your server (which could be good or bad) and also means you won't run across any CORS issues . But you don't have to have an ASP.NET Core site at all If your Blazor site is a standalone site that doesn't read/write from any server, or if it only talks to 3rd party APIs or an existing Web API running on the older .NET Framework, then you don't actually need an ASP.NET Core site at all. In that case you don't use the 'hosted' option . Instead, you can simply publish your Blazor project and then take the files from the release folder and host them in any site. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/58093386', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3187033/']} | jdg_72256 |
stackexchange | llm_judgeable_groundtruth_similarity | 72397763 |
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 updated Springboot version to 2.7.0, and after return me errors: Description: An attempt was made to call a method that does not exist. The attempt was made from the following location: org.webjars.WebJarAssetLocator.scanForWebJars(WebJarAssetLocator.java:183)The following method did not exist: 'io.github.classgraph.ClassGraph io.github.classgraph.ClassGraph.acceptPaths(java.lang.String[])'The calling method's class, org.webjars.WebJarAssetLocator, was loaded from the following location: jar:file:/home/gabriel/.m2/repository/org/webjars/webjars-locator-core/0.50/webjars-locator-core-0.50.jar!/org/webjars/WebJarAssetLocator.classThe called method's class, io.github.classgraph.ClassGraph, is available from the following locations: jar:file:/home/gabriel/.m2/repository/io/github/classgraph/classgraph/4.8.69/classgraph-4.8.69.jar!/io/github/classgraph/ClassGraph.classThe called method's class hierarchy was loaded from the following locations: io.github.classgraph.ClassGraph: file:/home/gabriel/.m2/repository/io/github/classgraph/classgraph/4.8.69/classgraph-4.8.69.jarAction:Correct the classpath of your application so that it contains compatible versions of the classes org.webjars.WebJarAssetLocator and io.github.classgraph.ClassGraph This is my pom.xml <?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.0</version> <relativePath /> <!-- lookup parent from repository --> </parent> <groupId>re.brasuka</groupId> <artifactId>bra</artifactId> <version>0.0.1-SNAPSHOT</version> <name>gto</name> <description>Projeto do BRASUKA</description> <properties> <java.version>11</java.version> <spring-cloud.version>2021.0.3-SNAPSHOT</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> <dependency> <groupId>org.hibernate.validator</groupId> <artifactId>hibernate-validator</artifactId> </dependency> <!-- Lib para Serealizar e Desserealizar Json --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency> <!-- Lib para acesso a servidor SFTP--> <dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.55</version> </dependency> <!-- Lib para converte arquivo em objeto --> <dependency> <groupId>com.univocity</groupId> <artifactId>univocity-parsers</artifactId> <version>2.9.0</version> </dependency> <!-- Documentação --> <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-ui</artifactId> <version>1.4.8</version> </dependency> <!-- Registri e Gateway --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <!-- Client FTP --> <dependency> <groupId>commons-net</groupId> <artifactId>commons-net</artifactId> <version>3.6</version> </dependency> <!-- Criação de Json para retornos --> <dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20201115</version> </dependency> <!-- Para gerar PDF --> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.22</version> </dependency> <!-- Starter do Spring para envio de email --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>spring-snapshots</id> <name>Spring Snapshots</name> <url>https://repo.spring.io/snapshot</url> <releases> <enabled>false</enabled> </releases> </repository> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> <snapshots> <enabled>false</enabled> </snapshots> </repository> </repositories></project> Can i fix this?
Now provide the response and nothing else.
| There's an incompatibility in the transitive dependencies of org.springdoc:springdoc-openapi-ui . It depends on both org.webjars:webjars-core-locator and io.github.classgraph:classgraph but their versions are incompatible. Spring Boot's dependency management for webjars-core-locator uses version 0.50 . webjars-core-locator 0.50 would use classgraph 4.8.139 by default but, due to the way that Maven resolves version conflicts, it's being downgraded to 4.8.69 . You can fix the problem by restoring the use of 4.8.139 by adding some dependency management to your pom.xml alongside your existing import of spring-cloud-dependencies : <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>io.github.classgraph</groupId> <artifactId>classgraph</artifactId> <version>4.8.139</version> </dependency> </dependencies></dependencyManagement> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/72397763', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/16346287/']} | jdg_72257 |
stackexchange | llm_judgeable_groundtruth_similarity | 50530 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Find the lowest degree polynomial that satisfies the following constraints: i) $F(0)=0$ ii) $F(1)=0$ iii)The maximum of $F$ on the interval $(0,1)$ occurs at point $c$ iv) $F(x)$ is positive on the interval $(0,1)$ The answer seems to depend pretty strongly on $c$. It's not difficult to find solutions for all $c$, but the solutions are not minimal. It seems like the solution involves Chebyshev polynomials, but I'm not familiar with them. Can anyone recommended a link?
Now provide the response and nothing else.
| I'll plunge in here. Edit: I've now added a proof, using Brownian motion. (Earlier this was only justified heuristically) Further revised Jan 5, 2011, to correct typos/formatting and to promote material from comments. The $n$th Chebyshev $T$-polynomials $T_n(x) = \cos(n \arccos( x))$are the unique degree n polynomials that fold the interval$[-1,1]$ exactly over itself $n$ times, taking $1$ to $1$. When $n$ is even, $T_n(-1) = 1$ as well, so by an affine transformation you can make it satisfy the inequalities of the question:$$f_n(x) = 1 - T(2 x - 1) . $$ Here for example is the plot of $f_{10}$: alt text http://dl.dropbox.com/u/5390048/Chebyshev10.jpg This has a maximum at $c = \cos(\pi/10) / 2 = .975528...$, pretty close to 1.(If a strict maximum is desired, modify the polynomial by adding $\epsilon x$, and change by a linear transformation of the domain so that $f(1)=0$.) For odd degrees, you can restrict the Chebyshev polynomials to an interval from the first local maximum to 1, and renormalize in a similar way, to get the unique degree $n$ polynomial $V_n(x)$ that folds the unit interval exactly $n-1$ times over itself and has a double root at 0. One way to know the existence of such a polynomial is this:extend the map of the interval to itself to all of $\mathbb C$ in a way that it is an $n+1$-fold branched cover of $\mathbb C$ (not yet analytic) with the branching pattern corresponds to the desired critical points and critical values. Pull back the complex structure in the range via this map. Using the Riemann mapping theorem, it can be seen that the resulting complex 1-manifold is $\mathbb C$, so you get a polynomial map. By symmetry, the critical points all lie on a straight line, so it can be renormalized as a map from the interval to itself. (This is a special case of more general theories, including Shabat polynomials and dessins d'enfants, as well as the theory of postcritically finite rational maps). For odd degree $n$, I think $V_n$ probably gives the maximal $c$. Here's a heuristic argument: One can ask, whereare the critical points in $\mathbb C$ for a polynomial that satisfies the given constraints and maximizes $c$. Given the $n-1$ critical points $\{c_i\}$, the derivative of $f$ is up to a constant $\prod x-c_i$. To make the ratio large, we need the ratio of the mean value of the integrand in $[0,c]$ to be small compared to the mean value of - integrand in $[c,1]$:since the integrals add to 0, this ratio is the same as the ratio of arc length. This seems to say that the $c_i$'s want to be close to --- actually, inside--- the interval $[0,c]$. The best way to squeeze them in seems to be to make the interval fold as described. It's easy to relax from the extreme case. For example, in even degrees, just make an affine change to a larger interval $f_n^{-1}( [1-t, \infty], t \ge 0$; as $t \rightarrow \infty$, $c \rightarrow .5$. For the odd degree examples, add a linear function and renormalize in a similar way. This is reminiscent of the phenomenon of monotonicity in the theory of iterated real polynomials, but simpler to establish. Added: a proof, using Brownian Motion Proof that Chebyshev polynomials are optimal for even degrees There's a way to formulate the problem as a probability question. If you start a Brownian path from a point near infinity in the plane, it almost surely eventually hits the line segment $J = [0,1]$. The position of $c$ in this line segment is determined by the ratio of the probability that the path first hits $[0,c]$ vs $[c,1]$. (To get the exact function, you can map the complement of the line segment coformally to the complement of a circle; on a circle, hitting measure is proportional to arc length). Now suppose we have a degree $n$ polymomial $g$, as in the question, scaled so that $g(x)$ with $g([0,1]) = [0,1]$ and $g(0)=g(1) = 0$. As a complex polynomial, it defines a branched cover of $\mathbb C$ over $\mathbb C$. In 2 dimensions, conformal maps preserve the trajectories of Brownian motion: only the time parameter changes. Therefore, Brownian motion on the branched cover of the plane looks exactly like Brownian motion on the plane, but with the extra information of which of the $n$ sheets the trajectory is on at any given time. As the trajectory goes around the various critical values, the sheets are permuted. At any given time, if we just know the position of a Brownian path, the distribution on the sheets is uniform. Let's denote by $J$ the unit interval $[0,1]$ in the domain (upstairs in the branched cover) and $K$ the same interval $[0,1]$ in the range (downstairs).Thus, $J$ is a union of line segments on sheets above $K$, and furthermore, the two subintervals of $J$, $[0,c]$ and $[c,1]$, both map surjectively to $[0,1]$. Therefore, the first time the Brownian path downstairs crosses $[0,1]$, it has at least a $1/n$ probability of crossing the $[c,1]$ segment in the branched cover. For the even degree Chebyshev polynomial, as soon as it hits the segment $K$ downstairs it also hits $J$ upstairs, so the probability is exactly $1/n$: therefore, this is optimal. It is the unique optimal example for even degree, since if $g^{-1}(K) \ne J$, there would be a nonzero second chance for paths that hit $g^{-1}(K) \setminus J$ to continue on and still hit $[c,1]$. The figures below illustrate this. The top figure shows the 6th Chebyshev polynomial, renormalized as above to take $[0,1] \rightarrow [0,1]$. The red interval is $J$, the caterpillar's skin is the inverse image of the circumscribed circle about $K$; also depicted is the inverse image of $\mathbb R$. Brownian motion starting at infinity has an equal probability of arriving in any of the 12 sectors (which each opens out under the map to a halfplane), so the probability of arriving in the leftmost segment is exactly 1/6, with length $(1-\cos(\pi/6))/2 = .0669873\dots$. alt text http://dl.dropbox.com/u/5390048/Chebyshev6.jpg The next figure (below) shows a comparison polynomial (also graphed, futher down) with an order 5 zero at 0 and one other critical point at $c$, mapping with critical value $1$. The same data is shown. When a Brownian path starting from infinity first hits $K$ (downstairs), it has equal probability of hitting any of the 6 segments inside the various curves: one of the two red segments (in $J$), or the vein in one of the four leaves. In the 4/6 probability event that it does not hit $J$, when the Brownian path continues on it has some chance of hitting the top interval, so this probability is strictly greater than $1/6$. alt text http://dl.dropbox.com/u/5390048/MonobumpFlower.jpg Proof that Chebyshev polynomials are optimal for odd degree For the odd degree case, a little more is needed. Since the requirement of the question is that $g(0)=g(1)=0$, there are an even number of sheets above any point of $K$, so at least one sheet is absent in $J \setminus g^{-1}(K)$. Let's suppose first that $g^{-1}(K)$ is connected. In that case, we can use the Riemann mapping theorem to map its complement conformally to the exterior of a unit disk; there is a set of measure at least $2\pi/n$ that does not map to $J$. We can follow Brownian motion by letting it "reflect" whenever it hits this portion of the boundary of the unit disk, and continue on until it hits a part that corresponds to $J$. With this formulation, it's obvious that to minimize the probability that the continuing trajectory hits the sensitive area corresponding to $[c,1]$, we need to minimize its length and put it as far away from the sensitive area as possible. That's exactly what happens for $V_n$: on the circle the extra sheet is antipodal to the sensitive sheet. A similar argument applies to the disconnected case, although without quite as simple a visual representation. It's easy to establish that any optimal polynomial must have the maximal number of sheets above each point in $K$. The hitting probability for the senstive area for random walks starting at points $z$ is a harmonic function on $\mathbb C \setminus J$, with limit 1 along $[c,1]$ and 0 along $[0,c]$. This harmonic function has no critical points, so if there is a component of $g^{-1}(K)$ not attached to $J$, its mean on this component can be reduced by moving it toward 0, by moving the critical values not on the $K$ toward $0$. Below is a picture for the optimal solution for degree 5.There's a short tail to the caterpillar where the Brownian path gets a second chance, but its far away from the sensitive portion so it has only a small chance to next hit there rather than in $[0,c]$. The interval $[c,1]$ is comparatively short because it is exposed out at the end of the interval, but not as exposed so not as short as in the Chebyshev case. alt text http://dl.dropbox.com/u/5390048/Chebyshev5.jpg The Constants When $n$ is even, there is a solution for $c$ between $(1−\cos(\pi/n))/2$ and $(1+\cos(\pi/n)/2$. If $n$ is odd, there is a solution for $c$ between $(1−\cos(\pi/n))/(1+\cos(\pi/n))$ and $2 \cos(\pi/n)/(1+\cos(\pi/n))$. Numerically, the low values for $c$ are {2, 0.5}, {3, 0.333333}, {4, 0.146447}, {5, 0.105573}, {6,0.0669873}, {7, 0.0520951}, {8, 0.0380602}, {9, 0.0310912}, {10, 0.0244717} **End of added proof ** Polynomials with a unique local maximum For comparison, here are plots of degree $n$ polynomials functions (unique up to a constant) that have an $n-1$-fold root at 0, a critical point at $c$, and take value $0$ at 1.At first I guessed that these might give the optimal $c$, but for them, $c = 1-1/n$, much smaller than for the Chebyshev polynomials. The plots are for $n = 2, 3, \dots, 10$. alt text http://dl.dropbox.com/u/5390048/InterpolatingFunctions.jpg However, these polynomials answer a different question: given c, what is the minimum degree of a polynomial that is 0 at 0 and 1 and has a unique local maximum at c. These polynomials, also discussed by Wadim Zudilin, have that property. For such a polynomial, the same technique as above can be used. For any candidate polynomial f, a Brownian path starting at infinity has a probability of a probability of 1/n to hit the interval [0,c], 1/n probability to hit [1,c], and (n−2)/n to first hit elsewhere on f−1([0,1]). The same proof shows these examples are optimal | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/50530', 'https://mathoverflow.net', 'https://mathoverflow.net/users/4126/']} | jdg_72258 |
stackexchange | llm_judgeable_groundtruth_similarity | 606178 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Prove that if $|f(x)| \le |x|^\frac53$ for all $x$, then $f$ is differentiable at $x = 0$. I have no idea where to begin with this question, can someone help me out with this?
Now provide the response and nothing else.
| Your ideas are good, but your proof contains some errors. First of all we are talking about $x,y\in\mathbb{R}$ not $x,y\in\mathbb{Z}$. Fixing your errors, the proof would look something like this: Reflexive: $\forall x\in\mathbb{R}$, $x-x=0$ so $x\sim x$. Therefore $\sim$ is reflexive. Symmetric: For $x,y\in\mathbb{R}$, if $x\sim y$ then $x-y\in\mathbb{Z}$ so $x-y=k$ for some $k\in\mathbb{Z}$. Since $-k\in\mathbb{Z}$ it follows that $y-x\in\mathbb{Z}$ and so $y\sim x$. Therefore $\sim$ is symmetric. Transitive: For $x,y,z\in\mathbb{R}$, if $x\sim y$ and $y\sim z$ then $x-y\in\mathbb{Z}$ and $y-z\in\mathbb{Z}$. Since addition is closed in the integers $(x-y)+(y-z)=x-z\in\mathbb{Z}$ and so $x\sim z$. Therefore $\sim$ is transitive. To find the equivalence class of $\frac13$ you need to find all $x\in\mathbb{R}$ such that $\frac13-x\in\mathbb{Z}$ i.e. $$\frac13-x=k,k\in\mathbb{Z}$$Therefore $x=\frac13-k$ and so the equivalnce class of $\frac13$ is just $$\frac13+\mathbb{Z}=\{\dots,\frac13-1,\frac13,\frac13+1,\dots\}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/606178', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/97904/']} | jdg_72259 |
stackexchange | llm_judgeable_groundtruth_similarity | 14673063 |
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 array of files that i want to merge. This is what I tried but it did not work. public static void joinf(File f1, File f2){ try{ InputStream in = new FileInputStream(f1); OutputStream out = new FileOutputStream(f2,true); byte[] buf = new byte[8192]; int len; while ((len = in.read(buf)) > 0){ out.write(buf, 0, len); } in.close(); out.close(); System.out.println("File copied."); } catch(FileNotFoundException ex){ System.out.println(ex.getMessage() + " in the specified directory."); System.exit(0); } catch(IOException e){ System.out.println(e.getMessage()); }}public void pro(File a,File[]b){ for(int i=0;i<b.length;i++){ joinf(a,b[i]); }}
Now provide the response and nothing else.
| Use IOUtils to do this. See my example: import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import org.apache.commons.io.IOUtils;public class SourceCodeProgram { public static void main(String[] args) throws Exception { IOCopier.joinFiles(new File("D:/d.txt"), new File[] { new File("D:/s1.txt"), new File("D:/s2.txt") }); }}class IOCopier { public static void joinFiles(File destination, File[] sources) throws IOException { OutputStream output = null; try { output = createAppendableStream(destination); for (File source : sources) { appendFile(output, source); } } finally { IOUtils.closeQuietly(output); } } private static BufferedOutputStream createAppendableStream(File destination) throws FileNotFoundException { return new BufferedOutputStream(new FileOutputStream(destination, true)); } private static void appendFile(OutputStream output, File source) throws IOException { InputStream input = null; try { input = new BufferedInputStream(new FileInputStream(source)); IOUtils.copy(input, output); } finally { IOUtils.closeQuietly(input); } }} If you can't use IOUtils lib, then write your own implementation. Example: class IOUtils { private static final int BUFFER_SIZE = 1024 * 4; public static long copy(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[BUFFER_SIZE]; long count = 0; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } public static void closeQuietly(Closeable output) { try { if (output != null) { output.close(); } } catch (IOException ioe) { ioe.printStackTrace(); } }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14673063', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1781384/']} | jdg_72260 |
stackexchange | llm_judgeable_groundtruth_similarity | 4262240 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Whilst playing around in an open source project, my attempt to ToString a DateTime object was thwarted by the compiler. When I jumped to the definition, I saw this: public DateTime? timestamp; Might someone please enlighten me on what this is called and why it might be useful?
Now provide the response and nothing else.
| This is a nullable type . Nullable types allow value types (e.g. int s and structures like DateTime) to contain null. The ? is syntactic sugar for Nullable<DateTime> since it's used so often. To call ToString() : if (timstamp.HasValue) { // i.e. is not null return timestamp.Value.ToString();}else { return "<unknown>"; // Or do whatever else that makes sense in your context} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4262240', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/209866/']} | jdg_72261 |
stackexchange | llm_judgeable_groundtruth_similarity | 7754901 |
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 came across the editorial review of the book The Art of R Programming, and found this The Art of R Programming takes you on a guided tour of software development with R, from basic types and data structures to advanced topics like closures, recursion, and anonymous functions I immediately became fascinated by the idea of anonymous functions, something I had come across in Python in the form of lambda functions but could not make the connection in the R language. I searched in the R manual and found this Generally functions are assigned to symbols but they don't need to be. The value returned by the call to function is a function. If this is not given a name it is referred to as an anonymous function. Anonymous functions are most frequently used as arguments other functions such as the apply family or outer. These things for a not-very-long-time programmer like me are "quirky" in a very interesting sort of way.Where can I find more of these for R (without having to buy a book) ? Thank you for sharing your suggestions
Now provide the response and nothing else.
| Functions don't have names in R. Whether you happen to put a function into a variable or not is not a property of the function itself so there does not exist two sorts of functions: anonymous and named. The best we can do is to agree to call a function which has never been assigned to a variable anonymous. A function f can be regarded as a triple consisting of its formal arguments, its body and its environment accessible individually via formals(f) , body(f) and environment(f) . The name is not any part of that triple. See the function objects part of the language definition manual . Note that if we want a function to call itself then we can use Recall to avoid knowing whether or not the function was assigned to a variable. The alternative is that the function body must know that the function has been assigned to a particular variable and what the name of that variable is. That is, if the function is assigned to variable f , say, then the body can refer to f in order to call itself. Recall is limited to self-calling functions. If we have two functions which mutually call each other then a counterpart to Recall does not exist -- each function must name the other which means that each function must have been assigned to a variable and each function body must know the variable name that the other function was assigned to. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7754901', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/177390/']} | jdg_72262 |
stackexchange | llm_judgeable_groundtruth_similarity | 1438152 |
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 model looks like this (example): class Bank < ActiveRecord::Base has_and_belongs_to_many :currencies # other stuffend When I want to get some bank from database i do: bank = Bank.first :joins => :some_table, :conditions => { #some conditions } Now, is there any way to explicitly retrieve currencies from database for provided conditions and sort them in some order and store them in bank.currencies ? I'm doing something like this: bank.currencies.reject! { |c| c.value < something }bank.currencies.sort! { |x,y| x.value <=> y.value } It works but this way I retrieve all records and filter them by myself.I would like to have DBMS do it for me. This is just an example with banks and currencies. I have some big records and I think it is important just to retrieve those which interest me.
Now provide the response and nothing else.
| I had this exact same requirement. I had my own user and role schema and did not want to migrate to the asp.net membership schema but I did want to use the ASP.NET MVC action filters for checking authorization and roles. I had to do a fair amount of digging to find out exactly what needed to be done, but in the end it was relatively easy. I'll save you the trouble and tell you what I did. 1) I created a class that derived from System.Web.Security.MembershipProvider. MembershipProvider has a ton of abstract methods for all sorts of authentication-related functions like forgot password, change password, create new user, etc. All I wanted was the ability to authenticate against my own schema. So my class contained mainly empty overrides. I just overrode ValidateUser: public override bool ValidateUser(string username, string password){ if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password)) return false; string hash = EncryptPassword(password); User user = _repository.GetByUserName(username); if (user == null) return false; return user.Password == hash;} 2) I created a class that derived from System.Web.Security.RoleProvider. Again, I just had empty implementations for all the fluff I did not need like creating and changing roles. I just overrode two methods: public override string[] GetRolesForUser(string username){ User user = _repository.GetByUserName(username); string[] roles = new string[user.Role.Rights.Count + 1]; roles[0] = user.Role.Description; int idx = 0; foreach (Right right in user.Role.Rights) roles[++idx] = right.Description; return roles;}public override bool IsUserInRole(string username, string roleName){ User user = _repository.GetByUserName(username); if(user!=null) return user.IsInRole(roleName); else return false;} 3) Then I plugged these two classes into my web.config: <membership defaultProvider="FirstlookMemberProvider" userIsOnlineTimeWindow="15"> <providers> <clear/> <add name="FirstlookMemberProvider" type="FirstlookAdmin.DomainEntities.FirstlookMemberProvider, FirstlookAdmin" /> </providers></membership><roleManager defaultProvider="FirstlookRoleProvider" enabled="true" cacheRolesInCookie="true"> <providers> <clear/> <add name="FirstlookRoleProvider" type="FirstlookAdmin.DomainEntities.FirstlookRoleProvider, FirstlookAdmin" /> </providers></roleManager> That's it. The default authorization action filters will use these classes. You will still have to handle the login page sign in and sign off. Just use the standard forms authentication classes for this like you normally would. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1438152', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/173967/']} | jdg_72263 |
stackexchange | llm_judgeable_groundtruth_similarity | 51774654 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I can start a background process like this: >user@host ~ $ sleep 2m &>[1] 123456 The job number and pid [1] 123456 are displayed immediately after starting the background job. After starting the job, I can check its status using jobs -l . >user@host ~ $ jobs -l>[1] 123456 Running sleep 2m & I would like to see the full output of jobs -l when I start my background process like this: >user@host ~ $ sleep 2m &>[1] 123456 Running sleep 2m & I would also be happy with just the command, like this: >user@host ~ $ sleep 2m &>[1] 123456 sleep 2m & I have looked in man pages for some environment variable that controls what is displayed but haven't found it yet. Is this possible and if so, how can it be done?
Now provide the response and nothing else.
| First, let me show the timing statistics on my laptop. I use a 5000 x 5000 matrix which is sufficient for benchmarking, and microbenchmark package is used for 100 evaluations. Unit: milliseconds expr min lq mean median uq max colSums(x) 71.40671 71.64510 71.80394 71.72543 71.80773 75.07696 Cpp_colSums(x) 71.29413 71.42409 71.65525 71.48933 71.56241 77.53056 Sugar_colSums(x) 73.05281 73.19658 73.38979 73.25619 73.31406 76.93369 Arma_colSums(x) 39.08791 39.34789 39.57979 39.43080 39.60657 41.70158 rowSums(x) 177.33477 187.37805 187.57976 187.49469 187.73155 194.32120 Cpp_rowSums(x) 54.00498 54.37984 54.70358 54.49165 54.73224 64.16104 Sugar_rowSums(x) 54.17001 54.38420 54.73654 54.56275 54.75695 61.80466 Arma_rowSums(x) 49.54407 49.77677 50.13739 49.90375 50.06791 58.29755 C code in R core is not always better than what we can write ourselves. That Cpp_rowSums is faster than rowSums shows this. I don't feel myself competent to explain why R's version is slower than it should be. I will focuse on: how we can further optimize our own colSums and rowSums to beat Armadillo . Note that I write C, use R's old C interface and do compilation with R CMD SHLIB . Is there any substantial difference between colSums and rowSums ? If we have an n x n matrix that is much larger than the capacity of a CPU cache, colSums loads n x n data from RAM to cache, but rowSums loads as twice as many, i.e., 2 x n x n . Think about the resulting vector that holds the sum: how many times this length- n vector is loaded into cache from RAM? For colSums , it is loaded only once, but for rowSums , it is loaded n times. Each time you add a matrix column to it, it is loaded into cache but then evicted since it is too big. For a large n : colSums causes n x n + n data load from RAM to cache; rowSums causes n x n + n x n data load from RAM to cache. In other words, rowSums is in theory less memory efficient, and is likely to be slower. How to improve the performance of colSums ? Since the data flow between RAM and cache is readily optimal, the only improvement is loop unrolling. Unrolling the inner loop (the summation loop) by a depth of 2 is sufficient and we will see a 2x boost. Loop unrolling works as it enables CPU's instruction pipeline. If we just do one addition per iteration, no pipelining is possible; with two additions this instruction-level parallelism starts to work. We can also unroll the loop by a depth of 4, but my experience is that a depth-2 unrolling is sufficient to gain most of the benefit from loop unrolling. How to improve the performance of rowSums ? Optimization of data flow is the first step. We need to first do cache blocking to reduce the data transfer from 2 x n x n down to n x n . Chop this n x n matrix into a number of row chunks: each being 2040 x n (the last chunk may be smaller), then apply the ordinary rowSums chunk by chunk. For each chunk, the accumulator vector has length-2040, about half of what a 32KB CPU cache can hold. The other half is reversed for a matrix column added to this accumulator vector. In this way, the accumulator vector can be hold in the cache until all matrix columns in this chunk are processed. As a result, the accumulator vector is only loaded into cache once, hence the overall memory performance is as good as that for colSums . Now we can further apply loop unrolling for the rowSums in each chunk. Unroll both the outer loop and inner loop by a depth of 2, we will see a boost. Once the outer loop is unrolled, the chunk size should be reduced to 1360, as now we need space in the cache to hold three length-1360 vectors per outer loop iteration. C code: Let's beat Armadillo Writing code with loop unrolling can be a nasty job as we now need to write several different versions for a function. For colSums , we need two versions: colSums_1x1 : both inner and outer loops are unrolled with depth 1, i.e., this is a version without loop unrolling; colSums_2x1 : no outer loop unrolling, while inner loop is unrolled with depth 2. For rowSums we can have up to four versions, rowSums_sxt , where s = 1 or 2 is the unrolling depth for inner loop and t = 1 or 2 is the unrolling depth for outer loop. Code writing can be very tedious if we write each version one by one. After many years or frustration on this I developed an "automatic code / version generation" trick using inlined template functions and macros. #include <stdlib.h>#include <Rinternals.h>static inline void colSums_template_sx1 (size_t s, double *A, size_t LDA, size_t nr, size_t nc, double *sum) { size_t nrc = nr % s, i; double *A_end = A + LDA * nc, a0, a1; for (; A < A_end; A += LDA) { a0 = 0.0; a1 = 0.0; // accumulator register variables if (nrc > 0) a0 = A[0]; // is there a "fractional loop"? for (i = nrc; i < nr; i += s) { // main loop of depth-s a0 += A[i]; // 1st iteration if (s > 1) a1 += A[i + 1]; // 2nd iteration } if (s > 1) a0 += a1; // combine two accumulators *sum++ = a0; // write-back } }#define macro_define_colSums(s, colSums_sx1) \SEXP colSums_sx1 (SEXP matA) { \ double *A = REAL(matA); \ size_t nrow_A = (size_t)nrows(matA); \ size_t ncol_A = (size_t)ncols(matA); \ SEXP result = PROTECT(allocVector(REALSXP, ncols(matA))); \ double *sum = REAL(result); \ colSums_template_sx1(s, A, nrow_A, nrow_A, ncol_A, sum); \ UNPROTECT(1); \ return result; \ }macro_define_colSums(1, colSums_1x1)macro_define_colSums(2, colSums_2x1) The template function computes (in R-syntax) sum <- colSums(A[1:nr, 1:nc]) for a matrix A with LDA (leading dimension of A) rows. The parameter s is a version control on inner loop unrolling. The template function looks horrible at first glance as it contains many if . However, it is declared static inline . If it is called by passing in known constant 1 or 2 to s , an optimizing compiler is able to evaluate those if at compile-time, eliminate unreachable code and drop "set-but-not-used" variables (registers variables that are initialized, modified but not written back to RAM). The macro is used for function declaration. Accepting a constant s and a function name, it generates a function with desired loop unrolling version. The following is for rowSums . static inline void rowSums_template_sxt (size_t s, size_t t, double *A, size_t LDA, size_t nr, size_t nc, double *sum) { size_t ncr = nc % t, nrr = nr % s, i; double *A_end = A + LDA * nc, *B; double a0, a1; for (i = 0; i < nr; i++) sum[i] = 0.0; // necessary initialization if (ncr > 0) { // is there a "fractional loop" for the outer loop? if (nrr > 0) sum[0] += A[0]; // is there a "fractional loop" for the inner loop? for (i = nrr; i < nr; i += s) { // main inner loop with depth-s sum[i] += A[i]; if (s > 1) sum[i + 1] += A[i + 1]; } A += LDA; } for (; A < A_end; A += t * LDA) { // main outer loop with depth-t if (t > 1) B = A + LDA; if (nrr > 0) { // is there a "fractional loop" for the inner loop? a0 = A[0]; if (t > 1) a0 += A[LDA]; sum[0] += a0; } for(i = nrr; i < nr; i += s) { // main inner loop with depth-s a0 = A[i]; if (t > 1) a0 += B[i]; sum[i] += a0; if (s > 1) { a1 = A[i + 1]; if (t > 1) a1 += B[i + 1]; sum[i + 1] += a1; } } } }#define macro_define_rowSums(s, t, rowSums_sxt) \SEXP rowSums_sxt (SEXP matA, SEXP chunk_size) { \ double *A = REAL(matA); \ size_t nrow_A = (size_t)nrows(matA); \ size_t ncol_A = (size_t)ncols(matA); \ SEXP result = PROTECT(allocVector(REALSXP, nrows(matA))); \ double *sum = REAL(result); \ size_t block_size = (size_t)asInteger(chunk_size); \ size_t i, block_size_i; \ if (block_size > nrow_A) block_size = nrow_A; \ for (i = 0; i < nrow_A; i += block_size_i) { \ block_size_i = nrow_A - i; if (block_size_i > block_size) block_size_i = block_size; \ rowSums_template_sxt(s, t, A, nrow_A, block_size_i, ncol_A, sum); \ A += block_size_i; sum += block_size_i; \ } \ UNPROTECT(1); \ return result; \ }macro_define_rowSums(1, 1, rowSums_1x1)macro_define_rowSums(1, 2, rowSums_1x2)macro_define_rowSums(2, 1, rowSums_2x1)macro_define_rowSums(2, 2, rowSums_2x2) Note that the template function now accepts s and t , and the function to be defined by the macro has applied row chunking. Even though I've left some comments along the code, the code is probably still not easy to follow, but I can't take more time to explain in greater details. To use them, copy and paste them into a C file called "matSums.c" and compile it with R CMD SHLIB -c matSums.c . For the R side, define the following functions in "matSums.R". colSums_zheyuan <- function (A, s) { dyn.load("matSums.so") if (s == 1) result <- .Call("colSums_1x1", A) if (s == 2) result <- .Call("colSums_2x1", A) dyn.unload("matSums.so") result }rowSums_zheyuan <- function (A, chunk.size, s, t) { dyn.load("matSums.so") if (s == 1 && t == 1) result <- .Call("rowSums_1x1", A, as.integer(chunk.size)) if (s == 2 && t == 1) result <- .Call("rowSums_2x1", A, as.integer(chunk.size)) if (s == 1 && t == 2) result <- .Call("rowSums_1x2", A, as.integer(chunk.size)) if (s == 2 && t == 2) result <- .Call("rowSums_2x2", A, as.integer(chunk.size)) dyn.unload("matSums.so") result } Now let's have a benchmark, again with a 5000 x 5000 matrix. A <- matrix(0, 5000, 5000)library(microbenchmark)source("matSums.R")microbenchmark("col0" = colSums(A), "col1" = colSums_zheyuan(A, 1), "col2" = colSums_zheyuan(A, 2), "row0" = rowSums(A), "row1" = rowSums_zheyuan(A, nrow(A), 1, 1), "row2" = rowSums_zheyuan(A, 2040, 1, 1), "row3" = rowSums_zheyuan(A, 1360, 1, 2), "row4" = rowSums_zheyuan(A, 1360, 2, 2)) On my laptop I get: Unit: milliseconds expr min lq mean median uq max neval col0 65.33908 71.67229 71.87273 71.80829 71.89444 111.84177 100 col1 67.16655 71.84840 72.01871 71.94065 72.05975 77.84291 100 col2 35.05374 38.98260 39.33618 39.09121 39.17615 53.52847 100 row0 159.48096 187.44225 185.53748 187.53091 187.67592 202.84827 100 row1 49.65853 54.78769 54.78313 54.92278 55.08600 60.27789 100 row2 49.42403 54.56469 55.00518 54.74746 55.06866 60.31065 100 row3 37.43314 41.57365 41.58784 41.68814 41.81774 47.12690 100 row4 34.73295 37.20092 38.51019 37.30809 37.44097 99.28327 100 Note how loop unrolling speeds up both colSums and rowSums . And with full optimization ("col2" and "row4"), we beat Armadillo (see the timing table at the beginning of this answer). The row chunking strategy does not clearly yield benefit in this case. Let's try a matrix with millions of rows. A <- matrix(0, 1e+7, 20)microbenchmark("row1" = rowSums_zheyuan(A, nrow(A), 1, 1), "row2" = rowSums_zheyuan(A, 2040, 1, 1), "row3" = rowSums_zheyuan(A, 1360, 1, 2), "row4" = rowSums_zheyuan(A, 1360, 2, 2)) I get Unit: milliseconds expr min lq mean median uq max neval row1 604.7202 607.0256 617.1687 607.8580 609.1728 720.1790 100 row2 514.7488 515.9874 528.9795 516.5193 521.4870 636.0051 100 row3 412.1884 413.8688 421.0790 414.8640 419.0537 525.7852 100 row4 377.7918 379.1052 390.4230 379.9344 386.4379 476.9614 100 In this case we observe the gains from cache blocking. Final thoughts Basically this answer has addressed all the issues, except for the following: why R's rowSums is less efficient than it should be. why without any optimization, rowSums ("row1") is faster than colSums ("col1"). Again, I cannot explain the first and actually I don't care that since we can easily write a version that is faster than R's built-in version. The 2nd is definitely worth pursuing. I copy in my comments in our discussion room for a record. This issue is down to this: "why adding up a single vector is slower than adding two vectors element-wise?" I see similar phenomenon from time to time. The first time I encountered this strange behavior was when I, a few years ago, coded my own matrix-matrix multiplication. I found that DAXPY is faster than DDOT. DAXPY does this: y += a * x , where x and y are vectors and a is a scalar; DDOT does this: a += x * y . Given than DDOT is a reduction operation I expect that it is faster than DAXPY. But no, DAXPY is faster. However, as soon as I unroll the loop in the triple loop-nest of the matrix-multiplication, DDOT is much faster than DAXPY. A very similar thing happens to your issue. A reduction operation: a = x[1] + x[2] + ... + x[n] is slower than element-wise add: y[i] += x[i] . But once loop unrolling is done, the advantage of the latter is lost. I am not sure whether the following explanation is true as I have no evidence. The reduction operation has a dependency chain so the computation is strictly serial; on the other hand, element-wise operation has no dependency chain, so that CPU may do better with it. As soon as we unroll the loop, each iteration has more arithmetics to do and CPU can do pipelining in both cases. The true advantage of the reduction operation can then be observed. In reply to Jaap on using rowSums2 and colSums2 from matrixStats Still using the 5000 x 5000 example above. A <- matrix(0, 5000, 5000)library(microbenchmark)source("matSums.R")library(matrixStats) ## NEWmicrobenchmark("col0" = base::colSums(A), "col*" = matrixStats::colSums2(A), ## NEW "col1" = colSums_zheyuan(A, 1), "col2" = colSums_zheyuan(A, 2), "row0" = base::rowSums(A), "row*" = matrixStats::rowSums2(A), ## NEW "row1" = rowSums_zheyuan(A, nrow(A), 1, 1), "row2" = rowSums_zheyuan(A, 2040, 1, 1), "row3" = rowSums_zheyuan(A, 1360, 1, 2), "row4" = rowSums_zheyuan(A, 1360, 2, 2))Unit: milliseconds expr min lq mean median uq max neval col0 71.53841 71.72628 72.13527 71.81793 71.90575 78.39645 100 col* 75.60527 75.87255 76.30752 75.98990 76.18090 87.07599 100 col1 71.67098 71.86180 72.06846 71.93872 72.03739 77.87816 100 col2 38.88565 39.03980 39.57232 39.08045 39.16790 51.39561 100 row0 187.44744 187.58121 188.98930 187.67168 187.86314 206.37662 100 row* 158.08639 158.26528 159.01561 158.34864 158.62187 174.05457 100 row1 54.62389 54.81724 54.97211 54.92394 55.04690 56.33462 100 row2 54.15409 54.44208 54.78769 54.59162 54.76073 60.92176 100 row3 41.43393 41.63886 42.57511 41.73538 41.81844 111.94846 100 row4 37.07175 37.25258 37.45033 37.34456 37.47387 43.14157 100 I don't see performance advantage of rowSums2 and colSums2 . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51774654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8935182/']} | jdg_72264 |
stackexchange | llm_judgeable_groundtruth_similarity | 2492123 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What are good questions to determine if applicant is really a pro JavaScript (browser side) developer ? Questions that can distinguish if someone is not an ad-hoc JavaScript programmer, but is really doing professional JavaScript development, object-oriented, reusable, and maintainable. Please provide answers , so an intermediate and ad-hoc JavaScript programmers can interview someone more experienced, coming up with answers to quite few of those advanced questions will elude me. Please avoid open questions . Please keep one interview question/answer per SO answer for better reading experience and easier interview preparation.
Now provide the response and nothing else.
| Because JavaScript is such a small language, yet with incredible complexity, you should be able to ask relatively basic questions and find out if they are really that good based on their answers. For instance, my standard first question to gauge the rest of the interview is: In JavaScript, what is the difference between var x = 1 and x = 1 ? Answer in as much or as little detail as you feel comfortable. Novice JS programmers might have a basic answer about locals vs globals. Intermediate JS guys should definitely have that answer, and should probably mention function-level scope. Anyone calling themselves an "advanced" JS programmer should be prepared to talk about locals, implied globals, the window object, function-scope, declaration hoisting, and scope chains. Furthermore, I'd love to hear about [[DontDelete]] , hoisting precedence (parameters vs var vs function ), and undefined . Another good question is to ask them to write a sum() function that accepts any number of arguments, and returns their sum. Then, ask them to use that function (without modification) to sum all the values in an array. They should write a function that looks like this: function sum() { var i, l, result = 0; for (i = 0, l = arguments.length; i < l; i++) { result += arguments[i]; } return result;}sum(1,2,3); // 6 And they should invoke it on your array like this (context for apply can be whatever, I usually use null in that case): var data = [1,2,3];sum.apply(null, data); // 6 If they've got those answers, they probably know their JavaScript. You should then proceed to asking them about non-JS specific stuff like testing, workflows, version control, etc. to find out if they're a good programmer . | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2492123', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/260480/']} | jdg_72265 |
stackexchange | llm_judgeable_groundtruth_similarity | 8541 |
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been trying to get my hands on a substantial resource for using Gibbs sampling in hybrid Bayesian networks, that is, networks with both continuous and discrete variables. So far I can't say I have succeeded. I'm interested in hybrid networks where there are no constraints regarding discrete children having continuous parents.Gibbs sampling is a very widely employed method in approximate inference in Bayesian methods, and yet, I can't seem to find detailed resources that focus on hybrid networks
Now provide the response and nothing else.
| Short answer: Gibbs or Metropolis-Hastings-within-Gibbs (MCMC) should work just fine on joint distributions and full conditional distributions that are mixed products of pmfs and pdfs. If you're doing MCMC, just make sure that sampling from the candidate distributions gives you values in the right domain. Long answer: The most comprehensive way we know of to account for probability is to use measure theory. In measure-theoretic probability theory, there is little difference between pmfs and pdfs. In measure-theoretic probability, pmfs and pdfs are both called "densities." More precisely, they are both Radon-Nikodym (pronounced "RahDOHN-NickohDEEM") derivatives. The only difference is that a pmf is a derivative with respect to a counting measure, and a pdf is a derivative with respect to Lebesgue ("LehBAYG") measure (i.e. n-dimensional volume). When you integrate under a pmf, you integrate with respect to counting measure: you sum over part of its domain. When you integrate under a pdf, you integrate with respect to Lebesgue measure. In every case that Bayesians tend to care about, the latter is equivalent to regular old Riemann integration. Because pmfs and pdfs are the same kind of thing, they obey the same laws, such as Bayes' law and the product rule. Thus, you can use both pmfs and pdfs in a model and get a meaningful joint density and meaningful conditional densities. But these densities won't necessarily be pdfs or pmfs. In general, they will be Radon-Nikodym derivatives with respect to products of counting and Lebesgue measures. Riemann integration can't handle Radon-Nikodym derivatives with respect to mixed spaces like that, but Lebesgue integration can. Sampling methods approximately carry out Lebesgue integration, so they just work. You might be wondering, then, what doesn't just work. Well, the only thing I've mentioned so far are products of densities and integrating under those products. A random variable with a distribution that is the sum of a distribution with a pmf and a distribution with a pdf can cause problems. Any easy way to get a sum like that is to use an "if." For example, say you have this model: $X \sim \mathrm{Normal}(0,1)$ $Y \sim \mathrm{Geometric}(1/2)$ $B \sim \mathrm{Bernoulli}(1/2)$ and you define a new random variable $Z$ by $Z = X$ if $B = 0$, otherwise $Z = Y$. The distribution of $Z$ can't be represented by a pmf or a pdf: its cdf has a discontinuity at each positive integer. You can still approximate $Z$'s distribution using samples. You can even use $Z$ as a parameter for another random variable's distribution, and answer conditional queries with a Gibbs sampler. But conditioning on $Z$ in a query will not work without measure-theoretic tools. Also, you might find your current tools, like the density version of Bayes' law, inadequate. (I haven't looked into it enough to say when.) Another easy way to get a non-pmf/non-pdf distribution is to truncate a random variable; something like $W = X$ if $X \le 0$, otherwise $W = 0$. (Note that truncating $X$'s distribution won't give you $W$'s, because $P[W=0] = 1/2$. Truncated distributions and truncated random variables are very different things.) $W$ would give you the same problems as $Z$. Other things off the cuff: You might have a hard time getting good n-dimensional KDEs that have discrete axes, if you want them. If you're doing Metropolis-Hastings, you might have a hard time coming up with candidate pmfs for categorical random variables. -- If you want another way to think about it, consider what would happen if you transformed your model. Convert your pmfs into pdfs and floor the corresponding discrete random variables before using them as parameters in other random variables' distributions. The joint distribution that includes the un-floored random variables (but not the floored ones) obviously has a pdf. The easiest way to get an equivalent model is to define each new pdf $d$ so that, if its corresponding pmf is $m$, $d(x) = m(\lfloor x \rfloor)$. Now suppose you created an MCMC sampler from the transformed model. It shouldn't take too long to convince yourself that the fractional part of a candidate sample for any originally discrete random variable contributes nothing to the accept/reject decision. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/8541', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/3280/']} | jdg_72266 |
stackexchange | llm_judgeable_groundtruth_similarity | 35032424 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
As illustrated, what I need to achieve is when swiping left, a button with an image shows up, the blue one, and when swiping right the green button shows up, how to do this? i use swift and xcode 6.4 This is what i tried before asking, I was able to show two options with text in the right of a cell, but i don't want that, what is needed is in the illustration, and as said, the buttons need to be images not text.
Now provide the response and nothing else.
| You can subclass UITableViewCell to incorporate a UIPanGestureRecognizer that manipulates the cell's contentView s frame and add your buttons behind the contentView . To see how this can work it detail, I added example code on how to do that below for reference. This also adds a tap gesture recognizer to 'close' the action on tap instead of selecting the cell. Also, as requested in the comments, here is a gif of how this works (showing the colors of the buttons on the side as an indication of action, but you can easily modify the contentView 's frame to be completely overlapping the buttons in your subclass.) //// MWSwipeableTableViewCell.swift// MW UI Toolkit//// Created by Jan Greve on 02.12.14.// Copyright (c) 2014 Markenwerk GmbH. All rights reserved.//import UIKitprotocol MWSwipeableTableViewCellDelegate : NSObjectProtocol { func swipeableTableViewCellDidRecognizeSwipe(cell : MWSwipeableTableViewCell) func swipeableTableViewCellDidTapLeftButton(cell : MWSwipeableTableViewCell) func swipeableTableViewCellDidTapRightButton(cell : MWSwipeableTableViewCell)}class MWSwipeableTableViewCell: UITableViewCell { weak var delegate : MWSwipeableTableViewCellDelegate? var animationOptions : UIViewAnimationOptions = [.AllowUserInteraction, .BeginFromCurrentState] var animationDuration : NSTimeInterval = 0.5 var animationDelay : NSTimeInterval = 0 var animationSpingDamping : CGFloat = 0.5 var animationInitialVelocity : CGFloat = 1 private weak var leftWidthConstraint : NSLayoutConstraint! private weak var rightWidthConstraint : NSLayoutConstraint! var buttonWidth :CGFloat = 80 { didSet(val) { if let r = self.rightWidthConstraint { r.constant = self.buttonWidth } if let l = self.leftWidthConstraint { l.constant = self.buttonWidth } } } private weak var panRecognizer : UIPanGestureRecognizer! private weak var buttonCancelTap : UITapGestureRecognizer! private var beginPoint : CGPoint = CGPointZero weak var rightButton : UIButton! { willSet(val) { if let r = self.rightButton { r.removeFromSuperview() } if let b = val { self.addSubview(b) b.addTarget(self, action: "didTapButton:", forControlEvents: .TouchUpInside) b.translatesAutoresizingMaskIntoConstraints = false self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(0)-[v]-(0)-|", options: [], metrics: nil, views: ["v":b])) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("[v]-(0)-|", options: [], metrics: nil, views: ["v":b])) let wc = NSLayoutConstraint(item: b, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: self.buttonWidth) b.addConstraint(wc) self.rightWidthConstraint = wc self.sendSubviewToBack(b) } } } weak var leftButton : UIButton! { willSet(val) { if let l = self.leftButton { l.removeFromSuperview() } if let b = val { self.addSubview(b) b.addTarget(self, action: "didTapButton:", forControlEvents: .TouchUpInside) b.translatesAutoresizingMaskIntoConstraints = false self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-(0)-[v]-(0)-|", options: [], metrics: nil, views: ["v":b])) self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-(0)-[v]", options: [], metrics: nil, views: ["v":b])) let wc = NSLayoutConstraint(item: b, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: self.buttonWidth) b.addConstraint(wc) self.leftWidthConstraint = wc self.sendSubviewToBack(b) } } } override func awakeFromNib() { super.awakeFromNib() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) commonInit() } private func commonInit() { let pan = UIPanGestureRecognizer(target: self, action: "didPan:") pan.delegate = self self.addGestureRecognizer(pan) self.panRecognizer = pan let tap = UITapGestureRecognizer(target: self, action: "didTap:") tap.delegate = self self.addGestureRecognizer(tap) self.buttonCancelTap = tap self.contentView.backgroundColor = UIColor.clearColor() } override func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { if let tap = gestureRecognizer as? UITapGestureRecognizer { if tap == self.buttonCancelTap { return self.contentView.frame.origin.x != 0 } else { return super.gestureRecognizerShouldBegin(gestureRecognizer) } } else if let pan = gestureRecognizer as? UIPanGestureRecognizer { let trans = pan.translationInView(self) if abs(trans.x) > abs(trans.y) { return true } else if self.contentView.frame.origin.x != 0 { return true } else { return false } } else { return super.gestureRecognizerShouldBegin(gestureRecognizer) } } func didTap(sender : UITapGestureRecognizer) { UIView.animateWithDuration(self.animationDuration, delay: self.animationDelay, usingSpringWithDamping: self.animationSpingDamping, initialSpringVelocity: self.animationInitialVelocity, options: self.animationOptions, animations: { () -> Void in self.contentView.frame.origin.x = 0 }, completion: nil) } func didPan(sender: UIPanGestureRecognizer) { switch sender.state { case .Began: self.delegate?.swipeableTableViewCellDidRecognizeSwipe(self) self.beginPoint = sender.locationInView(self) self.beginPoint.x -= self.contentView.frame.origin.x case .Changed: let now = sender.locationInView(self) let distX = now.x - self.beginPoint.x if distX <= 0 { let d = max(distX,-(self.contentView.frame.size.width-self.buttonWidth)) if d > -self.buttonWidth*2 || self.rightButton != nil || self.contentView.frame.origin.x > 0 { self.contentView.frame.origin.x = d } else { sender.enabled = false sender.enabled = true } } else { let d = min(distX,self.contentView.frame.size.width-self.buttonWidth) if d < self.buttonWidth*2 || self.leftButton != nil || self.contentView.frame.origin.x < 0 { self.contentView.frame.origin.x = d } else { sender.enabled = false sender.enabled = true } } default: delegate?.swipeableTableViewCellDidRecognizeSwipe(self) let offset = self.contentView.frame.origin.x if offset > self.buttonWidth && self.leftButton != nil { UIView.animateWithDuration(self.animationDuration, delay: self.animationDelay, usingSpringWithDamping: self.animationSpingDamping, initialSpringVelocity: self.animationInitialVelocity, options: self.animationOptions, animations: { () -> Void in self.contentView.frame.origin.x = self.buttonWidth }, completion: nil) } else if -offset > self.buttonWidth && self.rightButton != nil { UIView.animateWithDuration(self.animationDuration, delay: self.animationDelay, usingSpringWithDamping: self.animationSpingDamping, initialSpringVelocity: self.animationInitialVelocity, options: self.animationOptions, animations: { () -> Void in self.contentView.frame.origin.x = -self.buttonWidth }, completion: nil) } else { UIView.animateWithDuration(self.animationDuration, delay: self.animationDelay, usingSpringWithDamping: self.animationSpingDamping, initialSpringVelocity: self.animationInitialVelocity, options: self.animationOptions, animations: { () -> Void in self.contentView.frame.origin.x = 0 }, completion: nil) } } } func closeButtonsIfShown(animated:Bool = true) -> Bool { if self.contentView.frame.origin.x != 0 { if animated { UIView.animateWithDuration(self.animationDuration, delay: self.animationDelay, usingSpringWithDamping: self.animationSpingDamping, initialSpringVelocity: self.animationInitialVelocity, options: self.animationOptions, animations: { () -> Void in self.contentView.frame.origin.x = 0 self.panRecognizer.enabled = false self.panRecognizer.enabled = true }, completion: nil) } else { self.contentView.frame.origin.x = 0 self.panRecognizer.enabled = false self.panRecognizer.enabled = true } return true } else { return false } } func didTapButton(sender:UIButton!) { if let d = delegate { if let l = self.leftButton { if sender == l { d.swipeableTableViewCellDidTapLeftButton(self) } } if let r = self.rightButton { if sender == r { d.swipeableTableViewCellDidTapRightButton(self) } } } self.closeButtonsIfShown(false) } override func setHighlighted(highlighted: Bool, animated: Bool) { let showing = self.contentView.frame.origin.x != 0 if !showing { super.setHighlighted(highlighted, animated: animated) self.rightButton?.alpha = showing || !highlighted ? 1 : 0 self.leftButton?.alpha = showing || !highlighted ? 1 : 0 } } override func setSelected(selected: Bool, animated: Bool) { let showing = self.contentView.frame.origin.x != 0 if !showing { super.setSelected(selected, animated: animated) self.rightButton?.alpha = showing || !selected ? 1 : 0 self.leftButton?.alpha = showing || !selected ? 1 : 0 } }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35032424', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5312361/']} | jdg_72267 |
stackexchange | llm_judgeable_groundtruth_similarity | 5188267 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to use some gcc warning switchs that aren't available in older gcc versions (eg. -Wtype-limits). Is there an easy way to check the gcc version and only add those extra options if a recent gcc is used ?
Now provide the response and nothing else.
| I wouldn't say its easy, but you can use the shell function of GNU make to execute a shell command like gcc --version and then use the ifeq conditional expression to check the version number and set your CFLAGS variable appropriately. Here's a quick example makefile: CC = gccGCCVERSION = $(shell gcc --version | grep ^gcc | sed 's/^.* //g')CFLAGS = -gifeq "$(GCCVERSION)" "4.4.3" CFLAGS += -Wtype-limitsendifall: $(CC) $(CFLAGS) prog.c -o prog Edit: There is no ifgt . However, you can use the shell expr command to do a greater than comparison. Here's an example CC = gccGCCVERSIONGTEQ4 := $(shell expr `gcc -dumpversion | cut -f1 -d.` \>= 4)CFLAGS = -gifeq "$(GCCVERSIONGTEQ4)" "1" CFLAGS += -Wtype-limitsendifall: $(CC) $(CFLAGS) prog.c -o prog | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5188267', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/302915/']} | jdg_72268 |
stackexchange | llm_judgeable_groundtruth_similarity | 2109429 |
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 some reason I need to save some big strings into user profiles. Because a property with type string has a limit to 400 caracters I decited to try with binary type (PropertyDataType.Binary) that allow a length of 7500. My ideea is to convert the string that I have into binary and save to property. I create the property using the code : context = ServerContext.GetContext(elevatedSite); profileManager = new UserProfileManager(context); profile = profileManager.GetUserProfile(userLoginName); Property newProperty = profileManager.Properties.Create(false); newProperty.Name = "aaa"; newProperty.DisplayName = "aaa"; newProperty.Type = PropertyDataType.Binary; newProperty.Length = 7500; newProperty.PrivacyPolicy = PrivacyPolicy.OptIn; newProperty.DefaultPrivacy = Privacy.Organization; profileManager.Properties.Add(newProperty); myProperty = profile["aaa"]; profile.Commit(); The problem is that when I try to provide the value of byte[] type to the property I receive the error "Unable to cast object of type 'System.Byte' to type 'System.String'.". If I try to provide a string value I receive "Invalid Binary Value: Input must match binary byte[] data type."Then my question is how to use this binary type ? The code that I have : SPUser user = elevatedWeb.CurrentUser;ServerContext context = ServerContext.GetContext(HttpContext.Current);UserProfileManager profileManager = new UserProfileManager(context);UserProfile profile = GetUserProfile(elevatedSite, currentUserLoginName);UserProfileValueCollection myProperty= profile[PropertyName]; myProperty.Value = StringToBinary(GenerateBigString()); and the functions for test : private static string GenerateBigString() { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 750; i++) sb.Append("0123456789"); return sb.ToString(); } private static byte[] StringToBinary(string theSource) { byte[] thebytes = new byte[7500]; thebytes = System.Text.Encoding.ASCII.GetBytes(theSource); return thebytes; }
Now provide the response and nothing else.
| Here's a simple example. suppose you have an object like the following using System.ComponentModel.DataAnnotations;public class Contact{ [Required(AllowEmptyStrings = false, ErrorMessage = "First name is required")] [StringLength(20, MinimumLength = 5, ErrorMessage = "First name must be between 5 and 20 characters")] public string FirstName { get; set; } public string LastName { get; set; } [DataType(DataType.DateTime)] public DateTime Birthday { get; set; }} And suppose we have a method that creates an instance of this class and tries to validate its properties, as listed below private void DoSomething() { Contact contact = new Contact { FirstName = "Armin", LastName = "Zia", Birthday = new DateTime(1988, 04, 20) }; ValidationContext context = new ValidationContext(contact, null, null); IList<ValidationResult> errors = new List<ValidationResult>(); if (!Validator.TryValidateObject(contact, context, errors,true)) { foreach (ValidationResult result in errors) MessageBox.Show(result.ErrorMessage); } else MessageBox.Show("Validated"); } The DataAnnotations namespace is not tied to the MVC framework so you can use it in different types of applications. the code snippet above returns true, try to update the property values to get validation errors. And make sure to checkout the reference on MSDN: DataAnnotations Namespace | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2109429', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/105992/']} | jdg_72269 |
stackexchange | llm_judgeable_groundtruth_similarity | 130216 |
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am plotting a simple sinusoidal function as below. Is there a way to tick the intersection of the function and x axis automatically on the plot? Plot[Sin[2*Pi*t - Pi/3], {t, -1.5, 1.5}]
Now provide the response and nothing else.
| plot = Plot[Sin[2*Pi*t - Pi/3], {t, -1.5, 1.5}, Mesh -> {{0}}, MeshFunctions -> {#2 &}, MeshStyle -> Directive[Red, PointSize[.03]]] If you really want to display on the plot only the Ticks at the intersections, not just highlight the points, then you can extract the points from plot : ticks = SetAccuracy[#, 4]& @ Cases[Normal[plot], Point[x_] :> x[[1]], Infinity]Plot[Sin[2*Pi*t - Pi/3], {t, -1.5, 1.5}, Ticks -> {ticks, Automatic}] The Mesh approach is more likely to grasp all the intersections for more complicated functions, where FindInstance , NSolve , FindRoot etc. may fail in finding all solutions. Why SetAccuracy ? Because a = Cases[Normal[plot], Point[x_] :> x[[1]], Infinity] gives {-1.33346, -0.833429, -0.333212, 0.166831, 0.666733, 1.16661} which are correct to three, sometimes four, decimal places; it would require some way of rounding to be expressed in simple fractions (see Can Mathematica propose an exact value based on an approximate one? and Expressing a decimal as a fraction in lowest terms ). In this particular case, Rationalize does a good job: ticks = Rationalize[#, 10^-3]& @ a {-4/3, -5/6, -1/3, 1/6, 2/3, 7/6} Then Plot[Sin[2*Pi*t - Pi/3], {t, -1.5, 1.5}, Ticks -> {ticks, Automatic}] Note: the locations of the tick labels aren't very fortunate in this case. Relocating them might be possible by adapting these approaches: Is it possible to position ticklabels on the negative y axis on its right side? Labels and tickmarks inside Frame | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/130216', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/18805/']} | jdg_72270 |
stackexchange | llm_judgeable_groundtruth_similarity | 430382 |
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:
Does anyone know around what year MCMC became commonplace (i.e., a popular method for Bayesian inference)? A link to the number of published MCMC (journal) articles over time would be especially helpful.
Now provide the response and nothing else.
| This paper by Christian ( Xi'an ) Robert and George Casella provides a nice summary of the history of MCMC. From the paper (emphasis is mine). What can be reasonably seen as the first MCMC algorithm is what we now call the Metropolis algorithm, published by Metropolis et al. (1953). It emanates from the same group of scientists who produced the Monte Carlo method, namely, the research scientists of Los Alamos, mostly physicists working on mathematical physics and the atomic bomb. The Metropolis algorithm was later generalized by Hastings (1970) and his student Peskun (1973,1981) Although somewhat removed from statistical inference in the classical sense and based on earlier techniques used in Statistical Physics, the landmark paper by Geman and Geman (1984) brought Gibbs sampling into the arena of statistical application. This paper is also responsible for the name Gibbs sampling In particular, Geman and Geman (1984) influenced Gelfand and Smith (1990) to write a paper that is the genuine starting point for an intensive use of MCMC methods by the main-stream statistical community . It sparked new inter-est in Bayesian methods, statistical computing, algorithms and stochastic processes through the use of computing algorithms such as the Gibbs sampler and the Metropolis–Hastings algorithm. Interestingly, the earlier paper by Tanner and Wong (1987) had essentially the same ingredients as Gelfand and Smith (1990), namely, the fact that simulating from the conditional distributions is sufficient to asymptotically simulate from the joint.This paper was considered important enough to be a discussion paper in the Journal of the American Statistical Association, but its impact was somehow limited, compared with Gelfand and Smith (1990). I couldn't find the number of journal articles published over time, but here is a Google Ngram plot for the number of mentions over time. It more or less agrees with the notion that MCMC became commonplace after the 1990 paper of Gelfand and Smith. Reference Robert, Christian, and George Casella. "A short history of Markov chain Monte Carlo: Subjective recollections from incomplete data." Statistical Science (2011): 102-115. | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/430382', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/163639/']} | jdg_72271 |
stackexchange | llm_judgeable_groundtruth_similarity | 40472668 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to create a numeric TextField for Integers by using the TextFormatter of JavaFX 8. Solution with UnaryOperator: UnaryOperator<Change> integerFilter = change -> { String input = change.getText(); if (input.matches("[0-9]*")) { return change; } return null;};myNumericField.setTextFormatter(new TextFormatter<String>(integerFilter)); Solution with IntegerStringConverter: myNumericField.setTextFormatter(new TextFormatter<>(new IntegerStringConverter())); Both solutions have their own problems. With the UnaryOperator, I can only enter digits from 0 to 9 like intended, but I also need to enter negative values like "-512", where the sign is only allowed at the first position. Also I don't want numbers like "00016" which is still possible. The IntegerStringConverter method works way better: Every invalid number like "-16-123" is not accepted and numbers like "0123" get converted to "123". But the conversion only happens when the text is commited (via pressing enter) or when the TextField loses its focus. Is there a way to enforce the conversion of the second method with the IntegerStringConverter every time the value of the TextField is updated?
Now provide the response and nothing else.
| The converter is different to the filter: the converter specifies how to convert the text to a value, and the filter filters changes the user may make. It sounds like here you want both, but you want the filter to more accurately filter the changes that are allowed. I usually find it easiest to check the new value of the text if the change were accepted. You want to optionally have a - , followed by 1-9 with any number of digits after it. It's important to allow an empty string, else the user won't be able to delete everything. So you probably need something like UnaryOperator<Change> integerFilter = change -> { String newText = change.getControlNewText(); if (newText.matches("-?([1-9][0-9]*)?")) { return change; } return null;};myNumericField.setTextFormatter( new TextFormatter<Integer>(new IntegerStringConverter(), 0, integerFilter)); You can even add more functionality to the filter to let it process - in a smarter way, e.g. UnaryOperator<Change> integerFilter = change -> { String newText = change.getControlNewText(); // if proposed change results in a valid value, return change as-is: if (newText.matches("-?([1-9][0-9]*)?")) { return change; } else if ("-".equals(change.getText()) ) { // if user types or pastes a "-" in middle of current text, // toggle sign of value: if (change.getControlText().startsWith("-")) { // if we currently start with a "-", remove first character: change.setText(""); change.setRange(0, 1); // since we're deleting a character instead of adding one, // the caret position needs to move back one, instead of // moving forward one, so we modify the proposed change to // move the caret two places earlier than the proposed change: change.setCaretPosition(change.getCaretPosition()-2); change.setAnchor(change.getAnchor()-2); } else { // otherwise just insert at the beginning of the text: change.setRange(0, 0); } return change ; } // invalid change, veto it by returning null: return null;}; This will let the user press - at any point and it will toggle the sign of the integer. SSCCE: import java.util.function.UnaryOperator;import javafx.application.Application;import javafx.geometry.Pos;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.control.TextField;import javafx.scene.control.TextFormatter;import javafx.scene.control.TextFormatter.Change;import javafx.scene.layout.VBox;import javafx.stage.Stage;import javafx.util.StringConverter;import javafx.util.converter.IntegerStringConverter;public class IntegerFieldExample extends Application { @Override public void start(Stage primaryStage) { TextField integerField = new TextField(); UnaryOperator<Change> integerFilter = change -> { String newText = change.getControlNewText(); if (newText.matches("-?([1-9][0-9]*)?")) { return change; } else if ("-".equals(change.getText()) ) { if (change.getControlText().startsWith("-")) { change.setText(""); change.setRange(0, 1); change.setCaretPosition(change.getCaretPosition()-2); change.setAnchor(change.getAnchor()-2); return change ; } else { change.setRange(0, 0); return change ; } } return null; }; // modified version of standard converter that evaluates an empty string // as zero instead of null: StringConverter<Integer> converter = new IntegerStringConverter() { @Override public Integer fromString(String s) { if (s.isEmpty()) return 0 ; return super.fromString(s); } }; TextFormatter<Integer> textFormatter = new TextFormatter<Integer>(converter, 0, integerFilter); integerField.setTextFormatter(textFormatter); // demo listener: textFormatter.valueProperty().addListener((obs, oldValue, newValue) -> System.out.println(newValue)); VBox root = new VBox(5, integerField, new Button("Click Me")); root.setAlignment(Pos.CENTER); Scene scene = new Scene(root, 300, 120); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); }} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40472668', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6436041/']} | jdg_72272 |
stackexchange | llm_judgeable_groundtruth_similarity | 9605716 |
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 find environment variables in input and replace them with values. The pattern of env variable is ${\\.} Pattern myPattern = Pattern.compile( "(${\\.})" );String line ="${env1}sojods${env2}${env3}"; How can I replace env1 with 1 and env2 with 2 and env3 with 3 , so that after this I will have a new string 1sojods23 ?
Now provide the response and nothing else.
| Strings in Java are immutable, which makes this somewhat tricky if you are talking about an arbitrary number of things you need to find and replace. Specifically you need to define your replacements in a Map , use a StringBuilder (before Java 9, less performant StringBuffer should have been used) and the appendReplacements() and appendTail() methods from Matcher . The final result will be stored in your StringBuilder (or StringBuffer ). Map<String, String> replacements = new HashMap<String, String>() {{ put("${env1}", "1"); put("${env2}", "2"); put("${env3}", "3");}};String line ="${env1}sojods${env2}${env3}";String rx = "(\\$\\{[^}]+\\})";StringBuilder sb = new StringBuilder(); //use StringBuffer before Java 9Pattern p = Pattern.compile(rx);Matcher m = p.matcher(line);while (m.find()){ // Avoids throwing a NullPointerException in the case that you // Don't have a replacement defined in the map for the match String repString = replacements.get(m.group(1)); if (repString != null) m.appendReplacement(sb, repString);}m.appendTail(sb);System.out.println(sb.toString()); Output: 1sojods23 | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9605716', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1205079/']} | jdg_72273 |
stackexchange | llm_judgeable_groundtruth_similarity | 1232116 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to create a POD for my own custom command and display the syntax for that using pod2usage() function.. Can anyone give me a simple example for it? Regards,Anandan
Now provide the response and nothing else.
| I do this using Getopt::Long together with Pod::Usage . (I got into this habit after reading a tutorial on the PerlMonks site, so here's the link to that as well.) It looks something like this example: use Getopt::Long;use Pod::Usage;my( $opt_help, $opt_man, $opt_full, $opt_admins, $opt_choose, $opt_createdb, );GetOptions( 'help!' => \$opt_help, 'man!' => \$opt_man, 'full!' => \$opt_full, 'admin|admins!' => \$opt_admins, 'choose|select|c=s' => \$opt_choose, 'createdb!' => \$opt_createdb,) or pod2usage( "Try '$0 --help' for more information." );pod2usage( -verbose => 1 ) if $opt_help;pod2usage( -verbose => 2 ) if $opt_man; The options other than $opt_man and $opt_help are irrelevant to you in that example. I just copied the top of a random script I had here. After that, you just need to write the POD. Here's a good link describing the basics of POD itself. Edit : In response to the OP's question in the comments, here's how you might print just the NAME section when passed an appropriate option. First, add another option to the hash of options in GetOptions . Let's use 'name' => \$opt_name here. Then add this: pod2usage(-verbose => 99, -sections => "NAME") if $opt_name; Verbose level 99 is magic: it allows you to choose one or more sections only to be printed. See the documentation of Pod::Usage under -sections for more details. Note that -sections (the name) is plural even if you only want one section . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1232116', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/139923/']} | jdg_72274 |
stackexchange | llm_judgeable_groundtruth_similarity | 1013239 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it possible to do this: myfile.js:function foo() { alert(<my-function-name>); // pops-up "foo" // or even better: "myfile.js : foo"} I've got the Dojo and jQuery frameworks in my stack, so if either of those make it easier, they're available.
Now provide the response and nothing else.
| In ES5 and above, there is no access to that information. In older versions of JS you can get it by using arguments.callee . You may have to parse out the name though, as it will probably include some extra junk. Though, in some implementations you can simply get the name using arguments.callee.name . Parsing: function DisplayMyName() { var myName = arguments.callee.toString(); myName = myName.substr('function '.length); myName = myName.substr(0, myName.indexOf('(')); alert(myName);} Source: Javascript - get current function name . | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/1013239', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/24197/']} | jdg_72275 |
stackexchange | llm_judgeable_groundtruth_similarity | 34319303 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
When starting multiple threads, the id parameter I'm parsing is sometimes wrong. Here is my startup: for (int i = 0; i < _threadCount; i++){ Thread thread = new Thread(() => WorkerThread(i)); thread.Start(); _threads.Add(thread);} And my thread function: private void WorkerThread(int id){ Console.WriteLine("[{0}] Thread started {1}", DateTime.Now.ToLongTimeString(), id);} The output of this code is: [19:10:54] Thread start 3[19:10:54] Thread start 9[19:10:54] Thread start 4[19:10:54] Thread start 12[19:10:54] Thread start 11[19:10:54] Thread start 3[19:10:54] Thread start 12[19:10:54] Thread start 6[19:10:54] Thread start 9[19:10:54] Thread start 6[19:10:54] Thread start 13[19:10:54] Thread start 2[19:10:54] Thread start 15[19:10:54] Thread start 9[19:10:54] Thread start 15 Where in my mind, this code should create every thread with a unique id instead of duplicates as seen above. Compiler info: Platform target: x64 Target Framework: .NET Framework 4.5
Now provide the response and nothing else.
| You should be careful about accidentally modifying captured variables like i after starting the thread, because the i is shared . The i variable refers to the same memory location throughout the loop’s lifetime. The solution is to use a temporary variable like this: for (int i = 0; i < _threadCount; i++){ var i1 = i; Thread thread = new Thread(() => WorkerThread(i1)); thread.Start(); _threads.Add(thread);} Read more about Closures here : The Beauty of Closures from ( Jon Skeet ) and Lambda expressions and captured variables from ( Joseph Albahari ). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34319303', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1725772/']} | jdg_72276 |
stackexchange | llm_judgeable_groundtruth_similarity | 25363977 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Studying boost asio and find out a class called "strand", as far as I understand.If there are only one io_service associated to a specific strand and post the handle by the strand. example(from here ) boost::shared_ptr< boost::asio::io_service > io_service( new boost::asio::io_service);boost::shared_ptr< boost::asio::io_service::work > work( new boost::asio::io_service::work( *io_service ));boost::asio::io_service::strand strand( *io_service );boost::thread_group worker_threads;for( int x = 0; x < 2; ++x ){ worker_threads.create_thread( boost::bind( &WorkerThread, io_service ) );}boost::this_thread::sleep( boost::posix_time::milliseconds( 1000 ) );strand.post( boost::bind( &PrintNum, 1 ) );strand.post( boost::bind( &PrintNum, 2 ) );strand.post( boost::bind( &PrintNum, 3 ) );strand.post( boost::bind( &PrintNum, 4 ) );strand.post( boost::bind( &PrintNum, 5 ) ); Then the strand will serialized handler execution for us.But what is the benefits of doing this?Why don't we just create a single thread(ex : make x = 1 in the for loop) if we want the tasks become serialized?
Now provide the response and nothing else.
| Think of a system where a single io_service manages sockets for hundreds of network connections. To be able to parallelize workload, the system maintains a pool of worker threads that call io_service::run . Now most of the operations in such a system can just run in parallel. But some will have to be serialized. For example, you probably would not want multiple write operations on the same socket to happen concurrently. You would then use one strand per socket to synchronize writes: Writes on distinct sockets can still happen at the same time, while writes to same sockets will be serialized. The worker threads do not have to care about synchronization or different sockets, they just grab whatever io_service::run hands them. One might ask: Why can't we just use mutex instead for synchronization? The advantage of strand is that a worker thread will not get scheduled in the first place if the strand is already being worked on. With a mutex, the worker thread would get the callback and then would block on the lock attempt, preventing the thread from doing any useful work until the mutex becomes available. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25363977', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1281264/']} | jdg_72277 |
stackexchange | llm_judgeable_groundtruth_similarity | 18814522 |
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 wanted to write it functionally, and the best I could do was: list.zipWithIndex.filter((tt:Tuple2[Thing,Int])=>(tt._2%3==0)).unzip._1 to get elements 0, 3, 6,... Is there a more readable Scala idiom for this?
Now provide the response and nothing else.
| If efficiency is not an issue, you could do the following: list.grouped(3).map(_.head) Note that this constructs intermediate lists. Alternatively you can use a for-comprehension: for { (x,i) <- list zipWithIndex if i % 3 == 0} yield x This is of course almost identical to your original solution, just written differently. My last alternative for you is the use of collect on the zipped list: list.zipWithIndex.collect { case (x,i) if i % 3 == 0 => x} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18814522', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/833970/']} | jdg_72278 |
stackexchange | llm_judgeable_groundtruth_similarity | 536399 |
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 NavigationBar app with two views: a parent and a sub view. In the sub view I'm adding a button to the right corner as follows: - (void)viewDidLoad { UIBarButtonItem *tempButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"lock-unlocked.png"] style:UIBarButtonItemStylePlain target:self action:@selector(lockScreen)]; self.navigationItem.rightBarButtonItem = tempButton; [tempButton release];} When that button is clicked I want to change the image of this rightBarButtonItem and disable the leftBarButtonItem (which was added automatically by the controller). Basically have two states of a button, locked and unlocked. Question 1:The only way I can find how to change the image is to create a new UIButtonItem with a new image and replace rightBarButtonItem with that new one. But I'm wondering if there's a way to just change the image without creating a new UIBarButtonItem. Am I creating a memory leak if I keep creating new UIBarButtonItem? Question 2:How can I get a hold of self.navigationItem.leftBarButtonItem and disable/enable it? I don't create that one manually, it's created automatically for me by the controller. I don't see any method/property on UIBarButtonItem to enable/disable user interaction with it.
Now provide the response and nothing else.
| Question 1: Declare UIBarButtonItem *tempButton in the interface @interface MyAppDelegate : NSObject <UIApplicationDelegate> { UIBarButtonItem *tempButton;}@property (nonatomic, retain) UIBarButtonItem *tempButton; and synthesize it in the implementation. @synthesize tempButton; Create the object in viewDidLoad similiar to how you are now. - (void)viewDidLoad { tempButtom = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"lock-unlocked.png"] style:UIBarButtonItemStylePlain target:self action:@selector(lockScreen)]; self.navigationItem.rightBarButtonItem = tempButton;} But don't release it here, release it in the dealloc method normally found at the bottom. Then when lockScreen is called do tempButton.image = [UIImage imageNamed:@"myImage.png"] I don't have an answer for question 2, im afraid! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/536399', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/44091/']} | jdg_72279 |
stackexchange | llm_judgeable_groundtruth_similarity | 32773659 |
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 here and new to Android Development, I Have a question regarding the Android CountDownTimer. How am I able to use Android's CountDownTimer, to count down to a specific date, let's say the 6th Novemeber 2015? Also How would I use the Java code with corresponding XML Code? I had a llok at this question ( how to countdown to a date ) and couldn't really understand what was going on? Can anyone spare a moment to help me? Thanks
Now provide the response and nothing else.
| This is exactly how you do it UPDATE 3 @Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.your_layout); TextView tv_countdown = (TextView) findViewById(R.id.your_textview_id); Calendar start_calendar = Calendar.getInstance(); Calendar end_calendar = Calendar.getInstance(); long start_millis = start_calendar.getTimeInMillis(); //get the start time in milliseconds long end_millis = end_calendar.getTimeInMillis(); //get the end time in milliseconds long total_millis = (end_millis - start_millis); //total time in milliseconds end_calendar.set(2015, 10, 6); // 10 = November, month start at 0 = January //1000 = 1 second interval CountDownTimer cdt = new CountDownTimer(total_millis, 1000) { @Override public void onTick(long millisUntilFinished) { long days = TimeUnit.MILLISECONDS.toDays(millisUntilFinished); millisUntilFinished -= TimeUnit.DAYS.toMillis(days); long hours = TimeUnit.MILLISECONDS.toHours(millisUntilFinished); millisUntilFinished -= TimeUnit.HOURS.toMillis(hours); long minutes = TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished); millisUntilFinished -= TimeUnit.MINUTES.toMillis(minutes); long seconds = TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished); tv_countdown.setText(days + ":" + hours + ":" + minutes + ":" + seconds); //You can compute the millisUntilFinished on hours/minutes/seconds } @Override public void onFinish() { tv_countdown.setText("Finish!"); } }; cdt.start();} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32773659', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5352674/']} | jdg_72280 |
stackexchange | llm_judgeable_groundtruth_similarity | 1866236 |
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 looking for a way to perform pointer operations in C# or .NET in particular. I want to do something very simple Having a pointer IntPtr I want to get IntPtr object which points to 2 bytes ahead. I read some post that the foolowing snippet will work... IntPtr ptr = new IntPtr(oldptr.ToInt32() + 2); But I have doubts whether this statement is also valid for 64-bit machine (since addressing is in 64-bits there).. I found this elegant method to add offset, but unfortunately is in .NET 4.0 only http://msdn.microsoft.com/en-us/library/system.intptr.add%28VS.100%29.aspx
Now provide the response and nothing else.
| I suggest you to use ToInt64() and long to perform your computation. This way you will avoid problem on 64 bits version of the .NET framework. IntPtr ptr = new IntPtr(oldptr.ToInt64() + 2); This add a bit of overhead on 32 bits system, but it is safer. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1866236', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/40967/']} | jdg_72281 |
stackexchange | llm_judgeable_groundtruth_similarity | 44816519 |
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 cookie-parser, all the tutorial talk about how to set cookie and the time it expiries but no where teach us how to get the value of these cookie
Now provide the response and nothing else.
| First note that Cookies are sent to client with a server request and STORED ON THE CLIENT SIDE . Every time the user loads the website back, this cookie is sent with the request. So you can access the cookie in client side (Eg. in your client side Java script) by using document.cookie you can test this in the client side by opening the console of the browser (F12) and type console.log(document.cookie); you can access the cookie from the server (in your case, expressjs) side by using req.cookies Best practice is to check in the client side whether it stored correctly. Keep in mind that not all the browsers are allowing to store cookies without user permission. As per your comment, your code should be something like var express = require('express');var app = express();var username ='username';app.get('/', function(req, res){ res.cookie('user', username, {maxAge: 10800}).send('cookie set');});app.listen(3000); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/44816519', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8101715/']} | jdg_72282 |
stackexchange | llm_judgeable_groundtruth_similarity | 58393704 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Using android-studio for flutter development. After creating a new flutter app I created another file named home.dart But android-studio is not recognizing the file. The page won't show autocomplete or anything. Also I can see that home.dart don't have the globe symbol before the file name(in left side like other files). If I put any other file name it works fine. Could someone find what's the issue? Update I think its some sort of bug. I even tried creating a fresh project and tried the same. If I put another name it works fine(I tried hom.dart and it works). But if I rename it as home.dart it is having this weird error. Thank you
Now provide the response and nothing else.
| You have associated a different file type to that specific file by creating it as a regular file (right click -> New -> File) which has no implied type and instead shows a list of types to select from. You may have just clicked Next without changing the default selection of file type of 'Text'. Renaming the file afterwards may or may not change its type depending on the version of Android Studio. In order to fix it, open settings (Ctrl + Alt + S), go to Editor -> File Types, scroll down and select 'Text' from the list of file types, select your file from the list at the bottom, and click the minus (-) sign to remove it. Your file should no longer be associated to a type of 'Text' - I'm not sure whether it will automatically be reassigned based on its extension or not, but you should now be able to delete it and create it again with the same name without automatically setting itself back to 'Text' | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/58393704', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2874507/']} | jdg_72283 |
stackexchange | llm_judgeable_groundtruth_similarity | 25884038 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
After todays update of composer dependencies (with composer update command) my Yii2 application became broken - It throws Unknown Method – yii\base\UnknownMethodException: Calling unknown method: yii\web\UrlManager::addRules() After inspecting vendor/yiisoft/yii2/web/UrlManager.php file I found that there is no method addRule.And the whole entire class UrlManager is different from the class in the repository. My composer.json: "minimum-stability": "dev","require": { "php": ">=5.4.0", "yiisoft/yii2": "*", "yiisoft/yii2-bootstrap": "*", "yiisoft/yii2-swiftmailer": "*", "yiisoft/yii2-gii": "2.0.0-beta", "claudejanz/yii2-mygii": "*", "kartik-v/yii2-grid": "dev-master", "kartik-v/yii2-builder": "dev-master", "2amigos/yii2-switch-widget": "*", "yiisoft/yii2-jui": "*", "DsXack/yii2-underscore": "*", "2amigos/yii2-editable-widget": "*", "warrence/yii2-kartikgii": "*"},"require-dev": { "yiisoft/yii2-codeception": "*", "yiisoft/yii2-debug": "*"},
Now provide the response and nothing else.
| Here is an explaination of why this happened: I think this is again the composer dependency resolver doing unexpected things: you require yiisoft/yii2 in your composer.json but do not have the composer asset plugin installed. then the dependency resolver does not find packages with vendor bower-asset so it looks for other versions of yiisoft/yii2 that do not have conflict The result is to install the beta version of yii2 to be installed The correct solution as already mentioned is to install the composer-asset-plugin : php composer.phar global require "fxp/composer-asset-plugin:1.0.*@dev" | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/25884038', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/715012/']} | jdg_72284 |
stackexchange | llm_judgeable_groundtruth_similarity | 13198136 |
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 jQuery function that on the click of a div element, gets that elements predefined ID value. What I want to do is load that parent elements children, so I'm planning to dynamically build some html using jQuery. What I don't know how to do, is make a call to a controller (ASP.NET MVC 3) and have the controller return a collection to the client. I know how to send a JSON object from jQuery to a controller, but not the other way around. Thanks in advance!
Now provide the response and nothing else.
| Here is the code for how you send data from Controller to json: $.ajax({ url: '@Url.Action("GetData", "Home")', type: "GET", success: function (result) { $("#somediv").append(result.FirstName); $("#somediv").append(result.LastName); $("#somediv").append(result.Age); }}); Consider a class like the one below.... public class User { public string FirstName { get; set; } public string LastName { get; set; } } your action should look like this. public JsonResult GetData() { User user = new User(); user.FirstName = "Yasser"; user.LastName = "Shaikh"; user.Age = 100; return Json(user, JsonRequestBehavior.AllowGet);} Further Reading | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13198136', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1024920/']} | jdg_72285 |
stackexchange | llm_judgeable_groundtruth_similarity | 1490693 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider the C program composed of two files, f1.c: int x; f2.c: int x=2; My reading of paragraph 6.9.2 of the C99 standard is that this program should be rejected. In my interpretation of 6.9.2, variable x is tentatively defined in f1.c , but this tentative definition becomes an actual definition at the end of the translation unit, and (in my opinion), should therefore behave as if f1.c contained the definition int x=0; . With all compilers (and, importantly, linkers) I was able to try, this is not what happens. All compilation platforms I tried do link the above two files, and the value of x is 2 in both files. I doubt this happens by accident, or just as an "easy" feature to provide in addition to what the standard requires. If you think about it, it means there is special support in the linker for those global variables that do not have an initializer, as opposed to those explicitly initialized to zero. Someone told me that the linker feature may be necessary to compile Fortran anyway. That would be a reasonable explanation. Any thoughts about this? Other interpretations of the standard? Names of platforms on which files f1.c and f2.c refuse to be linked together? Note: this is important because the question occurs in the context of static analysis. If the two files may refuse to be linked on some platform, the analyzer should complain, but if every compilation platform accepts it then there is no reason to warn about it.
Now provide the response and nothing else.
| See also What are extern variables in C . This is mentioned in the C standard in informative Annex J as a common extension: J.5.11 Multiple external definitions There may be more than one external definition for the identifier of an object, with or without the explicit use of the keyword extern; if the definitions disagree, or more than one is initialized, the behavior is undefined (6.9.2). Warning As @litb points out here, and as stated in my answer to the cross-referenced question, using multiple definitions for a global variable leads to undefined behaviour, which is the standard's way of saying "anything could happen". One of the things that can happen is that the program behaves as you expect; and J.5.11 says, approximately, "you might be lucky more often than you deserve". But a program that relies on multiple definitions of an extern variable - with or without the explicit 'extern' keyword - is not a strictly conforming program and not guaranteed to work everywhere. Equivalently: it contains a bug which may or may not show itself. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1490693', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/139746/']} | jdg_72286 |
stackexchange | llm_judgeable_groundtruth_similarity | 8721019 |
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 looking to draw a UILabel (preferable through subclassing) as a transparent label, but with solid background. I draw up an quick example (sorry, it's ugly, but it gets the points across :)). Basically I have a UILabel and I would like the background to be a set colour, and the text should be transparent. I do not want to colour the text with the views background, but instead have it be 100% transparent, since I have a texture in the background that I want to make sure lines up inside and outside of the label. I've been spending the night browsing SO and searching on Google, but I have found no helpful sources. I don't have much experience with CG drawing, so I would appreciate any links, help, tutorial or sample code (maybe Apple has some I need to have a look at?). Thanks a bunch!
Now provide the response and nothing else.
| I've rewritten it as a UILabel subclass using barely any code and posted it on GitHub The gist of it is you override drawRect but call [super drawRect:rect] to let the UILabel render as normal. Using a white label color lets you easily use the label itself as a mask. - (void)drawRect:(CGRect)rect{ CGContextRef context = UIGraphicsGetCurrentContext(); // let the superclass draw the label normally [super drawRect:rect]; CGContextConcatCTM(context, CGAffineTransformMake(1, 0, 0, -1, 0, CGRectGetHeight(rect))); // create a mask from the normally rendered text CGImageRef image = CGBitmapContextCreateImage(context); CGImageRef mask = CGImageMaskCreate(CGImageGetWidth(image), CGImageGetHeight(image), CGImageGetBitsPerComponent(image), CGImageGetBitsPerPixel(image), CGImageGetBytesPerRow(image), CGImageGetDataProvider(image), CGImageGetDecode(image), CGImageGetShouldInterpolate(image)); CFRelease(image); image = NULL; // wipe the slate clean CGContextClearRect(context, rect); CGContextSaveGState(context); CGContextClipToMask(context, rect, mask); CFRelease(mask); mask = NULL; [self RS_drawBackgroundInRect:rect]; CGContextRestoreGState(context);} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8721019', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/118091/']} | jdg_72287 |
stackexchange | llm_judgeable_groundtruth_similarity | 1413022 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
In Guillemin and Pollack's Differential Topology , they give as an exercise (#1.8.14) to prove the following generalization of the Inverse Function Theorem: Use a partition-of-unity technique to prove a noncompact version of [the Inverse Function Theorem]. Suppose that the derivative of $f: X \to Y$ is an isomorphism whenever $x$ lies in the submanifold $Z \subset X$, and assume that $f$ maps $Z$ diffeomorphically onto $f(Z)$. Prove that $f$ maps a neighborhood of $Z$ diffeomorphically onto a neighborhood of $f(Z)$. There is an answer here , but there is one thing I don't understand. I'll summarize the answer. Take a local diffeomorphism neighborhood $U_z$ around each $z \in Z$, giving an open cover $f(U_z)$ of $f(Z)$. Take a locally finite refinement $V_i$. Let $g_i$ be the local inverses defined on each $V_i$. For each $V_i \cap V_j$, let $W_{ij}:= \{y \in V_i \cap V_j: g_i(y) \neq g_j(y)\}$. The sets $\overline{W_{ij}}$ are locally finite, so their union is closed, so $(\cup_z f(U_z)) \setminus \ (\cup_{i,j}\overline{W_{i,j}})$ is an open set on which an inverse is defined, and it contains $f(Z)$. My problem is: why does it contain $f(Z)$? Certainly $W_{ij} \cap f(Z) = \emptyset$ for all $i,j$, but why should $\overline{W_{ij}} \cap f(Z) = \emptyset$ for all $i,j$? In particular, why cannot a sequence of points in $W_{ij}$ converge to a point in $f(Z)$?
Now provide the response and nothing else.
| We can show that any two elements of the refined collection $\{g_i\}$ that are defined at $y$ have a nonempty open set around $y$ on which they agree: Suppose we have two neighborhoods $V_i=f(U_i)$ and $V_j=f(U_j)$ of $y =f(z) \in f(Z)$ together with local inverses $g_i$ and $g_j$. Then we have $$g_i(V_i) \cap g_j(V_j)=U_i \cap U_j \subset X,$$which is an open neighborhood of $z$ in $X$. Thus the set$$V=g_i^{-1}(U_i \cap U_j) \cap g_j^{-1}(U_i \cap U_j) $$ is an open neighborhood of $y$ in $Y$ on which $g_i$ and $g_j$ are both defined. Moreover, for $y' \in V$, we have$$f(g_i(y'))=y'=f(g_j(y'))$$and thus $g_i(y')=g_j(y')$ because $f$ is one-to-one. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1413022', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/76333/']} | jdg_72288 |
stackexchange | llm_judgeable_groundtruth_similarity | 24570793 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why is it an exc_bad_access and not a run-time or compile-time error? By mistake I wrote "@age" instead of @"age" , and it sparked my curiosity. What I understand of exc_bad_access is that : Bad-Access is caused by a pointer (okay reference) that is dereferenced to a memory location which is either not allocated yet or deallocated or unauthorized to access ( const or something). But in this case I am only writing data onto memory and the syntax doesn't match the NS Objective-c format. Hence it should be a run-time error instead of a Bad-Access . Where am I missing the concept?
Now provide the response and nothing else.
| The reason you get EXC_BAD_ACCESS is that the -initWithObjects: method expects all of its arguments to be valid Objective-C objects. Each Objective-C object starts with a small header; this used to be a straightforward pointer, called isa , to its class object (it isn't necessarily quite this simple any more, and these days you shouldn't poke about yourself; there are Objective-C runtime APIs you can use instead if necessary). The reason you don't get a compiler error here is that there is no way in C/C++/Objective-C to specify the correct types for a "varargs" method or function. As a result, the compiler allows you to pass arguments of any type, assuming you know what you’re doing. Anyway, within the implementation of -initWithObjects: , it’s going to try to send a -retain message to each of the objects you pass in. When it does that, it's going to try to dereference the isa pointer. In the case of your C string, that means it's going to treat the first four or eight bytes of the string as a pointer. This is very unlikely to have a good outcome, and very likely you'll get EXC_BAD_ACCESS straight away. Even if you were lucky and they do happen to point to valid memory, the Objective-C runtime is going to expect them to point to a valid Class structure, which is tremendously unlikely, and the result of that is also very probably going to be an EXC_BAD_ACCESS. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24570793', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_72289 |
stackexchange | llm_judgeable_groundtruth_similarity | 13678330 |
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 custom control with a data source of type IEnumerable (non-generic). Now I want to implement paging on the data source, and so I need something like Skip and Take, which List-of-T has. Right now I am using the following: List<object> pagingList = DataSource.Cast<object>().ToList() This can be inefficient, I'm guessing, so I'm looking for a better way to do this. Enumerating the collection, skipping elements and such with two counters might be more efficient, but it's so ugly I just don't want to do it. But maybe it's the best choice?
Now provide the response and nothing else.
| Why are you calling ToList() ? You can use Skip and Take without that: IEnumerable<object> paged = DataSource.Cast<object>() .Skip(page * pageSize) .Take(pageSize); That will save converting the whole data source to a list - but it does mean you can't skip efficiently when the source isn't an IList<T> . Two important questions though: You mention that you guess your original code is inefficient... have you measured? How big is this data, and what's its form in memory? What else are you doing with it? Is this really a bottleneck? Collect facts rather than guessing. It would be easier to use your data in various ways if you had a generic data source... is that something you could achieve? | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13678330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/625242/']} | jdg_72290 |
stackexchange | llm_judgeable_groundtruth_similarity | 34369 |
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to buy a new Monitor for Rpi. I don't have budget for HDMI monitors not even for powered HDMI to VGA converters. So can I use vga to usb data cable and use it with powered usb to connect display with Rpi 2. Will this idea work with Rpi 2? This link suggests to have a powered HDMi to VGA adapter if you don't want to damage you pi.
Now provide the response and nothing else.
| There are varying adapters available that you can use on the Pi: HDMI → DVI DVI → VGA HMDI → VGA composite → VGA composite → SCART You can get a list of verified peripherals here - these include and recommends externally powered adapters, but also includes some (cheaper) non-powered ones, as explained (this may concern only the old Pi models): Note that active converter boxes may draw power through the HDMI port, and thus will put an extra load on your PSU, and also increase the current running through the Raspberry Pi's primary input fuse. HDMI ports (and the raspberry PI) are designed so that they deliver a very limited amount of power (50 mA) to the TV/Monitor/display-adapter and much more isn't in theory allowed. In fact there is a diode (D1) in series with the power line which can only handle 200 mA, if the adapter tries to draw much more than that the diode might fail. Therefore only externally powered adapters are to be recommended. Despite this, many people report success with non externally powered devices. If you have bought a non externally powered HDMI to VGA adapter, and you experience problems with it (It behaves badly, D1 burns out, F3 "blows", or your PSU overloads), then not all is lost, there are cheap (a few dollars) adapters that allow you to add external power to the HDMI cable! An example can be found here: [13] The HDMI adapters require power ( here (from here ) shows pin 18 needs +5 V (min. 0.055 A)) , which usually should give 0.55A whilst adapters may need more power (VGA spec apparently does not specify ). This is why the page shows that you can use this , though it does show you can use a few non-powered converters work here . You can also use the composite video output (read here for newer versions), another alternative is to use a RDP or VNC server and a remote desktop client on another machine on the network to view what is on the Pis screen. | {} | {'log_upvote_score': 4, 'links': ['https://raspberrypi.stackexchange.com/questions/34369', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/33712/']} | jdg_72291 |
stackexchange | llm_judgeable_groundtruth_similarity | 1104536 |
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$ and $b$ be two positive integers and $M$ the set of all integer linear combinations of $a$ and $b$. Write $M^+=\{n \in M: n>0\}.$ Is $M^+$ non-empty? Explain. Just to provide more detail $n=au+bv$ where $u,v \in \mathbb{Z}$. I believe that $M^+$ is non-empty. But how would I prove this? Would I just show an example?
Now provide the response and nothing else.
| I think that if you want to work with norms on vector spaces over fields in general, then you have to use the concept of valuation. Valued field: Let $K$ be a field with valuation $|\cdot|:K\to\mathbb{R}$. This is, for all $x,y\in K$, $|\cdot|$ satisfies: $|x|\geq0$, $|x|=0$ iff $x=0$, $|x+y|\leq|x|+|y|$, $|xy|=|x||y|$. The set $|K|:=\{|x|:x\in K-\{0\}\}$ is a multiplicative subgroup of $(0,+\infty)$ called the value group of $|\cdot|$. The valuation is called trivial , discrete or dense accordingly as its value group is $\{1\}$, a discrete subset of $(0,+\infty)$ or a dense subset of $(0,+\infty)$. For example, the usual valuations in $\mathbb{R}$ and $\mathbb{C}$ are dense valuations. Norm: Let $(K,|\cdot|)$ be a valued field and $X$ be a vector space over $(K,|\cdot|)$. A function $p:X\to \mathbb{R}$ is a norm iff for each $a,b\in X$ and each $k\in K$, it satisfies: $p(a)\geq0$ and $p(a)=0$ iff $a=0_X$, $p(ka)=|k|p(a)$, $p(a+b)\leq p(a)+p(b)$ Proposition (Non-trivial valuation case): Let $(K,|\cdot|)$ be a valued field with non-trivial valuation and let $X$ be a vector space over $(K,|\cdot|)$. Two norms $p_1,p_2$ on $X$ are equivalent iff there are constants $c_1$ and $c_2$ such that $c_1p_1\leq p_2\leq c_2p_1$. Proof: If there are constants $c_1$ and $c_2$ such that $c_1p_1\leq p_2\leq c_2p_1$, then it is clear that $p_1$ and $p_2$ are equivalent. Now suppose that $p_1$ and $p_2$ are equivalent. Then there exists $ \delta>0$, such that, for all $ a\in X, p_2(a)<\delta\implies p_1(a)<1.$ Let $a\in X-\{0_X\}$, then $p_2(a)\neq0$. Claim: There exists $x\in K-\{0\}$ such that $|x|<1$. Since the valuation on $K$ is non-trivial, there exist $y\in X-\{0\}$ such that $|y|\neq1$. Because of the equality $|y||y^{-1}|=1$, we can choose $|x|=\min\{|y|,|y^{-1}|\}$. Claim: There exist $n\in\mathbb{Z}$ such that $\frac{\delta|x|}{2}< |x|^np_2(a)<\delta$. The claim is direct application of the following: Lemma: $(\forall 0<s<1)(\forall \delta>0)(\forall w>0)(\exists n\in\mathbb{Z})(\frac{\delta s}{2}<s^nw<\delta).$ Proof: Let $0<s<1, 0<\delta<1$ and $w>0$ be given. Consider $n$ such that $s^n w$ is as close to $\delta/2$ as possible while still being smaller or equal to $\delta/2$. Since $0<s<1$, this is $n=\lceil \log_s(\delta/2w) \rceil$. Then $n<\log_s(\delta/2w)+1$ so $\frac{\delta s}{2}<s^nw\leq\frac{\delta }{2}<\delta$. (Thanks to Ian for helping me with the lemma ). Now from the last claim we have that $\frac{1}{|x|^n}<\frac{2}{\delta|x|}p_2(a)$ and $p_2(x^n a)=|x|^np_2(a)<\delta$. The last inequality implies that $p_1(x^n a)<1.$ Finally, $p_1(a)<\frac{1}{|x|^n}<\frac{2}{\delta|x|}p_2(a)$. Hence, $p_1(a)\leq\frac{2}{\delta|x|}p_2(a)$, $\forall a\in X$. By symmetry, we can find a constant $c>0$ such that $p_2(a)\leq cp_1(a)$, $\forall a\in X$. $\blacksquare$ Notice that we didn't need any information about the dimension of $X$ in the proof. Cases with trivial valuation: If $X$ is a finite-dimensional space, then the proposition is still true when the valuation is trivial. In fact, in that case, for any norm $p$ there are constants $c_1$ and $c_2$ such that $c_1q\leq p\leq c_2q$, where $q$ is the trivial norm (i.e. $q(a)=1$ if $a\neq0$). See the proof here. If $X$ is an infinite-dimensional space and the valuation is trivial, then the proposition is false in general. See a counterexample here. Since all the possible cases are considered, and any field can be considered as a valued field (for example, we always may consider the trivial valuation), then the proof is complete. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1104536', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/62874/']} | jdg_72292 |
stackexchange | llm_judgeable_groundtruth_similarity | 23243457 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Right now I have doc = new XDocument( new XElement(xmlns + "displayMLResponse", new XAttribute("xmlns", "http://www.peek.se/DisplayML/"), new XAttribute("version", "1.12"), new XAttribute("dateTime", date), new XElement("getStatusResponse", new XElement("systemInformation", systemInformationList.Select(info => new XElement("item", new XElement("name", info.name), new XElement("value", info.value))).Where(item => item != null)), responceList.Select(fault => responceList.Count != 0 ? new XElement("faults", new XElement("systemFault", new XElement(fault.faultType, new XAttribute("description", fault.description), fault.name.Length == 0 ? new XAttribute("name", fault.name) : null, fault.size.Length == 0 ? new XAttribute("size", fault.size) : null))) : new XElement("OK")) ))); Problem is that the new XElement("OK") wont be added if responceList is empty as it wont evaluate the things inside responceList.Select(..) as it is empty. Cant get my head around the problem how I must do. Question is how to add either the elements faults if there are any otherwise add the element OK I am trying to create: <displayMLResponse xmlns="http://www.peek.se/DisplayML/" version="1.12"dateTime="2001-12-17T09:30:47"> <getStatusResponse> <systemInformation> <item> <name>Manufacturer</name> <value>PEEK</value> </item> <item> <name>Version</name> <value>1.0.0</value> </item> </systemInformation> <OK/> </getStatusResponse ></displayMLResponse> OK is replaced by: <faults> <systemFault> <missingTemplateFault name="templateAlfa"/> </systemFault> <systemFault> <missingFontFault name="arial" size="18"/> </systemFault></faults> if there are any faults, in this case responceList is a list of faults
Now provide the response and nothing else.
| tabsetPanel() will return the value assigned to the active tabPanel() . If you just want to update another output you could do something like this: ui.R library(shiny) shinyUI(basicPage( textOutput("text"), tabsetPanel(id = "tabs", tabPanel("Tab A", value = "A", "This is Tab A content"), tabPanel("Tab B", value = "B", "Here's some content for tab B.") ))) server.R library(shiny)shinyServer(function(input, output) { output$text <- renderText({paste0("You are viewing tab \"", input$tabs, "\"")})}) but something more complicated like creating a popup would probably require making an observer and some additional custom coding... | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/23243457', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/928535/']} | jdg_72293 |
stackexchange | llm_judgeable_groundtruth_similarity | 3015 |
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I always has this question in my mind. For example, FM Radio Station and Radio player, strong signal from Radio Station could help, because Station --> player is one direction only communication. But in the case of WIFI, is it the same? high power wifi from router could be helpful? What if router wifi --> computer is very strong, but computer wifi --> router is very weak. The network feedback from computer back to internet will fail anyway, no matter how strong is the router? Am I understanding is correct? So.....Repeater is a must to solve weak signal problem?
Now provide the response and nothing else.
| What you are describing is an imbalanced power situation, where one station (the access point) is transmitting at a higher power setting than the others. Increasing the transmit power of the AP will not really increase your coverage as your client has to be able to transmit back to the AP as you indicated. However, if the majority of your traffic is downstream (from AP to client), then this can sometimes increase performance. The reason this can help is that the larger data frames (in this case the majority of traffic) can be transmitted and received more reliably at higher data rates, with less retries/loss. Be careful though as this can also lead to a number of situations where you will actually hurt your performance. For instance, setting the transmit power too high (higher than the manufacturer intended) can increase the distortion of a signal (especially with cheaper hardware). In addition, some hardware will not allow you to increase the transmit power above a certain point, even if the firmware seems to indicate you can. Generally, you are better off using a passive means of producing gain, such as a higher dBi antenna. This will produce an increase for both transmit and receive signal strength. Make sure you understand how this will affect your environment (for instance a higher gain dipole will get you more signal strength on the horizontal/azimuth plane than a lower gain dipole, but it reduce the vertical/elevation providing less coverage above/below the plane of the antenna). As for a repeater being a must to solve weak signal problems, I have found that often repeaters create more problems than they solve. They will typically decrease performance of a busy wireless network and can introduce other problems as well (hidden node, etc). Instead of repeaters, I would recommend additional APs to provide additional coverage. You can do this by planning the placement of the additional APs or using directional/semi-directional antennas forming an "AP array" from a central location. | {} | {'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/3015', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/-1/']} | jdg_72294 |
stackexchange | llm_judgeable_groundtruth_similarity | 22808040 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to create a text fade-out effect when the amount of text is bigger than the row can handle. I am achieving this with the mixture of max-height , overflow and linear-gradient . Something like this. max-height:200px;overflow:hidden;text-overflow: ellipsis;background: -webkit-linear-gradient(#000, #fff); The full fiddle is available . I am trying to achieve effect similar to this one and I am kind of close. The problem is that in my case text start to fade-out from the very beginning and I want it to start fading out only if it is really close to maximum size. Lets say start fading out if it is already 150px. Also I am using only -webkit prefix and I assume that there may be other prefixes that I can add for other rendering engines. Is there a way to do this in pure CSS?
Now provide the response and nothing else.
| Looks like your requirement is just to fade out the text beginning at a certain height (about 150px), the text (if any) presenting at that height is considered as overflow. So you can try using some kind of transparent linear gradient layer placed on top of the text area, we can achieve this in a neat way using the pseudo-element :before like this: .row:before { content:''; width:100%; height:100%; position:absolute; left:0; top:0; background:linear-gradient(transparent 150px, white);} Fiddle | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/22808040', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1090562/']} | jdg_72295 |
stackexchange | llm_judgeable_groundtruth_similarity | 31040 |
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a number of values retrieved from a sampled signal that is generated randomly for no specific purpose. The task I am presented with (Quoted below): calculate the frequency of the highest amplitude wave in each file. Each wave is of fixed frequency. I was asked to calculate the frequency of each wave. How could I do this? Each file contains values of a sampled signal: Seconds,Volts0, 05.096646E-09, 0.022552921.019329E-08, 0.045089861.528994E-08, 0.067594852.038658E-08, 0.090051922.548323E-08, 0.11244523.057988E-08, 0.13475873.567652E-08, 0.15697674.077317E-08, 0.17908354.586981E-08, 0.20106335.096646E-08, 0.22290075.60631E-08, 0.244586.115975E-08, 0.2660866.62564E-08, 0.28740347.135304E-08, 0.30851717.644969E-08, 0.32941218.154633E-08, 0.35007378.664298E-08, 0.37048719.173962E-08, 0.39063799.683627E-08, 0.41051181.019329E-07, 0.43009481.070296E-07, 0.4493731.121262E-07, 0.46833261.172229E-07, 0.48696031.223195E-07, 0.50524291.274161E-07, 0.52316731.325128E-07, 0.54072091.376094E-07, 0.55789131.427061E-07, 0.57466631.478027E-07, 0.59103391.528994E-07, 0.60698261.57996E-07, 0.6225011 The signal goes on and on... This is all the information I have been provided for this task.
Now provide the response and nothing else.
| For digital notch filters, I like to use the following form for a notch filter at DC ( $ \omega $ =0): $$ H(z) = \frac{1+a}{2}\frac{(z-1)}{(z-a)} $$ where $a$ is a real positive number < 1. The closer $a$ is to 1, the tighter the notch (and the more digital precision needed to implement). This is of the form with a zero = 1, and a pole = $a$ , where $a$ is real. The multiplication by $\frac{1+a}{2}$ is just to normalize the magnitude back to 1. To move this to a frequency, rotate the pole and zero to the frequency desired. For a real filter we end up with complex conjugate pole zero pairs, resulting in a 2nd order filter: Defining a digital frequency range of 0 to 2 $\pi$ , with the sampling frequency at $f_s=2\pi$ and the notch frequency is $\omega_n$ , then if we rotated the pole and zero above to $\omega_n$ we would get: $$ H(z) =K\frac{(z-e^{+j\omega_n})(z-e^{-j\omega_n})}{(z-ae^{+j\omega_n})(z-ae^{-j\omega_n})} $$ Multiplying this out and setting $z= -1$ to determine $K$ results in: $$ H(z) = K\frac{z^2-2z\cos\omega_n+1}{(z^2-2az\cos\omega_n+a^2)} $$ $$K = \frac{1+2a\cos(\omega_n)+a^2}{2+2\cos(\omega_n)}$$ So for your case of 50Hz, if we assume a sampling frequency of 1KHz, $\omega_n$ would be: $$ \omega_n =\frac{f_c}{f_s}= \frac{50}{1000}2\pi$$ The coefficient $a$ is chosen to balance precision needed and bandwidth (bandwidth is tighter as $a$ approaches 1), and $cos(\omega_n)$ is a value between +1 and -1 that sets the frequency of the notch (+1 corresponds to DC with $\omega_n=0$ and -1 corresponds to $F_s/2$ with $\omega_n=\pi$ , and any values in between for all frequencies in the first Nyquist zone.) One possible implementation (using transposed Direct Form II) for this transfer function is shown below. For example, see below digital notch filter with $a = .99$ and $\omega_n$ = 0.707. (Frequency axis is normalized where 1 = $f_s/2$ Update: Please see further details including the closed form equation for the bandwidth of the notch for a given $\alpha$ here . | {} | {'log_upvote_score': 5, 'links': ['https://dsp.stackexchange.com/questions/31040', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/21179/']} | jdg_72296 |
stackexchange | llm_judgeable_groundtruth_similarity | 97076 |
Below is a question asked on the forum biology.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The main principle behind a vaccine is to take a deactivated virus, "show" it to the immune system so it can "learn" how it looks like, so if and when the real virus does attack us, our immune system is already prepared for it. Vaccines have been developed using this idea even in the 1880's. If that's the case, why does it take so much time and effort to develop a vaccine, for example, against covid-19? (and why are there several variants with different measures of reliability?) Is it only about balancing how strongly we damage the original pathogen, too much damage and our body might not learn the correct identifiers, and to little damage and it might still be active enough to cause the disease?
Now provide the response and nothing else.
| Roni Saiba's answer does a good job of explaining what goes into current vaccine development and why it takes so much effort, but I want to directly address the question of why we can't just grow some virus, kill it with UV and have a protective vaccine. The answer is that not all immune responses to viral antigens are helpful in fighting infections of that virus. In some cases it can be harmful; antibodies to dengue virus of one serotype will attach to viral particles of another serotype but aren't able to inactivate them. The attachment of antibodies to active viruses makes their absorption by cells more efficient, and infections where this antibody-dependent enhancement occurs are more severe than first-time dengue infections. Some viruses have evolved mechanisms to capitalize on this. The reason we need to get a new flu shot every year is that influenza viruses present a "knob" at the end of their glycoprotein that can change its structure and still retain function. This part is much more 'visible' to the immune system than parts of the virus that can't tolerate changes, so the immune response to this variable part outcompetes and prevents an immune response that would provide long-lasting protection. Conserved stalk-targeting vaccines are being intensely investigated for this reason. SARS-CoV-2 may have a immune-faking mechanism as well: the "spike" glycoproteins responsible for binding the ACE2 receptor and entering the cell convert to their post-binding form prematurely part of the time. Antibodies that bind the "post-fusion" form of the protein don't inactivate the virus, and this form sticks out more so may serve to compete for immune attention with the pre-fusion form that would provide protection if bound by antibodies. In this last example, we can see that a vaccine made of killed SARS-CoV-2 virus particles would be useless if all of the spike proteins had converted to the post-fusion state. The mRNA vaccines therefore don't encode the natural spike protein, but a mutated version which can't convert to the post fusion state as easily: S-2P is stabilized in its prefusion conformation by two consecutive proline substitutions at amino acid positions 986 and 987 In conclusion, viruses and the immune system are very complicated. Simple vaccines work for some viruses, and don't work for others. When they don't work, the reason is always different, but hopefully I've communicated some general understanding of the background issues. EDITS:This doesn't relate to the rest of my answer but I want to respond to Ilmari Karonen's and there is not enough room in a comment. Looking at the timeline for SARS-CoV-2 vaccine development gives a very misleading impression of how long it takes generally. This is because ~90% of the development work was already done before COVID-19 was ever identified, in the 18 years since the SARS-CoV-1 outbreak started in 2002. Vaccines against SARS were developed and tested up to phase I trials, but couldn't proceed further since the virus was eliminated. I discussed this in a previous answer to a similar question , but to expand/reformat, here's some of what we knew and had available on March 17th 2020, when the "covid vaccine timeline" begins: Identified the receptor as ACE2, and knew that antibodies targeting the receptor binding domain (RBD) of the spike protein neutralize the virus. Protocols to test that these were also true of SARS-CoV-2 were already developed and validated. Without this there would have been a lot more trial-and-error experimentation and false starts with vaccine candidates that looked promising but didn't pan out in testing. Animal models. There is no naturally-occurring model organism for COVID-19. This is a subtle point because other animals can be infected with the virus, and some develop morbidities because of it. However, these are different enough from what we see in humans that something that protects against the reactions we see in the animal can't be assumed to protect against the reactions that cause problems in humans. For SARS, researchers developed transgenic mice that used the human version of ACE2, and showed that the disease they got from SARS were analogous to the disease humans got. This took several years, and the colony was still available when the virus causing the outbreak in Wuhan was identified as SARS-like and researchers started looking for animal models. As an aside, in an interview on This Week in Virology that I can't find right now, one of the maintainers of that colony said they were months or weeks away from shutting it down and euthanizing all the transgenic mice when the pandemic began, so if funding had been just a bit tighter we probably would not be having this particular conversation now. How to stabilize the pre-fusion form of coronavirus spike proteins had been determined from work on SARS and MERS vaccines. In addition to these, a large amount of miscellaneous knowledge about coronavirus functions and the immune reactions to them had been accumulated, and this sped up development, and increased confidence in results, which allows vaccine candidate production and testing to proceed more aggressively. Historically, vaccine development has taken years or decades of research after the need has been identified. Testing is still longer in many cases, but the current case is very unusual. | {} | {'log_upvote_score': 6, 'links': ['https://biology.stackexchange.com/questions/97076', 'https://biology.stackexchange.com', 'https://biology.stackexchange.com/users/3798/']} | jdg_72297 |
stackexchange | llm_judgeable_groundtruth_similarity | 1489713 |
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 need to find all holomorphic functions on $\mathbb{C}$ such that $f(z^2)=(f(z))^2$.I'm familiar with the Cauchy-Riemann equations, but I'm stuck with this problem. Any hints?
Now provide the response and nothing else.
| The definition can be read, in human words: For every positive $\epsilon$, there exists such a positive $\delta$ that if $|x-c|$ is smaller than $\delta$, but larger than $0$, then $|f(x) - L|$ is smaller than $\epsilon$. First of all, lets's get the double inequality out of the way. Basically, $0<|x-c|$ is just saying that $|x-c|$ is not equal to $0$ (since it can't be negative), and saying that is just saying that $x-c$ cannot be $0$, or in other words, that $x$ is not allowed to equal $c$. Now to a non-mathematician, that still makes very little sense, but take into account that $|a-b|$ is really the distance between numbers $a$ and $b$. So, we can translate the definition into For every positive $\epsilon$, there exists such a positive $\delta$ that if $x$ and $c$ are two distinct numbers and the distance between them is smaller than $\delta$, then the distance between $f(x)$ and $L$ is smaller than $\epsilon$. But that still does not ring quite "natural" But what does the "for all $\epsilon$, there exists a $\delta$" in the beginning mean anyway? Well it means that whatever $\epsilon$ you give me, I can find a $\delta$ such that the condition will be true. So: No matter what $\epsilon$ you choose, I can find such a positive $\delta$ that whenever you take any $x$ near (but not equal to) $c$ that is less than $\delta$ away from $c$ which are closer together than $\delta$, $f(x)$ will be closer than $\epsilon$ away from $L$. Getting warmer to something readable? Well, let's get rid of the variables even further: No matter how close you want $f(x)$ to be to $L$, I can tell you how close to $c$ you need to pick your $x$, and if you pick your $x$ that closely, then I can guarantee that $f(x)$ will be as close to $L$ as you originally wanted it to be. This is very similar to what MPW wrote in comments: $f(x)$ can be made arbitrarily close to $L$ by taking $x$ sufficiently close to $c$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1489713', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/231497/']} | jdg_72298 |
stackexchange | llm_judgeable_groundtruth_similarity | 457903 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm studying about Newton's method and I get the single dimension case perfectly, but the multidimensional version makes me ask question... In Wikipedia Newton's method in higher dimensions is defined as: $$\textbf{x}_{n+1} = \textbf{x}_n - [Hf(\textbf{x}_n)]^{-1}\nabla f(\textbf{x}_n), \;\;\; n \geq 0.$$ Where $\textbf{x}_n$ is the $p$-dimensional vector at $n$th iteration, $[Hf(\textbf{x}_n)]^{-1}$ is the inverse of the Hessian matrix of the function $f(\textbf{x})$ at $\textbf{x}_n$ and $\nabla f(\textbf{x}_n)$ is the gradient of the function $f(\textbf{x})$ at $\textbf{x}_n$. That is: $$\left( \begin{array}{c}x_1^{(n+1)} \\x_2^{(n+1)} \\\vdots \\x_p^{(n+1)} \end{array} \right) = \left( \begin{array}{c}x_1^{(n)} \\x_2^{(n)} \\\vdots \\x_p^{(n)} \end{array} \right) - \left( \begin{array}{cccc}\frac{\partial^2f}{\partial x_1^2}(\textbf{x}_n) & \dots & \dots &\frac{\partial^2f}{\partial x_p\partial x_1}(\textbf{x}_n)\\\frac{\partial^2f}{\partial x_1\partial x_2}(\textbf{x}_n) & \ddots & \vdots & \vdots\\\vdots & \vdots & \vdots & \vdots\\\frac{\partial^2f}{\partial x_1\partial x_p}(\textbf{x}_n) & \dots & \dots & \frac{\partial^2f}{\partial x_p^2}(\textbf{x}_n) \end{array} \right)^{-1}\left( \begin{array}{c}\frac{\partial f}{\partial x_1}(\textbf{x}_n) \\\frac{\partial f}{\partial x_2}(\textbf{x}_n) \\\vdots \\\frac{\partial f}{\partial x_p}(\textbf{x}_n) \end{array} \right)$$ Now my question is: "What is the intuition behind this formula?" This resembles somehow the gradient descent algorithm, but the inverse of the Hessian is like it came from the magician's hat :S Can somebody give me a similar kind of proof as is given here on the one-dimensional case: Why does Newton's method work? Why the Hessian? Why its inverse?! :) Intuition of the formula? Thank you for any help :) P.S. I here is the page I got the formula above: http://en.wikipedia.org/wiki/Newton%27s_method_in_optimization#Higher_dimensions Note also that in my notation the topscript in the $x_i$s doesn't mean exponent, it's just an iteration label...
Now provide the response and nothing else.
| I'll assume we're trying to minimize a twice continuously differentiable function $f$ defined on $\mathbb R^p$. We wish to find $x$ such that $\nabla f(x) = 0$. Given $x_n$, we would ideally like to find $\Delta x$ such that $\nabla f(x_n + \Delta x) = 0$. Rather than satisfying this requirement exactly (which would probably be too difficult), we instead use the approximation\begin{equation*}\nabla f(x_n + \Delta x) \approx \nabla f(x_n) + Hf(x_n) \Delta x.\end{equation*}Setting the right hand side equal to $0$ gives us\begin{equation*}\Delta x = -Hf(x_n)^{-1} \nabla f(x_n).\end{equation*}We can hope that $x_{n+1} = x_n + \Delta x$ will be an improvement on $x_n$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/457903', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/53500/']} | jdg_72299 |
stackexchange | llm_judgeable_groundtruth_similarity | 9536827 |
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 generate a Key from a string, such that I can always create the same key from the same string. (Specifically a Key object, so that I can use it to create a Cipher in turn to create a SealedObject) Is this possible in Java, and what class/method combination should I be looking at to do so?
Now provide the response and nothing else.
| For AES encryption: SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);SecretKey tmp = factory.generateSecret(spec);SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");cipher.init(Cipher.ENCRYPT_MODE, secret);byte[] iv = cipher.getParameters().getParameterSpec(IvParameterSpec.class).getIV();byte[] ciphertext = cipher.doFinal("Hello, World!".getBytes("UTF-8"));// reinit cypher using param specCipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv)); Similarly for the deprecated PBKDF1 and insecure DES for communicating with legacy systems or learning purposes : byte[] salt = { (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c, (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99};int count = 20;PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES");cipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);SealedObject sealed = new SealedObject(object, cipher);... Note that the iteration count is too low as well in the last example. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9536827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1080648/']} | jdg_72300 |
stackexchange | llm_judgeable_groundtruth_similarity | 29112071 |
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 for several months to create a simple SNTP single Client/Server based on RFC5905 . Finally I manage to make it work at least I think it works correctly, but when I tried to test my code against a real NTP server (e.g. 0.se.pool.ntp.org:123) the timestamps that I am receiving need to be recalculated. I have tried several different approaches but no matter for 3 days now but no matter what I tried nothing yet. Does anybody know how to convert the NTP timestamp to Unix epoch timestamp? Syntax to execute the Server e.g. ./server 127.0.0.1:5000 and Client e.g. ./client 127.0.0.1:5000 Syntax to execute the Client against a real NTP server e.g. ./client 0.se.pool.ntp.org:123 Sample of working code Client: #include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <errno.h>#include <string.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <netdb.h>#include <time.h>#include <math.h>#include <sys/timeb.h>#include <inttypes.h>#include <limits.h>#include <assert.h>#define UNIX_EPOCH 2208988800UL /* 1970 - 1900 in seconds */typedef struct client_packet client_packet;struct client_packet { uint8_t client_li_vn_mode; uint8_t client_stratum; uint8_t client_poll; uint8_t client_precision; uint32_t client_root_delay; uint32_t client_root_dispersion; uint32_t client_reference_identifier; uint32_t client_reference_timestamp_sec; uint32_t client_reference_timestamp_microsec; uint32_t client_originate_timestamp_sec; uint32_t client_originate_timestamp_microsec; uint32_t client_receive_timestamp_sec; uint32_t client_receive_timestamp_microsec; uint32_t client_transmit_timestamp_sec; uint32_t client_transmit_timestamp_microsec;}__attribute__((packed));typedef struct server_send server_send;struct server_send { uint8_t server_li_vn_mode; uint8_t server_stratum; uint8_t server_poll; uint8_t server_precision; uint32_t server_root_delay; uint32_t server_root_dispersion; char server_reference_identifier[4]; uint32_t server_reference_timestamp_sec; uint32_t server_reference_timestamp_microsec; uint32_t server_originate_timestamp_sec; uint32_t server_originate_timestamp_microsec; uint32_t server_receive_timestamp_sec; uint32_t server_receive_timestamp_microsec; uint32_t server_transmit_timestamp_sec; uint32_t server_transmit_timestamp_microsec;}__attribute__((packed));/* Linux man page bind() */#define handle_error(msg) \ do {perror(msg); exit(EXIT_FAILURE);} while (0)uint32_t ClockGetTime() { struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); return (uint32_t)ts.tv_sec * 1000000LL + (uint32_t)ts.tv_nsec / 1000LL;}int main(int argc, char *argv[]) { int sockfd , numbytes; struct addrinfo hints, *servinfo, *p; int rv; client_packet memsend; server_send memrcv; memset( &memsend , 0 , sizeof memsend ); memset( &memrcv , 0 , sizeof memrcv ); char IP[16]; /* IP = 15 digits 1 extra for \0 null terminating character string */ char PORT_STR[6]; /* Port = 5 digits MAX 1 extra for \0 null terminating character string */ memset(IP , '\0' , sizeof(IP)); memset(PORT_STR , '\0' , sizeof(PORT_STR)); strcpy(IP, strtok(argv[1], ":")); strcpy(PORT_STR, strtok(NULL, ":")); memset( &hints , 0 , sizeof hints ); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; if ( ( rv = getaddrinfo( IP , PORT_STR , &hints , &servinfo ) ) != 0 ) { fprintf( stderr , "getaddrinfo: %s\n" , gai_strerror(rv) ); return 1; } // loop through all the results and make a socket for( p = servinfo; p != NULL; p = p->ai_next ) { if ( ( sockfd = socket( p->ai_family , p->ai_socktype , p->ai_protocol ) ) == -1 ) { handle_error( "socket" ); continue; } break; } if (p == NULL) { fprintf(stderr, "Error while binding socket\n"); return 2; } memsend.client_li_vn_mode = 0b00100011; memsend.client_stratum = 0; memsend.client_poll = 0; memsend.client_precision = 0; memsend.client_root_delay = 0; memsend.client_root_dispersion = 0; memsend.client_reference_identifier = 0; memsend.client_reference_timestamp_sec = 0; memsend.client_reference_timestamp_microsec = 0; memsend.client_receive_timestamp_sec = 0; memsend.client_receive_timestamp_microsec = 0; time_t time_originate_sec = time(NULL); memsend.client_originate_timestamp_sec = time_originate_sec; memsend.client_originate_timestamp_microsec = ClockGetTime(); memsend.client_transmit_timestamp_sec = memsend.client_originate_timestamp_sec; memsend.client_transmit_timestamp_microsec = memsend.client_originate_timestamp_microsec; if ( ( numbytes = sendto( sockfd, &memsend , sizeof memsend , 0 , p->ai_addr , p->ai_addrlen ) ) == -1 ) { handle_error("sendto"); exit(1); } if ( ( numbytes = recvfrom( sockfd , &memrcv , sizeof memrcv , 0 , (struct sockaddr *) &p->ai_addr, &p->ai_addrlen ) ) == -1 ) { handle_error( "recvfrom" ); exit(1); } time_t time_rcv_sec = time(NULL); uint32_t client_rcv_timestamp_sec = time_rcv_sec; uint32_t client_rcv_timestamp_microsec = ClockGetTime(); freeaddrinfo(servinfo); char Identifier[5]; memset(Identifier , '\0' , sizeof Identifier); memcpy(Identifier , memrcv.server_reference_identifier , sizeof memrcv.server_reference_identifier); printf("\t Reference Identifier \t %"PRIu32" \t\t\t %s\n",memsend.client_reference_identifier,Identifier); printf("\t Reference Timestamp \t %"PRIu32".%"PRIu32" \t\t\t %"PRIu32".%"PRIu32"\n",memsend.client_reference_timestamp_sec,memsend.client_reference_timestamp_microsec,memrcv.server_reference_timestamp_sec,memrcv.server_reference_timestamp_microsec); printf("\t Originate Timestamp \t %"PRIu32".%"PRIu32" \t %"PRIu32".%"PRIu32"\n",memsend.client_originate_timestamp_sec,memsend.client_originate_timestamp_microsec,memrcv.server_originate_timestamp_sec,memrcv.server_originate_timestamp_microsec); printf("\t Receive Timestamp \t %"PRIu32".%"PRIu32" \t %"PRIu32".%"PRIu32"\n",client_rcv_timestamp_sec,client_rcv_timestamp_microsec,memrcv.server_receive_timestamp_sec,memrcv.server_receive_timestamp_microsec); printf("\t Transmit Timestamp \t %"PRIu32".%"PRIu32" \t %"PRIu32".%"PRIu32"\n\n",memsend.client_transmit_timestamp_sec,memsend.client_transmit_timestamp_microsec,memrcv.server_transmit_timestamp_sec,memrcv.server_transmit_timestamp_microsec); close(sockfd); return 0;} Sample of Server code: #include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <errno.h>#include <string.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <netdb.h>#include <time.h>#include <math.h>#include <sys/timeb.h>#include <inttypes.h>#include <limits.h>#define TRUE 1typedef struct client_send client_send;struct client_send { uint8_t client_li_vn_mode; uint8_t client_startum; uint8_t client_poll; uint8_t client_precision; uint32_t client_root_delay; uint32_t client_root_dispersion; uint32_t client_reference_identifier; uint32_t client_reference_timestamp_sec; uint32_t client_reference_timestamp_microsec; uint32_t client_originate_timestamp_sec; uint32_t client_originate_timestamp_microsec; uint32_t client_receive_timestamp_sec; uint32_t client_receive_timestamp_microsec; uint32_t client_transmit_timestamp_sec; uint32_t client_transmit_timestamp_microsec;}__attribute__((packed));typedef struct server_packet server_packet;struct server_packet { uint8_t server_li_vn_mode; uint8_t server_startum; uint8_t server_poll; uint8_t server_precision; uint32_t server_root_delay; uint32_t server_root_dispersion; char server_reference_identifier[4]; uint32_t server_reference_timestamp_sec; uint32_t server_reference_timestamp_microsec; uint32_t server_originate_timestamp_sec; uint32_t server_originate_timestamp_microsec; uint32_t server_receive_timestamp_sec; uint32_t server_receive_timestamp_microsec; uint32_t server_transmit_timestamp_sec; uint32_t server_transmit_timestamp_microsec;}__attribute__((packed));/* Linux man page bind() */#define handle_error(msg) \ do {perror(msg); exit(EXIT_FAILURE);} while (0)uint32_t ClockGetTime() { struct timespec ts; clock_gettime(CLOCK_REALTIME, &ts); return (uint32_t)ts.tv_sec * 1000000LL + (uint32_t)ts.tv_nsec / 1000LL;}unsigned long int precision() { struct timespec res; if ( clock_getres( CLOCK_REALTIME, &res) == -1 ) { perror( "clock get resolution" ); return EXIT_FAILURE; } return res.tv_nsec / 1000;}void *get_in_addr(struct sockaddr *sa) { if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*)sa)->sin_addr); } return &(((struct sockaddr_in6*)sa)->sin6_addr);}int main(int argc, char *argv[]) { server_packet send_mem; client_send rcv_mem; /* Empty structs */ memset( &send_mem , 0 , sizeof send_mem ); memset( &rcv_mem , 0 , sizeof rcv_mem ); char s[INET_ADDRSTRLEN]; struct addrinfo hints, *servinfo, *p; struct sockaddr_storage their_addr; socklen_t addr_len; int get, numbytes; int sockfd; char IP[16]; char PORT_STR[6]; memset(IP , '\0' , sizeof(IP)); memset(PORT_STR , '\0' , sizeof(PORT_STR)); strcpy(IP, strtok(argv[1], ":")); strcpy(PORT_STR, strtok(NULL, ":")); memset( &hints , 0 , sizeof hints ); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_flags = AI_PASSIVE; hints.ai_protocol = IPPROTO_UDP; if ( ( get = getaddrinfo( NULL , PORT_STR , &hints , &servinfo ) ) != 0) { fprintf( stderr , "getaddrinfo: %s\n" , gai_strerror(get) ); return 1; } for( p = servinfo; p != NULL; p = p->ai_next ) { if ( ( sockfd = socket( p->ai_family , p->ai_socktype , p->ai_protocol ) ) == -1 ) { handle_error("socket"); continue; } if ( bind( sockfd , p->ai_addr , p->ai_addrlen ) == -1 ) { close(sockfd); handle_error("bind"); continue; } break; } if (p == NULL) { fprintf(stderr, "Not able to bind socket\n"); return 2; } freeaddrinfo(servinfo); printf("\nServer is up and running: waiting to recv msg at port: %s...\n", PORT_STR); while(TRUE) { time_t t_ref_sec = time(NULL); unsigned long int Ref_epoc_sec = t_ref_sec; send_mem.server_reference_timestamp_sec = Ref_epoc_sec; unsigned long int t_ref_nanosec = ClockGetTime(); send_mem.server_reference_timestamp_microsec = t_ref_nanosec; addr_len = sizeof(their_addr); if ((numbytes = recvfrom(sockfd, &rcv_mem , sizeof rcv_mem , 0, (struct sockaddr *)&their_addr, &addr_len)) == -1) { handle_error("recvfrom"); exit(1); } time_t t_rcv_sec = time(NULL); send_mem.server_receive_timestamp_sec = t_rcv_sec; send_mem.server_receive_timestamp_microsec = ClockGetTime(); printf("Peer address: %s\n", inet_ntop(their_addr.ss_family, get_in_addr((struct sockaddr *)&their_addr), s, sizeof(s))); printf("Peer port: %i\n",p->ai_socktype); send_mem.server_li_vn_mode = 0b00100100; send_mem.server_startum = 0b00000001; send_mem.server_poll = 0b00000110; send_mem.server_precision = precision(); send_mem.server_root_delay = 0; send_mem.server_root_dispersion = 0; memcpy( send_mem.server_reference_identifier , "LOCL" , sizeof send_mem.server_reference_identifier ); send_mem.server_originate_timestamp_sec = rcv_mem.client_originate_timestamp_sec; send_mem.server_originate_timestamp_microsec = rcv_mem.client_originate_timestamp_microsec; time_t t_send_sec = time(NULL); send_mem.server_transmit_timestamp_sec = t_send_sec; send_mem.server_transmit_timestamp_microsec = ClockGetTime(); if ( sendto( sockfd, &send_mem , sizeof send_mem , 0 , (struct sockaddr *) &their_addr , addr_len ) == -1 ) { handle_error("sendto"); exit(1); } } close(sockfd); return 0;} Sample of printed output when I use Server and Client. Reference Identifier 0 LOCLReference Timestamp 0.0 1426637081.3564398733Originate Timestamp 1426637087.3570333925 1426637087.3570333925Receive Timestamp 1426637087.3570334078 1426637087.3570334003Transmit Timestamp 1426637087.3570333925 1426637087.3570334046 Sample of printed output when I am probing a real NTP server (e.g. 0.se.pool.ntp.org:123). Reference Identifier 0 �$�Reference Timestamp 0.0 3879449560.3503094062Originate Timestamp 1426637090.3573978972 1426637090.3573978972Receive Timestamp 1426637090.3573992772 2722083800.781009125Transmit Timestamp 1426637090.3573978972 2722083800.937312997 The expected output would be something similar to print out as I posted before. Thank you in advance for everyones time and effort to assist me. Update Relevant question but not close to the answer that I am looking for How to write a NTP client? [closed] .
Now provide the response and nothing else.
| converting NTP timestamps to Unix timestamps (struct timeval) involves two problems to be solved. One is the offset between the two epochs. Unix uses an epoch located at 1/1/1970-00:00h (UTC) and NTP uses 1/1/1900-00:00h. This leads to an offset equivalent to 70 years in seconds (there are 17 leap years between the two dates so the offset is (70*365 + 17)*86400 = 2208988800 to be substracted from NTP time to get Unix struct timeval . The second is that struct timeval uses 1/1000000 sec as unit of subsecond fractions and NTP uses 1/2^32 sec as its unit of fractional time. To convert from NTP to struct timeval one might divide the fractional part by 2^32 (this is easy, it's a right shift) and then multiply by 1000000 . To cope with this, we have to use 64 bit arithmetic, as numbers range between 0 and 2^32 so, the best is: to convert from NTP to struct timeval copy the fractional part field (the right 32 bits of a NTP timestamp) to a uint64_t variable and multiply it by 1000000 , then right shift it by 32 bit positions to get the proper value. You must take into account that NTP timestamps are in network byte order, so perhaps you'll have to make some adjustments to be able to operate with the numbers. To convert from struct timeval copy the tv_usec field of the unix time to a uint64_t and left shift it 32 bit positions, then divide it by 1000000 and convert to network byte order (most significative byte first) The following code sample illustrates this. #include <stdio.h>#include <stdlib.h>#include <time.h>#include <stdint.h>#include <getopt.h>#define OFFSET 2208988800ULLvoid ntp2tv(uint8_t ntp[8], struct timeval *tv){ uint64_t aux = 0; uint8_t *p = ntp; int i; /* we get the ntp in network byte order, so we must * convert it to host byte order. */ for (i = 0; i < sizeof ntp / 2; i++) { aux <<= 8; aux |= *p++; } /* for */ /* now we have in aux the NTP seconds offset */ aux -= OFFSET; tv->tv_sec = aux; /* let's go with the fraction of second */ aux = 0; for (; i < sizeof ntp; i++) { aux <<= 8; aux |= *p++; } /* for */ /* now we have in aux the NTP fraction (0..2^32-1) */ aux *= 1000000; /* multiply by 1e6 */ aux >>= 32; /* and divide by 2^32 */ tv->tv_usec = aux;} /* ntp2tv */void tv2ntp(struct timeval *tv, uint8_t ntp[8]){ uint64_t aux = 0; uint8_t *p = ntp + sizeof ntp; int i; aux = tv->tv_usec; aux <<= 32; aux /= 1000000; /* we set the ntp in network byte order */ for (i = 0; i < sizeof ntp/2; i++) { *--p = aux & 0xff; aux >>= 8; } /* for */ aux = tv->tv_sec; aux += OFFSET; /* let's go with the fraction of second */ for (; i < sizeof ntp; i++) { *--p = aux & 0xff; aux >>= 8; } /* for */} /* ntp2tv */size_t print_tv(struct timeval *t){ return printf("%ld.%06ld\n", t->tv_sec, t->tv_usec);}size_t print_ntp(uint8_t ntp[8]){ int i; int res = 0; for (i = 0; i < sizeof ntp; i++) { if (i == sizeof ntp / 2) res += printf("."); res += printf("%02x", ntp[i]); } /* for */ res += printf("\n"); return res;} /* print_ntp */int main(int argc, char *argv[]){ struct timeval t; uint8_t ntp[8]; gettimeofday(&t, NULL); printf("tv2ntp\n"); tv2ntp(&t, ntp); printf("tv : "); print_tv(&t); printf("ntp: "); print_ntp(ntp); printf("ntp2tv\n"); ntp2tv(ntp, &t); printf("tv : "); print_tv(&t); printf("ntp: "); print_ntp(ntp);} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29112071', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2418001/']} | jdg_72301 |
stackexchange | llm_judgeable_groundtruth_similarity | 7995212 |
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 recently started using Eclipse IDE and have read at a number of places that one shouldn't use the default(src) package and create new packages. I just wanted to know the reason behind this.
Now provide the response and nothing else.
| Using the default package may create namespace collisions. Imagine you're creating a library which contains a MyClass class. Someone uses your library in his project and also has a MyClass class in his default package. What should the compiler do? Package in Java is actually a namespace which fully identifies your project. So it's important to not use the default package in the real world projects. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7995212', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1014342/']} | jdg_72302 |
stackexchange | llm_judgeable_groundtruth_similarity | 26532081 |
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 solve the codility MissingInteger problem link : Write a function: class Solution { public int solution(int[] A); } that, given a non-empty zero-indexed array A of N integers, returns the minimal positive integer that does not occur in A. For example, given: A[0] = 1 A[1] = 3 A[2] = 6 A[3] = 4 A[4] = 1 A[5] = 2 the function should return 5. Assume that: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [−2,147,483,648..2,147,483,647]. Complexity: expected worst-case time complexity is O(N); expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments). Elements of input arrays can be modified. My solution is: class Solution { TreeMap<Integer,Object> all = new TreeMap<Integer,Object>(); public int solution(int[] A) { for(int i=0; i<A.length; i++) all.put(i+1,new Object()); for(int i=0; i<A.length; i++) if(all.containsKey(A[i])) all.remove(A[i]); Iterator notOccur = all.keySet().iterator(); if(notOccur.hasNext()) return (int)notOccur.next(); return 1; }} The test result is: Can anyone explain me why I got this two wrong answers? Especially the first one, if there is only one element in the array, shouldn't the only right answer be 1?
Now provide the response and nothing else.
| returns the minimal positive integer that does not occur in A. So in an array with only one element, if that number is 1, you should return 2. If not, you should return 1. I think you're probably misunderstanding the requirements a little. Your code is creating keys in a map based on the indexes of the given array, and then removing keys based on the values it finds there. This problem shouldn't have anything to do with the array's indexes: it should simply return the lowest possible positive integer that isn't a value in the given array. So, for example, if you iterate from 1 to Integer.MAX_VALUE , inclusive, and return the first value that isn't in the given array, that would produce the correct answers. You'll need to figure out what data structures to use, to ensure that your solution scales at O(n) . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26532081', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3878104/']} | jdg_72303 |
stackexchange | llm_judgeable_groundtruth_similarity | 21943 |
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:
We're all familiar with the Java package name convention of turning the domain name around. I.e. www.evilcorp.com would, by convention, chose to have their java packages com.evilcorp.stuff . Increasingly I'm getting fed up with this. As a commercial programmer, I encounter time and again that the software package name is completely irrelevant due to some rebrand, acquisition or similar. In the opensource world there's less name changes so there it makes sense. However it seems to me the shelf life of many pieces of (commercial/internal) software are much longer than that of the organisation making them. The problem is often made worse by software projects taking the marketing department's lead to use the name du jour they use refer to a certain project. A name that will, without fail, change 3 months down the line to make the emperor's new clothes feel fresh and new. Because of this, I've mostly stopped using the reverse domain as package name. Granted, if this is done on a large scale, there's risk of name collisions, but surely this is mitigated by either using "unique" software names, avoiding generic words, or use the reverse domain for projects intended to be sold/released as libraries. Other thoughts?
Now provide the response and nothing else.
| I'm going to quote the advice Microsoft gives for namespaces (.NET's packages), which doesn't have the domain name convention. I think it's good advice for Java packages too, since I don't believe that a domain name represents a solid and stable identity. The general format for a namespace name is as follows: <Company>.(<Product>|<Technology>)[.<Feature>][.<Subnamespace>] For example, Microsoft.WindowsMobile.DirectX . Do prefix namespace names with a company name to prevent namespaces from different companies from having the same name and prefix. Do use a stable, version-independent product name at the second level of a namespace name. Do not use organizational hierarchies as the basis for names in namespace hierarchies, because group names within corporations tend to be short-lived. The namespace name is a long-lived and unchanging identifier. As organizations evolve, changes should not make the namespace name obsolete. If even your company name is unstable, you might want to just start with the product name. | {} | {'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/21943', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/8688/']} | jdg_72304 |
stackexchange | llm_judgeable_groundtruth_similarity | 171005 |
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:
A quick google for " 3v to 5v transistor " gives me dozens of circuit diagrams that look like option A below with a NPN transistor and a pull-up resistor. If I build the diagram in iCircult, it works as expected. However, when I wire it up on a breadboard, it doesn't work quite the way it should. Without any power to the base, I get Vout = 4.95v. With power to the base I get Vout = 0v so it is inverting my wave. A few experiments later, I solve my problem using a PNP transistor and a pull-down resistor (option B). In both cases I am taking Vout from the Collector side of the transistor. It's a pretty simple circuit, you'd think it would just work. I double and triple checked the connections. I have also posted a photo of the breadboard below. I always seem to have weird problems like this when working with transistors, so now I am sort of on a quest to understand why option A doesn't work like it should for me?
Now provide the response and nothing else.
| Both circuits invert your input signal. The second one will not work properly. If you want a non-inverting level shifter you can use this circuit: simulate this circuit – Schematic created using CircuitLab When the input is close to 3.3V, the transistor is off and R2 pulls the output up to 5V. When the input is close to ground, the transistor is saturated and the output is equal to the input plus maybe 50mV. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/171005', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/53740/']} | jdg_72305 |
stackexchange | llm_judgeable_groundtruth_similarity | 23535704 |
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 put image instead text in ActionLink button: @Html.ActionLink("Edit-link", "Edit", new { id=use.userID }) So how to change text "Edit-link" to image? Thanks for any idea.
Now provide the response and nothing else.
| do like this: <a href="@Url.Action("Edit")" id="@use.userID"><img src="@Url.Content("~/images/someimage.png")" /></a> or pass both action and controller name by using other override: <a href="@Url.Action("Edit","Controller")" id="@use.userID"> <img src="@Url.Content("~/images/someimage.png")" /> </a> UPDATE: You can also create a custom Html Helper , and can reuse it in any View in application: namespace MyApplication.Helpers{ public static class CustomHtmlHelepers { public static IHtmlString ImageActionLink(this HtmlHelper htmlHelper, string linkText, string action, string controller, object routeValues, object htmlAttributes,string imageSrc) { var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext); var img = new TagBuilder("img"); img.Attributes.Add("src", VirtualPathUtility.ToAbsolute(imageSrc)); var anchor = new TagBuilder("a") { InnerHtml = img.ToString(TagRenderMode.SelfClosing) }; anchor.Attributes["href"] = urlHelper.Action(action, controller, routeValues); anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes)); return MvcHtmlString.Create(anchor.ToString()); } }} and use it in View: @using MyApplication.Helpers;@Html.ImageActionLink("LinkText","ActionName","ControllerName",null,null,"~/images/untitled.png") Output HTML: <a href="/ControllerName/ActionName"> <img src="/images/untitled.png"></a> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23535704', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3493876/']} | jdg_72306 |
stackexchange | llm_judgeable_groundtruth_similarity | 2600663 |
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_{i\tilde i} \in \mathbb{R}^{d^2},B_{j\tilde j} \in \mathbb{R}^{n^2}$ be real invertible square matrices. Define $$ C_{ij,\tilde i\tilde j}:=A_{i\tilde i} B_{j\tilde j}$$ and suppose that $C_{ij,\tilde i\tilde j}=C_{\tilde i\tilde j,ij}$, that is$$ A_{i\tilde i} B_{j\tilde j}=A_{\tilde i i} B_{\tilde j j},$$ for all $i,\tilde i,j,\tilde j$. Is it true that $A,B$ are symmetric, that is $A_{\tilde i i}=A_{i\tilde i}, B_{j\tilde j}=B_{\tilde j j}$ (More abstractly, the question is the following: suppose a tensor product of two non-degenerate bilinear forms is symmetric. Is it true that the factros are symmetric?)
Now provide the response and nothing else.
| $x^2>y^2$, then, $x^2-y^2>0$ but this is equal to $(x-y)(x+y)>0$. We know that $x,y> 0$, then, $x+y>0$ and because $(x-y)(x+y)>0$, thus $x-y>0$. This is equivalent to $x>y$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2600663', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/104576/']} | jdg_72307 |
stackexchange | llm_judgeable_groundtruth_similarity | 11990090 |
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 know how to do a pull from repo based on a SHA? git pull origin master the above code will pull master once we've done git add remote .
Now provide the response and nothing else.
| A git pull does two things for you: Fetches a specific branch from the repository Merges it with your current branch. It sounds like what you want to do is to get a specific revision from the repository and merge it with your current branch. The best way to do this is two commands: git fetch origingit merge YOUR_SHA_HERE If what you want is just to see what's in a specific revision from the repository and make it the working tree, but not do a merge, then you would want: git fetch origingit checkout YOUR_SHA_HERE If what you want is to get the specific version, and make it the new "master" (or another branch), then you would want to run git fetch origingit reset --hard YOUR_SHA_HERE All of these will fetch new code from the repository (via the 'git fetch origin'), but then there are different ways to combine with / replace your current code. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11990090', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1471938/']} | jdg_72308 |
stackexchange | llm_judgeable_groundtruth_similarity | 18282328 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Consider the problem above where the 'CommonChild' entity can be a child of either sub-type A or B, but not C. How would I go about designing the physical model in a relational [SQL] database? Ideally, the solution would allow... for an identifying relationship between CommonChild and it's related sub-type. a 1:N relationship. Possible Solutions Add an additional sub-type to the super-type and move sub-type A and B under the new sub-type. The CommonChild can then have a FK constraint on the newly created sub-type. Works for the above, but not if an additional entity is added which can have a relationship with sub-type A and C, but not B. Add a FK constraint between the CommonChild and SuperType. Use a trigger or check constraint (w/ UDF) against the super-type's discriminator before allowing a new tuple into CommonChild. Seems straight forward, but now CommonChild almost seems like new subtype itself (which it is not). My model is fundamentally flawed. Remodel and the problem should go away. I'm looking for other possible solutions or confirmation of one of the above solutions I've already proposed. Thanks! EDIT I'm going to implement the exclusive foreign key solution provided by Branko Dimitrijevic (see accepted answer). I am going to make a slight modifications in this case as: the super-type, sub-type, and "CommonChild" all have the same PKs and; the PKs are 3 column composites. The modification is to to create an intermediate table whose sole role is to enforce the exclusive FK constraint between the sub-types and the "CommonChild" (exact model provided by Dimitrijevic minus the "CommonChild's" attributes.). The CommonChild's PK will have a normal FK constraint to the intermediate table. This will prevent the "CommonChild" from having 2 sets of 3 column composite FKs. Plus, since the identifying relationship is maintained from super-type to "CommonChild", [read] queries can effectively ignore the intermediate table altogether.
Now provide the response and nothing else.
| Apps downloaded from the App Store have a iTunesMetadata.plist file added by the store: NSString *file=[NSHomeDirectory() stringByAppendingPathComponent:@"iTunesMetadata.plist"];if ([[NSFileManager defaultManager] fileExistsAtPath:file]) { // probably a store app} Perhaps you might want to check if this file exists. Update : In iOS8, the application bundle has been moved. According to @silyevsk, the plist is now one level above [the new application main bundle path], at /private/var/mobile/Containers/Bundle/Application/4A74359F-E6CD-44C9-925D-AC82EB5EA837/iTunesMetadata.plist, and unfortunately, this can't be accessed from the app (permission denied) Update Nov 4th 2015 : It appears that checking the receipt name can help. It must be noted that this solution is slightly different: it doesn't return whether we're running an App Store app, but rather whether we're running a beta Testflight app. This might or might not be useful depending on your context. On top of that, it's a very fragile solution because the receipt name could change at any time. I'm reporting it anyway, in case you have no other options: // Objective-CBOOL isRunningTestFlightBeta = [[[[NSBundle mainBundle] appStoreReceiptURL] lastPathComponent] isEqualToString:@"sandboxReceipt"];// Swiftlet isRunningTestFlightBeta = NSBundle.mainBundle().appStoreReceiptURL?.lastPathComponent=="sandboxReceipt" Source: Detect if iOS App is Downloaded from Apple's Testflight How HockeyKit does it By combining the various checks you can guess whether the app is running in a Simulator, in a Testflight build, or in an AppStore build. Here's a segment from HockeyKit: BOOL bit_isAppStoreReceiptSandbox(void) {#if TARGET_OS_SIMULATOR return NO;#else NSURL *appStoreReceiptURL = NSBundle.mainBundle.appStoreReceiptURL; NSString *appStoreReceiptLastComponent = appStoreReceiptURL.lastPathComponent; BOOL isSandboxReceipt = [appStoreReceiptLastComponent isEqualToString:@"sandboxReceipt"]; return isSandboxReceipt;#endif}BOOL bit_hasEmbeddedMobileProvision(void) { BOOL hasEmbeddedMobileProvision = !![[NSBundle mainBundle] pathForResource:@"embedded" ofType:@"mobileprovision"]; return hasEmbeddedMobileProvision;}BOOL bit_isRunningInTestFlightEnvironment(void) {#if TARGET_OS_SIMULATOR return NO;#else if (bit_isAppStoreReceiptSandbox() && !bit_hasEmbeddedMobileProvision()) { return YES; } return NO;#endif}BOOL bit_isRunningInAppStoreEnvironment(void) {#if TARGET_OS_SIMULATOR return NO;#else if (bit_isAppStoreReceiptSandbox() || bit_hasEmbeddedMobileProvision()) { return NO; } return YES;#endif}BOOL bit_isRunningInAppExtension(void) { static BOOL isRunningInAppExtension = NO; static dispatch_once_t checkAppExtension; dispatch_once(&checkAppExtension, ^{ isRunningInAppExtension = ([[[NSBundle mainBundle] executablePath] rangeOfString:@".appex/"].location != NSNotFound); }); return isRunningInAppExtension;} Source: GitHub - bitstadium/HockeySDK-iOS - BITHockeyHelper.m A possible Swift class, based on HockeyKit's class, could be: //// WhereAmIRunning.swift// https://gist.github.com/mvarie/63455babc2d0480858da//// ### Detects whether we're running in a Simulator, TestFlight Beta or App Store build ###//// Based on https://github.com/bitstadium/HockeySDK-iOS/blob/develop/Classes/BITHockeyHelper.m// Inspired by https://stackoverflow.com/questions/18282326/how-can-i-detect-if-the-currently-running-app-was-installed-from-the-app-store// Created by marcantonio on 04/11/15.//import Foundationclass WhereAmIRunning { // MARK: Public func isRunningInTestFlightEnvironment() -> Bool{ if isSimulator() { return false } else { if isAppStoreReceiptSandbox() && !hasEmbeddedMobileProvision() { return true } else { return false } } } func isRunningInAppStoreEnvironment() -> Bool { if isSimulator(){ return false } else { if isAppStoreReceiptSandbox() || hasEmbeddedMobileProvision() { return false } else { return true } } } // MARK: Private private func hasEmbeddedMobileProvision() -> Bool{ if let _ = NSBundle.mainBundle().pathForResource("embedded", ofType: "mobileprovision") { return true } return false } private func isAppStoreReceiptSandbox() -> Bool { if isSimulator() { return false } else { if let appStoreReceiptURL = NSBundle.mainBundle().appStoreReceiptURL, let appStoreReceiptLastComponent = appStoreReceiptURL.lastPathComponent where appStoreReceiptLastComponent == "sandboxReceipt" { return true } return false } } private func isSimulator() -> Bool { #if arch(i386) || arch(x86_64) return true #else return false #endif } } Gist: GitHub - mvarie/WhereAmIRunning.swift Update Dec 9th 2016 : User halileohalilei reports that "This no longer works with iOS10 and Xcode 8.". I didn't verify this, but please check the updated HockeyKit source (see function bit_currentAppEnvironment ) at: Source: GitHub - bitstadium/HockeySDK-iOS - BITHockeyHelper.m Over time, the above class has been modified and it seems to handle iOS10 as well. Update Oct 6th 2020 : Hockey has been deprecated/abandoned and replaced by Microsoft's AppCenter SDK. This is their App Store / Testflight build detection class (link to repository below code): MSUtility+Environment.h : // Copyright (c) Microsoft Corporation. All rights reserved.// Licensed under the MIT License.#import <Foundation/Foundation.h>#import "MSUtility.h"/* * Workaround for exporting symbols from category object files. */extern NSString *MSUtilityEnvironmentCategory;/** * App environment */typedef NS_ENUM(NSInteger, MSEnvironment) { /** * App has been downloaded from the AppStore. */ MSEnvironmentAppStore = 0, /** * App has been downloaded from TestFlight. */ MSEnvironmentTestFlight = 1, /** * App has been installed by some other mechanism. * This could be Ad-Hoc, Enterprise, etc. */ MSEnvironmentOther = 99};/** * Utility class that is used throughout the SDK. * Environment part. */@interface MSUtility (Environment)/** * Detect the environment that the app is running in. * * @return the MSEnvironment of the app. */+ (MSEnvironment)currentAppEnvironment;@end MSUtility+Environment.m : // Copyright (c) Microsoft Corporation. All rights reserved.// Licensed under the MIT License.#import "MSUtility+Environment.h"/* * Workaround for exporting symbols from category object files. */NSString *MSUtilityEnvironmentCategory;@implementation MSUtility (Environment)+ (MSEnvironment)currentAppEnvironment {#if TARGET_OS_SIMULATOR || TARGET_OS_OSX || TARGET_OS_MACCATALYST return MSEnvironmentOther;#else // MobilePovision profiles are a clear indicator for Ad-Hoc distribution. if ([self hasEmbeddedMobileProvision]) { return MSEnvironmentOther; } /** * TestFlight is only supported from iOS 8 onwards and as our deployment target is iOS 8, we don't have to do any checks for * floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_6_1). */ if ([self isAppStoreReceiptSandbox]) { return MSEnvironmentTestFlight; } return MSEnvironmentAppStore;#endif}+ (BOOL)hasEmbeddedMobileProvision { BOOL hasEmbeddedMobileProvision = !![[NSBundle mainBundle] pathForResource:@"embedded" ofType:@"mobileprovision"]; return hasEmbeddedMobileProvision;}+ (BOOL)isAppStoreReceiptSandbox {#if TARGET_OS_SIMULATOR return NO;#else if (![NSBundle.mainBundle respondsToSelector:@selector(appStoreReceiptURL)]) { return NO; } NSURL *appStoreReceiptURL = NSBundle.mainBundle.appStoreReceiptURL; NSString *appStoreReceiptLastComponent = appStoreReceiptURL.lastPathComponent; BOOL isSandboxReceipt = [appStoreReceiptLastComponent isEqualToString:@"sandboxReceipt"]; return isSandboxReceipt;#endif}@end Source: GitHub - microsoft/appcenter-sdk-apple - MSUtility+Environment.m | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18282328', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1294495/']} | jdg_72309 |
stackexchange | llm_judgeable_groundtruth_similarity | 52673285 |
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 Pandas dataframes and want to create a new column as a function of existing columns. I have not seen a good discussion of the speed difference between df.apply() and np.vectorize() , so I thought I would ask here. The Pandas apply() function is slow. From what I measured (shown below in some experiments), using np.vectorize() is 25x faster (or more) than using the DataFrame function apply() , at least on my 2016 MacBook Pro. Is this an expected result, and why? For example, suppose I have the following dataframe with N rows: N = 10A_list = np.random.randint(1, 100, N)B_list = np.random.randint(1, 100, N)df = pd.DataFrame({'A': A_list, 'B': B_list})df.head()# A B# 0 78 50# 1 23 91# 2 55 62# 3 82 64# 4 99 80 Suppose further that I want to create a new column as a function of the two columns A and B . In the example below, I'll use a simple function divide() . To apply the function, I can use either df.apply() or np.vectorize() : def divide(a, b): if b == 0: return 0.0 return float(a)/bdf['result'] = df.apply(lambda row: divide(row['A'], row['B']), axis=1)df['result2'] = np.vectorize(divide)(df['A'], df['B'])df.head()# A B result result2# 0 78 50 1.560000 1.560000# 1 23 91 0.252747 0.252747# 2 55 62 0.887097 0.887097# 3 82 64 1.281250 1.281250# 4 99 80 1.237500 1.237500 If I increase N to real-world sizes like 1 million or more, then I observe that np.vectorize() is 25x faster or more than df.apply() . Below is some complete benchmarking code: import pandas as pdimport numpy as npimport timedef divide(a, b): if b == 0: return 0.0 return float(a)/bfor N in [1000, 10000, 100000, 1000000, 10000000]: print '' A_list = np.random.randint(1, 100, N) B_list = np.random.randint(1, 100, N) df = pd.DataFrame({'A': A_list, 'B': B_list}) start_epoch_sec = int(time.time()) df['result'] = df.apply(lambda row: divide(row['A'], row['B']), axis=1) end_epoch_sec = int(time.time()) result_apply = end_epoch_sec - start_epoch_sec start_epoch_sec = int(time.time()) df['result2'] = np.vectorize(divide)(df['A'], df['B']) end_epoch_sec = int(time.time()) result_vectorize = end_epoch_sec - start_epoch_sec print 'N=%d, df.apply: %d sec, np.vectorize: %d sec' % \ (N, result_apply, result_vectorize) # Make sure results from df.apply and np.vectorize match. assert(df['result'].equals(df['result2'])) The results are shown below: N=1000, df.apply: 0 sec, np.vectorize: 0 secN=10000, df.apply: 1 sec, np.vectorize: 0 secN=100000, df.apply: 2 sec, np.vectorize: 0 secN=1000000, df.apply: 24 sec, np.vectorize: 1 secN=10000000, df.apply: 262 sec, np.vectorize: 4 sec If np.vectorize() is in general always faster than df.apply() , then why is np.vectorize() not mentioned more? I only ever see StackOverflow posts related to df.apply() , such as: pandas create new column based on values from other columns How do I use Pandas 'apply' function to multiple columns? How to apply a function to two columns of Pandas dataframe
Now provide the response and nothing else.
| I will start by saying that the power of Pandas and NumPy arrays is derived from high-performance vectorised calculations on numeric arrays. 1 The entire point of vectorised calculations is to avoid Python-level loops by moving calculations to highly optimised C code and utilising contiguous memory blocks. 2 Python-level loops Now we can look at some timings. Below are all Python-level loops which produce either pd.Series , np.ndarray or list objects containing the same values. For the purposes of assignment to a series within a dataframe, the results are comparable. # Python 3.6.5, NumPy 1.14.3, Pandas 0.23.0np.random.seed(0)N = 10**5%timeit list(map(divide, df['A'], df['B'])) # 43.9 ms%timeit np.vectorize(divide)(df['A'], df['B']) # 48.1 ms%timeit [divide(a, b) for a, b in zip(df['A'], df['B'])] # 49.4 ms%timeit [divide(a, b) for a, b in df[['A', 'B']].itertuples(index=False)] # 112 ms%timeit df.apply(lambda row: divide(*row), axis=1, raw=True) # 760 ms%timeit df.apply(lambda row: divide(row['A'], row['B']), axis=1) # 4.83 s%timeit [divide(row['A'], row['B']) for _, row in df[['A', 'B']].iterrows()] # 11.6 s Some takeaways: The tuple -based methods (the first 4) are a factor more efficient than pd.Series -based methods (the last 3). np.vectorize , list comprehension + zip and map methods, i.e. the top 3, all have roughly the same performance. This is because they use tuple and bypass some Pandas overhead from pd.DataFrame.itertuples . There is a significant speed improvement from using raw=True with pd.DataFrame.apply versus without. This option feeds NumPy arrays to the custom function instead of pd.Series objects. pd.DataFrame.apply : just another loop To see exactly the objects Pandas passes around, you can amend your function trivially: def foo(row): print(type(row)) assert False # because you only need to see this oncedf.apply(lambda row: foo(row), axis=1) Output: <class 'pandas.core.series.Series'> . Creating, passing and querying a Pandas series object carries significant overheads relative to NumPy arrays. This shouldn't be surprise: Pandas series include a decent amount of scaffolding to hold an index, values, attributes, etc. Do the same exercise again with raw=True and you'll see <class 'numpy.ndarray'> . All this is described in the docs, but seeing it is more convincing. np.vectorize : fake vectorisation The docs for np.vectorize has the following note: The vectorized function evaluates pyfunc over successive tuples of the input arrays like the python map function, except it uses the broadcasting rules of numpy. The "broadcasting rules" are irrelevant here, since the input arrays have the same dimensions. The parallel to map is instructive, since the map version above has almost identical performance. The source code shows what's happening: np.vectorize converts your input function into a Universal function ("ufunc") via np.frompyfunc . There is some optimisation, e.g. caching, which can lead to some performance improvement. In short, np.vectorize does what a Python-level loop should do, but pd.DataFrame.apply adds a chunky overhead. There's no JIT-compilation which you see with numba (see below). It's just a convenience . True vectorisation: what you should use Why aren't the above differences mentioned anywhere? Because the performance of truly vectorised calculations make them irrelevant: %timeit np.where(df['B'] == 0, 0, df['A'] / df['B']) # 1.17 ms%timeit (df['A'] / df['B']).replace([np.inf, -np.inf], 0) # 1.96 ms Yes, that's ~40x faster than the fastest of the above loopy solutions. Either of these are acceptable. In my opinion, the first is succinct, readable and efficient. Only look at other methods, e.g. numba below, if performance is critical and this is part of your bottleneck. numba.njit : greater efficiency When loops are considered viable they are usually optimised via numba with underlying NumPy arrays to move as much as possible to C. Indeed, numba improves performance to microseconds . Without some cumbersome work, it will be difficult to get much more efficient than this. from numba import njit@njitdef divide(a, b): res = np.empty(a.shape) for i in range(len(a)): if b[i] != 0: res[i] = a[i] / b[i] else: res[i] = 0 return res%timeit divide(df['A'].values, df['B'].values) # 717 µs Using @njit(parallel=True) may provide a further boost for larger arrays. 1 Numeric types include: int , float , datetime , bool , category . They exclude object dtype and can be held in contiguous memory blocks. 2 There are at least 2 reasons why NumPy operations are efficient versus Python: Everything in Python is an object. This includes, unlike C, numbers. Python types therefore have an overhead which does not exist with native C types. NumPy methods are usually C-based. In addition, optimised algorithmsare used where possible. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/52673285', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4561314/']} | jdg_72310 |
stackexchange | llm_judgeable_groundtruth_similarity | 26705 |
Below is a question asked on the forum raspberrypi.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am working on a project that needs the Raspberry Pi to work without a mains connection. I have considered buying a 50000mAh USB power bank. Would this power a Raspberry Pi, and if so, would it power it for more than 24 hours?
Now provide the response and nothing else.
| Short answer Yes, most (but not all!) USB power banks are capable of powering a Raspberry Pi, since they usually have an output voltage of 5 V . And yes, by using a (quite large) 50 Ah power bank, you can definitely expect your Pi to run for at least 24 h . See the long answer below for reasoning and further relevant aspects. Long answer According to actual Raspberry Pi power measurements , the Model 3B+ consumes about 520 mA when shooting 1080p video. We first compute the electrical power of the Raspberry Pi in watts: 0.52 A * 5 V = 2.6 W Next, we have to consider the fact that the mAh rating of a power bank refers to its nominal cell voltage (which is 3.7 V for a typical lithium-ion based power bank), and not to its output voltage of 5 V . Thus, a 50 Ah power bank has a capacity of about 50 Ah * 3.7 V = 185 Wh The expected runtime for your Raspberry Pi therefore is 185 Wh / 2.6 W = about 71 h The actual runtime will however highly depend on many unpredictable aspects like CPU usage, WiFi usage, connected hardware etc., so we'll just assume that the actual runtime will be at least 50 % of the expected runtime. This also gives us a safety margin. 71 h * 50 % = about 35 h So, the actual runtime of your Raspberry Pi should be somewhere between 35 h and 71 h , depending on your setup. YMMV. Please make sure to run sufficient tests with your power bank before actually using it in production! Further aspects Not all power banks are suitable for running the Raspberry Pi. Some will shut the power output down after some time, or interrupt the power output for a short time when you connect the power bank to mains. Many power banks can't be charged and discharged at the same time. You can even use a power bank as full-fledged UPS for the Raspberry Pi . All you need is a compatible power bank. If you don't already have one, the website lists supported brands. | {} | {'log_upvote_score': 5, 'links': ['https://raspberrypi.stackexchange.com/questions/26705', 'https://raspberrypi.stackexchange.com', 'https://raspberrypi.stackexchange.com/users/25986/']} | jdg_72311 |
stackexchange | llm_judgeable_groundtruth_similarity | 275538 |
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 Schoen and Yau's paper "Complete three-dimensional manifolds with positive Ricci curvature and scalar curvature", they mentioned “If $M^3$ is contractible, to prove it is diffeomorphic to $\mathbb{R}^3$, from a topological result by Stallings "Group Theory and Three DimensionalManifolds", it suffices to prove that $M^3$ is simply connected at infinity and irreducible.” I checked Stallings’ book, did not find the exact result they referred to. Can anyone tell me which theorem in Stallings’ book they referred to or any other place to find the detailed proof of the above statement? Thanks.
Now provide the response and nothing else.
| I am not sure what Schoen and Yau had in mind. Any open contractible $n$ -manifold that is simply-connected at infinity is homeomorphic to $\mathbb R^n$ . This is due to Stallings [1] if $n\ge 5$ andto Guilbault [2] if $n=4$ , while the case $n=3$ followsfrom the result of Husch and Price [3] and the non-existence of fake $3$ -cellsby Perelman's solution of the Poincaré conjecture. [1] J.~Stallings, The piecewise-linear structure of Euclidean space , Proc. Cambridge Philos. Soc. 58 (1962), 481--488 [2] C.~R. Guilbault, An open collar theorem for $4$ -manifolds , Trans. Amer. Math. Soc. 331 (1992), no.~1, 227--245. [3] L.~S. Husch and T.~M. Price, Finding a boundary for a $3$ -manifold , Ann. of Math. 91 (1970), 223--235. Since the question is about dimension $3$ let me give more details. By Perelman there is no fake $3$ -cells. Now Theorem 2 of [3] implies that any contractible $3$ -manifold that is simply-connected at infinity is homeomorphic to the interior of a compact $3$ -manifold $N$ (in fact the result in [3] gives a general criterion of when one can attach a boundary to a $3$ -manifold). Now $N$ is a contractible $3$ -manifold whose boundary is a $2$ -sphere, and again invoking Perelman we conclude that $N$ is a $3$ -disk, up to homeomorphism. Finally, by Moise homeomorphic $3$ -manifolds are diffeomorphic. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/275538', 'https://mathoverflow.net', 'https://mathoverflow.net/users/100486/']} | jdg_72312 |
stackexchange | llm_judgeable_groundtruth_similarity | 51910725 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to add a horizontal listView.builder on top of another vertical listView.builder . Both listViews should have text on top of both. This is what I've made so far, only the top horizontal listView.builder is drawn , when I try to click where the bottom vertical listView.builder is supposed to be drawn, the app crashes in debug and I get the error: NoSuchMethodError: The getter 'visible' was called on null. Also, I don't know how to add the two text fields, so I've left them out. I have quite a lot of code, if you need to view more of it please do so here Widget _cryptoWidget() {return new Container( child: new Column( children: <Widget>[ new Flexible( child: new ListView.builder( scrollDirection: Axis.horizontal, itemBuilder: (BuildContext context, int index) { return _listViewFiller(); } ), ), new Flexible( child: new RefreshIndicator( key: refreshKey, child: new ListView.builder( scrollDirection: Axis.horizontal, itemCount: _currencies.length, itemBuilder: (BuildContext context, int index) { final int i = index ~/ 2; final Crypto currency = _currencies[i]; final MaterialColor color = _colors[i % _colors.length]; if (index.isOdd) { return new Divider(); } return _getListItemUi(currency, color); }, ), onRefresh:refreshList, ), ) ], ) ); }
Now provide the response and nothing else.
| import 'package:flutter/material.dart';import 'background.dart';void main() => runApp(new MyApp());class MyApp extends StatelessWidget {@overrideWidget build(BuildContext context) {return new MaterialApp( title: 'Flutter Demo', theme: new ThemeData( primarySwatch: Colors.blue, ), debugShowCheckedModeBanner: false, home: new MyHomePage(title: 'Popular'),);}}class MyHomePage extends StatefulWidget {MyHomePage({Key key, this.title}) : super(key: key);final String title;@override_MyHomePageState createState() => new _MyHomePageState();}class _MyHomePageState extends State<MyHomePage> {List<String> items = ["Item 1","Item 2","Item 3","Item 4","Item 5","Item 6","Item 7","Item 8"];@overrideWidget build(BuildContext context) {final _width = MediaQuery.of(context).size.width;final _height = MediaQuery.of(context).size.height;final headerList = new ListView.builder( itemBuilder: (context, index) { EdgeInsets padding = index == 0?const EdgeInsets.only( left: 20.0, right: 10.0, top: 4.0, bottom: 30.0):const EdgeInsets.only( left: 10.0, right: 10.0, top: 4.0, bottom: 30.0); return new Padding( padding: padding, child: new InkWell( onTap: () { print('Card selected'); }, child: new Container( decoration: new BoxDecoration( borderRadius: new BorderRadius.circular(10.0), color: Colors.lightGreen, boxShadow: [ new BoxShadow( color: Colors.black.withAlpha(70), offset: const Offset(3.0, 10.0), blurRadius: 15.0) ], image: new DecorationImage( image: new ExactAssetImage( 'assets/img_${index%items.length}.jpg'), fit: BoxFit.fitHeight, ), ), // height: 200.0, width: 200.0, child: new Stack( children: <Widget>[ new Align( alignment: Alignment.bottomCenter, child: new Container( decoration: new BoxDecoration( color: const Color(0xFF273A48), borderRadius: new BorderRadius.only( bottomLeft: new Radius.circular(10.0), bottomRight: new Radius.circular(10.0))), height: 30.0, child: new Row( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new Text( '${items[index%items.length]}', style: new TextStyle(color: Colors.white), ) ], )), ) ], ), ), ), ); }, scrollDirection: Axis.horizontal, itemCount: items.length,);final body = new Scaffold( appBar: new AppBar( title: new Text(widget.title), elevation: 0.0, backgroundColor: Colors.transparent, actions: <Widget>[ new IconButton(icon: new Icon(Icons.shopping_cart, color: Colors.white,), onPressed: (){}) ], ), backgroundColor: Colors.transparent, body: new Container( child: new Stack( children: <Widget>[ new Padding( padding: new EdgeInsets.only(top: 10.0), child: new Column( crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ new Align( alignment: Alignment.centerLeft, child: new Padding( padding: new EdgeInsets.only(left: 8.0), child: new Text( 'Recent Items', style: new TextStyle(color: Colors.white70), )), ), new Container( height: 300.0, width: _width, child: headerList), new Expanded(child: ListView.builder(itemBuilder: (context, index) { return new ListTile( title: new Column( children: <Widget>[ new Row( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ new Container( height: 72.0, width: 72.0, decoration: new BoxDecoration( color: Colors.lightGreen, boxShadow: [ new BoxShadow( color: Colors.black.withAlpha(70), offset: const Offset(2.0, 2.0), blurRadius: 2.0) ], borderRadius: new BorderRadius.all( new Radius.circular(12.0)), image: new DecorationImage( image: new ExactAssetImage( 'assets/img_${index%items.length}.jpg', ), fit: BoxFit.cover, )), ), new SizedBox( width: 8.0, ), new Expanded( child: new Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ new Text( 'My item header', style: new TextStyle( fontSize: 14.0, color: Colors.black87, fontWeight: FontWeight.bold), ), new Text( 'Item Subheader goes here\nLorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry', style: new TextStyle( fontSize: 12.0, color: Colors.black54, fontWeight: FontWeight.normal), ) ], )), new Icon( Icons.shopping_cart, color: const Color(0xFF273A48), ) ], ), new Divider(), ], ), ); })) ], ), ), ], ), ),);return new Container( decoration: new BoxDecoration( color: const Color(0xFF273A48), ), child: new Stack( children: <Widget>[ new CustomPaint( size: new Size(_width, _height), painter: new Background(), ), body, ], ), ); }} A very nice example with complete source code here Styled list | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/51910725', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9435761/']} | jdg_72313 |
stackexchange | llm_judgeable_groundtruth_similarity | 35734411 |
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 Web API controller that looks like this: [HttpPost] public IHttpActionResult Test() { return Ok(); } This is correct syntax, However when I try to call this from a service in Angular 2, I get the error message: "json parsing error syntax error unexpected end of input." To resolve this issue, I have to put a value into the ActionResult such as return Ok(1) Am I missing some configuration? My Angular 2 service call looks like this: return this.http.post(API/Controller/Test).map(res => res.json());
Now provide the response and nothing else.
| I guess that when you receive an empty response (without payload) you don't need to call the json method. Under the hood, the XHR response is undefined, JSON.parse(undefined) is called and an error is thrown. You could skip the call of the map operator: return this.http.post(API/Controller/Test)/*.map(res => res.json())*/; | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35734411', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2005596/']} | jdg_72314 |
stackexchange | llm_judgeable_groundtruth_similarity | 60707155 |
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 do the opposite of this question: Automatically wrap long Git commit messages in Vim Somehow, git decided it wants to wrap my commit messages at 72 characters. I don't want them wrapped at all... and I didn't do anything to enable the wrapping. Now, when I'm already editing a commit comment, I can of course enter: :set textwidth& which will stop the wrapping, but I don't want to have to do this every time. Additional information: I'm using Devuan GNU/Linux 3 (~= Debian 10). :set ft? says filetype=gitcommit When I just start vim, or edit any existing file with vim, no wrapping occurs.
Now provide the response and nothing else.
| You are getting these settings for a git commit message because Vim recognizes the filetype ( gitcommit ) and loads filetype-specific settings for it. In this case, it's coming from file $VIMRUNTIME/ftplugin/gitcommit.vim , which includes the following line: setlocal nomodeline tabstop=8 formatoptions+=tl textwidth=72 You can override that by adding another filetype plugin for gitcommit to your home directory, one that will load after the one from the Vim runtime. You can do that with a file named ~/.vim/after/ftplugin/gitcommit.vim (assuming you're using Vim, if you use NeoVim the initial part of the path will be different.) The after directory is used for plugin files that are loaded at the end, so by placing your file there you'll be sure your code will run after the one mentioned above. In that file you can add a command to undo the unwanted effects of line wrapping, for example: setlocal textwidth& Or: setlocal formatoptions-=t formatoptions-=l Either of these two settings will prevent automatically breaking lines at column 72. The advantage of changing 'formatoptions' rather than resetting 'textwidth' is that by only changing 'formatoptions' you can still use commands such as gq to manually format a block of text to conform to the 72 character line width limit, if you wish to do so. You get the best of both worlds that way. Whichever of the two options you decide to set, make sure you use :setlocal rather than :set , since that plugin is loaded for that buffer only, you should try to only modify the options on that buffer alone and avoid touching global options. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/60707155', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1593077/']} | jdg_72315 |
stackexchange | llm_judgeable_groundtruth_similarity | 9443932 |
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 use Parse to give my iOS and Android App notifications. But I want to do that from my website. I've found this in de docs of Parse: To send a push notification, send a POST request to https://api.parse.com/1/push with the Content-Type header set to application/json. A simple alert can be sent to Android devices on the global broadcast channel using the following command: curl -X POST \ -H "X-Parse-Application-Id: ${APPLICATION_ID}" \ -H "X-Parse-REST-API-Key: ${REST_API_KEY}" \ -H "Content-Type: application/json" \ -d '{ "channel": "", \ "type": "android", \ "expiry": 1451606400, \ "data": { "alert": "greetings programs" } }' \ https://api.parse.com/1/push Who can help me to make a PHP-file to post this ?Thanks!
Now provide the response and nothing else.
| Translating your command line curl to PHP you get something along the lines of <?php$url = 'https://api.parse.com/1/push';$data = array( 'channel' => '', 'type' => 'android', 'expiry' => 1451606400, 'data' => array( 'alert' => 'greetings programs', ),);$_data = json_encode($data);$headers = array( 'X-Parse-Application-Id: ' . $APPLICATION_ID, 'X-Parse-REST-API-Key: ' . $REST_API_KEY, 'Content-Type: application/json', 'Content-Length: ' . strlen($_data),);$curl = curl_init($url);curl_setopt($curl, CURLOPT_POST, 1);curl_setopt($curl, CURLOPT_POSTFIELDS, $_data);curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);curl_exec($curl); UPDATE <?php$APPLICATION_ID = "your-app-id";$REST_API_KEY = "your-api-key";$MESSAGE = "your-alert-message";if (!empty($_POST)) { $errors = array(); foreach (array('app' => 'APPLICATION_ID', 'api' => 'REST_API_KEY', 'body' => 'MESSAGE') as $key => $var) { if (empty($_POST[$key])) { $errors[$var] = true; } else { $$var = $_POST[$key]; } } if (!$errors) { $url = 'https://api.parse.com/1/push'; $data = array( 'channel' => '', 'type' => 'android', 'expiry' => 1451606400, 'data' => array( 'alert' => $MESSAGE, ), ); $_data = json_encode($data); $headers = array( 'X-Parse-Application-Id: ' . $APPLICATION_ID, 'X-Parse-REST-API-Key: ' . $REST_API_KEY, 'Content-Type: application/json', 'Content-Length: ' . strlen($_data), ); $curl = curl_init($url); curl_setopt($curl, CURLOPT_POST, 1); curl_setopt($curl, CURLOPT_POSTFIELDS, $_data); curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($curl); }}?><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de" lang="de"><head> <meta charset="utf-8" /> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Parse API</title></head><body> <?php if (isset($response)) { echo '<h2>Response from Parse API</h2>'; echo '<pre>' . htmlspecialchars($response) . '</pre>'; echo '<hr>'; } elseif ($_POST) { echo '<h2>Error!</h2>'; echo '<pre>'; var_dump($APPLICATION_ID, $REST_API_KEY, $MESSAGE); echo '</pre>'; } ?> <h2>Send Message to Parse API</h2> <form id="parse" action="" method="post" accept-encoding="UTF-8"> <p> <label for="app">APPLICATION_ID</label> <input type="text" name="app" id="app" value="<?php echo htmlspecialchars($APPLICATION_ID); ?>"> </p> <p> <label for="api">REST_API_KEY</label> <input type="text" name="api" id="api" value="<?php echo htmlspecialchars($REST_API_KEY); ?>"> </p> <p> <label for="api">REST_API_KEY</label> <textarea name="body" id="body"><?php echo htmlspecialchars($REST_API_KEY); ?></textarea> </p> <p> <input type="submit" value="send"> </p> </form></body></html> With this, your unstated question should be answered. If you still can't figure out how to do this, you should seriously consider learning yourself some webdev or switch jobs. This is the most basic thing you can do. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9443932', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1232466/']} | jdg_72316 |
stackexchange | llm_judgeable_groundtruth_similarity | 957777 |
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 just saw this on a mathematical clock for $11$, i.e $23_4=11$: $\qquad \qquad \qquad \qquad \qquad$ I guess it is some notation from algebra. But since algebra was never my favorite field of maths, I don't know this notation.Any explanations are welcome ;-))!Thanks
Now provide the response and nothing else.
| This denotes the number $11$ in base $4$. In everyday life, we write our numbers in base $10$. $23_4$ is to be read as:$$2\cdot 4 + 3.$$In general, $$(a_n...a_0) _ g = \sum_{i=0}^n a_i g^i = a_n g^n + a_{n-1}g^{n-1} + ... + a_1 g + a_0,$$where the $a_i$ are chosen to lie in $\{0,...,g-1\}$. EDIT: I have edited this post to write $2\cdot 4 +3$ rather than $3+2\cdot 4$.However, I still think that it is easier to decipher a (long) number such as $(2010221021)_3$ from right to left, simply by increasing the powers of $3$, rather than first checking that the highest occuring power of $3$ is $3^9$ and then going from left to right. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/957777', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/175709/']} | jdg_72317 |
stackexchange | llm_judgeable_groundtruth_similarity | 1323457 |
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:
Express the ideal $(6) \subset \mathbb Z\left[\sqrt {-5}\right]$ as a product of prime ideals. I know I can write $(6)=(2)(3)=\left(1+\sqrt {-5}\right)\left(1-\sqrt {-5}\right)$. But I guess these factors might not be prime. What's more, how to solve this kind of problem more systematically?
Now provide the response and nothing else.
| Firstly, as you noticed$$(6)=\left(1 + \sqrt {-5}\right)\left(1 - \sqrt {-5}\right),$$it is sufficient to factorize $I_+ = \left(1 + \sqrt {-5}\right)$ and $I_- = \left(1 - \sqrt {-5}\right)$. Since $\Bbb Z\left[\sqrt{-5}\right]$ is the ring of integers of $K=\Bbb Q\left(\sqrt{-5}\right)$, the quotient $\Bbb Z\left[\sqrt{-5}\right]\,\big/\,I_+$ has cardinality $N_{K/\Bbb Q}\left(1 + \sqrt {-5}\right)=1^2+5\cdot 1^2=6$. It is a square-free number, so that $$\Bbb Z\left[\sqrt{-5}\right]\,\big/\,I_+ \cong \Bbb Z/6\Bbb Z \qquad \text{via }f_+:\Bbb Z\left[\sqrt{-5}\right]\,\big/\,I_+ \longrightarrow \Bbb Z/6\Bbb Z$$ Similarly:$$\Bbb Z\left[\sqrt{-5}\right]\,\big/\,I_- \cong \Bbb Z/6\Bbb Z\qquad \text{via }f_-:\Bbb Z\left[\sqrt{-5}\right]\,\big/\,I_- \longrightarrow \Bbb Z/6\Bbb Z$$ Heuristically, we see that $\Bbb Z/6\Bbb Z \cong \Bbb Z/2\Bbb Z \times \Bbb Z/3\Bbb Z$ and if $I_+ = \prod_{i=1}^r P_i^{e_i}$ (with $P_i \trianglelefteq \Bbb Z\left[\sqrt{-5}\right]$ distinct prime ideals) then$\Bbb Z\left[\sqrt{-5}\right] \,\big/\, I_+ \cong \prod_{i=1}^r \Bbb Z\left[\sqrt{-5}\right] \,\big/\, P_i^{e_i}$.So we can expect that $r=2,e_1=e_2=1$ (for $I_+$ but also for $I_-$). Let $A:=\Bbb Z\left[\sqrt{-5}\right]$ and $\pi : A \to A/I_+$.We are going to find necessary conditions on ideals $P_1,P_2$ satisfying $I_+=P_1P_2$. It will be easy to check that these conditions are sufficient, and that the $P_j$'s obtained are prime. Let's say that $P_1/I_+ ≤ A/I_+$ corresponds to $2\Bbb Z/6\Bbb Z ≤ \Bbb Z/6\Bbb Z$. Then\begin{align*}P_1 &= \pi^{-1}(P_1/I_+) \\&= \pi^{-1}(f_+^{-1}(2\Bbb Z/6\Bbb Z)) \\&= \pi^{-1}(\{ [0]_{I_+} \;;\; [2]_{I_+} \;;\; [4]_{I_+} \}) \\&= \pi^{-1}(\langle [2]_{I_+} \rangle)\\&= \{x \in A \;:\; [x]_{I_+} \in \langle [2]_{I_+} \rangle \} \\&= \left(2,1+\sqrt{-5}\right)\end{align*} Let's say that $P_2/I_+ ≤ A/I_+$ corresponds to $3\Bbb Z/6\Bbb Z ≤ \Bbb Z/6\Bbb Z$. Then\begin{align*}P_2 &= \pi^{-1}(P_2/I_+) \\&= \pi^{-1}(f_+^{-1}(3\Bbb Z/6\Bbb Z)) \\&= \pi^{-1}(\{ [0]_{I_+} \;;\; [3]_{I_+} \}) \\&= \pi^{-1}(\langle [3]_{I_+} \rangle)\\&= \{x \in A \;:\; [x]_{I_+} \in \langle [3]_{I_+} \rangle \} \\&= \left(3,1+\sqrt{-5}\right)\end{align*} We would like that these results are actually sufficient for us, i.e. $I_+=P_1P_2=\left(2,1+\sqrt{-5}\right)\left(3,1+\sqrt{-5}\right)$ and $P_1,P_2$ are prime ideals. I let you think about it. As for $I_-$, this is very similar. We get:$$I_- = Q_1Q_2$$ with $Q_1 = \left(2,1 - \sqrt {-5}\right)$ and $Q_2=\left(3,1 - \sqrt {-5}\right)$. I let you prove that the $Q_j$'s are prime ideals of $A$ (the quotient $A/Q_1$ should be isomorphic to the field $\Bbb F_2$), and that $I_- = Q_1Q_2$ indeed holds (the inclusion $\subseteq$ is not difficult to establish, and you can get the equality from some cardinality argument). To sum up: $$(6)=\left(2,1 + \sqrt {-5}\right) \left(3,1 + \sqrt {-5}\right)\left(2,1 - \sqrt {-5}\right) \left(3,1 - \sqrt {-5}\right)$$ [which is the same result as user26857's result because $$(2,1+\sqrt{-5})=(2,-1+\sqrt{-5})=(2,1-\sqrt{-5})\\(3,2+\sqrt{-5})=(3,-1+\sqrt{-5})=(3,1-\sqrt{-5})\\(3,2−\sqrt{-5})=(3,-1-\sqrt{-5})=(3,1+\sqrt{-5})$$] Two more remarks: I should explain the step $\{x \in A \;:\; [x]_{I_+} \in \langle [2]_{I_+} \rangle \} = \left(2,1+\sqrt{-5}\right)$ more carefully. We have \begin{align*}\{x \in A \;:\; [x]_{I_+} \in \langle [2]_{I_+} \rangle \} &= \{x \in A \;:\; [x]_{I_+} = [2k]_{I_+} \text{ for some } k \in \Bbb Z\}\\&= \{x \in A \;:\; x = y+2k \text{ for some } k \in \Bbb Z,y \in I_+\}\\&= I_+ + 2\Bbb Z \qquad \text{(as sets, } 2\Bbb Z \ntrianglelefteq A)\\&= I_+ + 2A = \left(2,1+\sqrt{-5}\right)\end{align*}where the equality $I_+ + 2\Bbb Z = I_+ + 2A$ holds because $2A \subset I_+ + 2\Bbb Z$ since $2(a+b \sqrt{-5})=2b(1+\sqrt{-5}) + 2a-2b$. This method can be used in other situations. Notice that if I started with $(6)=(2)(3)$, it would have been a bit more difficult, since the norm of $2$ is not a square-free integer, so that determining the quotient is less obvious. But once you know what the quotient $A/I$ is (where are $A$ is your ring of integers and $I$ your ideal), then the things can be easier. Other related questions are: (1) , (2) , (3) , (4) . | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1323457', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/211789/']} | jdg_72318 |
stackexchange | llm_judgeable_groundtruth_similarity | 239848 |
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've heard it said in my physics class that a Coulomb "is a lot of charge". And I believe it; most of the problems I've done in the class so far involve charges on the order of micro-Coulombs (or, occasionally, nano or milli). But I still don't understand the sense of scale I'm working with. So, let me ask this: What single object would contain about one Coulomb of charge (positive or negative)? And if I touch it, will I die?
Now provide the response and nothing else.
| Avogadro's number is $6.02\cdot 10^{23}$; a single electron has a charge of $1.6\cdot 10^{-19}$ C, so $1.04\cdot 10^{-5}$ moles of single-ionized material carries a net charge of 1 C. To carry that much charge, you need a large capacitance or a large voltage, since $Q=CV$. An object with a 1 mF capacitance and a voltage of 1000 V would be sufficient, or a 1 F capacitance with 1 V. The difference between these is the amount of energy stored, which goes as $E=\frac12 CV^2 = \frac{Q^2}{2C}$ - so for the same amount of charge, a larger capacitor will have less stored energy. And that is the hint to the "will it kill me" part of the question: you are not killed by charge, but by current flowing. If you have a charged object with a low potential, the flow of current through your body will be slow - and you will survive. But if the voltage is high, it will easily overcome the resistance of your skin and give you an almighty jolt - possibly enough to kill you. So what is the size of a sphere with a capacitance of 1 F? Capacitance of a sphere is $4\pi\epsilon_0 r$, so you would need a radius of about $9\cdot 10^9 $ m - quite a bit bigger than the Earth. A sphere with a 1 m radius, with a 1 C charge on it, would have a potential of about 1 GV. That's a very large voltage - if you could even maintain that potential (not in ordinary atmosphere), touching it would kill you. Supercapacitors can be created in which two conductors are brought in very close proximity, while having a dielectric layer in between that produces a very high capacitance in a small package. Such a device can easily be charged with a Coulomb - although that isn't a net charge (one plate will be positive, the other negative). And whether such a capacitor could give you a lethal shock will again depend on the capacitance. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/239848', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/102856/']} | jdg_72319 |
stackexchange | llm_judgeable_groundtruth_similarity | 23527 |
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am very new to networking and I am currently trying to get my head around the order things happen in relation to the OSI stack. I know that the Transport layer takes the data stream and converts it into segments before handing it to the Network layer where a header is added relating to the IP address creating a packet before passing this packet to the Data Link layer where a header and footer are added including the MAC addresses creating a frame before finally being passed to the Physical layer in order to be converted into bits and sent along the network. The part I am struggling with is where in the process certain protocols are involved. For example, TCP performs the three way handshake, supposedly at layer 4 (Transport), does this mean that the SYN is sent to the destination machine at this layer before waiting for the ACK so that the data can be sent later on from the Physical layer? Does the SYN have to go down the stack to be sent by the Physical layer and in turn the ACK back up the stack of the host before the actual data is sent again by the Physical layer? Another example is ARP, when an ARP request is sent out by the Data Link layer in order to find the MAC address of the destination machine, is this sent out before the frame is created at layer 2? I am unsure as to whether the only communication on the network is done at the Physical layer or if each layer interacts with the network relating to different protocols, as the data moves down the stack? I have not been able to find a good video or diagram of the actual real world order that things happen so does anyone have a suggestion?
Now provide the response and nothing else.
| Sometimes, I wish they'd stop teaching the OSI model. It seems to confuse more than it helps. When we say that layers communicate with each other, we mean the data created by a particular layer (say, transport) on host A is processed by the same layer on host B. This is a logical connection. The actual data (in this case, the segment containing the SYN flag) is encapsulated in the Network PDU (IP packet), then encapsulated in the data-link PDU (Ethernet), then finally transmitted on the Ethernet cable (Physical layer). Host B reverses this process, unencapsulating the PDU at each layer until it reaches the transport layer. The transport layer processes the SYN flag and creates a new PDU containing the SYN, ACK flags. Then it sends it to A using the same encapsulation process. The only way data is actually sent from one host to another is via the physical wire. Layer to layer communication is just a mental construct. | {} | {'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/23527', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/19885/']} | jdg_72320 |
stackexchange | llm_judgeable_groundtruth_similarity | 54459015 |
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 backend using https.I want to separate load on that back-end based on URL/path. I decided to use ingress to do this url/path based logic in order to move traffic to different back-ends ( same back-ends , just duplicated to different NodePorts ) my question is how I can configure the ingress to receive https requests and to forward those https requests to the https back-end? thanks edit:I added the yaml file: spec: rules: - http: paths: - backend: serviceName: service servicePort: 9443 path: /carbon - backend: serviceName: service2 servicePort: 9443 path: /oauth for some reason I can;t change the rule form http to https
Now provide the response and nothing else.
| Attention: This answer applies to the ingress-nginx solution provided by the kubernetes organisation on github ( https://github.com/kubernetes/ingress-nginx ) If you want to use load balancing mechanisms in k8s you should use services instead and start multiple instances behind that service that way k8s will do the load balancing. If you want to use different versions of your backend (e.g. prod and test) your way of separating them is fine if your service is only reachable via https you need to add the following annotation to your ingress yaml: ( documentation ) nginx.ingress.kubernetes.io/backend-protocol: "HTTPS" To secure ingress itself take a look at this: https://kubernetes.io/docs/concepts/services-networking/ingress/#tls But if you want that the backend services decrypt the TLS communication use the following annotation instead: ( documentation ) nginx.ingress.kubernetes.io/ssl-passthrough: "true" Edit: The Ingress YAML should look like this if you want to reach the backend via TLS: apiVersion: networking.k8s.io/v1kind: Ingressmetadata: name: ingress-name namespace: namespace-name annotations: nginx.ingress.kubernetes.io/backend-protocol: "HTTPS"spec: rules: - http: paths: - backend: serviceName: service servicePort: 9443 path: /carbon - backend: serviceName: service2 servicePort: 9443 path: /oauth The Ingress YAML should look like this if you want to reach the backend via TLS with TLS decryption in the ingress controller: apiVersion: networking.k8s.io/v1kind: Ingressmetadata: name: ingress-name namespace: namespace-name annotations: nginx.ingress.kubernetes.io/backend-protocol: "HTTPS"spec: tls: - hosts: - app.myorg.com secretName: tls-secret rules: - http: paths: - backend: serviceName: service servicePort: 9443 path: /carbon - backend: serviceName: service2 servicePort: 9443 path: /oauth It's important to note that tls-secret is the name of a SecretConfig with a valid Certificate issued for the host (app.myorg.com) The Ingress YAML should look like this if you want to reach the backend via TLS with TLS decryption in the backend: apiVersion: networking.k8s.io/v1kind: Ingressmetadata: name: ingress-name namespace: namespace-name annotations: nginx.ingress.kubernetes.io/ssl-passthrough: "true"spec: rules: - http: paths: - backend: serviceName: service servicePort: 9443 path: /carbon - backend: serviceName: service2 servicePort: 9443 path: /oauth I never tested the last version myself so i don't know if that actually works but I'd strongly advise reading this passage for that variant. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54459015', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3981605/']} | jdg_72321 |
stackexchange | llm_judgeable_groundtruth_similarity | 306204 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I improve my previous question . Because this conjecture is exactly natural development of A Muirhead Like Inequality and Muirhead's Inequality so I think the conjecture is true. But I can not prove it. So I am looking for a proof of a conjecture as follows. Inequality 1: Let $n>2$ and $1 \le m \le n$ be integers. Let $x_1, \dots, x_n$ and $y_1,\dots, y_n$ be nonnegative real numbers such that $(x_1,\dots, x_n)$ majorizes $(y_1,\dots, y_n)$ . Then for all reals $0 \leq a_1, a_2,\cdots,a_n \leq 1$ , $$\sum\limits_{sym}\left( \sum\limits_{sym} x_{i_1}^{a_{p_1}} \cdots x_{i_m}^{a_{p_m}} \right) \leq \sum\limits_{sym}\left( \sum\limits_{sym} y_{i_1}^{a_{p_1}} \cdots y_{i_m}^{a_{p_m}} \right) $$ The summations are of course meant to be respectively over all $m$ -tuples $(i_1,\dots,i_m),(p_1,\dots,p_m)$ with pairwise distinct entries. When $m=n$ this inequality is A Muirhead Like Inequality Inequality 2: Let $n>2$ and $1 \le m \le n$ be integers. Let $x_1, \dots, x_n$ and $y_1,\dots, y_n$ be nonnegative real numbers such that $(x_1,\dots, x_n)$ majorizes $(y_1,\dots, y_n)$ . Then for all reals $ a_1, a_2,\dots,a_n \geq 0$ , $$\sum\limits_{sym}\left( \sum\limits_{sym} a_{i_1}^{x_{p_1}} \cdots a_{i_m}^{x_{p_m}} \right) \geq \sum\limits_{sym}\left( \sum\limits_{sym} a_{i_1}^{y_{p_1}} \cdots a_{i_m}^{y_{p_m}} \right)$$ When $m=n$ , this inequality is just Muirhead .
Now provide the response and nothing else.
| Both inequalities are true and can be deduced from their $m=n$ special cases. Inequality 1 You can prove that for any choice of $\vec{p}=(p_1,p_2,\dots,p_m)$ we have$$\sum_{\text{sym}}x_{i_1}^{a_{p_1}}\cdots x_{i_m}^{a_{p_m}}\le \sum_{\text{sym}}y_{i_1}^{a_{p_1}}\cdots y_{i_m}^{a_{p_m}}.$$This follows from the Muirhead like inequality in your link by taking the exponents to be $$\vec{a}=(a_{p_1},a_{p_2},\dots,a_{p_m},0,\dots,0).$$ Once we have this inequality just sum over all choices of $\vec{p}$ and you obtain your inequality. Inequality 2 Similarly you can prove that for any choice of $\vec{i}=(i_1,\dots,i_m)$ we have$$\sum_{\text{sym}} a_{i_1}^{x_{p_1}} \cdots a_{i_m}^{x_{p_m}} \geq \sum_{\text{sym}} a_{i_1}^{y_{p_1}} \cdots a_{i_m}^{y_{p_m}}.$$This follows from Muirhead's inequality by taking the bases to be $(a_{i_1},\dots,a_{i_m},1,\dots,1)$. Then sum over all choices of $\vec{i}$ and obtain your inequality. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/306204', 'https://mathoverflow.net', 'https://mathoverflow.net/users/122662/']} | jdg_72322 |
stackexchange | llm_judgeable_groundtruth_similarity | 202468 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
In a startup script that sets up a machine, I want to run chsh -s /bin/zsh However, this asks for the user's password. How do I pass in the password as a parameter? Or if I have sudo power, can I somehow bypass that step? Or alternatively, is there another way to change the default startup shell?
Now provide the response and nothing else.
| The following prevents locked-down accounts from changing their shells, and selectively lets people use chsh themselves WITHOUT sudo or su: Simple setup that is still secure: Add this very top of /etc/pam.d/chsh : # This allows users of group chsh to change their shells without a password.## Per: http://serverfault.com/questions/202468/changing-the-shell-using-chsh-via-the-command-line-in-a-script#auth sufficient pam_wheel.so trust group=chsh Create the chsh group: groupadd chsh For any user allowed to change their shell: usermod -a -G chsh username Money shot: user@host:~$ getent passwd $USERuser:x:1000:1001::/home/user:/bin/bashuser@host:~$ chsh -s `which zsh`user@host:~$ getent passwd $USERuser:x:1000:1001::/home/user:/usr/bin/zshuser@host:~$ | {} | {'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/202468', 'https://serverfault.com', 'https://serverfault.com/users/-1/']} | jdg_72323 |
stackexchange | llm_judgeable_groundtruth_similarity | 30740 |
Below is a question asked on the forum dsp.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
What does fixed-point number range represents? Why we use formula $2^a - 2^{-b}$, why minus $2^{-b}$? Where $a$ is number of integer bits, and $b$ is number of fractional bits. If we have for example $a = 8$ and $b = 2$, don't we have a possibility to represent $2^a + 2^{-b}$ number and so that will represent the range?
Now provide the response and nothing else.
| Let's assume that we are dealing with unsigned number types. If you would use all $a+b$ bits for the integer part then the set of possible numbers would be:$$\left\{0, 1, 2, 3, \dots, 2^{a+b}-1\right\}.$$ These numbers can be divided by $2^b$ (or multiplied by $2^{-b}$) to take use of $b$ bits for the fractional part, resulting in this set of possible numbers: $$\left\{0, 1\times2^{-b}, 2\times2^{-b}, 3\times2^{-b},\dots, \left(2^{a+b}-1\right)\times2^{-b}\right\}\\=\left\{0, 2^{-b}, 2\times2^{-b}, 3\times2^{-b},\dots, \underline{\underline{2^a-2^{-b}}}\right\}.$$ So your formula gives the largest number that can be represented (double underlined). The formula can also be understood as going a step $2^{-b}$ or one least significant bit (LSB) worth backwards from $2^a$ which is the first number that has the same truncated binary string representation as 0, the first number in the system. In a similar way in the 8-bit unsigned integer system we take a LSB-sized step backwards from 256 (1 0000 0000 binary) to obtain 255 (1111 1111 binary) which is the largest representable number in that system. I just found out that range has an established meaning in arithmetic: Largest value minus smallest value. The smallest value happens to be zero so in this case the largest value equals the range. | {} | {'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/30740', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/-1/']} | jdg_72324 |
stackexchange | llm_judgeable_groundtruth_similarity | 6187294 |
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 any way to override the the equals method used by a Set datatype? I wrote a custom equals method for a class called Fee . Now I have a LnkedList of Fee and I want to ensure that there are no duplicated entries. Thus I am considering using a Set insted of a LinkedList , but the criteria for deciding if two fees are equal resides in the overriden equals method in the Fee class. If using a LinkedList , I will have to iterate over every list item and call the overriden equals method in the Fee class with the remaining entries as a parameter. Just reading this alone sounds like too much processing and will add to computational complexity. Can I use Set with an overridden equals method? Should I?
Now provide the response and nothing else.
| As Jeff Foster said: The Set.equals() method is only used to compare two sets for equality. You can use a Set to get rid of the duplicate entries, but beware: HashSet doesn't use the equals() methods of its containing objects to determine equality. A HashSet carries an internal HashMap with <Integer(HashCode), Object> entries and uses equals() as well as the equals method of the HashCode to determine equality. One way to solve the issue is to override hashCode() in the Class that you put in the Set, so that it represents your equals() criteria For Example: class Fee { String name; public boolean equals(Object o) { return (o instanceof Fee) && ((Fee)o.getName()).equals(this.getName()); } public int hashCode() { return name.hashCode(); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6187294', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/127160/']} | jdg_72325 |
stackexchange | llm_judgeable_groundtruth_similarity | 35758 |
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 am by no means an expert in this field, however something puzzles me about the speed of light and the relativity of time and space (space-time). Is is universally acknowledged that the speed of light (299,792,458 m/s) is the universal speed limit, and that nothing can travel faster than light? That is a measurement based on a man-made interpretation of time ( hours, minutes and seconds etc. are man made...there is nothing natural dictating how long a second should be ). For instance, according to Einstein, time and space bend around the physical matter of the universe, so for example, time near or on the surface of a "super massive black hole" should be drastically slower, relative to that of earth. Lets say for example that for every second that passes on the black hole, 10 seconds pass on earth, so essentially time on the surface of the black hole is 10 times slower than the time on earth. Given the example above, is the speed of light at the surface of the black hole still 299,792,458 m/s, or is it 299,792,458,0 m/s?
Now provide the response and nothing else.
| There are more ways to understand this, and the answer is the same: yes, the speed of light is constant. I will try to explain this in the way I consider simpler, but I am sure that others have their preferred explanation. Anyway, to receive a fair explanation, I suggest you to read something more detailed about special relativity, and then about general relativity. My explanation is geometric. Being mathematical, this means that you try first to understand what I mean in an imagined world of mathematics, to see that the ideas are consistent. Think at it as a sci-fi movie, in which you are only concerned with logical possibility. I suggest you that only after you are happy with the self-consistency of the model, you try to judge this image and compare it with what you know about physical world. Spacetime is a space with four dimensions. Near each point, the spacetime is almost flat, but as we depart from the point, it becomes curved. On very short (infinitesimal) distances, the spacetime being almost flat, we can write a Pythagoras' theorem. In four dimension it is like $$d s^2= - c^2d t^2+d x^2 + d y^2 + d z^2.$$ We are interested to make it work also in frames which are not normalized, and have different scales (denoted here by $g_{aa}$), and hence different measurement units: $$d s^2= g_{00}d x_0^2+g_{11}d x_1^2 + g_{22}d x_2^2 + g_{33}d x_3^2.$$ Here I replaced $ct,x,y,z$ with $x_0,x_1,x_2,x_3$. But we also want to write this in coordinates whose axes are not necessarily orthogonal, so we have to add some cosines between the axies $a$ and $b$, which are written as $g_{ab}$: $$d s^2=\sum_{a,b}g_{ab}d x_a d x_b.$$ This also works for curvilinear coordinates (we allow the metric coefficients $g_{ab}$ to vary from point to point), which are the suitable ones for curved spacetime. The length is given by Pythagoras' theorem. Some infinitesimal distances are $d s^2>0$, and they separate points which can be in the same space. Some are $d s^2<0$, and they measure time intervals. Some are $d s^2=0$, and such directions are called light-like direction. So, if you measure the length of a curve described by a photon in spacetime, you measure it with this theorem, and you always obtain it to be $=0$. If you choose the reference frame so that $d x_2=d x_3=0$, and go back to $x,y,z,t$ notation, you obtain that $$g_{11}d x^2+g_{00}c^2d t^2=0,$$ and the light speed is apparently $$\frac{d x}{d t}=c\sqrt{-\frac{g_{00}}{g_{11}}},$$ which is not necessarily $=c$. Can we conclude that it is not constant? Well, not, because this formula doesn't show the speed of light in tehe units in which $c$ is expressed, but in some other units, which are scaled. To find the correct answer, we either choose the frame to be orthonormal, which gives $g_{11}=-g_{00}=1$, or we make sure to divide each infinitesimal distance with the unit "conversion factor" along that direction (they are just $\sqrt{-g_{00}}$ and $\sqrt{g_{11}}$). Hence, the speed of light is always $c$, although in rescaled coordinates may appear not to be. You cannot make it different, no matter how you try, unless you rescale it (i.e change the units). Now, please see that this is not a proof that the speed of light is constant. It is constant by the very construction of the spacetime. It would be circular to claim that this shows the speed of light is constant. I showed you this construction to explain how it is consistent to have constant speed of light, even if time and space intervals change in different frames. Now you can compare this model with the physical data. Now, the "true" speed of light is that present in the wave equation describing the light, in vacuum. And this is still $c$. Can it vary from point to point? It may be possible, in principle, but it is consistent with the observations that it remains constant. If it would vary, Maxwell's equations would not be covariant. This would not be a big deal, one can imagine worlds in which they are not covariant. But the theory of relativity originated from the study of their invariance. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/35758', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/11987/']} | jdg_72326 |
stackexchange | llm_judgeable_groundtruth_similarity | 36227224 |
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 below JSON response in which I need to check whether response field has null value or not. If response field has null value then I need to exit out of the program. [ { "results": { "response": null, "type": "ABC" }, "error": null }] What is the easiest way to check this out? One option I know is to convert JSON to POJO and then check response field. Is there any other way?
Now provide the response and nothing else.
| If you are using codehouse's JSON library , you could do something like this: JSONObject jsonObj = new JSONObject(jsonString); System.out.println(jsonObj .isNull("error") ? " error is null ":" error is not null" ); if using Google's gson : JsonObject jsonObject = new JsonParser().parse(st).getAsJsonObject();JsonElement el = jsonObject.get("error");if (el != null && !el.isJsonNull()){ System.out.println (" not null"); }else{ System.out.println (" is null");} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/36227224', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1950349/']} | jdg_72327 |
stackexchange | llm_judgeable_groundtruth_similarity | 33845 |
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:
Is it possible to get the username and password we enter into sites like facebook using proxy server? The scenario is like this : 1.My laptop is connected to a network. 2.It is configured to use a proxy server to connect to Internet. 3.I enter my credentials into secure sites. Is it possible for others to get credentials in the above scenario ?
Now provide the response and nothing else.
| If the URL uses SSL (i.e. is https:// ) and use the proxy only for transport, then no, the proxy sees only encrypted data and cannot peek at it. (Unless the proxy tries to feed you with a forged certificate, which requires some prior installation of a collaborating CA in your machine; this may happen in work environments, when your enemy is the local sysadmin.) If the connection, as it exits your machine, is unprotected, then yes, by definition the proxy sees every byte which comes and goes. This is true for all proxy technologies. The situation can be made more complex if the proxy itself asks for some authentication, and/or if the proxy negotiates some SSL between itself and the target server. For the technologically unwary, it can become a bit hard to know where the password you type actually goes. If: your browser and local machine are clean (it has not been touched by a potentially hostile sysadmin or malware); your browser says "that's SSL" with the (in)famous padlock icon; the server name in the URL bar is indeed what you expect (it is exactly www.facebook.com , and not something like www.facebook.com.sdjygsdb.com ); your browser sees nothing wrong with the server's certificate (no scary warning, URL bar turned red or something like that); Then: what you send to the server is safe from prying eyes of external entities, including proxies. Otherwise: anything goes. Your data is at least potentially insecurely transfered, and proxies are in ideal conditions to meddle with it. | {} | {'log_upvote_score': 4, 'links': ['https://security.stackexchange.com/questions/33845', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/21885/']} | jdg_72328 |
stackexchange | llm_judgeable_groundtruth_similarity | 1393976 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm reviewing for an intro calculus exam, and the following problem appears on a past final exam: If: $$\int^3_1 \frac{1}{x^4\sqrt{1+x}}\, dx = k$$ What is: $$\int^3_1 \frac{1}{x^5\sqrt{1+x}}\, dx $$ (I'm assuming the answer will be in terms of $k$) It seems that most basic integration techniques(substitution, integration by parts, trig sub, etc.) will not allow the solution of the integral, and I'm not sure how else to approach this problem at my level. I've run this by both my lecturers, and they cannot find a solution in a reasonable amount of time either. I'm curious because it seems the there would be a simple solution or rule I'm ignorant of (considering this is on an intro calc exam), but I'm stumped. Where am I going wrong? Thanks!
Now provide the response and nothing else.
| Let $I_4$ be the given integral (i.e. k) and let $I_5$ be the integral you want. I am just expanding on Zach Stone's comment, so credit due to him, one can intgrate by parts and write $$I_4 = \int^3_1 \frac{1}{x^4}\frac{1}{\sqrt{1+x}}\, dx $$ which will give$$I_4 = \left. \frac{2\sqrt{1+x}}{x^4}\right|_1^3 + \int^3_1 \frac{8\sqrt{1+x}}{x^5}dx$$ The trick is now to multiply and divide the second term within the integral by $\sqrt{1+x}$. The equation then easily simplifies to $$I_4 = \frac{4}{81} - 2\sqrt{2} +8I_4 +8I_5$$ which gives the required relation between $I_4$ and $I_5$. I verified that it agrees with Brian Tung's calculations from Wolfram. So, in short, yes, this was possible using simple integration by parts. Once again, credit to Zach Stone | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1393976', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/261475/']} | jdg_72329 |
stackexchange | llm_judgeable_groundtruth_similarity | 5296810 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm working in a company that has a Winforms application as our flagship product. we recently reworked the branding and UI. We have noticed that the Forms now do not display the text properly and some controls are out of alignment or have disappeared off the edge. Is it possible for me to make the forms on this application DPI-Aware with the least amount of re-factoring as we don't have time.
Now provide the response and nothing else.
| It's essential that you don't specify pixel coordinates and sizes. This rules out using Control.Top and Control.Left , which is what the designer does, when you "just place" the controls on a form. To get an UI that works with different DPI settings, pretty much everything has to be dynamically sized. The controls should have Control.AutoSize enabled. But just enabling AutoSize would totally screw up your layout, since the control position would still be static. To get dynamically position the controls, you can use container controls, like the FlowLayoutPanel and the TableLayoutPanel (with sizes set to AutoSize ). The normal controls inside of those would then just move arround the form, according to automatically determined sizes. As you can see, this isn't simple, requires a bit of experience to get it right and needs a huge amount of testing (virtual machines with different DPI settings work great). But I think it should definitely be done, since I'm always annoyed if something looks stupid and buggy on my laptop. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5296810', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/418103/']} | jdg_72330 |
stackexchange | llm_judgeable_groundtruth_similarity | 43913139 |
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 Firebase HTTPs function. The function needs to read a value from a Firebase database based on the query parameter, and return a result based on this data. The Firebase JS SDK says to do this using: return firebase.database().ref('/users/' + userId).once('value').then(function(snapshot) { var username = snapshot.val().username; // ...}); However, the Cloud functions examples have: var functions = require('firebase-functions');functions.database.ref('/'); But the DB reference doesn't have the method once , only onWrite ( https://firebase.google.com/docs/reference/functions/functions.database.RefBuilder ). This is obviously for DB write functions, rather than HTTP functions. Is there a correct way to read from the database once in a HTTP function? Can I use the normal Firebase SDK, or is there a better way? Thanks.
Now provide the response and nothing else.
| I found the solution in combining the answer here on how to get the parameter and an answer from Michael Blight to How to run query from inside of Cloud function? The answer there also shows what is required to use firebase-admin. The following works for me when calling my-project.firebaseapp.com/event/123/. var functions = require('firebase-functions');const admin = require('firebase-admin');admin.initializeApp(functions.config().firebase);exports.showEvent = functions.https.onRequest((req, res) => { const params = req.url.split("/"); const eventId = params[2]; return admin.database().ref('events/' + eventId).once('value', (snapshot) => { var event = snapshot.val(); res.send(` <!doctype html> <html> <head> <title>${event.name}</title> </head> <body> <h1>Title ${event. name} in ${event.city}</h1> </body> </html>` ); });}); | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/43913139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1578771/']} | jdg_72331 |
stackexchange | llm_judgeable_groundtruth_similarity | 12661648 |
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 do something with WMI (receiving some event notification) so I start with simple example from MSDN website: Receiving Event Notifications Through WMI this program receives an event notification (process creation) through WMI, and calls the function EventSink::Indicate upon receiving the event. I used the same code in the link above (copy/past) with one change:in the class EventSink, the function HRESULT EventSink::Indicate(long lObjectCount, IWbemClassObject **apObjArray) I added few lines to retrieve a property of the object (the object is returned in apObjArray): for (int i = 0; i < lObjectCount; i++) { VARIANT varName; hres = apObjArray[i]->Get(_bstr_t(L"Name"), 0, &varName, 0, 0);//... } now the Get(...) functions returns WBEM_E_NOT_FOUND (The specified property is not found) no matter what I look for (am sure from the documentation that the properties are there...) please let me know what have I missed ?! any help is appreciated.
Now provide the response and nothing else.
| The Name property is part of the TargetInstance object, so you must get the value of the TargetInstance object and then retrieve the value of the Name property. Try this sample HRESULT EventSink::Indicate(long lObjectCount, IWbemClassObject **apObjArray){ HRESULT hr = S_OK; _variant_t vtProp; for (int i = 0; i < lObjectCount; i++) { hr = apObjArray[i]->Get(_bstr_t(L"TargetInstance"), 0, &vtProp, 0, 0); if (!FAILED(hr)) { IUnknown* str = vtProp; hr = str->QueryInterface( IID_IWbemClassObject, reinterpret_cast< void** >( &apObjArray[i] ) ); if ( SUCCEEDED( hr ) ) { _variant_t cn; hr = apObjArray[i]->Get( L"Name", 0, &cn, NULL, NULL ); if ( SUCCEEDED( hr ) ) { if ((cn.vt==VT_NULL) || (cn.vt==VT_EMPTY)) wcout << "Name : " << ((cn.vt==VT_NULL) ? "NULL" : "EMPTY") << endl; else wcout << "Name : " << cn.bstrVal << endl; } VariantClear(&cn); } } VariantClear(&vtProp); } return WBEM_S_NO_ERROR;} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12661648', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1086958/']} | jdg_72332 |
stackexchange | llm_judgeable_groundtruth_similarity | 1701922 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Can mathematical functions have variable (arbitrarily large) number of arguments? If not, which mathematical objects have this property?
Now provide the response and nothing else.
| No. The Euclid-Euler theorem states that any even perfect number $n$ (we don't know whether there are any odd ones) is of the form$$n = 2^{k-1}(2^k - 1)$$with $2^k - 1$ prime, and furthermore that any $n$ of that form is perfect (this last part is relatively easy to prove, but it is the former part you need). This is clearly not a square, since $2^k - 1$ is strictly larger than $2^{k-1}$ and prime. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1701922', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/131461/']} | jdg_72333 |
stackexchange | llm_judgeable_groundtruth_similarity | 45395369 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Got an old application, that prints out quite a lot of messages using console.log , but I just can not find in which files and lines console.log is called. Is there a way to hook into the app and show file name and line numbers?
Now provide the response and nothing else.
| For a temporary hack to find the log statements that you want to get rid of, it's not too difficult to override console.log yourself. var log = console.log;console.log = function() { log.apply(console, arguments); // Print the stack trace console.trace();};// Somewhere else...function foo(){ console.log('Foobar');}foo(); That will print something like FoobarTraceat Console.console.log (index.js:4:13)at foo (index.js:10:13)at Object.<anonymous> (index.js:12:1)... A lot of noise in there but the second line in the call stack, at foo (index.js:10:13) , should point you to the right place. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/45395369', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3540852/']} | jdg_72334 |
stackexchange | llm_judgeable_groundtruth_similarity | 2871906 |
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 know containers of auto pointers should not be used and can cause problems. What is the actual reason for that? Is there any other kind of "smart" pointer which is safe to use in a container?
Now provide the response and nothing else.
| Container elements should be truly copyable; auto_ptr's are not. If you make a copy, the original is modified (it loses ownership). A boost::shared_ptr can be copied, as the two pointers will share ownership afterwards. Thus, it can be used in a STL container. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2871906', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/311151/']} | jdg_72335 |
stackexchange | llm_judgeable_groundtruth_similarity | 45270 |
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:
It is easy to understand the concepts of momentum and impulse. The formula $mv$ is simple, and easy to reason about. It has an obvious symmetry to it. The same cannot be said for kinetic energy, work, and potential energy. I understand that a lightweight object moving at very high speed is going to do more damage than a heavy object moving at a slower speed (their momenta being equal) because $E_k=\frac{1}{2}mv^2$, but why is that? Most explanations I have read use circular logic to derive this equation, implementing the formula $W=Fd$. Even Samlan Khan's videos on energy and work use circular definitions to explain these two terms. I have three key questions: What is a definition of energy that doesn't use this circular logic? How is kinetic energy different from momentum? Why does energy change according to $Fd$ and not $Ft$?
Now provide the response and nothing else.
| You may want to see Why does kinetic energy increase quadratically, not linearly, with speed? as well, it's quite related. Mainly the answer to your questions is "it just is". Sort of. What is a definition of energy that doesn't use this circular logic? Let's look at Newton's second law: $\vec F=\frac{d\vec p}{dt}$. Multiplying(d0t product) both sides by $d\vec s$, we get $\vec F\cdot d\vec s=\frac{d\vec p}{dt}\cdot d\vec s $ $$\therefore \vec F\cdot d\vec s=\frac{d\vec s}{dt}\cdot d\vec p$$$$\therefore \vec F\cdot d\vec s=m\vec v\cdot d\vec v$$$$\therefore \int \vec F\cdot d\vec s=\int m\vec v\cdot d\vec v$$$$\therefore \int\vec F\cdot d\vec s=\frac12 mv^2 +C$$ This is where you define the left hand side as work, and the right hand side (sans the C) as kinetic energy. So the logic seems circular, but the truth of it is that the two are defined simultaneously. How is kinetic energy different from momentum? It's just a different conserved quantity, that's all. Momentum is conserved as long as there are no external forces, kinetic energy is conserves as long as there is no work being done. Generally it's better to look at these two as mathematical tools, and not attach them too much to our notion of motion to prevent such confusions. Why does energy change according to $Fd$ and not $Ft$? See answer to first question. "It just happens to be", is one way of looking at it. | {} | {'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/45270', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/8758/']} | jdg_72336 |
stackexchange | llm_judgeable_groundtruth_similarity | 5300595 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Say I have a training set in a data frame train with columns ColA , ColB , ColC , etc. One of these columns designates a binary class, say column Class , with "yes" or "no" values. I'm trying out some binary classifiers, e.g.: library(klaR)mynb <- NaiveBayes(Class ~ ColA + ColB + ColC, train) I would like to run the above code in a loop, automatically generating all possible combinations of columns in the formula, i.e.: mynb <- append(mynb, NaiveBayes(Class ~ ColA, train)mynb <- append(mynb, NaiveBayes(Class ~ ColA + ColB, train)mynb <- append(mynb, NaiveBayes(Class ~ ColA + ColB + ColC, train)...mynb <- append(mynb, NaiveBayes(Class ~ ColB + ColC + ColD, train)... How can I automatically generate formulas for each possible linear model involving columns of a data frame?
Now provide the response and nothing else.
| Say we work with this ridiculous example : DF <- data.frame(Class=1:10,A=1:10,B=1:10,C=1:10) Then you get the names of the columns Cols <- names(DF)Cols <- Cols[! Cols %in% "Class"]n <- length(Cols) You construct all possible combinations id <- unlist( lapply(1:n, function(i)combn(1:n,i,simplify=FALSE) ) ,recursive=FALSE) You paste them to formulas Formulas <- sapply(id,function(i) paste("Class~",paste(Cols[i],collapse="+")) ) And you loop over them to apply the models. lapply(Formulas,function(i) lm(as.formula(i),data=DF)) Be warned though: if you have more than a handful columns, this will quickly become very heavy on the memory and result in literally thousands of models. You have 2^n - 1 different models with n being the number of columns. Make very sure that is what you want, in general this kind of model comparison is strongly advised against. Forget about any kind of inference as well when you do this. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5300595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/488719/']} | jdg_72337 |
stackexchange | llm_judgeable_groundtruth_similarity | 24196689 |
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 learning swift recently, but I have a basic problem that can't find an answer I want to get something like var a:Int = 3var b:Int = 3 println( pow(a,b) ) // 27 but the pow function can work with double number only, it doesn't work with integer, and I can't even cast the int to double by something like Double(a) or a.double()... Why it doesn't supply the power of integer? it will definitely return an integer without ambiguity !and Why I can't cast a integer to a double? it just change 3 to 3.0 (or 3.00000... whatever) if I got two integer and I want to do the power operation, how can I do it smoothly? Thanks!
Now provide the response and nothing else.
| If you like, you could declare an infix operator to do it. // Put this at file level anywhere in your projectinfix operator ^^ { associativity left precedence 160 }func ^^ (radix: Int, power: Int) -> Int { return Int(pow(Double(radix), Double(power)))}// ...// Then you can do this...let i = 2 ^^ 3// ... orprintln("2³ = \(2 ^^ 3)") // Prints 2³ = 8 I used two carets so you can still use the XOR operator . Update for Swift 3 In Swift 3 the "magic number" precedence is replaced by precedencegroups : precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }infix operator ^^ : PowerPrecedencefunc ^^ (radix: Int, power: Int) -> Int { return Int(pow(Double(radix), Double(power)))}// ...// Then you can do this...let i2 = 2 ^^ 3// ... orprint("2³ = \(2 ^^ 3)") // Prints 2³ = 8 | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/24196689', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2611007/']} | jdg_72338 |
stackexchange | llm_judgeable_groundtruth_similarity | 123373 |
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 there some way of solving $$\frac{e^x}{x^3} = 2x + 1 $$non-numerically?How would I go about proving if there exists a closed form solution? Similarly how would I go about proving if there exists an analytic solution?
Now provide the response and nothing else.
| GEdgar answers the question of proving that there's no algebraic closed form solution, i.e. a solution that is an algebraic number (a root of some finite degree polynomial with rational coefficients). However, as he mentions, if there were such a solution $a$, then $a^3(2a+1)$ would also be algebraic, and couldn't equal $e^a$ which would be transcendental by Lindemann's theorem. The best that you can do is to solve it numerically, e.g. with Newton's method. You could use the Lagrange inversion formula (as Robert Israel does), or perhaps some variation of Lambert's W function or an infinite continued fraction expansion for each of the three real solutions. The best general technique to find real solutions is to first locate the solutions, then use an appropriate iterative method to get the required accuracy. In this case, an excellent method that you could even do by hand if you had to would be to graph $e^x$ (in blue below) versus the polynomial $x^3(2x+1)$ (in red). Because of the contrast in scale near the origin, where there are two roots, and away from it in the first quadrant, where the third root lies, it is not possible to depict these on a linear scale (without ellipsis). So I show the important views below. The first graph, of the polynomial RHS near the origin, you should be able to sketch purely from looking at the factored form. Knowing the shape of an exponential $e^x$, and knowing that it always eventually outgrows any polynomial, you can then deduce that there must be three roots. As @RobertIsrael pointed out, there are actually infinitely many complex numbers satisfying the equation. If we rewrite it with the customary variables $z=x+iy=re^{i\theta}$ (i.e., with $z$ in stead of $x$), the equation becomes$$e^x(\cos y+i\sin y) = e^z = w = 2z^3 \left( z+\frac12 \right) = 2z^4+z^3.$$Now we can treat the right and left sides as two functions$w=f(z)=e^z$ and $w=g(z)=2z^4+z^3$ in the complex plane.The exponential function $f(z)$ takes each vertical line to a circle (a covering map).The imaginary axis gets mapped to the unit circle, with $0$ sent to $1$ and preserving length. Lines with fixed $x$ are first scaled by $r=e^x$ and then wrapped around the circle of radius $r$ centered at the origin. Each vertical line is mapped surjectively (and periodically) onto the corresponding circle. Each horizontal strip $y\in\left(2\pi t-\pi,2\pi t+\pi\right]$ (for each $t\in\mathbb{R}$) is consequently mapped smoothly and injectively onto $\mathbb{C}\setminus\{0\}$ by $z\rightarrow e^z$. So much for the left hand side. The right hand side is a degree $4$ polynomial map. As a function of its real and imaginary components, it is$$g(z) =2y^4 - i(8x+1)y^3 - 3x(4x+1)y^2 + ix^2(8x+3)y + x^3(2x+1) =$$$$\left(2y^4 - 3x(4x+1)y^2 + x^3(2x+1)\right)+\left( - (8x+1)y^3 + x^2(8x+3)y\right)\,i$$and as a function of its polar variables, it is$$g(z) =2z^4+z^3= r^3 e^{3i\theta} \left( 2 \, r e^{i\theta} + 1 \right)= 2 \, r^4 e^{4i\theta} + r^3 e^{3i\theta}$$from which we can see that circles centered at the originget mapped to closed curves with some fixed total curvature.Here are plots of the image of $r=1$, $r=2$, and $r=\frac12$(identifiable by their scale), which each have rotation index $4$and total curvature $8\pi$. In contrast, the winding number is not constant over the curve's interior because the curveintersects itself multiple times and hence is also not simple. Of course, the exponential map $f(z)$ also maps circles to closed curves,and in particular, it maps central circles $z=re^{i\theta}$ with fixed $r$to curves with reciprocal positive real interceptsand unit winding number about $w=1$.To investigate these images, let us notethat for $r > 0$ fixed and constant,$$\left.\eqalign{ & x+iy=z=re^{i\theta} \\\\ & \frac{dz}{d\theta}=iz=-y+ix}\right\}\qquad\implies\qquad\eqalign{ \frac{dx}{d\theta}&=-&y=-&r\sin\theta \\\\ \frac{dy}{d\theta}&= &x= &r\cos\theta}$$so that for $w=f(z)$,$$\left.\eqalign{ & u+iv = w=e^z = \frac{dw}{dz} \\\\ & \eqalign{ \frac{dw}{d\theta} &= \frac{dw}{dz}\,\frac{dz}{d\theta} = w \cdot iz = ire^{x+i(y+\theta)} \\\\& = izw = i(x+iy)(u+iv) \\\\& = -(xv+yu)+(xu-yv)i }}\right\}\qquad\implies\qquad\eqalign{ \frac{du}{d\theta}&=-&re^x\sin(\theta+y) \\\\ \frac{dv}{d\theta}&= &re^x\cos(\theta+y) \\\\ \frac{dv}{du} &=-&\cot(\theta+r\sin\theta)}$$Identifiying $f$ and $g$ with real functions$F,G:\mathbb{R}^2\rightarrow\mathbb{R}^2$,$$\eqalign{F(r,\theta)&=f(z) =e^{r\cos\theta} \left( \cos\left(r\sin\theta\right),~ \sin\left(r\sin\theta\right) \right)\\\\G(r,\theta)&=g(z) =r^3 \left( 2r\cos{4\theta} +\cos{3\theta},~ 2r\sin{4\theta} +\sin{3\theta} \right)}$$our complex equation becomes a system of two simultaneous real equations:$$\eqalign{ e^{r\cos\theta} \cos\left(r\sin\theta\right) &= r^3 \left( 2r\cos{4\theta} +\cos{3\theta} \right) = r^3 \left( 2r\,\href{http://en.wikipedia.org/wiki/Chebyshev_polynomials#Examples}{T_4}\left(\cos\theta)\right) +T_3\left(\cos\theta)\right) \right)\\\\ e^{r\cos\theta} \sin\left(r\sin\theta\right) &= r^3 \left( 2r\sin{4\theta} +\sin{3\theta} \right) = r^3 \left( 2r\,\href{http://en.wikipedia.org/wiki/Chebyshev_polynomials#Examples}{U_4}\left(\cos\theta)\right) +U_3\left(\cos\theta)\right) \right) \sin\theta}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/123373', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1798/']} | jdg_72339 |
stackexchange | llm_judgeable_groundtruth_similarity | 1407014 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
The question is to compute:$$(1+\cos A)+2(1+\cos A)^2 + 3(1+\cos A)^3+\ldots = \sum_{k=1}^{\infty}k(1+\cos A)^k.$$ I tried by setting $1+\cos A=y$, then the serie becomes $$y+2y^2+3y^3+\ldots = \sum_{k=1}^{\infty}ky^k$$ It's not a geometric progression as the coefficients are not in the series. How can I go further? Hints are welcome.
Now provide the response and nothing else.
| Using Ratio test, $$\lim_{n\to\infty}\dfrac{(n+1)(1+\cos A)^{n+1}}{n(1+\cos A)^n}=\left(1+\cos A\right)\lim_{n\to\infty}\left(1+\dfrac1n\right)=1+\cos A$$ So, the series can only converge if $|1+\cos A|<1\iff 1+\cos A<1\iff\cos A<0$ For $|y|<1,$ let $$S_n=\sum_{r=1}^nr y ^r$$ $$yS_n=\sum_{r=1}^nry^{r+1}$$ $$(1-y)S=y+y^2+y^3+\cdots=\dfrac y{1-y}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1407014', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/242814/']} | jdg_72340 |
Subsets and Splits