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 | 2217116 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose every proper subspace $(\neq V)$ of a vector space $V$ is finite dimensional. Prove that $V$ is finite dimensional. This question just popped into my head when I was reading about inner product space, so I can't guarantee how legitimate the question is. My try: Assume V is an inner product space. Take any proper subspace $U$ of $V$. Then $V=U\oplus U^{\bot}$. Both $U$ and $U^{\bot}$ are finite dimensional. So they both have a basis of finite dimension and we will be done. So for the inner product space $V$ the statement holds true. What about other cases? Does the statement hold true for every vector space? Does there exist a characteristic to identify vector spaces with this property?
Now provide the response and nothing else.
| You need to use the fact that every linearly independent set can be extended to a basis. Then you can take any nonzero vector $v$, extend $\{v\}$ to a basis $B$, and consider the span of $B\setminus\{v\}$. Being finitely dimensional, it means that $B\setminus\{v\}$ is finite, so $B$ is finite, and so $V$ has a finite dimension. It might be relevant to point out that the fact "every linearly independent set can be extended to a basis" is equivalent to the axiom of choice. Of course we need only a small fraction of choice for this specific proof (although that would alter the formulation a bit). Nevertheless, it is consistent without the axiom of choice that there is a vector space which is not finitely dimensional, but every proper subspace does in fact have a finite dimension. Weird. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2217116', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/71612/']} | jdg_75641 |
stackexchange | llm_judgeable_groundtruth_similarity | 95982 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
The exceptional complex simple Lie algebra $F_4$ has an irreducible 26-dimensional representation $V$ with Dynkin label [0,0,0,1] in the usual ordering of the simple roots one can find, say, in Humphreys's book on Lie algebras and representation theory. In fact, $F_4$ can be defined as the Lie subalgebra of $\mathfrak{sl}(V)$ which preserves a symmetric inner product and a certain cubic form on $V$ . Now there are three different real forms of $F_4$ and my question is about what happens to $V$ when restricting to these real forms. The three real forms are the compact real form, the split real form and a third form. They can be distinguished by the 'index' of the Killing form; i.e., if the Killing form $\kappa(X,Y) = \operatorname{Tr} \operatorname{ad}_X \operatorname{ad}_Y$ has signature $(p,q)$ , its index is $p-q$ . I am most familiar with the compact real form, for which the Killing form is negative-definite, whence of index $-52$ . The split real form has index $4$ and the third real form has index $-20$ , and are denoted $F_4^4$ and $F_4^{-20}$ , respectively. I would like to know the following (pointers to the literature would also be greatly appreciated): Questions What is the type of $V$ under the different real forms? I know that for the compact real form it is real, but I would like to know also for $F_4^{-20}$ and $F_4^4$ . And if the type is real (as I suspect is the case), what is the signature of the invariant inner product on the underlying real representation $V_{\mathbb{R}}$ ? Thanks in advance! Edit Based on Jim's answer below, the representations are of real type in all cases. From Bruce's answer, it would seem that for the split case $F_4^4$ the signature is (14,12). In a rather convoluted calculation, I seem to find that for $F_4^{-20}$ the signature is (16,10), but I would like confirmation since I have seen at least one claim in the Physics literature (see last equation in §4) that it is (25,1).
Now provide the response and nothing else.
| I think the best way to see the signature of these quadratic forms is by using the formula from "A Classification Theorem for Albert Algebras" by R. Parimala, R. Sridharan, and Maneesh L. Thakur, Trans. AMS 350 #3, March 1998. All forms of $F_4$ arise from Albert algebras. Over $R$, these are 27-dimensional algebras, whose unital automorphisms form groups of type $F_4$. They are classified, over fields of characteristic neither $2$ nor $3$, by cohomological invariants $f_3$ and $f_5$. These cohomological invariants determine 3-fold and 5-fold Pfister forms, $\phi_3$ and $\phi_5$ respectively. The formula of P-S-T (above), or maybe originally due to Serre, is that for an Albert algebra $A$ over $k$,$$Q_A \perp \phi_3 \cong <2,2,2> \perp \phi_5.$$ Now there are only two Pfister forms over $R$ for $\phi_3$ and $\phi_5$. The signature of $\phi_3$ is either $(8,0)$ or $(4,4)$. Similarly, the signature of $\phi_5$ is either $(32,0)$ or $(16,16)$. The signature of $<2,2,2>$ is $(3,0)$. Hence the possibilities for the signature $(p,n)$ of $Q_A$ are:$$(p,n) + (8,0) = (3,0) + (32,0),$$$$(p,n) + (8,0) = (3,0) + (16,16),$$$$(p,n) + (4,4) = (3,0) + (32,0),$$$$(p,n) + (4,4) = (3,0) + (16,16).$$ Only three cases are possible: $(p,n) = (27,0)$ or $(p,n) = (11,16)$ or $(p,n) = (15,12)$. As $F_4$ acts on the orthogonal complement of the identity, and the identity has positive norm, the possible signatures for the 26-dimensional rep of $F_4$ are:$$(26,0), (10,16), (14,12).$$ | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/95982', 'https://mathoverflow.net', 'https://mathoverflow.net/users/394/']} | jdg_75642 |
stackexchange | llm_judgeable_groundtruth_similarity | 48651166 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
While I was doing some basic HTML I was wondering why Sublime Text 3 always completes required into required="" . Like my Instructor in an online course said it is not necessary to set required="true" or required="false" but when I set it to false it still requires it. example code (it will require the field even if it is set tofalse): <form> <input type="password" name="password" required="false"> <button>Submit</button></form> I hope you can clear up the confusion. Thanks for every answer. Farcher
Now provide the response and nothing else.
| In HTML, the required attribute must be present (the field is required) or absent (the field is NOT required). When the attribute is present, it does not matter what value it has. The required attribute is a boolean attribute. When specified, the element is required. The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value. About boolean attributes : A boolean attribute without a value assigned to it (e.g. checked) is implicitly equivalent to one that has the empty string assigned to it (i.e. checked=""). As a consequence, it represents the true value. The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether. A common practice is to use the name of the attribute as its value : <form> <input type="password" name="password" required="required"><!-- this input is required --> <input type="text" name="sometext"><!-- this input is NOT required --> <button>Submit</button></form> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/48651166', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_75643 |
stackexchange | llm_judgeable_groundtruth_similarity | 8513408 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to have a C++ Interface that must be overridden (if this is possible) when inherited. So far, I have the following: class ICommand{public: // Virtual constructor. Needs to take a name as parameter //virtual ICommand(char*) =0; // Virtual destructor, prevents memory leaks by forcing clean up on derived classes? //virtual ~ICommand() =0; virtual void CallMe() =0; virtual void CallMe2() =0;};class MyCommand : public ICommand{public: // Is this correct? MyCommand(char* Name) { /* do stuff */ } virtual void CallMe() {} virtual void CallMe2() {}}; I have purposely left how I think the constructor/destructor's should be implemented in ICommand . I know if I remove the comments, it will not compile. Please could someone: Show me how to declare the constructor/destructor's in ICommand and how they are meant to be used in MyCommand Have I set things up correctly in ICommand so that MyCommand must override CallMe and CallMe2 .
Now provide the response and nothing else.
| C++ does not allow for virtual constructors. A simple implementation (without the virtual constructor) would look something like this: class ICommand {public: virtual ~ICommand() = 0; virtual void callMe() = 0; virtual void callMe2() = 0;};ICommand::~ICommand() { } // all destructors must exist Note that even a pure virtual destructor must be defined. A concrete implementation would look exactly like your example: class MyCommand : public ICommand {public: virtual void callMe() { } virtual void callMe2() { }}; You have a couple of options for the constructor. One option is to disable the default constructor for ICommand , so that subclasses will have to implement a constructor that calls your ICommand constructor: #include <string>class ICommand {private: const std::string name; ICommand();public: ICommand(const std::string& name) : name(name) { } virtual ~ICommand() = 0; virtual void callMe() = 0; virtual void callMe2() = 0;};ICommand::~ICommand() { } // all destructors must exist A concrete implementation would now look something like this: class MyCommand : public ICommand {public: MyCommand(const std::string& name) : ICommand(name) { } virtual void callMe() { } virtual void callMe2() { }}; | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8513408', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/315711/']} | jdg_75644 |
stackexchange | llm_judgeable_groundtruth_similarity | 20314098 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm new to Spring MVC (previously used Rails and ASP.NET MVC). I noticed that I still have to use servlets. From what I can see, Spring requires you to work with servlets--you can't swap it for a different view engine (like Apache Velocity). Is it possible to use Spring MVC with a different view engine? There doesn't seem to be any material about this that I can find.
Now provide the response and nothing else.
| There's some confusion. You can't have Spring MVC without servlets, simply because Spring MVC is built on top of the Servlet technology. (But that is not a problem, because you can have other view technologies.) You are confusing view technologies with servlets. There are several possible view technologies. If something, servlets are controllers, not views (actually, Spring MVC follows a Model 2 MVC , so servlets are not controllers inthe same sense as used in the standard MVC pattern). The Spring Framework has a chapter dedicated to view technologies: http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/view.html There you can find info and how to configure several views technologies, such as: JSP & JSTL Tiles Velocity & FreeMarker XSLT, Document views (PDF/Excel), JasperReports and others. But don't be limited to that guide. There are other view technologies not listed there (as the view mechanism is very flexible and extensible). A very good example of one that is not listed there is Thymeleaf . I'll try to clarify the Servlet vs. Controller question: MVC Pattern "Standard" MVC pattern works like the picture below: The first source of confusion is to try to "fit" Spring MVC (because of the name) into this MVC. This usually leads to a mistake, as Spring MVC relates better to a variation of this pattern, as discussed below. About the question, what I mean is: If really you just want to take this MVC pattern into account, Servlets are more like controller s, not views. Model 2 MVC Pattern To be really accurate, as said, Spring MVC does not follow the "standard" MVC, in fact it is more in tune with a Model 2 MVC , which includes a front controller component in addition to the already existing ones (model, view and controller), like the image: Now, in the Model 2 MVC, Servlets are not the controller components. They are the Front Controller (in fact, org.springframework.web.servlet.DispatcherServlet is the front controller). In this picture: Front Controller is the org.springframework.web.servlet.DispatcherServlet . Controller s are your classes (usually annotated with @Controller ). View Template is a JSP/VM/HTML file, which will be rendered, based on the Model , by your selected View Technology (as listed before JSP, Tiles, Velocity, Thymeleaf... -- not Servlets). Model is the data (objects) from your domain, being passed around from the controller to the view. What view engines are most commonly used? This is a very relative question. All of those listed in the Spring reference are very popular. Aside from them, Thymeleaf is another very good I know. It is not fair to say one is better than the other, and the ultimate decision would depend on your project's needs. Nevertheless, here's my two cents about the ones I've used: JSP is the oldest (which is good and bad at the same time) and one of the fastest, but can be very verbose and allow use of Java snippets in the pages. JSTL makes the syntax of JSP pages better, at the cost of performance. Freemarker and Velocity look very alike, they are very fast, their syntax is different than JSP (wether it is clearer is probably a personal opinion) and they have very good templating system. I haven't used Tiles , but I hear they have very good templating and componentization. Thymeleaf bets on having very maintainable HTML, and is a very healthy project with a growing comunity. See Thymeleaf vs. JSP . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20314098', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/210780/']} | jdg_75645 |
stackexchange | llm_judgeable_groundtruth_similarity | 3976959 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Suppose I have three events: $S_1$ , $S_2$ , $S_3$ . Is there a way to express $((S_1 \cup S_2) \cap (S_2 \cup S_3) \cap (S_3 \cup S_1))$ in a simpler manner?
Now provide the response and nothing else.
| zkutch's claim isn't quite right. If you draw the Venn diagram, you get: Which is not the same as $A\cap B\cap C$ . I guess you can also express your event as $$(S_1\cap S_2)\cup(S_2\cap S_3)\cup(S_3\cap S_1)$$ but this isn't really simpler. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3976959', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/871342/']} | jdg_75646 |
stackexchange | llm_judgeable_groundtruth_similarity | 33842 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
The Suzuki and Ree groups are usually treated at the level of points. For example, if $F$ is a perfect field of characteristic $3$, then the Chevalley group $G_2(F)$ has an unusual automorphism of order $2$, which switches long root subgroups with short root subgroups. The fixed points of this automorphism, form a subgroup of $G_2(F)$, which I think is called a Ree group. A similar construction is possible, when $F$ is a perfect field of characteristic $2$, using Chevalley groups of type $B$, $C$, and $F$, leading to Suzuki groups. I apologize if my naming is not quite on-target. I'm not sure which groups are attributable to Suzuki, to Ree, to Tits, etc.. Unfortunately (for me), most treatments of these Suzuki-Ree groups use abstract group theory (generators and relations). Is there a treatment of these groups, as algebraic groups over a base field? Or am I being dumb and these are not obtainable as $F$-points of algebraic groups. I'm trying to wrap my head around the following two ideas: first, that there might be algebraic groups obtained as fixed points of an algebraic automorphism that swaps long and short root spaces. Second, that the outer automorphism group of a simple simply-connected split group like $G_2$ is trivial (automorphisms of Dynkin diagrams mean automorphisms that preserve root lengths). So I guess that these Suzuki-Ree groups are inner forms... so there must be some unusual Cayley algebra popping up in characteristic 3 to explain an unusual form of $G_2$. Or maybe these groups don't arise from algebraic groups at all. Can someone identify and settle my confusion? Lastly, can someone identify precisely which fields of characteristic $3$ or $2$ are required for the constructions of Suzuki-Ree groups to work?
Now provide the response and nothing else.
| It is not really a question of inner forms. What happens is that the algebraic group $G_2$ has an extra endomorphism $\varphi$ whose squareis the Frobenius map (over the appropriate finite field). Just as for anyalgebraic group over a finite field $F$ its rational points over $F$ are thefixed points of the Frobenius endomorphism the Suziki groups are, by definition,the fixed points of $\varphi$. Again, just as the Frobenius, on points over thealgebraic closure of $F$ $\varphi$ is an automorphism of the abstract group.However, that is misleading, the essential points is that it is an endomorphism(which definitely is not an automorphism) of the algebraic group. Most of theproperties of points over $F$ of a semi-simple algebraic group $G$ defined over$F$ follows from the algebro-geometric theory of $G$ and the properties of theFrobenius endomorphism. Similarly, most of the properties of Suziki groupsfollows from the algebro-geometric theory of $G_2$ together with the propertiesof $\varphi$. As $\varphi$ is very similar to the Frobenius endomorphism thisworks almost the same way as if $\varphi$ were indeed a Frobenius endomorphism. Addendum : As one simple example of the similarity of $\varphi$ to a Frobenius consider the problem of computing the order of the Suzuki groups. As the square of $\varphi$ is the Frobenius, the action of it on the tangent space at any fixed point is nilpotent. This implies that such a fixed point appear with multiplicity one in the Lefschetz fixed point formula and the order of its group of fixed points is thus equal to the Lefschetz trace on (étale) cohomology of the algebraic group $G_2$. That cohomology can be canonically expressed in terms the action of the Weyl group on the character group of the maximal torus (see for instance example in SGA 4 1/2) and how $\varphi$ acts on that character group is essentially part of the definition of $\varphi$. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/33842', 'https://mathoverflow.net', 'https://mathoverflow.net/users/3545/']} | jdg_75647 |
stackexchange | llm_judgeable_groundtruth_similarity | 7644156 |
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 Entity Framework 4.1 database first approach. I've used legacy database. In my edmx file which created entity classes based on tables in the legacy database, there is a one-to-zero-or-one association between some entities. Although I explored the tables of database and relation between them I didn't find out how one-to-zero-or-one relation have been implemented in database. For more information I put some screenshots of my database diagram and the property of its relation and correspondent entities in edmx file:
Now provide the response and nothing else.
| The 1-0..1 relation in your database is directly visible. It is built between Course and OnlineCourse tables where Course is principal in relation (1) and OnlineCourse is dependent with FK configured on CourseID. FK is also PK of the OnlineCourse = it must be unique and because of that it is 0..1. Database "always" uses 1 - 0..1 because real 1 - 1 cannot be effectively used for data insertion. 1 - 1 means that left must be inserted after right but right must be inserted after left = impossible. Because of that 1 - 0..1 is used where left is principal and must be inserted before right and right is dependent and must be inserted after left. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7644156', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1904217/']} | jdg_75648 |
stackexchange | llm_judgeable_groundtruth_similarity | 70292 |
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:
Are the dies made for a BGA package any different from the dies for a QFN or a DIP Package? Do BGA dies have connections on the lower side of the die? In the substrate? How are terminals put in the package under the die? I came across this picture. Are BGA packages actually PCBs? and are signals just taken off the die edge and routed to the bottom of the package? If so, how does this help in decreasing inductance at high frequencies? I also came across the image below which makes it look like the BGA packages have connections from the bottom side - from the substrate.
Now provide the response and nothing else.
| Yes, BGA packages are like little circuit boards. On high pin count devices, in nearly all cases, the balls that lie directly under the die are mostly ground (and sometimes power) connections. The ground balls are fed directly through to the substrate of the die, while the power balls connect to internal power planes.Also, because of their direct metallic connection to the die, the ground balls help remove heat from the package. All of the I/O is connected to balls near the periphery of the package, keeping their internal traces — as well as the PCB traces they connect to — shorter and inductances lower. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/70292', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/4561/']} | jdg_75649 |
stackexchange | llm_judgeable_groundtruth_similarity | 201046 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am pretty new to electronics, and have mainly worked with DC circuits. I'm majoring in Computer Science, but I also find electrical engineering interesting, so I am learning as much as I can. Well, my multimeter measures about 0.050 to 0.100mV when not connected to anything. As soon as I move close to the wall outlet, it creeps up to 0.1 volts, then 2 volts, then when I am pretty close to it, it reads about 4 - 6 volts. Also, when I plug one lead into the hot or neutral, why does it read 6 volts or more? And between neutral and ground, it usually reads 0.4 volts when there is minimal load on the outlet. I heard that that is normal, but is 4.4 volts from neutral to ground normal when a 1300W heater is running? Thank you for your help. I'm still learning, so these questions may sound stupid. And yes, I am taking safety precautions so that I do not get shocked.
Now provide the response and nothing else.
| 0.050 to 0.100mV when not connected to anything This is pretty normal. It's not a big number and probably just represents the noise floor of your multimeter. As soon as I move close to the wall outlet, it creeps up to 0.1 volts, then 2 volts, then when I am pretty close to it, it reads about 4 - 6 volts. Also pretty normal. The electric fields emanating from house AC wiring can make a multimeter show these kind of voltages when close up. It's mainly due to the electric fields capacitively coupling to you probes with your body acting as a capacitor to ground. It would be interesting to see what the voltage drops to when you stop holding the multimeter - I would expect it to still register a number but a smaller number. between neutral and ground, it usually reads 0.4 volts when there is minimal load on the outlet. I heard that that is normal, but is 4.4 volts from neutral to ground normal when a 1300W heater is running? 4.4 volts is certainly no un-heard of. Usually neutral is connected to earth at some point between your house and the local sub-station and given the volt drop down the neutral wire when passing several amps this would be fairly commonplace. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/201046', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/91858/']} | jdg_75650 |
stackexchange | llm_judgeable_groundtruth_similarity | 3941719 |
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 access notes and calendar using native iphone app. I want to know is it possible in new iphone os? Is there any public pi for that?
Now provide the response and nothing else.
| There is the Event Kit API which is documented in T he Event Kit Programming Guide . As far as I know you cannot access Notes. The Event Kit and Event Kit UI frameworks together allow iOS applications to access event information from a user’s Calendar database. You can fetch events based on a date range or a unique identifier, receive notifications when event records change, and allow users to create and edit events for any of their calendars. Changes made to events in a user’s Calendar database with Event Kit are automatically synced with the appropriate calendar (CalDAV, Exchange, and so on). This document describes Event Kit concepts and common programming tasks. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3941719', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/443242/']} | jdg_75651 |
stackexchange | llm_judgeable_groundtruth_similarity | 3989219 |
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 first thing that I tried to do is to differentiate both functions and try to see if there establishes inequality that we want (considering that they are equal when $x = 0$ ). This attempt failed because firstly it really is true but after that we get opposing inequality. Also, I have noticed that $\lim \frac{x}{1 + x \cdot \frac{2}{\pi}} = \lim \arctan(x) = \frac{\pi}{2}$ as $x \rightarrow + \infty$ but it didn't lead me to solution. I also tried to apply Taylor's formula but it didn't help much either. So, what are available ways to solve this problem?
Now provide the response and nothing else.
| A possible way is to set $x = \tan t$ with $t \in \left(0,\frac{\pi}{2}\right)$ . So, the inequality is equivalent to $$\frac{\tan t}{1+\frac 2{\pi} \tan t}< t \text{ for } t \in \left(0,\frac{\pi}{2}\right)$$ or after rearranging $$ \tan t < \frac t{1-\frac 2{\pi}t} \text{ for } t \in \left(0,\frac{\pi}{2}\right)$$ But this is true because for $t \in \left(0,\frac{\pi}{2}\right)$ we have $\sin t < t$ and because of the concavity of $\cos$ on this interval we have $\cos t > 1-\frac 2{\pi} t$ . Hence, $$\tan t = \frac{\sin t}{\cos t} < \frac t{1-\frac 2{\pi} t} \text{ for } t \in \left(0,\frac{\pi}{2}\right)$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3989219', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/824195/']} | jdg_75652 |
stackexchange | llm_judgeable_groundtruth_similarity | 37002677 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
UPDATE: Solution found! Scroll down for my accepted answer! I want to animate multiple elements of one image and link the animation to ViewPagers position (so multiple elements are morphing or flying in/out depending on the current page being dragged). So, is there a way to precisely control the current frame of the animation? For example let's assume i have this set: <?xml version="1.0" encoding="utf-8"?><set xmlns:android="http://schemas.android.com/apk/res/android"> <objectAnimator android:interpolator="@android:anim/decelerate_interpolator" android:duration="800" android:propertyName="scaleY" android:valueFrom="0" android:valueTo="1" /> <objectAnimator android:interpolator="@android:anim/decelerate_interpolator" android:duration="800" android:propertyName="scaleX" android:valueFrom="0" android:valueTo="1" /> <objectAnimator android:interpolator="@android:anim/decelerate_interpolator" android:duration="800" android:propertyName="rotation" android:valueFrom="0" android:valueTo="360" /></set> Animated vector file: <animated-vector xmlns:android="http://schemas.android.com/apk/res/android" android:drawable="@drawable/pre_signup_1" > <target android:name="plus_button" android:animation="@anim/pre_signup_1_plus_container" /> <target android:name="plus" android:animation="@anim/pre_signup_1_plus_sign" /></animated-vector> Java code to run the animation: ImageView mImage1 = (ImageView) findViewById(R.id.image_1);AnimatedVectorDrawableCompat animated = (AnimatedVectorDrawableCompat) mImage1.getDrawable();animated.start(); Is there a way to control the animation like setCurrentDuration(400) which will presumably set the current state of the animation to it's half? Maybe there is a way to split that vector drawable into layers and animate them programmatically? Thanks in advance!
Now provide the response and nothing else.
| Looks like it is possible to access paths and groups inside VectorDrawableCompat and animate/morph them however you want! After a some research I ended up duplicating the following classes from the android.support.graphics.drawable package: AndroidResources , PathParser , TypedArrayUtils , VectorDrawableCommon and VectorDrawableCompat . Next we need to make the following method and classes public inside of the VectorDrawableCompat class: getTargetByName , VGroup and VFullPath . Next in the VectorDrawableCompat class remove the block that checks for Android version ( Build.VERSION.SDK_INT >= 23 ). Don't know why, but if you don't do it, the animating won't work on android API 23 and up (need more research). I may have missed a couple of private methods, but it's just a matter of making them public if you run into problems. So, now we have access to the layers of our VectorDrawable ! Here is a small example of scaling a vector group depending on the ViewPager 's position: <?xml version="1.0" encoding="utf-8"?><vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="276dp" android:height="359dp" android:viewportWidth="276" android:viewportHeight="359"> <group android:pivotX="205.5" android:pivotY="214.5" android:name="my_group"> <path android:strokeColor="#4D394B" android:strokeWidth="7" android:strokeLineJoin="bevel" android:fillColor="#1ED761" android:pathData="M206.5,180 C186.9,180,171,195.9,171,215.5 S186.9,251,206.5,251C226.1,251,242,235.1,242,215.5 S226.1,180,206.5,180 Z" /> <path android:fillColor="#4D394B" android:pathData="M210,211 L210,190 L202,190 L202,211 L181,211 L181,219 L202,219 L202,241 L210,241L210,219 L232,219 L232,211 Z" /> </group></vector> And this is the code used to animate the group: ImageView myImageView;VectorDrawableCompat.VGroup myVectorGroup;@Overrideprotected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); myImageView = (ImageView) findViewById(R.id.image_1); VectorDrawableCompat vectorDrawable = VectorDrawableCompat.create(getResources(), R.drawable.my_vector_drawable, null); vectorDrawable.setAllowCaching(false); // Important to allow image updates myVectorGroup = (VectorDrawableCompat.VGroup) vectorDrawable.getTargetByName("my_group"); myImageView.setImageDrawable(vectorDrawable); mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { if(myVectorGroup != null && position < 1) { myVectorGroup.setScaleX(1f - positionOffset); myVectorGroup.setScaleY(1f - positionOffset); myImageView.invalidate(); } } });} I need some more testing to determine compatibility, but it works for now! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37002677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1669107/']} | jdg_75653 |
stackexchange | llm_judgeable_groundtruth_similarity | 22077725 |
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 speed up the npm install during the build process phase. My package.json has the list of packages pretty much with locked revisions in it. I've also configured the cache directory using the command npm config set cache /var/tmp/npm-cache --global However, on trying to install using npm install -g --cache , I find that this step isn't reducing the time to install by just loading the packages from cache as I would expect. In fact, I doubt if it's even using the local cache to look up packages first.
Now provide the response and nothing else.
| Proposing two more modern approches: 1) npm ci Use npm ci , which is available from npm version 5.7.0 (although I recommend 5.7.1 and upwards because of the broken release ) - this requires package-lock.json to be present and it skips building your dependency tree off of your package.json file, respecting the already resolved dependency URLs in your lock file. A very quickboost for your CI/CD envs (our build time was cut down to a quarter of the original!) and/or to make sure all your developers sit on the same versions of dependencies during development (without having to hard-code strict versions in your package.json file). Note however that npm ci removes the node_modules/ directory before installing, so it won't benefit from any caching strategies. 2) npm i --prefer-offline Use the --prefer-offline flag with your regular npm install / npm i . With this approach, you need to make sure you've cached your node_modules/ directory between builds (in a CI/CD environment). If it fails to find packages locally with the specific version, it falls back to the network safely. You can also add --no-audit --progress=false to reduce pre-install checks and remove the progress bar (latter is only a very slight improvement) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22077725', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3361904/']} | jdg_75654 |
stackexchange | llm_judgeable_groundtruth_similarity | 554378 |
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 given: $$\begin{align*}x_1&=\frac32\\\\x_{n+1}&=\frac3{4-x_n}\end{align*}$$ How do I go about to formally prove the sequence converges and show it? Thanks in advance.
Now provide the response and nothing else.
| We prove by induction that: $1<x_n<3$ $x_n$ is decreasing. The base case is obvious. Now assume that $1<x_{n-1}<3$ for some $n$. Then$$\frac{3}{4-1}< \frac{3}{4-x_{n-1}}<\frac{3}{4-3}$$or, after simplifying, $1<x_n<3$, so $1.$ holds for $n$. Also, note that $1<x_{n-1}<3$ implies$$(x_{n-1}-1)(x_{n-1}-3)<0\Rightarrow 3<4x_{n-1}-x_{n-1}^2$$so$$x_n=\frac{3}{4-x_{n-1}}<x_{n-1}$$So $2.$ holds as well. Now by the monotone convergence theorem, $x_n$ converges. With a little more work, we can show that this limit is actually $1$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/554378', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/105885/']} | jdg_75655 |
stackexchange | llm_judgeable_groundtruth_similarity | 1203583 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
$(a)$ Find all rational points on the circle $x^2 + y^2 = 3$, if there are any. If there is none, prove so. $(b)$ Find all rational points on the circle $x^2 + y^2 = 17$, if there are any. If there is none, prove so. I'm not sure how proceed with finding a general formula (if there is one) I know that for $(a)$ there is no rational points but I don't know how to explain that there are none. whereas for $(b)$ there are such points, $(1,4)$ for example. I think that we can find the intersection between the line $y=m(x-1)+4$ and $x^2 + y^2 = 17$ Any help is appreciated!
Now provide the response and nothing else.
| $a)$ it amounts to solving in $\mathbb{Z}: x^2+y^2=3z^2$. You have that $x^2+y^2 = 0 \pmod 3 \to x = y = 0 \pmod 3$, and you get back the original one using descending method, and this proves $x = y = z = 0$, but this means the first equation $x^2+y^2 = 3$ has no rational solutions. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1203583', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/210491/']} | jdg_75656 |
stackexchange | llm_judgeable_groundtruth_similarity | 45437222 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What is the difference between using a List<Map<String, String>> vs List<Object> in terms of usage and performance.Suppose I have to create a list of map having only 3 types of key value pair, I can instead create an Object having only 3 properties and make a list of objects. The question here is out of the two approaches which one should be used in which scenario?
Now provide the response and nothing else.
| Lets first clarify what we are talking about: it is List<Map<String, String>> versus List<Foo> where Foo objects have a number of "properties", that would be stored in a map (as key value pairs) with option one. In that case, you absolutely go for option two . Simply because good OOP is about creating helpful abstractions , aka models . Meaning: when you have attributes that belong together , then using a class to wrap around them is the natural way to go. That gives you slight advantages on performance (because you avoid the map access), but the core thing is: it allows you to write compile time checked code. You see: int foo = list.get(0).map.get("key"); can fail at runtime - you don't know if map contains that key, and if that is an Integer. But int foo = list.get(0).getFoo(); // resp. ...get(0).fieldName can be checked by the compiler! (yes, those get() calls can still fail at runtime, but that is something you don't get around anyway) Beyond that: do not worry about performance on this level: first of all, you have to understand what really affects your performance when writing Java code. Because you absolutely want to avoid that "this code is ugly but might give better performance" thoughts sneak into your design. Focus on writing clean code that gets the job done in a straight forward way. Do never write less expressive code because you assume it is faster. When you have a performance problem - profile your code, identify the root cause and fix that. But do not allow for premature optimization thoughts to impact the quality of your code. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/45437222', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2299687/']} | jdg_75657 |
stackexchange | llm_judgeable_groundtruth_similarity | 20312765 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Short version: I am having a problem with auto layout top layout guide when used in conjunction with custom transition and UINavigationController in iOS7. Specifically, the constraint between the top layout guide and the text view is not being honored. Has anyone encountered this issue? Long version: I have a scene which has unambiguously define constraints (i.e. top, bottom, left and right) that renders a view like so: But when I use this with a custom transition on the navigation controller, the top constraint to the top layout guide seems off and it renders is as follows, as if the top layout guide was at the top of the screen, rather than at the bottom of the navigation controller: It would appear that the "top layout guide" with the navigation controller is getting confused when employing the custom transition. The rest of the constraints are being applied correctly. And if I rotate the device and rotate it again, everything is suddenly rendered correctly, so it does not appear to be not a matter that the constraints are not defined properly. Likewise, when I turn off my custom transition, the views render correctly. Having said that, _autolayoutTrace is reporting that the UILayoutGuide objects suffer from AMBIGUOUS LAYOUT , when I run: (lldb) po [[UIWindow keyWindow] _autolayoutTrace] But those layout guides are always reported as ambiguous whenever I look at them even though I've ensured that there are no missing constraints (I've done the customary selecting of view controller and choosing "Add missing constraints for view controller" or selecting all of the controls and doing the same for them). In terms of how precisely I'm doing the transition, I've specified an object that conforms to UIViewControllerAnimatedTransitioning in the animationControllerForOperation method: - (id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController*)fromVC toViewController:(UIViewController*)toVC{ if (operation == UINavigationControllerOperationPush) return [[PushAnimator alloc] init]; return nil;} And @implementation PushAnimator- (NSTimeInterval)transitionDuration:(id <UIViewControllerContextTransitioning>)transitionContext{ return 0.5;}- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext{ UIViewController* toViewController = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey]; UIViewController* fromViewController = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey]; [[transitionContext containerView] addSubview:toViewController.view]; CGFloat width = fromViewController.view.frame.size.width; toViewController.view.transform = CGAffineTransformMakeTranslation(width, 0); [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{ fromViewController.view.transform = CGAffineTransformMakeTranslation(-width / 2.0, 0); toViewController.view.transform = CGAffineTransformIdentity; } completion:^(BOOL finished) { fromViewController.view.transform = CGAffineTransformIdentity; [transitionContext completeTransition:![transitionContext transitionWasCancelled]]; }];}@end I've also done a rendition of the above, setting the frame of the view rather than the transform , with the same result. I've also tried manually make sure that the constraints are re-applied by calling layoutIfNeeded . I've also tried setNeedsUpdateConstraints , setNeedsLayout , etc. Bottom line, has anyone successfully married custom transition of navigation controller with constraints that use top layout guide?
Now provide the response and nothing else.
| I solved this by fixing the height constraint of the topLayoutGuide . Adjusting edgesForExtendedLayout wasn't an option for me, as I needed the destination view to underlap the navigation bar, but also to be able to layout subviews using topLayoutGuide . Directly inspecting the constraints in play shows that iOS adds a height constraint to the topLayoutGuide with value equal to the height of the navigation bar of the navigation controller. Except, in iOS 7, using a custom animation transition leaves the constraint with a height of 0. They fixed this in iOS 8. This is the solution I came up with to correct the constraint (it's in Swift but the equivalent should work in Obj-C). I've tested that it works on iOS 7 and 8. func animateTransition(transitionContext: UIViewControllerContextTransitioning) { let fromView = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!.view let destinationVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)! destinationVC.view.frame = transitionContext.finalFrameForViewController(destinationVC) let container = transitionContext.containerView() container.addSubview(destinationVC.view) // Custom transitions break topLayoutGuide in iOS 7, fix its constraint if let navController = destinationVC.navigationController { for constraint in destinationVC.view.constraints() as [NSLayoutConstraint] { if constraint.firstItem === destinationVC.topLayoutGuide && constraint.firstAttribute == .Height && constraint.secondItem == nil && constraint.constant == 0 { constraint.constant = navController.navigationBar.frame.height } } } // Perform your transition animation here ...} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20312765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1271826/']} | jdg_75658 |
stackexchange | llm_judgeable_groundtruth_similarity | 4046986 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
code looks like below: class workers1(Thread): def __init__(self): Thread.__init__(self) def run(self): # ...do some stuff class workers2(Thread): def __init__(self): Thread.__init__(self) def run(self): # ...do some stuff if __name__ == "__main__": # start workerswhile True: print "Number of threads active", threading.activeCount() print "Number of worker1 threads", ?????, "Number of worker2 threads", ????? Is there a way to get the number of threads being active by originating class ?
Now provide the response and nothing else.
| This is a minor modification of Doug Hellman's multiprocessing ActivePool example code (to use threading). The idea is to have your workers register themselves in a pool, unregister themselves when they finish, using a threading.Lock to coordinate modification of the pool's active list: import threadingimport timeimport randomclass ActivePool(object): def __init__(self): super(ActivePool, self).__init__() self.active=[] self.lock=threading.Lock() def makeActive(self, name): with self.lock: self.active.append(name) def makeInactive(self, name): with self.lock: self.active.remove(name) def numActive(self): with self.lock: return len(self.active) def __str__(self): with self.lock: return str(self.active)def worker(pool): name=threading.current_thread().name pool.makeActive(name) print 'Now running: %s' % str(pool) time.sleep(random.randint(1,3)) pool.makeInactive(name)if __name__=='__main__': poolA=ActivePool() poolB=ActivePool() jobs=[] for i in range(5): jobs.append( threading.Thread(target=worker, name='A{0}'.format(i), args=(poolA,))) jobs.append( threading.Thread(target=worker, name='B{0}'.format(i), args=(poolB,))) for j in jobs: j.daemon=True j.start() while threading.activeCount()>1: for j in jobs: j.join(1) print 'A-threads active: {0}, B-threads active: {1}'.format( poolA.numActive(),poolB.numActive()) yields Now running: ['A0']Now running: ['B0']Now running: ['A0', 'A1']Now running: ['B0', 'B1'] Now running: ['A0', 'A1', 'A2'] Now running: ['B0', 'B1', 'B2']Now running: ['A0', 'A1', 'A2', 'A3']Now running: ['B0', 'B1', 'B2', 'B3']Now running: ['A0', 'A1', 'A2', 'A3', 'A4']Now running: ['B0', 'B1', 'B2', 'B3', 'B4']A-threads active: 4, B-threads active: 5A-threads active: 2, B-threads active: 5A-threads active: 0, B-threads active: 3A-threads active: 0, B-threads active: 3A-threads active: 0, B-threads active: 3A-threads active: 0, B-threads active: 3A-threads active: 0, B-threads active: 3A-threads active: 0, B-threads active: 0A-threads active: 0, B-threads active: 0A-threads active: 0, B-threads active: 0 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4046986', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/490324/']} | jdg_75659 |
stackexchange | llm_judgeable_groundtruth_similarity | 5986980 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have the following code: float f = 0.3f;double d1 = System.Convert.ToDouble(f);double d2 = System.Convert.ToDouble(f.ToString()); The results are equivalent to: d1 = 0.30000001192092896;d2 = 0.3; I'm curious to find out why this is?
Now provide the response and nothing else.
| Its not a loss of precision .3 is not representable in floating point . When the system converts to the string it rounds; if you print out enough significant digits you will get something that makes more sense. To see it more clearly float f = 0.3f;double d1 = System.Convert.ToDouble(f);double d2 = System.Convert.ToDouble(f.ToString("G20"));string s = string.Format("d1 : {0} ; d2 : {1} ", d1, d2); output "d1 : 0.300000011920929 ; d2 : 0.300000012 " | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5986980', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/378706/']} | jdg_75660 |
stackexchange | llm_judgeable_groundtruth_similarity | 27365 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
When I'm ssh'ed into one of our office servers (which run Fedora 10) from home, my session times out after a fairly short period of activity (5 minutes or so). I've tried using TcpKeepAlive on the client side, to no effect. The thing I don't understand is that if I'm in the office on the company LAN, I can leave a session inactive all day without it timing out, so the behaviour seems to be dependent on my location. Any ideas why this is happening and how to prevent timeouts when I'm not on the LAN ? I'm using the Terminal client on Mac OSX if that helps. UPDATE - Dave Drager's suggestion of using the ServerAliveInterval set to non-zero with TcpKeepAlive=no worked for me. Regarding some of the other answers, the ClientAlive ... settings aren't accepted by the Mac OSX SSH client.
Now provide the response and nothing else.
| There is a good writeup on this problem here . They recommend: ssh -o TCPKeepAlive=yes or: ssh -o TCPKeepAlive=no -o ServerAliveInterval=15 However, I do have an issue at my work site where I get disconnected from sessions, where at home they are fine. I believe my firewall (SonicWall) may be flucking with TCPKeepAlive, maybe because of NAT. My SSH client, SecureCRT, fortunately has an option for a "NO-OP" protocol, which I believe basically sends a command that doesn't do anything to the server. By manually enabling this I am able to remain connected. Not sure what the MacOSX terminal client has that is similar to that. There is a writeup on how to implement "NO-OP" on command line. Finally, you may wish to use Wireshark or other sniffer to watch your actual TCP connection to find out what is going on with it. That would be the final way to see why it is still disconnecting occasionally. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/27365', 'https://serverfault.com', 'https://serverfault.com/users/1101/']} | jdg_75661 |
stackexchange | llm_judgeable_groundtruth_similarity | 41870309 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In a controller in an ASP.NET Core web application I want to refresh the user and claims in the cookie ticket stored on the client. The client is authenticated and authorized, ASP.NET Core Identity stores this Information in the cookie ticket - now in some Controller actions I want to refresh the data in the cookie. The SignInManager has a function to refresh RefreshSignInAsync , but it does not accept HttpContext.User as parameter. [HttpPost("[action]")][Authorize]public async Task<IActionResult> Validate(){ // todo: update the Client Cookie await _signInManager.RefreshSignInAsync(User); // wrong type} How do I refresh the cookie?
Now provide the response and nothing else.
| public static class HttpContextExtensions{ public static async Task RefreshLoginAsync(this HttpContext context) { if (context.User == null) return; // The example uses base class, IdentityUser, yours may be called // ApplicationUser if you have added any extra fields to the model var userManager = context.RequestServices .GetRequiredService<UserManager<IdentityUser>>(); var signInManager = context.RequestServices .GetRequiredService<SignInManager<IdentityUser>>(); IdentityUser user = await userManager.GetUserAsync(context.User); if(signInManager.IsSignedIn(context.User)) { await signInManager.RefreshSignInAsync(user); } }} Then use it in your controller [HttpPost("[action]")][Authorize]public async Task<IActionResult> Validate(){ await HttpContext.RefreshLoginAsync();} Or abstract it in an action filter public class RefreshLoginAttribute : ActionFilterAttribute{ public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { await context.HttpContext.RefreshLoginAsync(); await next(); }} Then use it like this in your controller [HttpPost("[action]")][Authorize][RefreshLogin] // or simpler [Authorize, RefreshLogin]public async Task<IActionResult> Validate(){ // your normal controller code} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41870309', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7021/']} | jdg_75662 |
stackexchange | llm_judgeable_groundtruth_similarity | 41980650 |
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 got several divs using classes like .wrap-1-addon-1 .wrap-2-addon-1 .wrap-3-addon-1 I want to select all of them and use if ( $(this).hasClass() ) to check if its one of them. Currently I only do check for a single class. How can I check all of these, for example .hasClass('wrap-*-addon-1') ? Best regards.
Now provide the response and nothing else.
| You can combine two jquery Attribute Starts With Selector [name^=”value”] and Attribute Ends With Selector [name$=”value”] to do this work. $('div[class^="wrap-"][class$="-addon-1"]') $('div[class^="wrap-"][class$="-addon-1"]').css("color", "red"); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="wrap-1-addon-1">wrap-1-addon-1</div><div class="wrap-2-addon-1">wrap-2-addon-1</div><div class="wrap-3-addon-1">wrap-3-addon-1</div><div class="wrap-3-addon-2">wrap-3-addon-2</div> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41980650', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2113599/']} | jdg_75663 |
stackexchange | llm_judgeable_groundtruth_similarity | 5564 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am reading a Set Theory book by Kunen. He presents first-order logic and claims that if a set of sentences in inconsistent, then it proves every possible sentence. Since he does not explicitly specify the inference rules, I became curious as to how fundamental this property of inconsistent systems is. So my question is what is the simplest proof, with the least use of assumptions, of the vague claim that "inconsistent systems can prove anything" - in particular I'm interested in the assumptions about the system needed to prove this - is it true only for first order logic? Only for first order logic with the "standard" rules of inference (Modus ponens and GEN)? Or is it such a basic truth that it can be proved for every "reasonable" proof system (and what is "reasonable")?
Now provide the response and nothing else.
| It doesn't have to: logics which don't are called paraconsistent. The most important paraconsistent logic is relevance logic, which repudiates the K axiom: $$\alpha \rightarrow (\beta \rightarrow \alpha)$$ and replaces it by axioms that do not allow there to be unused assumptions. This is equivalent to saying weakening, the principle that if $\Gamma \vdash \alpha$ then $\Gamma'\vdash \alpha$ for $\Gamma\subset\Gamma'$ . This blocks derivations such as Weltschmertz's, which appeals to the K axiom once, Asaf's which uses it twice; Francesco appeals to monotonicity in his proof, which is another name for weakening. It's not difficult to see that this also blocks proofs of everything from a contradictory pair of propositions in a logic satisfying compactness, since one can prove inductively about such proof systems that if $\alpha\rightarrow\beta$ , then all positive atoms in $\beta$ must occur either negatively in $\beta$ or positively in $\alpha$ . So if our contradictory pair (over an assumption) takes the form $\alpha\rightarrow\beta$ and $\alpha\rightarrow\neg\beta$ , we need to prove for any $\gamma$ that $\alpha\rightarrow\gamma$ . But if we choose $\gamma$ to be any positive atom not occuring in $\alpha$ , our inductive proof tells us this cannot be done. We need compactness here, to be ensure that the basis for all contradictory pairs can be expressed by a finitary formula. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/5564', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1818/']} | jdg_75664 |
stackexchange | llm_judgeable_groundtruth_similarity | 5780648 |
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 never posted a question of this nature before, so if it's not proper for SO, just don't hurt my feelings too bad and I'll delete it. In the interest of keeping everything I care about as close to the left margin as possible, I keep wishing I could write something like: DataService1.DataEntities dataEntities = new(constructorArg1, ...) I think another reason is I like the extra screen real estate I get by using var when the type is already present on the right side of the assignment, but my brain has too many years of looking for the type on the left side. Then again, being stuck in my ways isn't such a good reason to wish for a spec...
Now provide the response and nothing else.
| Has the C# design committee ever considered this object creation syntax? Yes, we have. We considered it a couple years ago. As evidence of this claim, see the last paragraph of my article here: http://blogs.msdn.com/b/ericlippert/archive/2009/01/26/why-no-var-on-fields.aspx The consensus of the design team was that this was a "nice to have" feature but not sufficiently compelling that it was worth the considerable cost of designing, implementing, testing, documenting and maintaining the feature. I note also that the comments to the blog entry I linked to are very negative about the feature; it seemed like a lot of people found the syntax unattractive. That was also points against doing the feature. However, the proposed syntax becomes particularly nice if you can combine it with other language features that promote the concise declaration of immutable types; if we do such a feature in a hypothetical future version of the language, then the syntax you propose becomes more compelling. I note further that we in general resist features that require inference from "outside" to "inside"; we prefer that type information flow from the inside out. Consider for example this problem: M(new(blah)); Suppose M has two overloads, one that takes a C, and one that takes a D. Is that "new C(blah)" or "new D(blah)"? It could be either. Now we have to analyze both! And if they both work then we have to figure out which is better. It gets worse. Suppose you have M(new(new(blah))); where again M takes a C and a D, and C has two constructors that take an E or an F, and D has two constructors that take an G and an H. Which of: M(new C(new E(blah)));M(new C(new F(blah)));M(new D(new G(blah)));M(new D(new H(blah))); is chosen, and why? When you reason from outside to inside you quickly get into "combinatoric explosions" where the number of cases to analyze becomes O(c n ) in the depth of the nesting. C# does reason in this manner for lambdas and that is one of the hardest parts of the compiler to make performant and correct, believe me. We're not eager to add a similar feature to constructors. If we were to add this syntax it would probably be limited to scenarios in which the type was unambiguously known by analyzing the left hand side of a variable declaration or assignment expression. (As always, I note that Eric's musings about hypothetical future language features in unannounced and entirely fictional products that do not have schedules or budgets is for entertainment purposes only, and not to be construed as a promise of any particular future product with any particular feature set.) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5780648', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/398546/']} | jdg_75665 |
stackexchange | llm_judgeable_groundtruth_similarity | 5344823 |
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 listen for key combinations such as Control + S without adding key listeners to each component in my Swing application. How can I achieve this?
Now provide the response and nothing else.
| It is possible. KeyboardFocusManager.getCurrentKeyboardFocusManager() .addKeyEventDispatcher(new KeyEventDispatcher() { @Override public boolean dispatchKeyEvent(KeyEvent e) { System.out.println("Got key event!"); return false; }}); That will grab all key events. Returning false allows the keyboard focus manager to resume normal key event dispatching to the various components. If you want to catch key combos, you can keep a set of "pressed keys." Whenever a key is pressed, add it to the set and check what keys are already in the set. When a key is released, remove it from the set. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/5344823', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/306480/']} | jdg_75666 |
stackexchange | llm_judgeable_groundtruth_similarity | 2724371 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been programming in Java for a while, and I've just come across this syntax for the first time: public Object getSomething(){return something;}; What's interesting me is the final semicolon. It doesn't seem to be causing a compiler error, and as far as I know isn't generating runtime errors, so it seems to be valid syntax. When would I use this syntax? Or is it just something that is allowed but generally not used?
Now provide the response and nothing else.
| It's allowed by the grammar as a concession to harmless syntax errors, but it's not generally used and doesn't mean anything different (than leaving the semicolon out). Just as a }; inside a method (such as after an if block) is a null statement and is allowed, an errant semicolon outside a method is considered a null declaration and is allowed. Specifically, the following production from the Java Language Specification allows this: ClassBodyDeclaration: ; [static] Block ModifiersOpt MemberDecl | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2724371', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/259541/']} | jdg_75667 |
stackexchange | llm_judgeable_groundtruth_similarity | 2081213 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I was doing a project Euler problem where I needed to find several Fibonacci numbers, but their index was so large that I could not use the typical recursive method. Instead, I used Binet's rule: $$ F_n = \frac{\phi^n - \psi^n}{\sqrt{5}}$$ But since phi and psi and root 5 are all irrational, I didn't know how many digits past the decimal place I needed to drag them out, especially since the Fibonacci numbers were hundreds or thousands of digits long. I ended up making the irrational numbers obscenely accurate to 1000 or 10000 decimal places just to be safe. Is there some kind of rule like "x amount of precision before will result in y amount of precision in the answer"? I have already solved the problem just fine, I was just wondering about the precision part.
Now provide the response and nothing else.
| You do not really need to work in floating point: Fibonacci numbers fulfill interesting duplication identities, so there are fast algorithms in integer arithmetic, as Brevan Ellefsen mentioned. Here it is some $\text{Maxima}$ code for the fast computation of the $n$-th Fibonacci number. /* Fast Fibonacci Numbers Computation */ fastfib(n):=block([O:2,L:?integer\-length(n),i,f0:2,f1:1,u,v], for i:1 thru L do ( u:f0^2, v:f1^2, if ?logbitp(L-i,n) then (f1:v+O, f0:f1-u+O, O:-2 ) else (f0:u-O, f1:v+O-f0, O:2 )), return((?ash(f1,1)-f0)/5) ); This is included in the $\text{gf}$ package. In order to compute $F_n$, we just need to compute $2\log_2(n)$ squares. With Karatsuba algorithm (invoked in $\text{Maxima}$ through the $\text{fasttimes}$ command) or similar approaches the computation of $m^2$ requires just $\log_2(m)^{1.585}$ elementary operations. This is pretty efficient. Here it is some test on my machine: Maxima 5.32.1 http://maxima.sourceforge.netusing Lisp GNU Common Lisp (GCL) GCL 2.6.10 (a.k.a. GCL)Distributed under the GNU Public License. See the file COPYING.Dedicated to the memory of William Schelter.The function bug_report() provides bug reporting information.(%i1) load("gfpatch.mac");(%o1) gfpatch.mac(%i2) showtime:true;Evaluation took 0.0000 seconds (0.0000 elapsed)(%o2) true(%i3) fastfib(10000000)$Evaluation took 0.0800 seconds (0.0900 elapsed) Back to the actual question: since $\phi^n=\exp(n\log\phi)$ and $\frac{d}{dx}x^n = n x^{n-1}$, we roughly have$(\phi+\varepsilon)^n \approx \phi^n+n\varepsilon\phi^{n-1}$, so a good accuracy is achieved as soon as $\varepsilon\ll\frac{1}{n\phi^{n-1}}$, and we need to store $\approx 0.7n$ binary digits of $\varphi$ to compute $\varphi^n$ with decent accuracy. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2081213', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/265617/']} | jdg_75668 |
stackexchange | llm_judgeable_groundtruth_similarity | 38344220 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Job Scheduler is working as expected on Android Marshmallow and Lollipop devices, but it is not running and Nexus 5x (Android N Preview). Code for scheduling the job ComponentName componentName = new ComponentName(MainActivity.this, TestJobService.class.getName()); JobInfo.Builder builder; builder = new JobInfo.Builder(JOB_ID, componentName); builder.setPeriodic(5000); JobInfo jobInfo; jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE); jobInfo = builder.build(); int jobId = jobScheduler.schedule(jobInfo); Service is defined in manifest as: <service android:name=".TestJobService" android:permission="android.permission.BIND_JOB_SERVICE" /> Is any one having this issue on Android N (Preview)?
Now provide the response and nothing else.
| In Android Nougat the setPeriodic(long intervalMillis) method call makes use of setPeriodic (long intervalMillis, long flexMillis) to schedule periodic jobs. As per the documentation: JobInfo.Builder setPeriodic (long intervalMillis, long flexMillis) Specify that this job should recur with the provided interval and flex. The job can execute at any time in a window of flex length at the end of the period. intervalMillis long: Millisecond interval for which this job will repeat. A minimum value of getMinPeriodMillis() is enforced. flexMillis long: Millisecond flex for this job. Flex is clamped to be at least getMinFlexMillis() or 5 percent of the period, whichever is higher. Sample periodic job scheduled for 5 seconds: private static final int JOB_ID = 1001;private static final long REFRESH_INTERVAL = 5 * 1000; // 5 secondsJobInfo jobInfo = new JobInfo.Builder(JOB_ID, serviceName) .setPeriodic(REFRESH_INTERVAL) .setExtras(bundle).build(); The above code works well in Lollipop & Marshmallow but when you run in Nougat you will notice the following log: W/JobInfo: Specified interval for 1001 is +5s0ms. Clamped to +15m0s0msW/JobInfo: Specified flex for 1001 is +5s0ms. Clamped to +5m0s0ms Since we have set the periodic refresh interval to 5 seconds which is less than the threshold getMinPeriodMillis() . Android Nougat enforces the getMinPeriodMillis() . As a workaround, I'm using following code to schedule jobs at periodic intervals if job interval is less than 15minutes. JobInfo jobInfo;if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { jobInfo = new JobInfo.Builder(JOB_ID, serviceName) .setMinimumLatency(REFRESH_INTERVAL) .setExtras(bundle).build();} else { jobInfo = new JobInfo.Builder(JOB_ID, serviceName) .setPeriodic(REFRESH_INTERVAL) .setExtras(bundle).build();} Sample JobService example: public class SampleService extends JobService { @Override public boolean onStartJob(JobParameters params) { doSampleJob(params); return true; } @Override public boolean onStopJob(JobParameters params) { return false; } public void doSampleJob(JobParameters params) { // Do some heavy operation ...... // At the end inform job manager the status of the job. jobFinished(params, false); }} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38344220', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/328518/']} | jdg_75669 |
stackexchange | llm_judgeable_groundtruth_similarity | 9164926 |
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 inexperienced in Spring and everything I need to do now is to access and obtain a reference to files and folders in the webapp folder. Here is my relevant project hierarchy: -src--main---java (marked as source root)----my-----package------controller-------Home.java---webapp----images-----avatars My code in Home.java: @Controller@RequestMapping("/")public class Home{ @RequestMapping(method = RequestMethod.GET) public String index(Model model, HttpServletRequest request) throws Exception { String test1 = request.getSession().getServletContext().getRealPath(""); String test2 = request.getSession().getServletContext().getRealPath("/"); String test3 = request.getRealPath(""); String test4 = request.getRealPath("/"); String test5 = request.getSession().getServletContext().getRealPath(request.getServletPath()); return "index"; }} All the 5 requests return null. Am I doing something wrong? web.xml: <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <display-name>Test</display-name> <servlet> <servlet-name>test</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>test</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <session-config> <session-timeout>10</session-timeout> </session-config></web-app> What I'm trying to achieve (not shown in this example), is to code a controller responsible for the scaling of an image. For this reason I would need access to the src/main/webapp/_images folder. Thank you! Update: simplified the example for better understanding. Update2: thanks to the suggestion of @gigadot, I deployed the application as an exploded WAR and the problem is partly solved. Can someone tell me what's the difference in deploying the WAR as exploded? Is it something not recommended to do on a production server? Advantages/disadvantages? I think it's worth to explain the situation with an example. Let's say I'm coding a social network and I have to possibility to upload my personal profile picture. This picture will be uploaded to the src/main/webapp/_images/avatars/[myid].jpg folder.Is it recommended to upload pictures to the webapp folder? Or is there a better solution?I would like to be able to return a scaled instance of the image when accessing the URL /images/[width]x[height]/[userid].jpg . Deploying the WAR as exploded and implementing the ResourceLoaderAware (thanks @KevinSchmidt), I can make it work using this: resourceLoader.getResource("file:" + request.getSession().getServletContext().getRealPath("/") + "_images/avatars/"); To me it looks quite dirty, is it a good idea for a production server? Is there a better solution?
Now provide the response and nothing else.
| How exactly did you deploy your application? ServletContext().getRealPath("/") may return null if it is not deployed as exploded. Read the link below for further information. However, the method to configure this may not be the same for your servlet container. http://ananthkannan.blogspot.com/2009/12/servletcontextgetrealpath-returns-null.html Updates Can someone tell me what's the difference in deploying the WAR as exploded? When you deploy the war file as exploded, the servlet container, e.g. Tomcat, will extract the content of war file into a temporary folder and runs everything from that folder so the {WEB_ROOT]/_images/avatars/[myid].jpg is actually exist on file system (hard disk). Therefore, you can actually get the real path (as it already says in the name of the method). However, if your servlet container does not extract the war file, the folder you are looking for is inside the war file and there is no real path to it so it will return null . Is it something not recommended to do on a production server? Advantages/disadvantages? You should not store dynamic contents under your source folder or the webroot folder (webapp) since servlet container will use it temporarily and delete it or change to a new folder when you redeploy your web application. You will likely lost the dynamic data you put into these folders. The web root folder is usually designed for storing static content, which means content you don't want to change - for example, graphic images for your web component like background images, css, etc. The usual method for storing user data is to somehow create a folder in userspace and put your dynamic data in there. However, you will not be able to serve the content of the folder outside webroot. You will need to write your own static servlet to pipe the data when they are requested. This is quite complicated for a beginner. The easiest way for implementing your own static servlet to serve dynamic content is to extend the static servlet of your servlet container. However, your code will highly depend on the servlet container you are deploying to. Since you are going to provide a REST interface for resizing images, you can create a controller which reads in the original images from the dynamic content folder, do the resizing, save it as a temporary file or flush the content of the HttpResponse . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9164926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1031658/']} | jdg_75670 |
stackexchange | llm_judgeable_groundtruth_similarity | 1177 |
Below is a question asked on the forum quant.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
We all know it does mean revert. The question is why. What's making volatility mean-revert? Is it some sort of cyclical behaviour of option traders? The way it's calculated? Why?
Now provide the response and nothing else.
| Volatility is mean reverting if the underlying security doesn't drop to zero. If the security has some underlying "value" then its price is co-integrated with that "value". The volatility is the uncertainty of that price as it tracks the security's "value". Edit 12/03/2011 ================================================= @pteetor, I may have missed something, but the question was " Why is volatility mean-reverting?". I realize that the standard answer is that the VIX (I'm assuming he's asking about the VIX) is related to the historical volatility of the S&P. A simple version of that relationship provides a reasonable R^2 (see Fig. 1). It relates the VIX to the S&P "wiggliness" (30-day standard deviation of the daily log differences of the S&P), but it doesn't explain why more or less "wiggliness" takes place. To explain that, I have to look at the underlying fundamentals. Figure 2 below, shows the S&P Price (in gray) and what I think is the underlying S&P VALUE (in red). Both lines refer to the left hand scale. This VALUE is calculated from my estimate of sustainable earnings and the appropriate P/E ratio. It is what I think an Investor would set for the "value" (money generating value) of the S&P. The blue line is the VIX, and is read on the right hand scale. On the right hand side of the graph, I have divided the VIX range into three regions. From past experience, a VIX of 20 or less seems to be a time of "Don't Worry, Be Happy". Personally, that's when I worry the most, but the market seems to be in a care-free state, so I tagged it as such. Next, for a VIX from about 20 to 40, the market seems to be in an "I'm Nervous" state (not care-free, but also not panicky). For a VIX above 40, a "Panic" state seems to show up. Our current VIX of 28 puts us in the "I'm Nervous" state. Now to the issue of WHY . Don't the Happy/Nervous/Panicky states of the VIX have to be consistent with the level of the S&P Price (not just its "wiggliness")? If I'm "Happy" then I'm happy with the level of the Price. If I'm "Nervous" aren't I nervous about the level of the Price? If I'm "Panicky" then isn't the level of the Price nose-diving? As an Investor , the only way I can be "Happy" with the level of the Price is for the Price to be somewhere near or below my estimate of the VALUE of the S&P. That happened from 1991 to 1997, 2003 to 2007, and part of 2010 and 2011. As an Investor , I will be "Nervous" with the level of the Price when the Price is too high compared to the VALUE or when some external "thing" is going on (for example, the Euro-mess). That happened in 1990, 1997 to 2003, part of 2007, 2008, 2009, 2010, and 2011. And, as stated above, when "Panic" takes place, the market sells everything and the Price level nose-dives (1998 LTCM/Russian thing, 9/11/2001, July and Sept 2002, Sept 2008, the Debt-mess in 2010 and 2011). So, if all of the above fits the hypothesis, then " Why is volatility mean-reverting?" can be answered as.....the market has, and probably will continue to spend most of its time in the "Don't Worry, Be Happy" state or the "I'm Nervous" state (i.e. reverting to a state that is not extreme). I agree that my three-sentence answer at the top of this post left out a lot of details, but it is the short version of the same answer. Edit 12/09/2011 ======================================================= @pteetor, I must be getting old and forgetful. In your comment below, you asked for references (which I forgot to include above). Here are a few: http://faculty.fuqua.duke.edu/~charvey/Research/Working_Papers/W104_The_equity_risk.pdf http://research.stlouisfed.org/wp/2006/2006-007.pdf http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1268567 With a little Googling, you'll find more. In my answer above, I purposely didn't get into my technique for setting the "value" of the S&P. It always starts an argument about which is best, Modified Gordon Models, Modified Miller-Modigliani Models, Modified XXXX Models, or whatever. The bottom line is, no matter what valuation technique you use, you'll always find some form of "equity risk premium" that is related to volatility. It's just common sense......there has to be a "price" for being "Nervous" or "Happy". Another issue that usually comes up has to do with using Historical Volatility versus Implied Volatility. All I can say is, the volatility part of the equity risk premium existed long before options were traded. | {} | {'log_upvote_score': 6, 'links': ['https://quant.stackexchange.com/questions/1177', 'https://quant.stackexchange.com', 'https://quant.stackexchange.com/users/40/']} | jdg_75671 |
stackexchange | llm_judgeable_groundtruth_similarity | 17410734 |
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 onClick event in my android app that triggers the following code but it keeps crashing my app. I put it in a thread only because i read that that's supposed to prevent crashing. Also ctx refers to the Activity's context (it's a variable I created in the activity set equal to this. I've read and tried several things. Any help would be awesome. Thanks! Thread toastThread = new Thread() { public void run() { Toast alertFailure = Toast.makeText(ctx, "Login Failed", Toast.LENGTH_LONG); alertFailure.show(); }};toastThread.start();
Now provide the response and nothing else.
| You need to use runOnUiThread Something like runOnUiThread(new Runnable() { public void run() { Toast.makeText(ctx, toast, Toast.LENGTH_SHORT).show(); }}); Toast is a UI element so it needs to run on the UI Thread , not a background Thread . However, if this is all you are using it for then you don't need a separate Thread just to show a Toast . If you can explain the context of how you are using it then maybe we can help with a better way. Also, if you are inside of your Activity then you don't need a variable for Context . You can use ActivityName.this instead to access the Activity Context | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/17410734', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2486343/']} | jdg_75672 |
stackexchange | llm_judgeable_groundtruth_similarity | 9958180 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
With the stl priority_queue you can set the underlying container, such as a vector . What are some of the advantages of specifying a container for the stl priority_queue ?
Now provide the response and nothing else.
| Setting the underlying container makes it possible to separate out two logically separate concerns: How do you store the actual elements that make up the priority queue (the container), and How do you organize those elements to efficiently implement a priority queue (the priority_queue adapter class). As an example, the standard implementation of vector is not required to shrink itself down when its capacity is vastly greater than its actual size. This means that if you have a priority queue backed by a vector , you might end up wasting memory if you enqueue a lot of elements and then dequeue all of them, since the vector will keep its old capacity. If, on the other hand, you implement your own shrinking_vector class that does actually decrease its capacity when needed, you can get all the benefits of the priority_queue interface while having the storage be used more efficiently. Another possible example - you might want to change the allocator being used so that the elements of the priority queue are allocated from a special pool of resources. You can do this by just setting the container type of the priority_queue to be a vector with a custom allocator. One more thought - suppose that you are storing a priority_queue of very large objects whose copy time is very great. In that case, the fact that the vector dynamically resizes itself and copies its old elements (or at least, in a C++03 compiler) might be something you're not willing to pay for. You could thus switch to some other type, perhaps a deque , that makes an effort not to copy elements when resizing and could realize some big performance wins. Hope this helps! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9958180', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/754087/']} | jdg_75673 |
stackexchange | llm_judgeable_groundtruth_similarity | 14047940 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Background Something that catches every Smalltalk newbie is that add: does not return "self" but the object being added. For example, with this code: myCollection := OrderedCollection new add: 'Peter'; add: 'John'; add: 'Paul'. myCollection will containt the String "Paul", and not the collection itself. This is because add: returns the object being added, and the whole cascade expression evaluates to the last message being sent. Instead, it should be written with yourself at the end: myCollection := OrderedCollection new add: 'Peter'; add: 'John'; add: 'Paul'; yourself. Questions Why is this so? What was this designed this way? What are the benefits of add: behaving this way?
Now provide the response and nothing else.
| I've thought about this a lot. I've never heard any of the original designers of Smalltalk defend this decision, so we don't know for sure why they did it. I've decided that the reason was because of cascades. If add: returned the receiver, then (things add: thing1) add: thing2 would be the same as things add: thing1; add: thing2. By having add: return the argument, those two expressions are different and the programmer can use each when it is appropriate. However, I think it is a mistake. I've been teaching Smalltalk for over 25 years, and every time I teach it, people have trouble with this. I always warn them, but they still make mistakes with add:. So, I consider this a bad design decision. This design decision is about the library, not the compiler. You could change it by going into the collection classes and changing them. Of course, it is impossible to predict how many Smalltalk programs would break. Collections are so fundamental that this change would be as hard to make as a real change to the language. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14047940', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1781008/']} | jdg_75674 |
stackexchange | llm_judgeable_groundtruth_similarity | 120148 |
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am a high school student studying basic chemistry and I am confused about the process of writing decomposition reactions. The question I have encountered asks me to decompose $\ce{BaCO3}$ . Online, I have found that this decomposes to $\ce{BaO + CO2}$ . My question is, essentially, is there a method to determine which elements go where. I'm having trouble finding answers.
Now provide the response and nothing else.
| Chemistry, despite being several hundred year old science, it is still very much empirical. In the beginning you will have to learn and accept some facts. Later you will start to see patterns (hence the periodic table). If you learn that the carbonate of barium decomposes into carbon dioxide and barium oxide, it will be safe to say that Mg, Ca, Ba, Sr, will do the same. Here you have learnt four more chemical reactions. If you recall the periodic functions in mathematics, which repeat themselves periodically, in the same way, elements repeat their properties in the periodic table. When you strongly heat inorganic salts, usually you get smaller products (e.g., carbon dioxide and barium oxide) which are energetically more stable with respect to the starting material. | {} | {'log_upvote_score': 5, 'links': ['https://chemistry.stackexchange.com/questions/120148', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/82606/']} | jdg_75675 |
stackexchange | llm_judgeable_groundtruth_similarity | 2840798 |
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 Tanh-1 in C# (and Sinh-1 and Cosh-1) I did not found it in Math library.. Any suggestions ? EDIT:Tanh not Tan !!
Now provide the response and nothing else.
| You need to derive them yourself using existing functions e.g. Math.sin You might find this useful: Secant Sec(X) = 1 / Cos(X) Cosecant Cosec(X) = 1 / Sin(X) Cotangent Cotan(X) = 1 / Tan(X) Inverse Sine Arcsin(X) = Atn(X / Sqr(-X * X + 1)) Inverse Cosine Arccos(X) = Atn(-X / Sqr(-X * X + 1)) + 2 * Atn(1) Inverse Secant Arcsec(X) = 2 * Atn(1) - Atn(Sgn(X) / Sqr(X * X - 1)) Inverse Cosecant Arccosec(X) = Atn(Sgn(X) / Sqr(X * X - 1)) Inverse Cotangent Arccotan(X) = 2 * Atn(1) - Atn(X) Hyperbolic Sine HSin(X) = (Exp(X) - Exp(-X)) / 2 Hyperbolic Cosine HCos(X) = (Exp(X) + Exp(-X)) / 2 Hyperbolic Tangent HTan(X) = (Exp(X) - Exp(-X)) / (Exp(X) + Exp(-X)) Hyperbolic Secant HSec(X) = 2 / (Exp(X) + Exp(-X)) Hyperbolic Cosecant HCosec(X) = 2 / (Exp(X) - Exp(-X)) Hyperbolic Cotangent HCotan(X) = (Exp(X) + Exp(-X)) / (Exp(X) - Exp(-X)) Inverse Hyperbolic Sine HArcsin(X) = Log(X + Sqr(X * X + 1)) Inverse Hyperbolic Cosine HArccos(X) = Log(X + Sqr(X * X - 1)) Inverse Hyperbolic Tangent HArctan(X) = Log((1 + X) / (1 - X)) / 2 Inverse Hyperbolic Secant HArcsec(X) = Log((Sqr(-X * X + 1) + 1) / X) Inverse Hyperbolic Cosecant HArccosec(X) = Log((Sgn(X) * Sqr(X * X + 1) + 1) / X) Inverse Hyperbolic Cotangent HArccotan(X) = Log((X + 1) / (X - 1)) / 2 Logarithm to base N LogN(X) = Log(X) / Log(N) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2840798', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/279691/']} | jdg_75676 |
stackexchange | llm_judgeable_groundtruth_similarity | 2287795 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to decompose $A = \begin{pmatrix} 3 & 1 & 2 \\ -2 & 1 & 3 \end{pmatrix}$ using the SVD. So $A = U \Sigma V^\star$. Now, I calculated the matrices $U$,$\Sigma$ which are $\frac{1}{\sqrt{2}}\begin{pmatrix} 1 & -1\\ 1 & 1 \end{pmatrix}$ and $\begin{pmatrix} \sqrt{15} & 0 & 0 \\ 0&\sqrt{13} & 0 \end{pmatrix}$ respectively. Now this is where my problem comes. So I know the correct matrix for $V$ which should be the matrix with columns $$v_1 = \frac{1}{\sqrt{30}}\begin{pmatrix}1 \\ 2 \\ 5 \end{pmatrix}, v_2 = \frac{1}{\sqrt{26}}\begin{pmatrix}-5 \\ 0 \\ 1 \end{pmatrix}, v_3 = \frac{1}{\sqrt{175}}\begin{pmatrix} 1 \\ -13 \\ 5 \end{pmatrix}.$$ Now, I made a mistake in computing $v_3$ and got $v_3 = \frac{1}{\sqrt{611}}\begin{pmatrix}21 \\ -13 \\ 1 \end{pmatrix}$, and upon substituting this in, it still worked. In fact, I found that any vector in the form $v_3 = b \begin{pmatrix} \frac{26}{a} - 5 \\ \frac{-13}{a} \\ 1\end{pmatrix}$ still worked, with $a$ being any real number and $b$ being the modulus of that vector. Why does this vector $v_3$ still work?
Now provide the response and nothing else.
| Your question provides a forum to clear common confusion about the singular value decomposition: $$ \mathbf{A} =\mathbf{U} \, \Sigma \, \mathbf{V}^{*}\tag{1}$$ The specific example will use $$ \mathbf{A} =\left[\begin{array}{rcc} 3 & 1 & 2 \\ -2 & 1 & 3 \\\end{array}\right]\tag{2}$$ # Computing the SVD Consider the general matrix $\mathbf{A} = \mathbb{C}^{m \times n}_{\rho}$ .The steps for computing the SVD are Resolve the eigensystem for a product matrix $\mathbf{W}$ Compute remaining component matrix from $(1)$ . Recipes The choice is whether to first resolve the row space or the column space. The table below compares the two parallel paths. The notation $$\lambda \left( \mathbf{W} \right)$$ represents the eigenvalue spectrum for the matrix $\mathbf{W}$ ,while $$\tilde{\lambda} \left( \mathbf{W} \right)$$ represents the ordered, eigenvalue spectrum with the $0$ elements removed. There will be $\rho$ nonzero eigenvalues. $$\begin{array}{lll}% \text{Operation} & \text{Row space first} & \text{Column space first} \\\hline% \text{1. Construct product matrix} & \mathbf{W} = \mathbf{A}^{*} \mathbf{A} & \mathbf{W} = \mathbf{A} \, \mathbf{A}^{*} \\% \text{2. Solve for eigenvalues} & \sigma = \sqrt{\tilde{\lambda} \left( \mathbf{W} \right)} & \sigma = \sqrt{\tilde{\lambda} \left( \mathbf{W} \right)} \\% \color{blue}{\text{3. Solve for eigenvectors }} w_{k},\ k=1, \rho & \left( \mathbf{W} - \lambda_{k} \mathbf{I}_{n} \right) w_{k} = \mathbf{0} & \left( \mathbf{W} - \lambda_{k} \mathbf{I}_{m} \right) w_{k} = \mathbf{0} \\% \text{4. Assemble domain matrix} & \mathbf{V}_{k} = \frac{w_{k}}{\lVert w_{k} \rVert_{2}} & \mathbf{U}_{k} = \frac{w_{k}}{\lVert w_{k} \rVert_{2}} &\\% \text{5. Compute complementary domain matrix} & \mathbf{U}_{k} = \sigma_{k}^{-1} \mathbf{A} \mathbf{V}_{k} & \mathbf{V}_{k} = \sigma_{k}^{-1} \mathbf{A}^{*} \mathbf{U}_{k} &\\%\end{array}$$ The step highlighted in $\color{blue}{blue}$ is the step where we must pick a sign (or phase). Ambiguity enters here. The following example computes the SVD by 1) resolving the row space first and then 2) resolving the column space first. The decompositions are expressed in terms of complex phase factors, and so represent the most general case of sign conventions. Notice that life is easier when we work with the smaller of the two product matrices $\mathbf{A}\mathbf{A}^{*}$ and $\mathbf{A}^{*}\mathbf{A}$ . Example I: Row space first Construct product matrix $$\mathbf{W} = \mathbf{A}^{*} \, \mathbf{A} =\left[\begin{array}{ccc} 13 & 1 & 0 \\ 1 & 2 & 5 \\ 0 & 5 & 13 \\\end{array}\right]$$ Solve for eigenvalues The characteristic polynomial is computed using $$ p(\lambda) = \det \left( \mathbf{W} - \lambda \mathbf{I}_{3}\right)=\det \left[\begin{array}{ccc} 13-\lambda & 1 & 0 \\ 1 & 2-\lambda & 5 \\ 0 & 5 & 13-\lambda \\\end{array}\right]$$ Solve for the determinant by computing the minors: $$\left|\begin{array}{ccc} 13-\lambda & 1 & 0 \\ 1 & 2-\lambda & 5 \\ 0 & 5 & 13-\lambda \\\end{array}\right| =%\boxed{13-\lambda}\left|\begin{array}{cc} 2-\lambda & 5 \\ 5 & 13-\lambda \\\end{array}\right|%-\boxed{1}\left|\begin{array}{cc} 1 & 5 \\ 0 & 13-\lambda \\\end{array}\right|%+\boxed{0}\left|\begin{array}{cc} 1 & 2-\lambda \\ 0 & 5 \\\end{array}\right|$$ The characteristic polynomial is $$ p \left( \lambda \right) = -\lambda ^3+28 \lambda ^2-195 \lambda= -\lambda \left( \lambda - 13 \right) \left( \lambda - 15 \right)$$ The eigenvalue spectrum is $$\lambda\left( \mathbf{W} \right) = \left\{ 0, 13, 15\right\}$$ The truncated, ordered eigenvalue spectrum is $$\tilde{\lambda} \left( \mathbf{W} \right) = \left\{ 15, 13 \right\}$$ is the foundation for the singular values: $$\sigma = \sqrt{\tilde{\lambda}}$$ The matrix of singular values, $$ \mathbf{S} = \left[\begin{array}{cc} \sqrt{15} & 0 \\ 0 & \sqrt{13} \\\end{array}\right],$$ is embedded in the sabot matrix: $$ \Sigma = %\left[\begin{array}{cc} \mathbf{S} & \mathbf{0}\end{array}\right]%=%\left[\begin{array}{cc|c} \sqrt{15} & 0 & 0 \\ 0 & \sqrt{13} & 0 \\\end{array}\right]%$$ $\color{blue}{\text{Solve for eigenvectors}}$ First eigenvector $$\begin{align}\left( \mathbf{W} - \lambda_{1} \mathbf{I}_{3} \right) w_{1} &= \mathbf{0} \\%\left[\begin{array}{rrr} -2 & 1 & 0 \\ 1 & -13 & 5 \\ 0 & 5 & -2 \\\end{array}\right]%\left[\begin{array}{rr} w_{x} \\ w_{y} \\ w_{z} \\\end{array}\right]%&= %\left[\begin{array}{c} 0 \\ 0 \\ 0 \\\end{array}\right] %\end{align}$$ The general solution is $$\left[\begin{array}{c} w_{x} \\ w_{y} \\ w_{z} \\\end{array}\right]=e^{i \theta_{1}}\left[\begin{array}{c} 1 \\ 2 \\ 5 \\\end{array}\right]$$ with $0 \le \theta_{k} \le 2\pi$ . This is the general phase angle. The normalized vector is the first column vector in the domain matrix $$\mathbf{V}_{1} = \frac{e^{i \theta_{1}}}{\sqrt{30}}\left[\begin{array}{c} 1 \\ 2 \\ 5 \\\end{array}\right]$$ Second eigenvector $$\begin{align}\left( \mathbf{W} - \lambda_{2} \mathbf{I}_{3} \right) w_{2} &= \mathbf{0} \\%\left[\begin{array}{crr} 0 & 1 & 0 \\ 1 & -11 & 5 \\ 0 & 5 & 0 \\\end{array}\right]%\left[\begin{array}{rr} w_{x} \\ w_{y} \\ w_{z} \\\end{array}\right]%&= %\left[\begin{array}{c} 0 \\ 0 \\ 0 \\\end{array}\right] %\end{align}$$ The general solution is $$\left[\begin{array}{c} w_{x} \\ w_{y} \\ w_{z} \\\end{array}\right]=e^{i \theta_{2}}\left[\begin{array}{r} -5 \\ 0 \\ 1 \\\end{array}\right]$$ For the purposes of the thin SVD, we are done as we have found the $\rho=2$ eigenvectors. However, we can compute the null space term by solving for the eigenvector of the $0$ eigenvalue. Third eigenvector $$\begin{align}\left( \mathbf{W} - \lambda_{3} \mathbf{I}_{3} \right) w_{3} &= \mathbf{0} \\%\left[\begin{array}{ccc} 13 & 1 & 0 \\ 1 & 2 & 5 \\ 0 & 5 & 13 \\\end{array}\right]%\left[\begin{array}{rr} w_{x} \\ w_{y} \\ w_{z} \\\end{array}\right]%&= %\left[\begin{array}{c} 0 \\ 0 \\ 0 \\\end{array}\right] %\end{align}$$ The general solution is $$\left[\begin{array}{c} w_{x} \\ w_{y} \\ w_{z} \\\end{array}\right]=e^{i \theta_{3}}\left[\begin{array}{r} 1 \\-13 \\ 5 \\\end{array}\right]$$ This normalized vector is the third and final column vector in the domain matrix $$\mathbf{V}_{3} = \frac{e^{i \theta_{3}}}{\sqrt{195}}\color{gray}{\left[\begin{array}{r} 1 \\-13 \\ 5 \\\end{array}\right]}$$ Null space vectors are shaded in gray. Assemble domain matrix $$ \mathbf{V} = \left[\begin{array}{cc} % c1\frac{e^{i \theta_{1}}}{\sqrt{30}}\left[\begin{array}{c} 1 \\ 2 \\ 5 \\\end{array}\right] % c2\frac{e^{i \theta_{2}}}{\sqrt{26}}\left[\begin{array}{r} -5 \\ 0 \\ 1 \\\end{array}\right] % c3\frac{e^{i \theta_{3}}}{\sqrt{195}}\color{gray}{\left[\begin{array}{r} 1 \\-13 \\ 5 \\\end{array}\right]}%\end{array}\right]$$ Compute columns of $\mathbf{U}$ $$ \mathbf{U}_{1} = \sigma^{-1}_{1} \mathbf{A} \mathbf{V}^{*}_{1} = \frac{e^{i \theta_{1}}} {\sqrt{2}} \left[\begin{array}{r} 1 \\ 1 \\\end{array}\right]$$ $$ \mathbf{U}_{2} = \sigma^{-2}_{1} \mathbf{A} \mathbf{V}^{*}_{2} = \frac{e^{i \theta_{2}}} {\sqrt{2}} \left[\begin{array}{r}-1 \\ 1 \\\end{array}\right]$$ We're done. The singular value decomposition is $$\begin{align} \mathbf{A} &= \mathbf{U} \, \Sigma \, \mathbf{V}^{*} \\\\ & =% U\underbrace{\frac{1}{\sqrt{2}}\left[\begin{array}{cc} % c1 e^{i \theta_{1}} \left[\begin{array}{c} 1\\ 1\\\end{array}\right] % c2 e^{i \theta_{2}} \left[\begin{array}{r} -1\\ 1\\\end{array}\right]%\end{array}\right]}_{\mathbf{U}}% Sigma\underbrace{\left[\begin{array}{cc|c} \sqrt{15} & 0 & 0 \\ 0 & \sqrt{13} & 0 \\\end{array}\right]}_{\Sigma}% V*\underbrace{\left[\begin{array}{cc} % c1 \frac{e^{i \theta_{1}}} {\sqrt{30}} \left[\begin{array}{r} 1 \\ 2 \\ 5 \\\end{array}\right] % c2 \frac{e^{i \theta_{2}}} {\sqrt{26}} \left[\begin{array}{r} -5 \\ 0 \\ 1 \\\end{array}\right]\color{gray}{\frac{e^{i \theta_{3}}}{\sqrt{195}}\left[\begin{array}{r} 1 \\-13 \\ 5 \\\end{array}\right]}%\end{array}\right]^{*}}_{\mathbf{V}}% A\\[3pt] & =\left[\begin{array}{rcc} 3 & 1 & 2 \\ -2 & 1 & 3 \\\end{array}\right]%\end{align}$$ ## Example II: Column space first Construct product matrix $$\mathbf{W} = \mathbf{A} \, \mathbf{A}^{*} =\left[\begin{array}{cc} 14 & 1 \\ 1 & 14 \\\end{array}\right]$$ Solve for eigenvalues The eigenvalues are the roots of the characteristic polynomial $$ p \left( \lambda \right) = \lambda^{2} - \lambda \, \text{tr }\mathbf{W} + \det \mathbf{W}$$ The trace and determinant are $$ \text{tr }\mathbf{W} = 28, \qquad \det \mathbf{W} = 195$$ The eigenvalue spectrum is $$ \lambda \left( \mathbf{W} \right) = \tilde{\lambda} \left( \mathbf{W} \right) = \left\{ 15, 13\right\},$$ already in a form suitable to compute singular values: $$\sigma = \sqrt{\tilde{\lambda}}$$ The matrix of singular values is $$ \mathbf{S} = \left[\begin{array}{cc} \sqrt{15} & 0 \\ 0 & \sqrt{13} \\\end{array}\right],$$ and is embedded in the sabot matrix like so: $$ \Sigma = %\left[\begin{array}{cc} \mathbf{S} & \mathbf{0}\end{array}\right]%\left[\begin{array}{cc|c} \sqrt{15} & 0 & 0 \\ 0 & \sqrt{13} & 0 \\\end{array}\right]%$$ $\color{blue}{\text{Solve for eigenvectors}}$ First eigenvector $$\begin{align}\left( \mathbf{W} - \lambda_{1} \mathbf{I}_{2} \right) w_{1} &= \mathbf{0} \\%\left[\begin{array}{rr} -1 & 1 \\ 1 & -1 \\\end{array}\right]%\left[\begin{array}{rr} w_{x} \\ w_{y} \\\end{array}\right]%&= %\left[\begin{array}{rr} 0 \\ 0 \\\end{array}\right] %\end{align}$$ The general solution is $$\left[\begin{array}{rr} w_{x} \\ w_{y} \\\end{array}\right]=e^{i \phi_{1}}\left[\begin{array}{rr} 1 \\ 1 \\\end{array}\right]$$ with $0 \le \phi_{k} \le 2\pi$ . This is the juncture where one picks a sign; instead, we leave the general phase. The normalized vector is the first column vector in the domain matrix $$\mathbf{U}_{1} = \frac{e^{i \phi_{1}}}{\sqrt{2}}\left[\begin{array}{rr} 1 \\ 1 \\\end{array}\right]$$ Second eigenvector $$\begin{align}\left( \mathbf{W} - \lambda_{2} \mathbf{I}_{2} \right) w_{1} &= \mathbf{0} \\%\left[\begin{array}{cc} 1 & 1 \\ 1 & 1 \\\end{array}\right]%\left[\begin{array}{rr} w_{x} \\ w_{y} \\\end{array}\right]%&= %\left[\begin{array}{rr} 0 \\ 0 \\\end{array}\right] %\end{align}$$ The general solution is $$\left[\begin{array}{rr} w_{x} \\ w_{y} \\\end{array}\right]=e^{i \phi_{2}}\left[\begin{array}{rr} -1 \\ 1 \\\end{array}\right]$$ The minus sign could go in the top entry as shown or the bottom entry. The normalized vector is the second column vector in the domain matrix $$\mathbf{U}_{2} = \frac{e^{i \phi_{2}}}{\sqrt{2}}\left[\begin{array}{r} -1 \\ 1 \\\end{array}\right]$$ Assemble domain matrix $$ \mathbf{U} = \frac{1}{\sqrt{2}}\left[\begin{array}{cc} % c1 e^{i \phi_{1}} \left[\begin{array}{c} 1\\ 1\\\end{array}\right] % c2 e^{i \phi_{2}} \left[\begin{array}{r} -1\\ 1\\\end{array}\right]%\end{array}\right]$$ Compute columns of $\mathbf{V}$ $$ \mathbf{V}_{1} = \sigma^{-1}_{1} \mathbf{A}^{*} \mathbf{U}_{1} = \frac{e^{i \phi_{1}}} {\sqrt{30}} \left[\begin{array}{r} 1 \\ 2 \\ 5 \\\end{array}\right]$$ $$ \mathbf{V}_{2} = \sigma^{-1}_{2} \mathbf{A}^{*} \mathbf{U}_{2} = \frac{e^{i \phi_{2}}} {\sqrt{26}} \left[\begin{array}{r} -5 \\ 0 \\ 1 \\\end{array}\right]$$ The third and final column for $\mathbf{V}$ is in the null space $\mathcal{N}(\mathbf{A})$ . One way to compute this vector is to use the cross product $$ \left[\begin{array}{c} 1 \\ 2 \\ 5 \\\end{array}\right]\times \left[\begin{array}{r} -5 \\ 0 \\ 1 \\\end{array}\right]= 2\left[\begin{array}{r} 1 \\-13 \\ 5 \\\end{array}\right]$$ The third and final vector is the normalized version $$ \color{gray}{\mathbf{V}_{3}} = \color{gray}{\frac{1}{\sqrt{195}}\left[\begin{array}{r} 1 \\-13 \\ 5 \\\end{array}\right]}$$ The lighter shading reminds that this vector is lives in a null space. The singular value decomposition is $$\begin{align} \mathbf{A} &=\mathbf{U} \, \Sigma \, \mathbf{V}^{*} \\ & =% U\underbrace{\frac{1}{\sqrt{2}}\left[\begin{array}{cc} % c1 e^{i \phi_{1}} \left[\begin{array}{c} 1\\ 1\\\end{array}\right] % c2 e^{i \phi_{2}} \left[\begin{array}{r} -1\\ 1\\\end{array}\right]%\end{array}\right]}_{\mathbf{U}}% Sigma\underbrace{\left[\begin{array}{cc|c} \sqrt{15} & 0 & 0 \\ 0 & \sqrt{13} & 0 \\\end{array}\right]}_{\Sigma}% V*\underbrace{\left[\begin{array}{cc} % c1 \frac{e^{i \phi_{1}}} {\sqrt{30}} \left[\begin{array}{r} 1 \\ 2 \\ 5 \\\end{array}\right] % c2 \frac{e^{i \phi_{2}}} {\sqrt{26}} \left[\begin{array}{r} -5 \\ 0 \\ 1 \\\end{array}\right]\color{gray}{\frac{1}{\sqrt{195}}\left[\begin{array}{r} 1 \\-13 \\ 5 \\\end{array}\right]}%\end{array}\right]^{*}}_{\mathbf{V}}% A\\[3pt] & =\left[\begin{array}{rcc} 3 & 1 & 2 \\ -2 & 1 & 3 \\\end{array}\right]\end{align}\tag{1}$$ ## Error in postThe null space vector is unique up to the general phase.The vector cited in the question does not work. For example, when $a=1$ $$\mathbf{U} \, \Sigma \,\left[\begin{array}{cc} % c1 \frac{e^{i \phi_{1}}} {\sqrt{30}} \left[\begin{array}{r} 1 \\ 2 \\ 5 \\\end{array}\right] % c2 \frac{e^{i \phi_{2}}} {\sqrt{26}} \left[\begin{array}{r} -5 \\ 0 \\ 1 \\\end{array}\right]\color{gray}{\frac{1}{\sqrt{611}}\left[\begin{array}{r} 21 \\ -13 \\ 1 \\\end{array}\right]}%\end{array}\right]^{*}=\left[\begin{array}{rcc} 3 & 1 & 21 \sqrt{\frac{15}{1222}}+\frac{13}{\sqrt{94}} \\ -2 & 1 & 21 \sqrt{\frac{15}{1222}}-\frac{13}{\sqrt{94}} \\\end{array}\right]\ne \mathbf{A}$$ | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2287795', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/424197/']} | jdg_75677 |
stackexchange | llm_judgeable_groundtruth_similarity | 8600125 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two issues with activity indicator:1. Activity Indicator not showing up on UIViewController I have activity indicator added in .xib file. On button click it should start animating. and when response from server is received, before going to next page it should stop animating.I am doing it as follows: activityIndicator.hidden = NO;[activityIndicator performSelector:@selector(startAnimating) withObject:nil afterDelay:0.1];[self.view bringSubviewToFront:activityIndicator];....rest of code here....activityIndicator.hidden = YES;[activityIndicator stopAnimating]; Activity Indicator not showing up on UITableView For table view I am doing it same way but on didselectrowatindexpath... For tableview I also tried adding activity view to cell accessory, but still not showing up In both cases activity Indicator is not showing up. Please help Thanks
Now provide the response and nothing else.
| If all this code is in one method or in response to one event, then none of the changes to the views are going be visible until you return to the event loop. You set the activityIndicator.hidden to NO and then set it again to YES before the UI has an opportunity to even refresh. You also apparently stop the animation before you start it. What you need to do is make the activity indicator visible here and start its animation. Then schedule the work to be done (start an asynchronous network connection, or put some work into a queue, or whatever it is you need to get done) and return from this method so that the UI can refresh, the indicator can be drawn, and the animation can actually start. Then later at some point after the work is complete, you can hide the indicator and stop the animation. But you can't do all of that on the main thread within one single turn of the event loop. None of your changes will be visible because no drawing at all will happen here while this method is executing (assuming this is on the main thread) I hope that makes sense? | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8600125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/95873/']} | jdg_75678 |
stackexchange | llm_judgeable_groundtruth_similarity | 32398007 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a problem when it comes to filling a javafx tableview. I am currently working on a GUI based event management tool (for university) and I am stuck trying to fill a Tableview list, that should be in the center of a border pane layout. This is my code (its pretty long thought, its the main window function): import java.sql.Date;import java.sql.SQLException;import java.util.List;//--main imports--//import javafx.application.Application;import javafx.beans.property.SimpleIntegerProperty;import javafx.beans.property.SimpleObjectProperty;import javafx.beans.property.SimpleStringProperty;import javafx.collections.FXCollections;import javafx.collections.ObservableList;import javafx.scene.Scene;import javafx.scene.control.Label;//--table imports--//import javafx.scene.control.TableView;import javafx.scene.control.cell.PropertyValueFactory;import javafx.scene.control.TableColumn;import javafx.scene.text.Font;import javafx.stage.Stage;public class MainWindow extends Application {private static Label tableHeadline;private static TableView table;private static TableColumn dateCol;private static TableColumn nameCol;private static TableColumn numberOfGuestsCol;private static TableColumn locationCol;private static BorderPane layout;//This is just some test data, this is where the program crashes, I thinkfinal static ObservableList<Event> data = FXCollections.observableArrayList( new Event("Jacob", "Smith", 30, new Date(10000)) );//----------------------////--Private constants--// private static final String DATE = "Date";private static final String NAME = "Name";private static final String NUMBER_OF_GUESTS = "Number of guests";private static final String LOCATION = "Location";//---------------------///**The main method, launching the application*/public static void main(String[] args) { try { //--launching the application with given arguments--// launch(args);} catch (Exception e) {e.printStackTrace();}}/** * The start-method, that is called first when 'launch' is used */@Overridepublic void start(Stage primaryWindow) throws Exception { //--initialize all the objects in the window--// initializeObjects(); //--get the layout--// initializeLayout(); //--give functionality to the objects in the window--// functionalizeObjects(); //--create the new scene--// Scene main = new Scene(layout); //--Giving the main window a title and bringing it up front--// primaryWindow.setMinHeight(DEFAULT_WIN_HEIGHT); primaryWindow.setMinWidth(DEFAULT_WIN_WIDTH); primaryWindow.setScene(main); primaryWindow.show(); //TODO: on window close, save the content of the list to the db primaryWindow.setOnCloseRequest(null);}/** * Initializes all given elements of the main window by creating and naming them */private static void initializeObjects () { //--table--// tableHeadline = new Label (TABLE_HEAD); tableHeadline.setFont(new Font ("Arial", 20)); table = new TableView<>(); table.setEditable(true); //--date column--// dateCol = new TableColumn<Event, Date>(DATE); dateCol.setCellFactory( new PropertyValueFactory<>("Date") ); //--name column--// nameCol = new TableColumn<Event, String>(NAME); nameCol.setCellValueFactory( new PropertyValueFactory<>("name") ); //--numberOfGuests column--// numberOfGuestsCol = new TableColumn<Event, Integer>(NUMBER_OF_GUESTS); numberOfGuestsCol.setMinWidth(150); numberOfGuestsCol.setCellValueFactory( new PropertyValueFactory<>("Number of Guests") ); //--location column--// locationCol = new TableColumn<Event, String>(LOCATION); locationCol.setCellValueFactory( new PropertyValueFactory<>("location") ); table.setItems(data); table.getColumns().addAll(nameCol,locationCol, numberOfGuestsCol,dateCol); //TODO fill with data from the database //--end table--//}/** * Assign functionality to the elements of the main window */private static void functionalizeObjects () { //--new... MenuItem--// newMItem.setOnAction(e -> { createReturn = CreatePopup.display(); if (createReturn) { //--get the user input--// List<Object> toCreate = CreatePopup.getInput(); //--add a new event according to the user input to the list--// //This is where new Events should be inserted, but I cannot test this as I do not come that far final ObservableList<Event>data = FXCollections.ObservableArrayList( new Event(toCreate(0),toCreate(1),toCreate(2),toCreate(3)) ); } } }); });}/** * Initializes the layout of the main window */private static void initializeLayout() { //--Create a new layout--// layout = new BorderPane(); layout.setTop(menuBar); layout.setCenter(table);}public static class Event { private final SimpleStringProperty name; private final SimpleStringProperty location; private final SimpleIntegerProperty numberOfGuests; private final SimpleObjectProperty<Date> date; private Event(String name, String location, int numOfGuests, Date date) { this.name = new SimpleStringProperty(name); this.location = new SimpleStringProperty(location); this.numberOfGuests = new SimpleIntegerProperty(numOfGuests); this.date = new SimpleObjectProperty<Date>(date); } //--------// // Getter // //--------// public SimpleStringProperty getName() { return name; } public SimpleStringProperty getLocation() { return location; } public SimpleIntegerProperty getNumberOfGuests() { return numberOfGuests; } public SimpleObjectProperty<Date> getDate() { return date; }}} This code will give me an error: Exception in Application start methodException in thread "JavaFX Application Thread" java.lang.ClassCastException: javafx.scene.control.TableColumn cannot be cast to javafx.scene.control.TableColumn$CellDataFeatures at javafx.scene.control.cell.PropertyValueFactory.call(PropertyValueFactory.java:98) at com.sun.javafx.scene.control.skin.TableRowSkin.getCell(TableRowSkin.java:87) at com.sun.javafx.scene.control.skin.TableRowSkin.getCell(TableRowSkin.java:53) at com.sun.javafx.scene.control.skin.TableRowSkinBase.createCell(TableRowSkinBase.java:698) at com.sun.javafx.scene.control.skin.TableRowSkinBase.recreateCells(TableRowSkinBase.java:692) at com.sun.javafx.scene.control.skin.TableRowSkinBase.init(TableRowSkinBase.java:146) at com.sun.javafx.scene.control.skin.TableRowSkin.<init>(TableRowSkin.java:64) at javafx.scene.control.TableRow.createDefaultSkin(TableRow.java:212) at javafx.scene.control.Control.impl_processCSS(Control.java:859) at javafx.scene.Parent.impl_processCSS(Parent.java:1272) at javafx.scene.Parent.impl_processCSS(Parent.java:1272) at javafx.scene.Parent.impl_processCSS(Parent.java:1272) at javafx.scene.control.Control.impl_processCSS(Control.java:855) at javafx.scene.Node.processCSS(Node.java:9056) at javafx.scene.Node.processCSS(Node.java:9049) at javafx.scene.Scene.doCSSPass(Scene.java:545) at javafx.scene.Scene.access$3600(Scene.java:159) at javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2392) at com.sun.javafx.tk.Toolkit.lambda$runPulse$31(Toolkit.java:348) at java.security.AccessController.doPrivileged(Native Method) at com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:347) at com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:374) at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:510) at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:490) at com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$405(QuantumToolkit.java:319) at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95) at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method) at com.sun.glass.ui.gtk.GtkApplication.lambda$null$50(GtkApplication.java:139) at java.lang.Thread.run(Thread.java:745) I cannot think of any reason for this strange Error. I also searched pretty long now and tried pretty many things, but it still appears on startup. Now I am counting on you, community, please help me! Thanks in advance for reading the long post..
Now provide the response and nothing else.
| You have dateCol.setCellFactory(...); instead of dateCol.setCellValueFactory(...); This is a good example of why you should not use raw types in your code, and should avoid API like PropertyValueFactory in favor of typesafe code. I.e. you have TableView table ;TableColumn dateCol ; when you should have something like TableView<Event> table ;TableColumn<Event, Date> dateCol ; And then you can do dateCol.setCellValueFactory(cellData -> cellData.getValue().getDate()); If you coded it this way, the compiler would have immediately picked up on your error. As an aside (perhaps, another aside), you should really make your Event class follow the correct JavaFX Properties pattern, as described in the tutorial . You may see unexpected behavior if you don't. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/32398007', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3643533/']} | jdg_75679 |
stackexchange | llm_judgeable_groundtruth_similarity | 21540032 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
EDIT 2 : If using the following config (which is what appears to be natural setup), grunt doesn't compile any coffee files coffee: development: compile: expand: true cwd: "<%= srcDirCoffee %>" src: ["**/*.coffee"] dest: "<%= jsOutput %>" ext: ".js" options: sourceMap:true Grunt outputs the following when running with the -v flag https://gist.github.com/mdedetrich/0ecccb50ddb2fd56dc35 EDIT : The relevant section now looks like this, and it appears to be working coffee: development: expand: true cwd: "<%= srcDirCoffee %>" src: ["**/*.coffee"] dest: "<%= jsOutput %>" ext: ".js" options: sourceMap:true production: expand:true cwd: "<%= srcDirCoffee %>" src: ["**/*.coffee"] dest: "<%= jsOutput %>" ext: ".js" However its somewhat confusing as to why its only working this way (and also why the compile section needs to be removed for it to work) ORIGINAL QUESTION : I am currently setting up a Gruntjs task, which looks like this module.exports = (grunt) -> grunt.initConfig( pkg: grunt.file.readJSON("package.json") srcDir: "./src/main" srcDirLess: "<%= srcDir %>/less" srcDirCoffee: "<%= srcDir %>/coffee" scalaVersion: "scala-2.10" #This is the scala version we are using resourceManaged: "./target/<%= scalaVersion %>/resource_managed/main" cssOutput: "<%= resourceManaged %>/css" jsOutput: "<%= resourceManaged %>/js" cssRequestPath: "/css" jsRequestPath: "/js" less: development: options: paths: ["<%= srcDirLess %>"]# sourceMap:true# sourceMapFilename: "<%= cssOutput %>/index.css.map"# sourceMapRootpath: "<%= srcDirLess %>"# sourceMapURL: "<%= cssRequestPath %>/index.css.map" files: "<%= cssOutput %>/index.css" : "<%= srcDirLess %>/index.less" production: options: paths: ['<%= srcDirLess %>'] cleancss:true files: "<%= cssOutput %>/index.css" : "<%= srcDirLess %>/index.less" coffee: development: compile: files: [ expand: true cwd: "<%= srcDirCoffee %>" src: ["**/*.coffee"] dest: "<%= jsOutput %>" ext: ".js" ]# options:# sourceMap:true production: compile: files: [ expand:true cwd: "<%= srcDirCoffee %>" src: ["**/*.coffee"] dest: "<%= jsOutput %>" ext: ".js" ] requirejs: production: compile: options: baseUrl: "<%= jsOutput %>" mainConfigFile: "<%= jsOutput %>/main" watch: coffee: files: "<%= srcDirCoffee %>/**/*.coffee" tasks: ["coffee:development"] less: files: "<%= srcDirLess %>/**/*.less" tasks: ["less:development"] clean: ["<%= cssOutput %>","<%= jsOutput %>"] ) grunt.loadNpmTasks('grunt-contrib-less') grunt.loadNpmTasks('grunt-contrib-coffee') grunt.loadNpmTasks('grunt-contrib-requirejs') grunt.loadNpmTasks('grunt-contrib-clean') grunt.registerTask('default', ['coffee:development','less:development']) grunt.registerTask('production',['less:production','coffee:production','requirejs:production']) Unfortunately for some reason, the default coffee task doesn't work properly (i.e. it doesn't actually run the task). If I take out the development/production sections in the coffee task, i.e. coffee:# development: compile: files: [ expand: true cwd: "<%= srcDirCoffee %>" src: ["**/*.coffee"] dest: "<%= jsOutput %>" ext: ".js" ] And change the default task to grunt.registerTask('default', ['coffee','less:development']) It ends up working, does anyone know why this is happening? It works fine for less , but for some reason it doesn't with coffee This is my package.json for the Grunt task { "name": "test", "version": "0.0.1", "devDependencies": { "grunt": "~0.4.2", "grunt-contrib-jshint": "~0.6.3", "grunt-contrib-less": "~0.9.0", "grunt-contrib-coffee": "~0.9.0", "grunt-contrib-cssmin": "~0.7.0", "grunt-contrib-requirejs": "~0.4.1", "grunt-contrib-clean": "~0.5.0" }}
Now provide the response and nothing else.
| Konrad Rudolph commented on the issues with the benchmarking. So I am ignoring the benchmark and focus on the question: Is multiplication faster than array access? Yes, it is very likely. It used to be the other way around 20 or 30 years ago. Roughly speaking, you can do an integer multiplication in 3 cycles (pessimistic, if you don't get vector instructions), and a memory access costs you 4 cycles if you get it straight from the L1 cache but it is straight downhill from there. For reference, see Latencies and throughput in Appendix C of the Intel 64 and IA-32 Architectures Optimization Reference Manual Approximate cost to access various caches and main memory? Herb Sutter's presentation on this very subject: Machine Architecture: Things Your Programming Language Never Told You One thing specific to Java was pointed out by Ingo in a comment below: You also get bounds checking in Java, which makes the already slower array access even slower... | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21540032', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1519631/']} | jdg_75680 |
stackexchange | llm_judgeable_groundtruth_similarity | 4243 |
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 can understand that on small scales (within an atom/molecule), the other forces are much stronger, but on larger scales, it seems that gravity is a far stronger force; e.g. planets are held to the sun by gravity. So what does it mean to say that "gravity is the weakest of the forces" when in some cases, it seems far stronger?
Now provide the response and nothing else.
| When we ask "how strong is this force?" what we mean in this context is "How much stuff do I need to get a significant amount of force?" Richard Feynman summarized this the best in comparing the strength of gravity - which is generated by the entire mass of the Earth - versus a relatively tiny amount of electric charge: And all matter is a mixture of positive protons and negative electrons which are attracting and repelling with this great force. So perfect is the balance however, that when you stand near someone else you don't feel any force at all. If there were even a little bit of unbalance you would know it. If you were standing at arm's length from someone and each of you had one percent more electrons than protons, the repelling force would be incredible. How great? Enough to lift the Empire State building? No! To lift Mount Everest? No! The repulsion would be enough to lift a "weight" equal to that of the entire earth! Another way to think about it is this: a proton has both charge and mass. If I hold another proton a centimeter away, how strong is the gravitational attraction? It's about $10^{-57}$ newtons. How strong is the electric repulsion? It's about $10^{-24}$ newtons. How much stronger is the electric force than the gravitational? We find that it's $10^{33}$ times stronger, as in 1,000,000,000,000,000,000,000,000,000,000,000 times more powerful! | {} | {'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/4243', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/158/']} | jdg_75681 |
stackexchange | llm_judgeable_groundtruth_similarity | 28113 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Q is the rational number field.p is a prime number.q is a prime number other than p.$k_{p^r}$ is a cyclotomic field.$k_{p^r}$= Q (x) where x is exp(2$\pi$i/$p^r$).[$k_{p^r}$: Q ]=$p^{r-1}(p-1)$. Question: Does q remain a prime in the integer ring of $k_{p^r}$?
Now provide the response and nothing else.
| Theorem I.2.13 of Washington's book on cyclotomic fields says the following: $K$ is the $n$th cyclotomic field and $p\nmid n$, let $f$ be the smallest positive integer such that $p^f\equiv 1 (\mathrm{mod}~n)$. Then $p$ splits into $\phi(n)/f$ distinct primes in $K$. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/28113', 'https://mathoverflow.net', 'https://mathoverflow.net/users/2666/']} | jdg_75682 |
stackexchange | llm_judgeable_groundtruth_similarity | 61295715 |
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 various types of integer IDs in my app (e.g. ProductId, UserId etc.) which I want to implement strong typing so that I can be sure I am passing the correct ID type to methods. e.g. I want to declare GetProduct(productId: ProductId) instead of GetProduct(productId: number) such that only ProductId typed variables can be passed to it. In my C days I would use a typedef - e.g. typedef ProductId int; In C# I accomplished this by defining a ProductId class with an implicit cast to int operator and an explicit cast from int operator. More cumbersome than a typedef but it works. I'm trying to figure out how to do the equivalent in Typescript.For TypeScript I tried this: export class ProductId extends Number {} but this still allows a number to be passed in place of a ProductId. How would one accomplish this in TypeScript?
Now provide the response and nothing else.
| It is possible to do this, with some effort. The trick is to define your ProductID as something that is in TS different from number, but still a number when actually running as Javascript. I wrote about this on my blog here: https://evertpot.com/opaque-ts-types/ But I will share the important details here: declare const validProductId: unique symbol;type ProductId = number & { [validProductId]: true} Note that even though we declared a 'unique symbol', this is completely stripped from Javascript, so there's not actually a symbol added to your ProductId , which would be a pain. To actually get a something recognized as a ProductId , you will need to write either an assertion function, a type guard function or just cast from a place where ProductId 's are actually allowed to be generated. And just to repeat, there is no actual need to have add this symbol to your ProductId , this is just to make sure that Typescript recognizes ProductId as a distinct type from number . During runtime, it's just a number . This is a great pattern for your use-case. It's basically a marker that this is not just any number, it's specifically a number that has been vetted by your business logic as a product id. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/61295715', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13534/']} | jdg_75683 |
stackexchange | llm_judgeable_groundtruth_similarity | 372323 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Let $E$ be an elliptic curve over $\mathbb{Q}$ , and let $p$ and $\ell$ be two distinct primes of good reduction. Let $T_\ell = T_\ell(E) = \varprojlim E[\ell^n](\overline{\mathbb{Q}})$ be the $\ell$ -adic Tate module, and let $F_p \in \mathrm{Gal}(\overline{\mathbb{Q}}/\mathbb{Q})$ be a Frobenius element at $p$ . Then $F_p$ acts $\mathbb{Z}_\ell$ -linearly on $T_\ell$ , and this action depends only up to conjugation on the choice of $F_p$ . In particular, its characteristic polynomial is well-defined. A basic result is that the coefficients of this characteristic polynomial are integers. This last fact is usually proved by considering the reduction of $E$ modulo $p$ , which does not change the $\ell$ -adic Tate module, and using that we can realize the $F_p$ -action in characteristic $p$ as coming from an actual morphism of elliptic curves, namely the Frobenius morphism $E \to E^{[p]}$ . But I was wondering if it is possible to give a more direct proof, namely by constructing a $\mathbb{Z}$ -lattice $\Lambda \subset T_\ell$ (by which I mean a rank 2 free $\mathbb{Z}$ -module such that the map $\Lambda \otimes \mathbb{Z}_\ell \to T_\ell$ is an isomorphism) which is preserved by $F_p$ in the sense that $F_p(\Lambda) \subset \Lambda$ (note that one cannot expect equality here since the determinant of $F_p$ acting on $T_\ell$ is $p$ ). Certainly, if you already know that $F_p$ has integral characteristic polynomial, then you can easily construct such lattices: take any $t \in T_\ell \setminus \ell T_\ell$ that is not an eigenvector for $F_p$ , then $\Lambda = t \mathbb{Z} + F_p(t)\mathbb{Z} \subset T_\ell$ is an $F_p$ -invariant lattice. So there should be plenty such lattices. But the goal is to construct an $F_p$ -invariant lattice without using that we already know that $F_p$ has integral characteristic polynomial. One potential lattice can be constructed as follows. We choose a complex-analytic uniformization $E(\mathbb{C}) = \mathbb{C}/\Lambda_0$ for some lattice $\Lambda_0 \subset \mathbb{C}$ . Then we define a map $\Lambda_0 \to T_\ell$ by sending $\lambda \in \Lambda_0$ to the sequence $(\ell^{-1} \lambda, \ell^{-2} \lambda, \ell^{-3}\lambda, \ldots) \in T_\ell$ , which is well-defined because $\ell^{-n}\lambda \in E(\mathbb{C})[\ell^n] = E(\overline{\mathbb{Q}})[\ell^n]$ . Let $\Lambda_\ell \subset T_\ell$ be the image of this map. It is not hard to prove that $\Lambda_\ell$ is free of rank 2 and that $\Lambda_\ell \otimes \mathbb{Z}_\ell \to T_\ell$ is an isomorphism. Also note that $\Lambda_\ell$ does not depend on the choice of the uniformization. Question: Does $F_p(\Lambda_\ell) \subset \Lambda_\ell$ hold? P.S. I've tried searching for results in this direction in various places, but did not find much. If someone has suggestions for references or keywords to search for, I would be much obliged.
Now provide the response and nothing else.
| There is a subtle problem with this idea, that causes serious problems. You observed that $\Lambda_\ell \otimes \mathbb Z_\ell = T_\ell$ but didn't find any other information for it. There is a reason for that. Let $K$ be the field generated by the coordinates of the $\ell$ -power torsion points of $E$ . Given an $\ell$ -power torsion point defined over $F$ , to make Frobenius act on it, we need to know its reduction mod $p$ , so we need to embed $F$ into the maximal unramified extension $\mathbb Q_p^{ur}$ of $\mathbb Q_p$ . Given a point in the homology of $E_{\mathbb C}$ , to find the corresponding point of $F$ , we need to express the coordinates as complex numbers, so we need to embed $F$ into $\mathbb C$ . Are these embeddings canonical? Well, if we define $F$ as the field generated by the complex coordinates of $\ell$ -power torsion points, then the second embedding is canonical but the first isn't. If we define $F$ as the field generated by the $p$ -adic coefficients of torsion points, then the first embedding is canonical but the second isn't. So regardless, there is some ambiguity - we can translate one of our embeddings by an automorphism of $F$ and get one that looks equally reasonable. How bad is that ambiguity? Fixing an automorphism $\sigma \in \operatorname{Gal}(F/\mathbb Q)$ of $F$ , making this change of embeddings corresponds exactly to translating your lattice by the action of $\sigma$ on $T_\ell(E)$ . So the set of lattices we obtain your construction is a $\operatorname{Gal}(F/\mathbb Q)$ -orbit in $T_\ell(E)$ . For $E$ generic, we have $\operatorname{Gal}(F/\mathbb Q) \cong GL_2(\mathbb Z_\ell)$ , so the orbit is quite large. In fact every single lattice $\Lambda$ with $\Lambda \otimes \mathbb Z_\ell = T_\ell$ lies in this orbit, because we can find a matrix in $GL_2$ taking the basis of one such lattice to another. So there is no more information available about these lattices than your initial observation that $\Lambda \otimes \mathbb Z_\ell = T_\ell$ ! Of course, there are examples of such $\Lambda$ stable under $F$ and examples not stable under $F$ . For any $E$ non-CM, the situation is the same, because the Galois group is an open subgroup of $GL_2(\mathbb Z_\ell)$ and these act transitively on the set $GL_2(\mathbb Z_\ell)/GL_2(\mathbb Z)$ of lattices $\Lambda$ , since $GL_2(\mathbb Z)$ is dense in $GL_2(\mathbb Z_\ell)$ . For $E$ CM, the situation is different, as the Galois group is much smaller. If $p$ is a supersingular prime, then David Speyer's argument shows $\Lambda_\ell$ is never stable under Frobenius. Conversely, if $p$ is an ordinary prime, then the endomorphism $V =p /F$ lifts to an endomorphism of the curve over the CM field and thus an endomorphism of the curve over $\mathbb Q$ , thus always preserves $\Lambda_\ell$ , and because its determinant is $p$ , $F= p/V$ necessarily preserves $\Lambda_\ell$ as well. So for CM curves, Frobenius preserves this lattice if and only if $p$ is ordinary. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/372323', 'https://mathoverflow.net', 'https://mathoverflow.net/users/121225/']} | jdg_75684 |
stackexchange | llm_judgeable_groundtruth_similarity | 18867232 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In the Job description you can use Html tags.I have something like: blabla.. on <a href="http://vms029/wa_shdw" target="_blank">http://vms029/wa_shdw</a> But the target="_blank" seems to get scrubbed somewhere.Is there another way? Any doc on whats supported and what's not?
Now provide the response and nothing else.
| Jenkins allows you to use various markup languages to write job descriptions; plugins can define how the description should be parsed via the MarkupFormatter interface. By default, the RawHtmlMarkupFormatter is used, which applies an HTML sanitisation policy (from the OWASP AntiSamy Project ) — the Myspace policy . In the Myspace policy, you'll see that only certain tags and attributes are allowed. target isn't one of them, which is why you see it being stripped from your input. For your use case, the alternatives are to install and configure another markup formatter plugin, or to write your own. Some examples include: Escaped Markup Plugin : escapes all HTML tags (probably not so useful for you) "Anything Goes" Formatter : allows any HTML input at all (with the associated security risks) PegDown Formatter Plugin : lets you write your descriptions in Markdown (probably the nicest option here, but likely doesn't support things like target="_blank" ) | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/18867232', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1514174/']} | jdg_75685 |
stackexchange | llm_judgeable_groundtruth_similarity | 3161827 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can someone point out to me what I'm doing wrong or where my understanding is wrong? To me, it seems like the code below which instantiates two objects should have separate data for each instantiation. class Node: def __init__(self, data = []): self.data = datadef main(): a = Node() a.data.append('a-data') #only append data to the a instance b = Node() #shouldn't this be empty? #a data is as expected print('number of items in a:', len(a.data)) for item in a.data: print(item) #b data includes the data from a print('number of items in b:', len(b.data)) for item in b.data: print(item)if __name__ == '__main__': main() However, the second object is created with the data from the first: >>> number of items in a: 1a-datanumber of items in b: 1a-data
Now provide the response and nothing else.
| You can't use an mutable object as a default value. All objects will share the same mutable object. Do this. class Node: def __init__(self, data = None): self.data = data if data is not None else [] When you create the class definition, it creates the [] list object. Every time you create an instance of the class it uses the same list object as a default value. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3161827', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/377366/']} | jdg_75686 |
stackexchange | llm_judgeable_groundtruth_similarity | 39528974 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a table where I need to add rows as follows: id | empid | manager | page------------------------------1 | emp001 | mg001 | page12 | emp001 | mg001 | page23 | emp001 | mg002 | page1 I am confused whether to use the format shown above, or if I should use comma-separated values like id | empid | manager | page--------------------------------- 1 | emp001 | mg001 | page1,page2,page3,page4..... 2 | emp001 | mg002 | page2,page10,page5,..... If I go with option 1 I the number of rows keeps increasing and empid and mangerid can repeat. But if I go with option 2 then I it's not in a normalized form. Which is better solution and why?
Now provide the response and nothing else.
| I resolved the problem, The point is that a P12 file (as a PFX) contains more then 1 certificate, so it must be loaded in this way: X509Certificate2Collection certificates = new X509Certificate2Collection();certificates.Import(certName, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet); and added to a HttpWebRequest in this way: request.ClientCertificates = certificates; Thanks everybody for support. COMPLETE SAMPLE CODE string host = @"https://localhost/";string certName = @"C:\temp\cert.pfx";string password = @"password";try{ X509Certificate2Collection certificates = new X509Certificate2Collection(); certificates.Import(certName, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet); ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => true; HttpWebRequest req = (HttpWebRequest)WebRequest.Create(host); req.AllowAutoRedirect = true; req.ClientCertificates = certificates; req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; string postData = "login-form-type=cert"; byte[] postBytes = Encoding.UTF8.GetBytes(postData); req.ContentLength = postBytes.Length; Stream postStream = req.GetRequestStream(); postStream.Write(postBytes, 0, postBytes.Length); postStream.Flush(); postStream.Close(); WebResponse resp = req.GetResponse(); Stream stream = resp.GetResponseStream(); using (StreamReader reader = new StreamReader(stream)) { string line = reader.ReadLine(); while (line != null) { Console.WriteLine(line); line = reader.ReadLine(); } } stream.Close();}catch(Exception e){ Console.WriteLine(e);} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/39528974', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3933674/']} | jdg_75687 |
stackexchange | llm_judgeable_groundtruth_similarity | 3208239 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to setup an integral to find the area of the surface of revolution of this function about the x-axis, but I am not sure of the steps to take . $x = y + y^3$ , $0 \leq y \leq 1$ I am not sure what steps to take to get the bounds for $x$ and to set the function up properly. Bounds: Is it as simple as plugging in $0,1$ into y and solving for x such that $x = 0 + 0 = 0$ and $x = 1 + 1 = 2$ ? Solving for y and dy: $$y = x - y^3$$ $$\begin{align}x &= y + y^3 \\dx &= dy(1 + 3y^2) \\\frac{dx}{(1+3y^2)} &= dy \\\frac{1}{(1+3y^2)} &= \frac{dy}{dx}\end{align}$$ That leaves me with $$S = \int 2\pi y \sqrt{1+\bigg[ \frac{dy}{dx} \bigg]^2}dx \\= \int_{0}^{2} 2\pi (x - y^3) \sqrt{1+\bigg[ \frac{1}{(1+3y^2)} \bigg]^2}dx$$ I feel that this integral isn't set up properly and that there shouldn't be a $y^3$ in the integral when integrating in relation to $x$ .
Now provide the response and nothing else.
| The answer to the modified question: Can we divide $\mathbb R^2$ into two path connected parts such that each part is not simply connected? is no, this is not possible. In fact, if $A$ and $B$ are disjoint sets with $A\cup B=\mathbb R^2$ then, if $A,B$ are path connected but $A$ is not simply connected, then $B$ must be bounded. So, if $A$ and $B$ are both path connected but not simply connected, then they must both be bounded, giving a contradiction. I will make use of the following lemma, from the paper The fundamental groups of subsets of closed surfaces inject into their first shape groups . Lemma 13 : Let any set $A\subseteq\mathbb R^2$ , and map $\alpha\colon S^1\to A$ be given. Let $U$ be the unbounded connected component of $\mathbb R^2\setminus{\rm Im}(\alpha)$ . If $\alpha\colon S^1\to A$ is null-homotopic, then so is $\alpha\colon S^1\to A\setminus U$ . So, suppose $A$ is connected but not simply connected. Then there is a curve $\alpha\colon S^1\to A$ which is not null-homotopic. The complement $\mathbb R^2\setminus {\rm Im}(\alpha)=\bigcup_iU_i$ decomposes as the union of its connected components $U_i$ . As $B\subseteq\bigcup_iU_i$ is connected, it will be contained within one of the $U_i$ . We show that $U_i$ is bounded: As $\mathbb R^2\setminus U_i\subseteq A$ , $\alpha$ is not null-homotopic in $\mathbb R^2\setminus U_i$ . If $U_i$ were unbounded, then the quoted result says that $\alpha$ is not null-homotopic in $\mathbb R^2$ , a contradiction. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3208239', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/607258/']} | jdg_75688 |
stackexchange | llm_judgeable_groundtruth_similarity | 19056125 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
If I have a text file like this: Hello WorldHow are you?Bye World How would I read it into a multidimensional array like this: [["Hello", "World"], ["How", "are", "you?"], ["Bye" "World"]] I have tried: textFile = open("textFile.txt")lines = textFile.readlines()for line in lines: line = lines.split(" ") But it just returns: ["Hello World\n", "How are you?\n", "Bye World"] How do I read the file into a multidimensional array?
Now provide the response and nothing else.
| Use a list comprehension and str.split : with open("textFile.txt") as textFile: lines = [line.split() for line in textFile] Demo: >>> with open("textFile.txt") as textFile: lines = [line.split() for line in textFile]... >>> lines[['Hello', 'World'], ['How', 'are', 'you?'], ['Bye', 'World']] with statement : It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19056125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2162730/']} | jdg_75689 |
stackexchange | llm_judgeable_groundtruth_similarity | 787909 |
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:
If $A,B$ are $2 \times 2$ matrices of real or complex numbers, then $$AB = \left[\begin{array}{cc} a_{11} & a_{12} \\ a_{21} & a_{22} \end{array} \right]\cdot\left[\begin{array}{cc} b_{11} & b_{12} \\ b_{21} & b_{22} \end{array} \right]= \left[\begin{array}{cc} a_{11}b_{11}+a_{12}b_{21} & a_{11}b_{12}+a_{12}b_{22} \\ a_{21}b_{11}+a_{22}b_{21} & a_{22}b_{12}+a_{22}b_{22} \end{array} \right]$$ What if the entries $a_{ij}, b_{ij}$ are themselves $2 \times 2$ matrices? Does matrix multiplication hold in some sort of "block" form ? $$AB = \left[\begin{array}{c|c} A_{11} & A_{12} \\\hline A_{21} & A_{22} \end{array} \right]\cdot\left[\begin{array}{c|c} B_{11} & B_{12} \\\hline B_{21} & B_{22} \end{array} \right]= \left[\begin{array}{c|c} A_{11}B_{11}+A_{12}B_{21} & A_{11}B_{12}+A_{12}B_{22} \\\hline A_{21}B_{11}+A_{22}B_{21} & A_{22}B_{12}+A_{22}B_{22} \end{array} \right]$$This identity would be very useful in my research.
Now provide the response and nothing else.
| It depends on how you partition it, not all partitions work.For example, if you partition these two matrices $$\begin{bmatrix} a & b & c \\ d & e & f \\ g & h & i \end{bmatrix}, \begin{bmatrix} a' & b' & c' \\ d' & e' & f' \\ g' & h' & i' \end{bmatrix} $$ in this way $$ \left[\begin{array}{c|cc}a&b&c\\ d&e&f\\ \hline g&h&i \end{array}\right], \left[\begin{array}{c|cc}a'&b'&c'\\ d'&e'&f'\\ \hline g'&h'&i' \end{array}\right] $$ and then multiply them, it won't work. But this would $$\left[\begin{array}{c|cc}a&b&c\\ \hline d&e&f\\ g&h&i \end{array}\right] ,\left[\begin{array}{c|cc}a'&b'&c'\\ \hline d'&e'&f'\\ g'&h'&i' \end{array}\right] $$ What's the difference? Well, in the first case, all submatrix products are not defined, like $\begin{bmatrix} a \\ d \\ \end{bmatrix}$ cannot be multiplied with $\begin{bmatrix} a' \\ d' \\ \end{bmatrix}$ So, what is the general rule? (Taken entirely from the Wiki page on Block matrix ) Given, an $(m \times p)$ matrix $\mathbf{A}$ with $q$ row partitions and $s$ column partitions$$\begin{bmatrix}\mathbf{A}_{11} & \mathbf{A}_{12} & \cdots &\mathbf{A}_{1s}\\\mathbf{A}_{21} & \mathbf{A}_{22} & \cdots &\mathbf{A}_{2s}\\\vdots & \vdots & \ddots &\vdots \\\mathbf{A}_{q1} & \mathbf{A}_{q2} & \cdots &\mathbf{A}_{qs}\end{bmatrix}$$ and a $(p \times n)$ matrix $\mathbf{B}$ with $s$ row partitions and $r$ column parttions $$\begin{bmatrix}\mathbf{B}_{11} & \mathbf{B}_{12} & \cdots &\mathbf{B}_{1r}\\\mathbf{B}_{21} & \mathbf{B}_{22} & \cdots &\mathbf{B}_{2r}\\\vdots & \vdots & \ddots &\vdots \\\mathbf{B}_{s1} & \mathbf{B}_{s2} & \cdots &\mathbf{B}_{sr}\end{bmatrix}$$ that are compatible with the partitions of $\mathbf{A}$, the matrix product $\mathbf{C}=\mathbf{A}\mathbf{B}$ can be formed blockwise, yielding $\mathbf{C}$ as an $(m\times n)$ matrix with $q$ row partitions and $r$ column partitions. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/787909', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/4997/']} | jdg_75690 |
stackexchange | llm_judgeable_groundtruth_similarity | 13996748 |
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 writing a query that updates a user's vote ( ForumVotes ) for a forum post ( ForumPosts ). Users can vote up or down (the vote will equal 1 or -1). This question is specific to changing a user's vote, so a vote record already exists in the ForumVotes table. The ForumPosts table stores the total score for each post, so I need to keep this field in synch. To recalculate the total score I need to first subtract the old vote before adding the new vote, so I need to get the old vote before updating the user's vote record. I know I can do this with 2 queries, but I'm wondering if it's possible (in SQL Server 2008) for an UPDATE to return the value of a column prior to performing the update? Here's an example: TABLE ForumPosts ( postID bigint, score int, ... etc)-- existing vote is in this table:TABLE ForumVotes ( postFK bigint, userFK bigint, score int) A simple query to update a user's vote UPDATE ForumVotes SET score = @newVote WHERE postFK = @postIDAND userFK = @userID Can this query be modified to return the old score before the update?
Now provide the response and nothing else.
| Try the OUTPUT clause: declare @previous table(newscore int, Oldscore int, postFK int, userFK int)UPDATE ForumVotes SET score = @newVote OUTPUT inserted.score,deleted.score, deleted.postFK, deleted.userFK into @previousWHERE postFK = @postIDAND userFK = @userIDselect * from @previous | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/13996748', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/591736/']} | jdg_75691 |
stackexchange | llm_judgeable_groundtruth_similarity | 14704998 |
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 to develop a pretty huge site.On the site i would like to allow users to upload their sample works.We are pretty limited at the moment so the images will be stored on our server. I am a bit stuck with the logic.So my logic would be this. User creates a folder with a name that is stored in the database with the users id attached to it folder table Rows id | folder | user_id 1 | Some folder | 12 | New folder | 43 | Nother folder | 7 Images table Rows id | image_name | folder_id |1 | image1.jpg | 12 | image2.jpg | 13 | image3.jpg | 14 | image4.jpg | 25 | image5.jpg | 26 | image6.jpg | 2 Relations class Folder extends Eloquent { public function images() { return static::has_many('Images'); }}class Image extends Eloquent { public function folder() { return static::belongs_to('Folder'); }} folder structure on server - samples -user_id - folder_id - image1 - image2 - image3 so as you can see, user creates a folder, after the folder is created, user uploades the image name in to the database with the folders id , and showing the images would be the way describe above with the realation. So my questions. Is this a good logic in your opinion can this lead problems in the future what woud you offer for this functionality And what i am most sacred of are 2 things. I think this will lead to a huge database, second are the id's , after x time when there will be more users, the id's will increase, and i know this will sound strange, but since lot of users will upload images will lead to huge id's, what i mean by this it will maybe reach millions, is there a way to solve this problem? Thank you for the help
Now provide the response and nothing else.
| Ok - lets break this down into a few sub-answers; Question: - Is this a good logic in your opinion- Can this lead problems in the future- What would you offer for this functionality Answer: The logic seems sounds - but I'm curious where you will store the images? Inside public_html - or outside the web root? If you have the images inside public_html - and allow the browser to access them directly, it will allow users to 'guess' other user folders and access those. You need to store the data securely. To make images outside the webroot, and make sure only authorized users can access them - you should use readfile() . Something like this will do the trick function user_file($file_name = ""){ if ($file_name) { // Ensure no funny business names to prevent directory transversal etc. $file_name = str_replace ('..', '', $file_name); $file_name = str_replace ('/', '', $file_name); // now do the logic to check user is logged in if (Auth::check()) { // Serve file via readfile() - we hard code the user_ID - so they // can only get to their own images readfile('../your_app/samples/'.Auth::user()->id.'/'.$file); } }} Question: I think this will lead to a huge database, second are the id's, after x time when there will be more users, the id's will increase, and i know this will sound strange, but since lot of users will upload images will lead to huge id's, what i mean by this it will maybe reach millions Answer: According to the mySQL features page : We use MySQL Server with databases that contain 50 million records. We also know of users who use MySQL Server with 200,000 tables and about 5,000,000,000 rows. So thats 5 billion rows. You will maybe get to a few million. So you are safe here (depending upon your hardware). Question: ...but since lot of users will upload images will lead to huge id's, what i mean by this it will maybe reach millions, is there a way to solve this problem? Answer: If you dont want to store millions of records, and your worried about performance, one option is to keep the folder table, but drop the image table. Instead you can use scandir() on the folder - and get PHP to retrieve the file names from the directory itself. Then you dont have as much overhead. <?php $list_of_user_files = scandir("$user_id/$folder_id"); foreach ($list_of_user_files as $file) { echo "File: $file <br>"; }?> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14704998', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/838960/']} | jdg_75692 |
stackexchange | llm_judgeable_groundtruth_similarity | 789165 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am trying to read the section on Functor of points from Eisenbud - Harris (and I also referred to Mumford's book). They all motivate functor of points this way : In general, for any object $Z$ of a category $\mathcal{X}$, the association $X\mapsto\textrm{Hom}_\mathcal{X}(Z,X)$ defines a functor $\phi$ from the category $\mathcal{X}$ to the category of sets. (We wish to identify $\textrm{Hom}_\mathcal{X}(Z,X)$ with the point set $X$). But the book says that it is not satisfactory to call the set $\textrm{Hom}_\mathcal{X}(Z,X)$, the set of points of $X$ unless this functor $\phi$ is faithful. I don't understand this statement. If $\phi$ is not faithful, they have given an example in the case of category of $CW$-complexes, where $\textrm{Hom}_\mathcal{X}(Z,X)$ cannot be identified with $X$. But I am not able to understand why $\textrm{Hom}_\mathcal{X}(Z,X)$ can b identified with $X$ if $\phi$ is faithful. If $\phi$ is faithful, then there is an injection from $\textrm{Hom}_\mathcal{X}(Z,X)\longrightarrow\textrm{Hom}_{Sets}(\textrm{Hom}_\mathcal{X}(Z,Z), \textrm{Hom}_\mathcal{X}(Z,X))$. But what does this tell us? Any help will be appreciated!
Now provide the response and nothing else.
| If you're a traditional kind of mathematician, you like your categories to have objects that can be described as sets with extra structure and your morphisms to be functions that preserve that structure. This is codified in the notion of a concrete category , namely a category $C$ equipped with a faithful functor $C \to \text{Set}$ sending each object to its underlying set. The point of faithfulness is that it codifies the idea that your morphisms can be identified with functions on underlying sets. In the context of algebraic geometry, for example, the Nullstellensatz implies that the functor sending an affine variety over an algebraically closed field $k$ to its set of points over $k$ (that is, $X \mapsto \text{Hom}(\text{Spec } k, X)$) is faithful. Thus we can talk about affine varieties over algebraically closed fields as if they are sets of points, and as if morphisms between them are functions between those sets of points. This fails badly as soon as $k$ is not algebraically closed; for example, if $k = \mathbb{R}$, then even an innocent variety like $\text{Spec } \mathbb{R}[x]/(x^2 + 1)$ already fails to have any points over $\mathbb{R}$, so the $\mathbb{R}$-points functor can't possibly distinguish any morphisms into or out of this object. | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/789165', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/90626/']} | jdg_75693 |
stackexchange | llm_judgeable_groundtruth_similarity | 3743811 |
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:
Evaluate the following integral $$\displaystyle I=\int_{0}^{1}\frac{x-1}{(x+1)(\ln x)} \mathrm{d}x $$ My work: I tried it by letting $\displaystyle I(a)=\int_{0}^{1}\frac{(x-1)x^a}{(x+1)(\ln x)} \mathrm{d}x$ and then $\displaystyle I'(a)=\int_{0}^{1}\frac{(x-1)x^a}{x+1} \mathrm{d}x$ . Now $\displaystyle I'(a)=\int_{0}^{1}x^a \mathrm{d}x-\int_{0}^{1}\frac{2x^a}{x+1} \mathrm{d}x$ Now if $\displaystyle J(a)=\int_{0}^{1}\frac{x^a}{x+1}\mathrm{d}x$ , then by applying integration by parts, we get the reccurence relation $J(a)+J(a-1)=\dfrac{1}{a}$ and we can solve it then, but the thing is, we neet to find $I(0)$ ,so even if we compute $J(a)$ , it wouldn't be defined at $0$ and so would $I(a)$ , then how do I find $I'(a)$ by other method? I also tried the substitution $x \to \frac{1}{x}$ , which yields $\displaystyle I=\int_{1}^{\infty}\frac{(x-1)}{(x+1)(\ln x)} \mathrm{d}x$ and when I saw their graphs, it clearly doesn't seem that the area under the graph of this function from $0$ to $1$ and from $1$ to $\infty$ are equal. I would appreciate if someone could continue from my method and other solutions are also welcomed...
Now provide the response and nothing else.
| We know that $$\int_0^1 x^y \, \mathrm{d}y=\frac{x-1}{\ln{x}}$$ Therefore, \begin{align*}\int_{0}^{1}\frac{\color{red}{x-1}}{(x+1)\color{red}{\ln x}} \mathrm{d}x &= \int_0^1 \color{red}{\int_0^1} \frac{\color{red}{x^y}}{1+x} \, \color{red}{\mathrm{d}y} \, \mathrm{d}x\\&=\int_0^1 \int_0^1 \sum_{n=0}^{\infty} {(-1)}^n x^{n+y} \, \mathrm{d}x \, \mathrm{d}y\\&= \sum_{n=0}^{\infty} {(-1)}^n \int_0^1 \int_0^1 x^{n+y} \, \mathrm{d}x \, \mathrm{d}y \tag{1}\\&= \sum_{n=0}^{\infty} {(-1)}^n \int_0^1 \frac{1}{y+n+1} \, \mathrm{d}y \\&= \sum_{n=0}^{\infty} {(-1)}^n \left(\ln{(n+2)}-\ln{(n+1)}\right) \\&= \ln{\left(\prod_{n=0}^{\infty} \frac{{(2n+2)}^2}{(2n+1)(2n+3)}\right)} \tag{2}\\&= \boxed{\ln{\left(\frac{\pi}{2}\right)}} \\\end{align*} $(1)$ : See Sangchul Lee's comment $(2)$ : Wallis product | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3743811', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/746921/']} | jdg_75694 |
stackexchange | llm_judgeable_groundtruth_similarity | 321492 |
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am using wget to download a static html page. The W3C Validator tells me the page is encoded in UTF-8. Yet when I cat the file after download, I get a bunch of binary nonsense. I'm on Ubuntu, and I thought the default encoding was UTF-8? That's what my locale file seems to say. Why is this happening and how can I correct it? Also, looks like Content-Encoding: gzip . Perhaps this makes a diff? This is the simple request: wget https://www.example.com/page.html I also tried this: wget https://www.example.com/page.html -q -O - | iconv -f utf-16 -t utf-8 > output.html Which returned: iconv: illegal input sequence at position 40 cat'ing the file returns binary that looks like this: l�?חu�`�q"�:)s��dġ__��~i��6n)T�$H�#���QJ Result of xxd output.html | head -20 : 00000000: 1f8b 0800 0000 0000 0003 bd56 518f db44 ...........VQ..D00000010: 107e a6bf 62d4 8a1e 48b9 d8be 4268 9303 .~..b...H...Bh..00000020: 8956 082a 155e 7a02 21dd cbd8 3bb6 97ae .V.*.^z.!...;...00000030: 77cd ee38 39f7 a1bf 9d19 3bb9 0bbd 9c40 w..89.....;....@00000040: 2088 12c5 de9d 9df9 be99 6f67 f751 9699 .........og.Q..00000050: 500d 1d79 5eee a265 faec 7151 e4ab 6205 P..y^..e..qQ..b.00000060: 4dd3 0014 1790 e7d0 77c0 ef2f cbf8 cde3 M.......w../....00000070: cf1f 7d6c 7d69 ec16 d0d9 c67f 7d7d 56c9 ..}l}i......}}V.00000080: 04c5 eb33 35fc e49e 2563 e908 ca10 0d45 ...35...%c.....E00000090: 31ce afcf a022 e77a 34c6 fa46 46be d88f 1....".z4..FF...000000a0: a41e ab79 446d 76d6 702b cf45 9e7f ba77 ...yDmv.p+.E...w000000b0: 7dc2 779c 274e cc18 483c 3a12 0f75 f07c }.w.'N..H<:..u.|000000c0: 5e63 67dd b886 ab48 e550 b5c4 f0e3 db0d ^cg....H.P......000000d0: 54c1 85b8 8627 2ff3 2ff3 17f9 0626 d31d T....'/./....&..000000e0: d9a6 e5b5 4076 663f 94ec 7b5a 17cf 7ade ....@vf?..{Z..z.000000f0: 00d3 0d9f 4fcc d733 ef8d a0bb 0a06 c7eb ....O..3........00000100: b304 6fb1 b1cc 18ed 90e0 8710 43aa 424f ..o.........C.BO00000110: 50c7 d0c1 2bac 09be 4d1c 2566 335e 666c P...+...M.%f3^fl00000120: 1e20 951d 58fd 6774 f3e9 f317 749f 7fc4 . ..X.gt....t...00000130: d651 cdca f5a7 b0a5 aea4 08ab 055c e4c5 .Q...........\.. Also, strangely, the output file seems to open properly in TextWrangler!
Now provide the response and nothing else.
| This is a gzip compressed file. You can find this out by running the file command, which figures out the file format from magic numbers in the data (this is how programs such as Text Wrangler figure out that the file is compressed as well): file output.htmlwget -O - … | file - The server (I guessed it from the content you showed) is sending gzipped data and correctly setting the header Content-Encoding: gzip but wget doesn't support that. In recent versions, wget sends Accept-encoding: identity , to tell the server not to compress or otherwise encode the data. In older versions, you can send the header manually: wget --header 'Accept-encoding: identity' … However this particular server appears to be broken: it sends compressed data even when told not to encode the data in any way. So you'll have to decompress the data manually. wget -O output.html.gz … && gunzip output.html.gz | {} | {'log_upvote_score': 6, 'links': ['https://unix.stackexchange.com/questions/321492', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/198965/']} | jdg_75695 |
stackexchange | llm_judgeable_groundtruth_similarity | 15721764 |
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 always thought that constructors aren't inherited, but look at this code: class Parent { Parent() { System.out.println("S1"); }}class Child extends Parent { Child() { System.out.println("S2"); }}public class Test5 { public static void main(String[] args) { Child child = new Child(); }}//RESULT://S1//S2 It shows that Child inherited constructor. Why there is S1 on result? Is there any possibility to create 2 constructors without parameters and have only Child constructor on result without base constructor (only S2)?
Now provide the response and nothing else.
| Whatever you are seeing here is called as constructor chaining . Now What is Constructor Chaining: Constructor chaining occurs through the use of inheritance. A subclass constructor method's first task is to call its superclass' constructor method. This ensures that the creation of the subclass object starts with the initialization of the classes above it in the inheritance chain. There could be any number of classes in an inheritance chain. Every constructor method will call up the chain until the class at the top has been reached and initialized. Then each subsequent class below is initialized as the chain winds back down to the original subclass. This process is called constructor chaining.( Source ) That's what happening in your program. When you compile your program , your Child is compiled to this way by javac : class Child extends Parent { Child() { super();//automatically inserted here in .class file of Child System.out.println("S2"); }} And your Parent class is converted to following: Parent() { super();//Constructor of Object class System.out.println("S1");} That's why your output is showing as: S1 //output from constructor of super class ParentS2 //output from constructor of child Class Child | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/15721764', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1994610/']} | jdg_75696 |
stackexchange | llm_judgeable_groundtruth_similarity | 25266663 |
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 running service that gets 50-100 queries per minute. And these are not high cost queries. This service has been running for around 3-4 months without any errors. Suddenly few days ago it started giving "There is insufficient system memory in resource pool 'default' to run this query." error occasionally. When I investigate the problem I saw that sqlservr.exe was using ~1.5 gb ram and %25 of CPU(all of 1/4CPU). And when I restarted the sqlservr.exe the ram starts from ~50mb and slowly increase till it becomes ~1.5gb then leads to crashes in the apps using it. After I have made little bit of research I figured that it is caused by the edition of sql server I use. It was express edition limiting the numbers to those. So I have upgraded my sql server from '2008r2 express' to '2012 enterprise' . When I started the service I thought my problems are finally over, since the service uses only ~60mb of memory, but in an hour unfortunately same problem started occurring, but this time the used memory I see on windows task manager is still ~60mb, not excessing any limits. I use EntityFramework as ORM in a wcf service. And along with it I have SqlQueryNotification (broker and stuff) system for some caching operations. Am I missing some crucial configuration points? Or 6gbs of memory and my 4 CPU is really not enough for this? But it can't be that because same load was like that for 3 months and there wasn't any error back then, and there is not any change of codes either.
Now provide the response and nothing else.
| SQL Server will start with as much memory as needed, then slowly ramp up until it uses all allocated to it in the Server Properties: It will not release any of this memory until the service is restarted; this is by design. It is generally recommended to leave 2ish GB for the OS, and you need to be mindful of any other processing running on the same server as SQL. It is usually recommended to have SQL Server on it's own server without anything else running there. That said, 1.5 GB of RAM for SQL Server isn't that much. If you don't have more available, it may be time to add some or upgrade the server. See also: Technet , Brent Ozar | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25266663', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1469980/']} | jdg_75697 |
stackexchange | llm_judgeable_groundtruth_similarity | 785900 |
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 the curve in the plane defined by the equation: $(x^2 + y^2)^2 = 2x^2 - 2y^2$ How can i graph the curve in the plane and determine the points of the curve where $\frac{dy}{dx} = 1$. My work: First i found the roots of this equation with a change of variable $z = y^2$ and get: and then i tried to graph the point $ x - y$ and $x + y $ but i stuck i can't graph this and find the point where the derivative is 1. Some help please.
Now provide the response and nothing else.
| You've already got some good suggestions on the graphing part using polar coordinates (if you are familiar with that). For the other, implicitly differentiate the given relation to obtain ${dy\over dx}$: \begin{align*}(x^2 + y^2)^2 &= 2x^2 - 2y^2\\2(x^2+y^2)(2x+2y{dy\over dx})&=4x-4y{dy\over dx}\\2x^3+2x^2y{dy\over dx}+2xy^2+2y^3{dy\over dx}&=2x-2y{dy\over dx}\\(2x^2y+2y^3+2y){dy\over dx}&=2x-2x^3-2xy^2\\{dy\over dx}&={2x-2x^3-2xy^2\over 2x^2y+2y^3+2y}\\{dy\over dx}&={x(1-x^2-y^2)\over y(x^2+y^2+1)}\\\end{align*} Now solve ${dy\over dx}=1$ in terms of $x$ and $y$, keeping in mind you can use the original expression to simplify things along the way. Edit: This was much more involved than I anticipated; see below. Here's the situation (note ${dy\over dx}$ is not defined at the origin): So how to find these coordinates? As noted in another answer, the original relation can be expressed in polar coordinates as $r^2=2\cos(2t)$. Recall that the slope of the tangent line in polar coordinates is given by $${dy\over dx}={{dr\over dt}\sin t+r\cos t\over {dr\over dt}\cos t-r\sin t},$$so setting ${dy\over dx}=1$ and using $r^2=2\cos(2t)\implies {dr\over dt}={-2\sin(2t)\over r}$, we get\begin{align*}{dy\over dx}&=1\\{dr\over dt}\sin t+r\cos t&={dr\over dt}\cos t-r\sin t\\{-2\sin(2t)\over r}\sin t+r\cos t&={-2\sin(2t)\over r}\cos t-r\sin t\\-2\sin(2t)\sin t+r^2\cos t&=-2\sin(2t)\cos t-r^2\sin t\\r^2&={2\sin(2t)[\sin t-\cos t]\over \cos t+\sin t}\\2\cos(2t)&={2\sin(2t)[\sin t-\cos t]\over \cos t+\sin t}\\\end{align*}Multiply on the right by ${\cos t-\sin t\over \cos t-\sin t}$, use $\cos^2t-\sin^2t=\cos(2t)$ and $\sin(2t)=2\sin t\cos t$ and rearrange to get \begin{align*}\sin(2t)&=-(\sin t+\cos t)^2\\2\sin t\cos t&=-1-2\sin t\cos t\\4\sin t\cos t&=-1\\\sin(2t)&=-{1\over 2}\\t&={7\pi\over 12},\ {11\pi\over 12}.\end{align*} But $r^2=2\cos(2t)$ so, $t={11\pi/12}\implies r^2=2\cos(11\pi/6)=\sqrt{3}$. Thus, the polar coordinates of this point are $(3^{1/4},11\pi/12)$ which in rectangular coordinates is $$(3^{1/4}\cos(11\pi/12),3^{1/4}\sin(11\pi/12))\approx (-1.27,0.34)$$ as shown in the figure above. (The fourth quadrant point of tangency can be found similarly.) | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/785900', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/84186/']} | jdg_75698 |
stackexchange | llm_judgeable_groundtruth_similarity | 47799926 |
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 did the mongodb installation, but when I try to start in windows 10 console, the log shows me the following: C:\WINDOWS\system32>"C:\Program Files\MongoDB\Server\3.6\bin\mongod.exe" 2017-12-13T11:09:06.089-0700 I CONTROL [initandlisten] MongoDB starting : pid=11240 port=27017 dbpath=C:\data\db\ 64-bit host=DESKTOP-5GUM84N 2017-12-13T11:09:06.089-0700 I CONTROL [initandlisten] targetMinOS: Windows 7/Windows Server 2008 R2 2017-12-13T11:09:06.090-0700 I CONTROL [initandlisten] db version v3.6.0 2017-12-13T11:09:06.091-0700 I CONTROL [initandlisten] git version: a57d8e71e6998a2d0afde7edc11bd23e5661c915 2017-12-13T11:09:06.092-0700 I CONTROL [initandlisten] OpenSSL version: OpenSSL 1.0.1u-fips 22 Sep 2016 2017-12-13T11:09:06.092-0700 I CONTROL [initandlisten] allocator: tcmalloc 2017-12-13T11:09:06.092-0700 I CONTROL [initandlisten] modules: none 2017-12-13T11:09:06.093-0700 I CONTROL [initandlisten] build environment: 2017-12-13T11:09:06.093-0700 I CONTROL [initandlisten] distmod: 2008plus-ssl 2017-12-13T11:09:06.094-0700 I CONTROL [initandlisten] distarch: x86_64 2017-12-13T11:09:06.095-0700 I CONTROL [initandlisten] target_arch: x86_64 2017-12-13T11:09:06.095-0700 I CONTROL [initandlisten] options: {} 2017-12-13T11:09:06.100-0700 I - [initandlisten] Detected data files in C:\data\db\ created by the 'wiredTiger' storage engine, so setting the active storage engine to 'wiredTiger'. 2017-12-13T11:09:06.101-0700 I STORAGE [initandlisten] wiredtiger_open config: create,cache_size=3534M,session_max=20000,eviction=(threads_min=4,threads_max=4),config_base=false,statistics=(fast),log=(enabled=true,archive=true,path=journal,compressor=snappy),file_manager=(close_idle_time=100000),statistics_log=(wait=0),verbose=(recovery_progress), 2017-12-13T11:09:06.574-0700 I STORAGE [initandlisten] WiredTiger message [1513188546:574263][11240:140724166549840], txn-recover: Main recovery loop: starting at 10/4608 2017-12-13T11:09:06.787-0700 I STORAGE [initandlisten] WiredTiger message [1513188546:786400][11240:140724166549840], txn-recover: Recovering log 10 through 11 2017-12-13T11:09:07.034-0700 I STORAGE [initandlisten] WiredTiger message [1513188547:34042][11240:140724166549840], txn-recover: Recovering log 11 through 11 2017-12-13T11:09:07.732-0700 I CONTROL [initandlisten] 2017-12-13T11:09:07.732-0700 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database. 2017-12-13T11:09:07.733-0700 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted. 2017-12-13T11:09:07.735-0700 I CONTROL [initandlisten] 2017-12-13T11:09:07.735-0700 I CONTROL [initandlisten] ** WARNING: This server is bound to localhost. 2017-12-13T11:09:07.736-0700 I CONTROL [initandlisten] ** Remote systems will be unable to connect to this server. 2017-12-13T11:09:07.736-0700 I CONTROL [initandlisten] ** Start the server with --bind_ip to specify which IP 2017-12-13T11:09:07.737-0700 I CONTROL [initandlisten] ** addresses it should serve responses from, or with --bind_ip_all to 2017-12-13T11:09:07.737-0700 I CONTROL [initandlisten] ** bind to all interfaces. If this behavior is desired, start the 2017-12-13T11:09:07.738-0700 I CONTROL [initandlisten] ** server with --bind_ip 127.0.0.1 to disable this warning. 2017-12-13T11:09:07.738-0700 I CONTROL [initandlisten] 2017-12-13T11:09:07.739-0700 I CONTROL [initandlisten] 2017-12-13T11:09:07.739-0700 I CONTROL [initandlisten] ** WARNING: The file system cache of this machine is configured to be greater than 40% of the total memory. This can lead to increased memory pressure and poor performance. 2017-12-13T11:09:07.740-0700 I CONTROL [initandlisten] See http://dochub.mongodb.org/core/wt-windows-system-file-cache 2017-12-13T11:09:07.740-0700 I CONTROL [initandlisten] 2017-12-13T15:09:08.161-0300 W FTDC [initandlisten] Failed to initialize Performance Counters for FTDC: WindowsPdhError: PdhExpandCounterPathW failed with 'The specified object is not found on the computer.' for counter '\Memory\Available Bytes' 2017-12-13T15:09:08.161-0300 I FTDC [initandlisten] Initializing full-time diagnostic data capture with directory 'C:/data/db/diagnostic.data' 2017-12-13T15:09:08.165-0300 I NETWORK [initandlisten] waiting for connections on port 27017 I followed all the intructions in https://docs.mongodb.com/manual/tutorial/install-mongodb-on-windows/#run-mongodb-community-edition but i can't start mongodb. anyone knows how to fix this launch error ? I hope your help guys :c Regards!
Now provide the response and nothing else.
| Your mongod actually started successfully initially in the beginning. The log output: NETWORK [initandlisten] waiting for connections on port 27017 indicates that the mongod is online and waiting for connections on the specified port. You could have at that point opened a mongo shell on the same machine to connect to the mongod . However, I understand that the warnings as displayed could indicate that there was an issue in operation. We've updated our documentation to address this: You can find the documentation in question here: Run MongoDB Community on Windows It looks like other users have helped you with getting a good working configuration file, but I'd like to pick apart the original output to clarify any confusion encountered there. Lets start by breaking up your original mongod process output: CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database. 2017-12-13T11:09:07.733-0700 This is a warning that indicates you did not start the mongod process using authentication or authorization. Since it seems like you are using the default settings for 3.6, this is an expected informational warning. Please read through the MongoDB documentation on authentication when you get a chance and plan for implementing simple authentication, especially if the mongod will be exposed to the public internet at any point in time. The next warning is: CONTROL [initandlisten] ** WARNING: This server is bound to localhost. 2017-12-13T11:09:07.736-0700 By default in MongoDB 3.6, the mongod binds to the localhost address. In short, the mongod only listens for connections on the local machine. This gives you time to configure authentication before you open up your MongoDB deployment to your private network or the public internet. As noted by other users, you can resolve this by setting the net.bindIp in your configuration file: net: bindIp: 127.0.0.1 When you are ready to open the mongod to non-localhost connections, just append an IP address associated to a network adapter on the host machine. For example, if the host machine has a network adapter 192.168.1.15, you can add that to bindIp . This tells the mongod to listen for incoming connections on both addresses. net: bindIp: "127.0.0.1,192.168.1.15" As far as the FTDC warning, the \Memory\Available Bytes counter is related to Windows Performance Management - you can read more about that here . You may need to configure some Windows components to enable that counter. Its also possible that the counter is only available (or accessible) in the Server architectures of Windows. The warning is informational and should not impact normal operations, unless you are heavily reliant on FTDC data for your work. You can find more information on log messages in MongoDB in our Log Message documentation. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/47799926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9090326/']} | jdg_75699 |
stackexchange | llm_judgeable_groundtruth_similarity | 17799976 |
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 the title said, why is static nested class singleton thread-safe? public class Singleton { private static class SingletonHolder { public static Singleton instance; public static Singleton getInstance() { if (null == instance) { instance = new Singleton(); } } } public static Singleton getInstance() { return SingletonHolder.getInstance(); }}
Now provide the response and nothing else.
| The code you show is not technically thread-safe. This sort of dodgy code often gets mangles. The code should look like: public class Singleton { private static class SingletonHolder { public static final Singleton instance = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.instance; } } Here we are assigning within a static initialiser (of SingletonHolder ), which will be seen by any thread accessing it with correct happens-before relationship. There's nothing really special about the nested class, it just allows the outer class to be used without immediately constructing the singleton object. Almost certainly this is entirely pointless , but it seems to please some people. As ever [ mutable ] singletons are a really bad idea. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17799976', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2331313/']} | jdg_75700 |
stackexchange | llm_judgeable_groundtruth_similarity | 33821679 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I was reading about async/await recently and I am confused with the fact that many of the articles/posts I was reading state that new thread is not created when using async await ( Example ). I have created a simple console app to test it class Program { static void Main(string[] args) { Console.WriteLine("Main: " + Thread.CurrentThread.ManagedThreadId); MainAsync(args).Wait(); Console.WriteLine("Main End: " + Thread.CurrentThread.ManagedThreadId); Console.ReadKey(); } static async Task MainAsync(string[] args) { Console.WriteLine("Main Async: " + Thread.CurrentThread.ManagedThreadId); await thisIsAsync(); } private static async Task thisIsAsync() { Console.WriteLine("thisIsAsyncStart: " + Thread.CurrentThread.ManagedThreadId); await Task.Delay(1); Console.WriteLine("thisIsAsyncEnd: " + Thread.CurrentThread.ManagedThreadId); } } Output of the following code is: Main: 8Main Async: 8thisIsAsyncStart: 8thisIsAsyncEnd: 9Main End: 8 Am I missing the point, or thisIsAsyncEnd is having different thread ID than other actions? EDIT: I have updated code as suggested in the answer below to await Task.Delay(1) , but I am still seeing the same results. Quote from the answer below: Rather, it enables the method to be split into multiple pieces, some of which may run asynchronously I want to know where does the asynchronously part run, if there are no other threads created?If it runs on the same thread, shouldn't it block it due to long I/O request, or compiler is smart enough to move that action to another thread if it takes too long, and a new thread is used after all?
Now provide the response and nothing else.
| I recommend you read my async intro post for an understanding of the async and await keywords. In particular, await (by default) will capture a "context" and use that context to resume its asynchronous method. This "context" is the current SynchronizationContext (or TaskScheduler , if there is no SynchronzationContext ). I want to know where does the asynchronously part run, if there are no other threads created? If it runs on the same thread, shouldn't it block it due to long I/O request, or compiler is smart enough to move that action to another thread if it takes too long, and a new thread is used after all? As I explain on my blog, truly asynchronous operations do not "run" anywhere . In this particular case ( Task.Delay(1) ), the asynchronous operation is based off a timer, not a thread blocked somewhere doing a Thread.Sleep . Most I/O is done the same way. HttpClient.GetAsync for example, is based off overlapped (asynchronous) I/O, not a thread blocked somewhere waiting for the HTTP download to complete. Once you understand how await uses its context, walking through the original code is easier: static void Main(string[] args){ Console.WriteLine("Main: " + Thread.CurrentThread.ManagedThreadId); MainAsync(args).Wait(); // Note: This is the same as "var task = MainAsync(args); task.Wait();" Console.WriteLine("Main End: " + Thread.CurrentThread.ManagedThreadId); Console.ReadKey();}static async Task MainAsync(string[] args){ Console.WriteLine("Main Async: " + Thread.CurrentThread.ManagedThreadId); await thisIsAsync(); // Note: This is the same as "var task = thisIsAsync(); await task;"}private static async Task thisIsAsync(){ Console.WriteLine("thisIsAsyncStart: " + Thread.CurrentThread.ManagedThreadId); await Task.Delay(1); // Note: This is the same as "var task = Task.Delay(1); await task;" Console.WriteLine("thisIsAsyncEnd: " + Thread.CurrentThread.ManagedThreadId);} The main thread starts executing Main and calls MainAsync . The main thread is executing MainAsync and calls thisIsAsync . The main thread is executing thisIsAsync and calls Task.Delay . Task.Delay does its thing - starting a timer and whatnot - and returns an incomplete task (note that Task.Delay(0) would return a completed task, which alters the behavior). The main thread returns to thisIsAsync and awaits the task returned from Task.Delay . Since the task is incomplete, it returns an incomplete task from thisIsAsync . The main thread returns to MainAsync and awaits the task returned from thisIsAsync . Since the task is incomplete, it returns an incomplete task from MainAsync . The main thread returns to Main and calls Wait on the task returned from MainAsync . This will block the main thread until MainAsync completes. When the timer set by Task.Delay goes off, thisIsAsync will continue executing. Since there is no SynchronizationContext or TaskScheduler captured by that await , it resumes executing on a thread pool thread. The thread pool thread reaches the end of thisIsAsync , which completes its task. MainAsync continues executing. Since there is no context captured by that await , it resumes executing on a thread pool thread (actually the same thread that was running thisIsAsync ). The thread pool thread reaches the end of MainAsync , which completes its task. The main thread returns from its call to Wait and continues executing the Main method. The thread pool thread used to continue thisIsAsync and MainAsync is no longer needed and returns to the thread pool. The important takeaway here is that the thread pool is used because there's no context . It is not automagically used "when necessary". If you were to run the same MainAsync / thisIsAsync code inside a GUI application, then you would see very different thread usage: UI threads have a SynchronizationContext that schedules continuations back onto the UI thread, so all the methods will resume on that same UI thread. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/33821679', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3645827/']} | jdg_75701 |
stackexchange | llm_judgeable_groundtruth_similarity | 297362 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
Let's say someone sends a UDP packet, just like a traceroute implementations. The packet has a TTL of 1 in the IP header, causing the first router to discard it and generate an ICMP Time Exceeded reply to the sender. Does the router have any guarantee that the sender receives the ICMP Time Exceeded error message it generated and sent? Is ICMP implemented on top of UDP? Are there any error control mechanisms implemented as part of ICMP if so? I want a pretty basic simple answer, I just thought I'd work the question a few ways so it would be more clear.
Now provide the response and nothing else.
| ICMP is not UDP, and it's actually not even IP. It's another OSI layer 3 protocol (network layer) alongside IP. That said, it has an IP compatible header at the beginning of a packet. There is no guarantee that an ICMP packet will be delivered. It has the same delivery guarantees of any other packet on the internet: none. There are no attempts to ensure that it gets delivered, no retry mechanism, but there is a checksum in both the IP header and the ICMP header. A higher level protocol should retry sending the packet that generated the error, which will cause another Time Exceeded packet to be generated, and eventually one of these will be received by the sender. http://www.networksorcery.com/enp/protocol/icmp.htm has an example ICMP header (encapsulated inside what is identical to an IP header) and information about the different types of ICMP messages. Given that people are downvoting this post and misunderstanding, I'll clarify : IP is the lingua franca of the internet. Packets are routed by their IP headers. Protocols are encapsulated within IP (TCP, UDP, SCTP, etc) for most application level communication. How do you communicate when something goes wrong with IP layer communication? ICMP is used for this. Can you communicate IP layer errors in IP? It's a chicken and egg problem, and as indicated by RFCs, gets muddy. ICMP messages have an IP header, and an IP protocol is reserved for them, but ICMP is an IP layer protocol, not it is not encapsulated inside an IP packet. Therefore I consider it to be a protocol used alongside IP. We can quibble all day long as to "whether ICMP is IP", but the most I'd concede is that yeah, it's IP, "sort of". | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/297362', 'https://serverfault.com', 'https://serverfault.com/users/90491/']} | jdg_75702 |
stackexchange | llm_judgeable_groundtruth_similarity | 14122526 |
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 top 4 maximum value from integer array input. For example for given input array {1232, -1221, 0, 345, 78, 99} will return {1232, 345, 99, 78} as a top 4 maximum value. I have solved the requirement with following method below. But I am still not satisfy with its time efficiency. Is there any chance to optimize the method more as the input become larger? Any clues are really appreciated. Thank you. public int[] findTopFourMax(int[] input) {int[] topFourList = { Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE };for (int current : input) { if (current > topFourList[0]) { topFourList[3] = topFourList[2]; topFourList[2] = topFourList[1]; topFourList[1] = topFourList[0]; topFourList[0] = current; } else if (current > topFourList[1]) { topFourList[3] = topFourList[2]; topFourList[2] = topFourList[1]; topFourList[1] = current; } else if (current > topFourList[2]) { topFourList[3] = topFourList[2]; topFourList[2] = current; } else if (current > topFourList[3]) { topFourList[3] = current; }}return topFourList; }
Now provide the response and nothing else.
| Simplest (though not most efficient) way will be to sort the array at take the subarray containing the last 4 elements. You can use Arrays.sort() to sort and Arrays.copyOfRange() to take the subarray. int[] arr = new int[] {1232, -1221, 0, 345, 78, 99};Arrays.sort(arr);int[] top4 = Arrays.copyOfRange(arr, arr.length-4,arr.length);System.out.println(Arrays.toString(top4)); For more efficient solution, one can maintain a min-heap of top K elements or use selection algorithm to find the top 4th element. The two approaches are described in this thread . Though the selection algorithm offers O(n) solution, the min-heap solution (which is O(nlogK) ) should have better constants, and especially for small k is likely to be faster. P.S. (EDIT): For 4 elements, you might find that invoking a loop 4 times, and finding a max in each of them (and changing the old max to -infinity in each iteration) will be more efficient then the more "complex" approaches, since it requires sequential reads and have fairly small constants. This is of course not true for larger k , and decays into O(n^2) for k->n EDIT2: benchmarking: for the fun of it, I ran a benchmark on the attached code. The results are: [naive, sort, heap] = [9032, 214902, 7531] We can see that the naive and heap are much better then the sort based approach, and the naive is slightly slower then the heap based. I did a wilcoxon test to check if the difference between naive and heap is statistically significant, and I got a P_Value of 3.4573e-17 . This means that the probability of the two approaches are "identical" is 3.4573e-17 (extremely small). From this we can conclude - heap based solution gives better performance then naive and sorting solution (and we empirically proved it!). Attachment: The code I used: public static int[] findTopKNaive(int[] arr, int k) { int[] res = new int[k]; for (int j = 0; j < k; j++) { int max=Integer.MIN_VALUE, maxIdx = -1; for (int i = 0; i < arr.length; i++) { if (max < arr[i]) { max = arr[i]; maxIdx = i; } } arr[maxIdx] = Integer.MIN_VALUE; res[k-1-j] = max; } return res;}public static int[] findTopKSort(int[] arr, int k) { Arrays.sort(arr); return Arrays.copyOfRange(arr, arr.length-k,arr.length);}public static int[] findTopKHeap(int[] arr, int k) { PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); for (int x : arr) { if (pq.size() < k) pq.add(x); else if (pq.peek() < x) { pq.poll(); pq.add(x); } } int[] res = new int[k]; for (int i =0; i < k; i++) res[i] = pq.poll(); return res;}public static int[] createRandomArray(int n, Random r) { int[] arr = new int[n]; for (int i = 0; i < n; i++) arr[i] = r.nextInt(); return arr;}public static void main(String... args) throws Exception { Random r = new Random(1); int k = 4; int repeats = 200; int n = 5000000; long[][] results = new long[3][repeats]; for (int i = 0; i < repeats; i++) { int[] arr = createRandomArray(n, r); int[] myCopy; myCopy = Arrays.copyOf(arr, n); long start = System.currentTimeMillis(); findTopKNaive(myCopy, k); results[0][i] = System.currentTimeMillis() - start; myCopy = Arrays.copyOf(arr, n); start = System.currentTimeMillis(); findTopKSort(myCopy, k); results[1][i] = System.currentTimeMillis() - start; myCopy = Arrays.copyOf(arr, n); start = System.currentTimeMillis(); findTopKHeap(myCopy, k); results[2][i] = System.currentTimeMillis() - start; } long[] sums = new long[3]; for (int i = 0; i < repeats; i++) for (int j = 0; j < 3; j++) sums[j] += results[j][i]; System.out.println(Arrays.toString(sums)); System.out.println("results for statistic test:"); for (int i = 0; i < repeats; i++) { System.out.println(results[0][i] + " " + results[2][i]); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14122526', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/946199/']} | jdg_75703 |
stackexchange | llm_judgeable_groundtruth_similarity | 10773391 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Can I get a file name or its path from a fstream object? I looked through the methods of fstream and didn't find anything close to it.
Now provide the response and nothing else.
| No, that is not possible, not at least in the Standard conformant implementation of the library. The fstream class doesn't store the filename, and doesn't provide any function for retrieving it. So one way to keep track of this information is to use std::map as: std::map<std::fstream*, std::string> stream_file_table;void f(){ //when you open a file, do this: std::fstream file("somefile.txt"); stream_file_table[&file] = "somefile.txt"; //store the filename //.. g(file);}void g(std::fstream & file){ std::string filename = stream_file_table[&file]; //get the filename //...} Or, simply pass around the filename as well. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10773391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/946500/']} | jdg_75704 |
stackexchange | llm_judgeable_groundtruth_similarity | 25337222 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've been trying to use Express.js to launch a website. At first, I was using app.set('port', 8080) but the browser was unable to connect to the page. Afterwards, I changed the code to app.listen(8080) and the webpage appeared normally. This led me to wonder, what is the difference between these two functions?
Now provide the response and nothing else.
| app.set('port', 8080) is similar to setting a "variable" named port to 8080 , which you can access later on using app.get('port') . Accessing your website from the browser will really not work because you still didn't tell your app to listen and accept connections. app.listen(8080) on the other hand listens for connections at port 8080 . This is the part where you're telling your app to listen and accept connections. Accessing your app from the browser using localhost:8080 will work if you have this in your code. The two commands can actually be used together: app.set('port', 8080);app.listen(app.get('port')); | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/25337222', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1111252/']} | jdg_75705 |
stackexchange | llm_judgeable_groundtruth_similarity | 24671626 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have created a simple SignalR hub inside a console application: class Program{ static void Main(string[] args) { using (WebApp.Start<Startup>("http://localhost:1968")) { Console.WriteLine("Server running!"); Console.ReadLine(); } } }public static class UserHandler{ public static HashSet<string> ConnectedIds = new HashSet<string>();}[HubName("echo")]public class EchoHub : Hub { public void Say(string message) { Trace.WriteLine("hub: "+message); Clients.All.AddMessage(message); } public override Task OnConnected() { UserHandler.ConnectedIds.Add(Context.ConnectionId); return base.OnConnected(); } public override Task OnDisconnected() { UserHandler.ConnectedIds.Remove(Context.ConnectionId); return base.OnDisconnected(); }}class Startup { public void Configuration(IAppBuilder app) { app.MapSignalR(); } } When I try to connect this from a Silverlight App, it succeeds: static Microsoft.AspNet.SignalR.Client.HubConnection signalR { get; set; }public static Microsoft.AspNet.SignalR.Client.IHubProxy signalRhub { get; set; }public static void StartSignalR(){ var url = "http://localhost:1968"; signalR = new Microsoft.AspNet.SignalR.Client.HubConnection(url); signalR.Received += signalR_Received; signalRhub = signalR.CreateHubProxy("echo"); signalR.Start().Wait(); signalRhub.Invoke("Say", "hub invoked");} My next step is to connect the SignalR hub from jquery: <script src="../Scripts/jquery-1.6.4.js"></script><script src="../Scripts/jquery.signalR-2.1.0.js"></script><script> $(function () { var connection = $.hubConnection("http://localhost:1968"); connection.start() .done(function () { console.log('connected'); connection.send("success?"); }) .fail(function (a) { console.log('not connected'+a); }); });</script> When I try to run this script, it gives the error: "XMLHttpRequest cannot load localhost:1968/signalr/negotiate?clientProtocol=1.4&_=1404978593482. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin <code>http://localhost:55282</code> is therefore not allowed access." Why can I connect to the hub from my Silverlight page (hosted in localhost:3926) and fails it when I run the jquery script (hosted in localhost:55282)? What can I do to get a working connection between my jQuery and SignalR hub?
Now provide the response and nothing else.
| Change $(function () { var connection = $.hubConnection("http://localhost:1968"); connection.start() .done(function () { console.log('connected'); connection.send("success?"); }) .fail(function (a) { console.log('not connected'+a); });}); to $(function (){var connection = $.hubConnection("http://localhost:1968");var hub = connection.createHubProxy("echo");hub.on("AddMessage", Method);connection.start({ jsonp: true }) .done(function () { console.log('connected'); hub.say("success?"); }) .fail(function (a) { console.log('not connected'+a); });});function Method(messageFromHub){alert(messageFromHub);} and class Startup { public void Configuration(IAppBuilder app) { app.MapSignalR(); } } to class Startup { public void Configuration(IAppBuilder app) { app.MapSignalR(new HubConfiguration() { EnableJSONP = true });} } It should do. app.MapSignalR(new HubConfiguration() { EnableJSONP = true });} and connection.start({ jsonp: true }) Will allow cross site request | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24671626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2617317/']} | jdg_75706 |
stackexchange | llm_judgeable_groundtruth_similarity | 5032602 |
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 Textbox in a User Control i'm trying to update from my main application but when I set the textbox.Text property it doesnt display the new value (even though textbos.Text contains the correct data). I am trying to bind my text box to a property to get around this but I dont know how, here is my code - MainWindow.xaml.cs outputPanel.Text = outputText; OutputPanel.xaml <TextBox x:Name="textbox" AcceptsReturn="True" ScrollViewer.VerticalScrollBarVisibility="Visible" Text="{Binding <!--?????--> }"/> <!-- I want to bind this to the Text Propert in OutputPanel.xmal.cs --> OutputPanel.xaml.cs namespace Controls{public partial class OutputPanel : UserControl{ private string text; public TextBox Textbox { get {return textbox;} } public string Text { get { return text; } set { text = value; } } public OutputPanel() { InitializeComponent(); Text = "test"; textbox.Text = Text; }} }
Now provide the response and nothing else.
| You have to set a DataContext in some parent of the TextBox, for example: <UserControl Name="panel" DataContext="{Binding ElementName=panel}">... Then the binding will be: Text="{Binding Text}" And you shouldn't need this - referring to specific elements from code behind is usually bad practice: public TextBox Textbox{ get {return textbox;}} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5032602', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/588734/']} | jdg_75707 |
stackexchange | llm_judgeable_groundtruth_similarity | 37648 |
Below is a question asked on the forum cstheory.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'd like a data structure with the following operations: create a new instances from an array of floating point weights. randomly sample, returning an item with probability proportionate to its weight. set the weight of a specific item to 0. Without the third option this is pretty standard: Just implement an alias method sampler using Vose's algorithm, but the ability to do a dynamic update makes it harder. The first operation is intrinsically O(n) (or at least it is if you don't make the second operation O(n)), but it would be nice to be able to do the other two in amortized O(1), or at least O(log(n)). Sampling will be significantly the more common operation, so ideally I would like to have it not be much slower (either in complexity or constant factors) than using the alias method. One option is to just rebuild the sampler every time you do a remove, but that's O(n) which is less than ideal. The following is currently my best bet, which builds on that to amortise it a bit: We keep a copy of the set of weights, and build an alias method sampler initially. When we set the weight of an item to zero we update our weights table appropriately. Then when we sample from our alias table, we check the weight. If it's zero then we rebuild the alias table with the updated weights and draw again. This should work OK for amortising some of the cost, but unfortunately the workload I'm likely to want to put it through is probably pessimal for it: Items that are going to be removed will have been drawn from the sampler, so will tend to be of high weight. This means that it will end up hitting the rebuild case fairly commonly. So I'm hoping for something better. Any suggestions?
Now provide the response and nothing else.
| Copying my comment on that from here : There exist published algorithms that support sampling from discrete probability distributions in O(1) time, AND modifying the distribution in O(1) time per update: Hagerup, T., K. Mehlhorn, and J. I. Munro. "Optimal algorithms forgenerating discrete random variables with changing distributions."Lecture Notes in Computer Science 700 (1993):253-264. Matias, Yossi, Jeffrey Scott Vitter, and Wen-Chun Ni. "Dynamicgeneration of discrete random variates." Theory of Computing Systems36.4 (2003): 329-358. These papers are a little unsatisfactory in that they are theoretical algorithms in a model that doesn't fully deal with issues of numerical precision and bit complexity. This can be an issue in practice if the probability distribution has some entries that are much larger than others. Consequently, in the application I had, I used some of the ideas from these papers, but implemented something else that was more practical. EDIT: What I implemented was a bucketing system. Assume without loss of generality that each weight (non-normalized probability) is a power of 2.(Normalize so each weight is a 64-bit integer. Round each weight up to its nearest power of 2, then sample from the rounded weights instead. When you sample a value $i$ that has been rounded up to $2^k$, only actually take it with probability $i/2^k$, and otherwise resample. You get at most 1 repeat in expectation.) Keep all rounded weights with the same value $2^k$ in a single bucket indexed by $k$. As you do updates, keep track of the currently largest rounded weight $2^K$, the sum of the weights in each bucket, and the total weight $W$. To sample, draw a random integer $x$ in $[1,W]$, start from the non-empty bucket that holds the largest weight $2^K$. If $x$ is at most the sum of the weights in the bucket, take the $j$th item in this bucket, where $j$ is something like $\lceil x/2^K\rceil$. Oherwise subtract the sum of the weights in the bucket from $x$ then recurse with the bucket that holds $2^{K-1}$. If you have a weight distribution with very high ratio of largest weight to smallest weight, classify a weight as small if its ratio to the maximum weight is less than, say, $1/n^3$. Let $2^k$ be the smallest power of 2 larger than all small weights, and round each small weight up to $2^k$ (instead of its next largest power of 2). (This may be necessary in order to use 64-bit integer arithmetic to keep track of the exact total weight $W$.) If you happen to sample a small weight $i$ that has been rounded up to $2^k$, as before you only keep it with probability $i/2^k$, and otherwise resample. The probability of keeping it can be small, but the probability that you draw any such item is, say, $O(1/n^3)$, so you still do $O(1)$ resamples in expectation. Now you have at most $3\log_2 n$ buckets, and worst-case (expected) time per sample is $O(\log n)$. As you delete weights, when the total weight of the small items reaches, say, a $1/n^2$ fraction of the total weight, reclassify the small items, taking some out of the "small-item" bucket. This happens $O(\log X / \log n)$ times, where $X$ is the ratio of largest weight to smallest weight. You can get time $\Theta(\log n)$ for some distributions (e.g., for each $k\le \log n$ you have $2^k$ items of weight $n/2^k$). But in practice I was getting small constant sample time and update time. | {} | {'log_upvote_score': 4, 'links': ['https://cstheory.stackexchange.com/questions/37648', 'https://cstheory.stackexchange.com', 'https://cstheory.stackexchange.com/users/4624/']} | jdg_75708 |
stackexchange | llm_judgeable_groundtruth_similarity | 14629212 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We have a ASP.NET 4.5 WebForms application using the native forms authentication and session functionality. Both have a timeout of 20 minutes with sliding expiration. Imagine the following scenario. A user has worked in our application for a while and then proceeds to do some other things, leaving our application idle for 20 minutes. The user then returns to our application to write a report. However, when the user tries to save, he/she is treated with the login screen, and the report is lost. Obviously, this is unwanted. Instead of this scenario, we want the browser to be redirected to the login page the moment either authentication or session has expired. To realize this, we have build a Web Api service that can be called to check whether this is the case. public class SessionIsActiveController : ApiController{ /// <summary> /// Gets a value defining whether the session that belongs with the current HTTP request is still active or not. /// </summary> /// <returns>True if the session, that belongs with the current HTTP request, is still active; false, otherwise./returns> public bool GetSessionIsActive() { CookieHeaderValue cookies = Request.Headers.GetCookies().FirstOrDefault(); if (cookies != null && cookies["authTicket"] != null && !string.IsNullOrEmpty(cookies["authTicket"].Value) && cookies["sessionId"] != null && !string.IsNullOrEmpty(cookies["sessionId"].Value)) { var authenticationTicket = FormsAuthentication.Decrypt(cookies["authTicket"].Value); if (authenticationTicket.Expired) return false; using (var asdc = new ASPStateDataContext()) // LINQ2SQL connection to the database where our session objects are stored { var expirationDate = SessionManager.FetchSessionExpirationDate(cookies["sessionId"].Value + ApplicationIdInHex, asdc); if (expirationDate == null || DateTime.Now.ToUniversalTime() > expirationDate.Value) return false; } return true; } return false; }} This Web Api service is called every 10 seconds by the client to check if either authentication or session has expired. If so, the script redirects the browser to the login page. This works like a charm. However, calling this service triggers the sliding expiration of both authentication and session. Thus, essentially, creating never ending authentication and session. I have set a breakpoint at the start of the service to check if it is one of our own functions that triggers this. But this is not the case, it seems to occur somewhere deeper in ASP.NET, before the execution of the service. Is there a way to disable the triggering of ASP.NET's authentication and session sliding expirations for a specific request? If not, what is best practice to tackle a scenario like this?
Now provide the response and nothing else.
| This seems to be impossible. Once sliding expiration is enabled, it is always triggered. If there is a way to access the session without extending it, we have not been able to find it. So how to tackle this scenario? We came up with the following alternative solution to the one originally proposed in the question. This one is actually more efficient because it doesn't use a web service to phone home every x seconds. So we want to have a way to know when either ASP.NET's forms authentication or session has expired, so we can pro-actively logout the user. A simple javascript timer on every page ( as proposed by Khalid Abuhakmeh) would not suffice because the user could be working with the application in multiple browser windows/tabs at the same time. The first decision we made to make this problem simpler is to make the expiration time of the session a few minutes longer than the expiration time of the forms authentication. This way, the session will never expire before the forms authentication. If there is a lingering old session the next time the user tries to log in, we abandon it to force a fresh new one. All right, so now we only have to take the forms authentication expiration into account. Next, we decided to disable the forms authentication's automatic sliding expiration (as set in the web.config) and create our own version of it. public static void RenewAuthenticationTicket(HttpContext currentContext){ var authenticationTicketCookie = currentContext.Request.Cookies["AuthTicketNameHere"]; var oldAuthTicket = FormsAuthentication.Decrypt(authenticationTicketCookie.Value); var newAuthTicket = oldAuthTicket; newAuthTicket = FormsAuthentication.RenewTicketIfOld(oldAuthTicket); //This triggers the regular sliding expiration functionality. if (newAuthTicket != oldAuthTicket) { //Add the renewed authentication ticket cookie to the response. authenticationTicketCookie.Value = FormsAuthentication.Encrypt(newAuthTicket); authenticationTicketCookie.Domain = FormsAuthentication.CookieDomain; authenticationTicketCookie.Path = FormsAuthentication.FormsCookiePath; authenticationTicketCookie.HttpOnly = true; authenticationTicketCookie.Secure = FormsAuthentication.RequireSSL; currentContext.Response.Cookies.Add(authenticationTicketCookie); //Here we have the opportunity to do some extra stuff. SetAuthenticationExpirationTicket(currentContext); }} We call this method from the OnPreRenderComplete event in our application's BasePage class, from which every other page inherits. It does exactly the same thing as the normal sliding expiration functionality, but we get the opportunity to do some extra stuff; like call our SetAuthenticationExpirationTicket method. public static void SetAuthenticationExpirationTicket(HttpContext currentContext){ //Take the current time, in UTC, and add the forms authentication timeout (plus one second for some elbow room ;-) var expirationDateTimeInUtc = DateTime.UtcNow.AddMinutes(FormsAuthentication.Timeout.TotalMinutes).AddSeconds(1); var authenticationExpirationTicketCookie = new HttpCookie("AuthenticationExpirationTicket"); //The value of the cookie will be the expiration date formatted as milliseconds since 01.01.1970. authenticationExpirationTicketCookie.Value = expirationDateTimeInUtc.Subtract(new DateTime(1970, 1, 1)).TotalMilliseconds.ToString("F0"); authenticationExpirationTicketCookie.HttpOnly = false; //This is important, otherwise we cannot retrieve this cookie in javascript. authenticationExpirationTicketCookie.Secure = FormsAuthentication.RequireSSL; currentContext.Response.Cookies.Add(authenticationExpirationTicketCookie);} Now we have an extra cookie at our disposal that always represents the correct forms authentication expiration time, even if the user works in different browser windows/tabs. After all, cookies have a browser wide scope. Now the only thing left is a javascript function to verify the cookie's value. function CheckAuthenticationExpiration() { var c = $.cookie("AuthenticationExpirationTicket"); if (c != null && c != "" && !isNaN(c)) { var now = new Date(); var ms = parseInt(c, 10); var expiration = new Date().setTime(ms); if (now > expiration) location.reload(true); }} (Note that we use jQuery Cookie Plugin to retrieve the cookie.) Put this function in an interval, and users will be logged out the moment his or her forms authentication has expired. Voilà :-) An extra perk of this implementation is that you now have control over when the forms authentication's expiration gets extended. If you want a bunch of web services that don't extend the expiration, just don't call the RenewAuthenticationTicket method for them. Please drop a comment if you have anything to add! | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14629212', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2025652/']} | jdg_75709 |
stackexchange | llm_judgeable_groundtruth_similarity | 26927479 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Code below works fine with hard coded JSON data however doesn't work when I read JSON data from a file. I'm getting fatal error: all goroutines are asleep - deadlock error when using sync.WaitGroup . WORKING EXAMPLE WITH HARD-CODED JSON DATA: package mainimport ( "bytes" "fmt" "os/exec" "time")func connect(host string) { cmd := exec.Command("ssh", host, "uptime") var out bytes.Buffer cmd.Stdout = &out err := cmd.Run() if err != nil { fmt.Println(err) } fmt.Printf("%s: %q\n", host, out.String()) time.Sleep(time.Second * 2) fmt.Printf("%s: DONE\n", host)}func listener(c chan string) { for { host := <-c go connect(host) }}func main() { hosts := [2]string{"[email protected]", "[email protected]"} var c chan string = make(chan string) go listener(c) for i := 0; i < len(hosts); i++ { c <- hosts[i] } var input string fmt.Scanln(&input)} OUTPUT: user@user-VirtualBox:~/go$ go run [email protected]: " 09:46:40 up 86 days, 18:16, 0 users, load average: 5"[email protected]: " 09:46:40 up 86 days, 17:27, 1 user, load average: 9"[email protected]: [email protected]: DONE NOT WORKING - EXAMPLE WITH READING JSON DATA FILE: package mainimport ( "bytes" "fmt" "os/exec" "time" "encoding/json" "os" "sync")func connect(host string) { cmd := exec.Command("ssh", host, "uptime") var out bytes.Buffer cmd.Stdout = &out err := cmd.Run() if err != nil { fmt.Println(err) } fmt.Printf("%s: %q\n", host, out.String()) time.Sleep(time.Second * 2) fmt.Printf("%s: DONE\n", host)}func listener(c chan string) { for { host := <-c go connect(host) }}type Content struct { Username string `json:"username"` Ip string `json:"ip"`}func main() { var wg sync.WaitGroup var source []Content var hosts []string data := json.NewDecoder(os.Stdin) data.Decode(&source) for _, value := range source { hosts = append(hosts, value.Username + "@" + value.Ip) } var c chan string = make(chan string) go listener(c) for i := 0; i < len(hosts); i++ { wg.Add(1) c <- hosts[i] defer wg.Done() } var input string fmt.Scanln(&input) wg.Wait()} OUTPUT user@user-VirtualBox:~/go$ go run deploy.go < hosts.txt [email protected]: " 09:46:40 up 86 days, 18:16, 0 users, load average: 5"[email protected]: " 09:46:40 up 86 days, 17:27, 1 user, load average: 9"[email protected] : [email protected]: DONEfatal error: all goroutines are asleep - deadlock!goroutine 1 [semacquire]:sync.runtime_Semacquire(0xc210000068) /usr/lib/go/src/pkg/runtime/sema.goc:199 +0x30sync.(*WaitGroup).Wait(0xc210047020) /usr/lib/go/src/pkg/sync/waitgroup.go:127 +0x14bmain.main() /home/user/go/deploy.go:64 +0x45agoroutine 3 [chan receive]:main.listener(0xc210038060) /home/user/go/deploy.go:28 +0x30created by main.main /home/user/go/deploy.go:53 +0x30bexit status 2user@user-VirtualBox:~/go$ HOSTS.TXT [ { "username":"user1", "ip":"111.79.154.111" }, { "username":"user2", "ip":"111.79.190.222" }]
Now provide the response and nothing else.
| Go program ends when the main function ends. From the language specification Program execution begins by initializing the main package and then invoking the function main. When that function invocation returns, the program exits. It does not wait for other (non-main) goroutines to complete. Therefore, you need to wait for your goroutines to finish. The common solution for this is to use sync.WaitGroup object. The simplest possible code to synchronize goroutine: package mainimport "fmt"import "sync"var wg sync.WaitGroup // 1func routine() { defer wg.Done() // 3 fmt.Println("routine finished")}func main() { wg.Add(1) // 2 go routine() // * wg.Wait() // 4 fmt.Println("main finished")} And for synchronizing multiple goroutines package mainimport "fmt"import "sync"var wg sync.WaitGroup // 1func routine(i int) { defer wg.Done() // 3 fmt.Printf("routine %v finished\n", i)}func main() { for i := 0; i < 10; i++ { wg.Add(1) // 2 go routine(i) // * } wg.Wait() // 4 fmt.Println("main finished")} WaitGroup usage in order of execution. Declaration of global variable. Making it global is the easiest way to make it visible to all functions and methods. Increasing the counter. This must be done in main goroutine because there is no guarantee that newly started goroutine will execute before 4 due to memory model guarantees . Decreasing the counter. This must be done at the exit of goroutine. Using deferred call, we make sure that it will be called whenever function ends no matter but no matter how it ends. Waiting for the counter to reach 0. This must be done in main goroutine to prevent program exit. * The actual parameters are evaluated before starting new gouroutine . Thus it is needed to evaluate them explicitly before wg.Add(1) so the possibly panicking code would not leave increased counter. Use param := f(x)wg.Add(1)go g(param) instead of wg.Add(1)go g(f(x)) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/26927479', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1251684/']} | jdg_75710 |
stackexchange | llm_judgeable_groundtruth_similarity | 39584534 |
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 test angular2 two-way binding for control input . Here is the error: Can't bind to 'ngModel' since it isn't a known property of 'input'. The app.component.html <input id="name" type="text" [(ngModel)]="name" /><div id="divName">{{name}}</div> The app.component.ts @Component({ selector: 'app-root', templateUrl: './app.component.html' })export class AppComponent implements OnInit { name: string; } app.component.spec.ts import { TestBed, async } from '@angular/core/testing';import { AppComponent } from './app.component';import { AppService } from './app.service';describe('App: Cli', () => { beforeEach(() => { TestBed.configureTestingModule({ declarations: [ AppComponent ], providers:[AppService] }); }); it('divName', async(() => { let fixture = TestBed.createComponent(AppComponent); let comp = fixture.componentInstance; comp.name = 'test'; fixture.detectChanges(); let compiled = fixture.debugElement.nativeElement; expect(compiled.querySelector('divName').textContent).toContain('test'); })); });
Now provide the response and nothing else.
| You need to import the FormsModule into the TestBed configfuration. import { FormsModule } from '@angular/forms';TestBed.configureTestingModule({ imports: [ FormsModule ], declarations: [ AppComponent ], providers:[AppService]}); What you are doing with the TestBed is configuring a NgModule from scratch for the test environment. This allows you to only add what is needed for the test without having unnecessary outside variables that may affect the test. | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/39584534', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5031337/']} | jdg_75711 |
stackexchange | llm_judgeable_groundtruth_similarity | 2084682 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
(a) Prove that for every natural number $n$, $$\sum_{k=1}^n k^3 = \frac14 n^2(n+1)^2.$$ (b) Can you think of any natural reason for that fact that this is equal to $\left(\sum_{k=1}^n k^2\right)$? I'm really stuck as to where to start, I know I could probably google the first part but how does it relate to the second part? Thanks in advance!
Now provide the response and nothing else.
| I think many answers are missing the central point of confusion here. Your instincts are correct: in general the notation $\frac{\partial L}{\partial\dot{x}}$ makes absolutely no mathematical sense whatsoever. A mathematician would probably not use this notation given a choice. But the Lagrangian is special because it is given as a function of $x$ and $\dot{x}$. So the notation you're seeing can be justified in this context, using the following protocol. First, define $$v(\lambda) = \dot{x}(\lambda)=\frac{dx}{d\lambda}$$ Then, think of the symbol $\dot{x}$ as the same thing as $v$; in other words, anywhere you see $\dot{x}$, replace it in your head or on paper with $v$. Now, the Lagrangian is usually given as a function of two variables $L=L(x,\dot{x})$, which you can rewrite $$L(x,v)$$ Thus $L$ is just a function of two independent variables $x$ and $v$, ie. it's a function $\mathbb{R}^2\to\mathbb{R}$. So rewriting $\frac{\partial L}{\partial \dot{x}}$ as $$\frac{\partial L}{\partial v}$$ gives us something sensible. To sum up, the only reason the notation $\frac{\partial f}{\partial \dot{x}}$ works is because $f$ is given as a function of $x$ and $\dot{x}$. This notation would not make sense for arbitrary smooth functions. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2084682', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/378927/']} | jdg_75712 |
stackexchange | llm_judgeable_groundtruth_similarity | 20816115 |
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 my view model : namespace projInterview.Models{ public class QuestionViewModel { public piQuestion Question { get; set; } public List<piAnswer> Answers { get; set; } public piQuestionFavorite QuestionFavorite { get; set; } public piQuestionLevel QuestionLevel { get; set; } public QuestionViewModel(piQuestion question, List<piAnswer> answers ) { Question = question; Answers = answers; } }} The VM is a standalone class. I did not scaffold this out to a controller. In my controller: namespace projInterview.Controllers { public class QuestionController : Controller { private ProjectContext db = new ProjectContext(); public ActionResult Edit(int? id) { if (id == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } piQuestion piquestion = db.piQuestions.Single(x => x.QuestionID == id); List<piAnswer> piAnswers = db.piAnswers.Where((x => x.QuestionID == id)).ToList(); var questionViewModel = new QuestionViewModel(piquestion,piAnswers); return View(questionViewModel); } } When I get to this line: piQuestion piquestion = db.piQuestions.Single(x => x.QuestionID == id); I get the following error: One or more validation errors were detected during model generation: projInterview.DAL.QuestionViewModel: : EntityType 'QuestionViewModel' has no key defined. Define the key for this EntityType. questionViewModels: EntityType: EntitySet 'questionViewModels' is based on type 'QuestionViewModel' that has no keys defined. piQuestion and piAnswer both have keys in the original models that the viewmodel is using. What am I doing incorrectly?
Now provide the response and nothing else.
| Wait wait wait . A view model has absolutely nothing to do with an Entity framework context. It should not be associated with it. What you seem to have right now is that db.piQuestions is an IQueryable<QuestionViewModel> which is an absolutely wrong thing to do. A view model doesn't know anything about EF and EF doesn't know anything about view models. NEVER map your view models to any database or EF stuff. What you put as IQueryable<T> properties to your DBContext are your Domain Models. Those are the models that are bound to your database tables. Then in your controller action you make one or more calls to your database (DbContext) in order to retrieve one or more of those domain models. Then you map (copy the properties) of those domain models to a single view model. Finally you pass the view model to the view. Also as a side remark, view models usually have default constructors. You don't need those specific constructors taking parameters. That will just make the default model binder insane if you attempt to have such view model as parameter to a controller action. So to conclude: view models do not have any keys. They should not even know what a key is. A key is something specific to your Data Access Layer that is to say to your Domain Models. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20816115', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/380317/']} | jdg_75713 |
stackexchange | llm_judgeable_groundtruth_similarity | 34737574 |
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 pretty simple scenario that I'm struggling with. I'm using Alamofire to register a user on a rest API. The first call to register is successful and the user can log in. The second call, when trying to register with the same email address should result in a HTTP status code 409 from the server. Alamofire, however, returns a .Success with an empty request and response. I have tested this this API with postman and it correctly returns a 409. Why is Alamofire not returning .Failure(error), where the error has status code info etc? Here is the call I run with the same input each time. Alamofire.request(.POST, "http://localhost:8883/api/0.1/parent", parameters: registrationModel.getParentCandidateDictionary(), encoding: .JSON).response(completionHandler: { (req, res, d, e) -> Void in print(req, res, d, e) })
Now provide the response and nothing else.
| From the Alamofire manual : Validation By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling validate before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type. You can manually validate the status code using the validate method, again, from the manual: Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) .validate(statusCode: 200..<300) .validate(contentType: ["application/json"]) .response { response in print(response) } Or you can semi-automatically validate the status code and content-type using the validate with no arguments: Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]) .validate() .responseJSON { response in switch response.result { case .success: print("Validation Successful") case .failure(let error): print(error) } } | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/34737574', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/148325/']} | jdg_75714 |
stackexchange | llm_judgeable_groundtruth_similarity | 35804763 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I just do not know how to google for my question, so I apologize if there is an answer out there for this question already. I have my query working, but while I was troubleshooting, I came across behavior I don't understand. I have three tables with the exact same structure--one for employees that have been terminated, one for employees that have chosen to waive medical coverage, and one for employees that do not have medical coverage. There are multiple companies in this data, and I am grouping by company and division. I am doing FULL OUTER JOINs because some company/division groups may have 0 terminated employees, but may have some waiver employees(for example). The structure of the three source tables are:Company---Division---NumbOfEmployees The structure of the destination view is: Company---Division---NumbOfTermEmp---NumbOfWaiverEmp---NumbOfNonMedEmp So I am basically flattening out the data. If I join table 1 to table 2 and then table 2 to table 3, I get the data I expect. If I join table 1 to table 2, and then table 1 to table 3, I do not. I will get an extra row where, for instance, no data exists in table 1 but it does in table 2. Visual representation below: I do not understand what is going on behind the scenes enough to figure out this behavior. Why is this?
Now provide the response and nothing else.
| Spark >= 3.0 : In Spark 3.0 OneHotEncoderEstimator has been renamed to OneHotEncoder : from pyspark.ml.feature import OneHotEncoderEstimator, OneHotEncoderModelencoder = OneHotEncoderEstimator(...) with from pyspark.ml.feature import OneHotEncoder, OneHotEncoderModelencoder = OneHotEncoder(...) Spark >= 2.3 You can use newly added OneHotEncoderEstimator : from pyspark.ml.feature import OneHotEncoderEstimator, OneHotEncoderModelencoder = OneHotEncoderEstimator( inputCols=[indexer.getOutputCol() for indexer in indexers], outputCols=[ "{0}_encoded".format(indexer.getOutputCol()) for indexer in indexers])assembler = VectorAssembler( inputCols=encoder.getOutputCols(), outputCol="features")pipeline = Pipeline(stages=indexers + [encoder, assembler])pipeline.fit(df).transform(df) Spark < 2.3 It is not possible. StringIndexer transformer operates only on a single column at the time so you'll need a single indexer and a single encoder for each column you want to transform. from pyspark.ml import Pipelinefrom pyspark.ml.feature import StringIndexer, OneHotEncoder, VectorAssemblercols = ['a', 'b', 'c', 'd']indexers = [ StringIndexer(inputCol=c, outputCol="{0}_indexed".format(c)) for c in cols]encoders = [ OneHotEncoder( inputCol=indexer.getOutputCol(), outputCol="{0}_encoded".format(indexer.getOutputCol())) for indexer in indexers]assembler = VectorAssembler( inputCols=[encoder.getOutputCol() for encoder in encoders], outputCol="features")pipeline = Pipeline(stages=indexers + encoders + [assembler])pipeline.fit(df).transform(df).show() | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35804763', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3204536/']} | jdg_75715 |
stackexchange | llm_judgeable_groundtruth_similarity | 2369950 |
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:
He says (direct quote): "In higher mathematics the absolute value of a number, $|x|$, is equal to positive and negative $x$, if $x$ is a positive number." Then he wrote: $|x|=\pm x,\quad \text{if}\enspace x>0 $. I think he misunderstood the definition of absolute value, or did I? From what I understand, absolute value of a number is the distance of a number from zero, so it is always positive. Am I wrong?
Now provide the response and nothing else.
| I think you are right, and your teacher - though I would assume he knows the definition - was too sloppy when he introduced the absolute value. You are right, the absolute value of a number is its distance to the point $0$ on the real line, so the correct definition would be$$ |x| :=\begin{cases} x, \quad & \text{if } x \geq 0 \\ -x, \quad & \text{if } x<0.\end{cases}$$The definition $|x| = \pm x$ yields not even a function, because this would have two $y$-values for every $x$-value and this is certainly not what he wants. I guess he might have wanted to say it is $\pm x$, depending on whether $x$ is positive or negative, in the way I wrote it above. Maybe to have an additional example: $|5| = 5$, since $5 > 0$, so you do not have to change anything. But $|-3| = -(-3) = 3$, since $-3 < 0$, so the absolute value function tells you to multiply with $(-1)$, i.e. to cancel the minus sign. And, to round things up, as pointed out above in the comments, if you want to solve an equation involving an absolute value, you typically get two solutions. Let us say you are looking for all $x$ that satisfy the equation$$|x| = 4.$$Then there are two solutions, namely $x = \pm 4$, but note that the absolute value itself is NOT $\pm 4$. It is just $4$, in either case. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2369950', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/466742/']} | jdg_75716 |
stackexchange | llm_judgeable_groundtruth_similarity | 67064682 |
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 per the demo, the label for a MUI outlined select input should sit on top of the top border of the select box. However, in my application, the z-index of the label seems to be placing it behind the top border and thus it looks like a line is cutting through the label. I have pretty much taken the code exactly from the documentation, and as far as I know, do not have any styles conflicting with this input element. I have compared the styles in the debugger to what I have and what is present in the documentation, and I do not see any of my first party CSS files causing a different style to be set on the element. Any idea what might be going wrong here? Here is the source code: <FormControl variant='outlined' style={{ width: '100%' }} margin={'1'}> <InputLabel id='test-select-label'>Label</InputLabel> <Select labelId='test-select-label' id='test-select' value={'test1'} onChange={e => setTest(e.target.value)} size='small' > <MenuItem key={1} value={'test'} >Test 1</MenuItem> <MenuItem key={2} value={'test2'} >Test 2</MenuItem> </Select></FormControl>
Now provide the response and nothing else.
| Solution 1: Use TextField This is what TextField is for. It uses FormControl and InputLabel internally and make sure they work well together. You can tell TextField to render select instead input by overriding the select props: <TextField value={value} onChange={(e) => setValue(e.target.value)} select // tell TextField to render select label="Label"> <MenuItem key={1} value="test"> Test 1 </MenuItem> <MenuItem key={2} value="test2"> Test 2 </MenuItem></TextField> For more detail about how TextField works, see this answer. Solution 2: Use Select If you decide to use Select , you need to write more code to do the same amount of work: Pass the label text as InputLabel children <InputLabel id="test-select-label">Label</InputLabel> This label text will be rendered on the screen as the Select label when put inside FormControl and next to the Select component. Pass the label text to the label props of the Select component This label text is hidden and used to override and remove the part of the border-top where the real label is occupied when the Select label is shrinked . <Select labelId="test-select-label" label="Label"> Putting it together we'll have something like below, note that with this approach we need to set the label in 2 different places which is not very DRY, so I'd prefer the first approach. <FormControl> <InputLabel id="test-select-label">Label</InputLabel> <Select value={value} onChange={(e) => setValue(e.target.value)} labelId="test-select-label" label="Label" > <MenuItem key={1} value="test"> Test 1 </MenuItem> <MenuItem key={2} value="test2"> Test 2 </MenuItem> </Select></FormControl> Live Demo | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/67064682', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3716628/']} | jdg_75717 |
stackexchange | llm_judgeable_groundtruth_similarity | 67332108 |
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 got a page on my Next.js app that does the following: It's a search page The pathname is like: /search?q=search+slug It loads data on the client It needs to read the router.query to get the router.query.q value PS: I'm using Redux const dispatch = useDispatch(); const router = useRouter(); const query = router.query as { q: string }; const queryString = query.q; console.log("SEARCH CONTAINER"); console.log(`queryString: ${queryString}`); useEffect(() => { dispatch(THUNK.LOAD(queryString)); return () => { dispatch(ACTION.RESET_STATE()); }; },[dispatch,queryString]); See the useEffect . In theory is should run only once for every queryString (which is actually req.query.q ). But I was getting duplicated THUNK.LOAD actions. That's why I've added the console.log() there. And this is what it's logging out: And then: And this is why I'm getting duplicated dispatches. Of course I can check for if (queryString) before dispatching, or maybe I can get it from window.location.search . But I am surprised the router.query.q comes as undefined on the first place. How is that even possible? Why would the req.query object be populated asynchronously? What is the explanation for this?
Now provide the response and nothing else.
| Just found out what is the solution to my problem: From: https://nextjs.org/docs/api-reference/next/router#router-object isReady : boolean - Whether the router fields are updatedclient-side and ready for use. Should only be used inside of useEffect methods and not for conditionally rendering on the server. This is what happens to the router.query on client when you hit /search?q=XXX . 1st render router.isReady: falserouter.query: {} Subsequent renders router.isReady: truerouter.query: {"q":"xxx"} Conclusion The fact that router.query is not populated on the client (for SSG pages) on the first run is a design implementation detail. And you can monitor whether it's has been populated or not by checking the router.isReady boolean property. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/67332108', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10128619/']} | jdg_75718 |
stackexchange | llm_judgeable_groundtruth_similarity | 19266015 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to use Pessimistic locking in JPA, over Hibernate 3 against a Postgres Database. I can't get the lock to time out - it just seems to hang forever. Here's an example: EntityManagerFactory factory; // (initialise the factory )EntityManager em1 = factory.createEntityManager();EntityManager em2 = factory.createEntityManager();// em1 gets a lockEntityTransaction transaction1 = em1.getTransaction();transaction1.begin();MyObject object1 = em1.find( MyObject.class, 1, LockModeType.PESSIMISTIC_READ );// em2 tries for a lockMap<String,Object> timeoutProperties = new HashMap<String,Object>();timeoutProperties.put("javax.persistence.lock.timeout", 5000);EntityTransaction transaction2 = em2.getTransaction();transaction2.begin();MyObject object2 = em2.find( MyObject.class, 1, LockModeType.PESSIMISTIC_READ, timeoutProperties );// After five seconds I expect em2 to bail out, but it never does.transaction1.rollback();transaction2.rollback(); As I understand it, em2 should have tried for up to five seconds (5000ms) to get the lock and then should have thrown an exception. Instead the code becomes deadlocked. If I run this in two different threads then I see that thread2 (with em2) gets the lock as soon as thread1 (em1) releases it. So the locking is happening, just never timing out. I get the same effect with PESSIMISTIC_WRITE, and with any timeout value (2ms, 0ms 'NO WAIT') etc. I'm using Hibernate 3.6.10 Final (the latest Hibernate 3 version) and Postgres jdbc driver 9.2-1003.jdbc4 (the latest driver). I'm running against a Postgres 8.4 database. All the documentation I've found suggests this should work. Any ideas? thanks,Alastair
Now provide the response and nothing else.
| Postgres SELECT for update syntax only provides the options to not wait if a lock can not be obtained right away. See postgres docs. To prevent the operation from waiting for other transactions to commit, use the NOWAIT option. With NOWAIT, the statement reports an error, rather than waiting, if a selected row cannot be locked immediately. Note that NOWAIT applies only to the row-level lock(s) — the required ROW SHARE table-level lock is still taken in the ordinary way (see Chapter 13). You can use LOCK with the NOWAIT option first, if you need to acquire the table-level lock without waiting. When working with postgres I have observed that any value over 0 for the timeout will cause hibernate to issue SELECT FOR UPDATE but when timeout is 0 it will issue SELECT FOR UPDATE NO WAIT | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19266015', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/483223/']} | jdg_75719 |
stackexchange | llm_judgeable_groundtruth_similarity | 3117957 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
What's the difference between #1 and #2: Code 1 (compiled ok): byte[] GetSomeBytes() { return (byte[])this.Invoke((MethodInvoker)delegate { GetBytes(); }); } byte[] GetBytes() { GetBytesForm gbf = new GetBytesForm(); if(gbf.ShowDialog() == DialogResult.OK) { return gbf.Bytes; } else return null; } Code 2 (didn't complied ok) int GetCount(){ return (int)this.Invoke((MethodInvoker)delegate { return 3; });} Code #2 gives me Since 'System.Windows.Forms.MethodInvoker' returns void, a return keyword must not be followed by an object expression . How can I fix it? And why (do) complier think code #1 is right?
Now provide the response and nothing else.
| To answer your first question, try altering your first sample like this: return (byte[])this.Invoke((MethodInvoker)delegate { return GetBytes(); }); At this point, you'll have the same compilation error. public object Invoke(Delegate method) returns an object, so you can cast the return value to anything and it will compile. However, you are passing in a delegate of type MethodInvoker , which has a signature delegate void MethodInvoker() . So, within the body of the method that you cast to MethodInvoker, you cannot return anything. Try this instead for the second one: return (int)this.Invoke((Func<int>)delegate{ return 3;}); Func<int> is a delegate that returns an int, so it will compile. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3117957', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2177867/']} | jdg_75720 |
stackexchange | llm_judgeable_groundtruth_similarity | 954141 |
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 anybody find a closed form for this infinite sum? $$S = \sum _{k=4}^{\infty }{\frac { \left( -\ln \left( 2 \right) \right) ^{k}\zeta \left( 4-k \right) }{k!}},$$ where $\zeta$ is the Riemann zeta function . An approximate value of $S$ is $$S \approx -0.00469807827332540098459248437391306962194656968313196911104278149327118$$ I found nothing with Maple , Mathematica or ISC .
Now provide the response and nothing else.
| Starting with the well-known expansion for the polylogarithm in terms of the zeta function,$$ \mathrm{Li}_n(z) = \sum_{m\geq 0, m\neq n-1}\zeta(n-m)\frac{\log^m z}{m!} + \frac{\log^{n-1}z}{(n-1)!}(H_{n-1}-\log\log\tfrac1z), $$which is valid for $|\log z|<2\pi$, we can substitute $n=4$, $z=\frac12$, and obtain$$ S = \text{Li}_4(\tfrac{1}{2})+\zeta (3) \log2-\zeta (4)-\tfrac{1}{2} \zeta (2) \log^22-\tfrac{1}{6} \log^32 \log \log2+\tfrac{11}{36} \log^32. $$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/954141', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/153012/']} | jdg_75721 |
stackexchange | llm_judgeable_groundtruth_similarity | 4166122 |
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:
Or is there some $a_0$ , $b_0$ for which this does not hold?
Now provide the response and nothing else.
| Notice that $f(0) = 1$ (since $0 < 1 + 0$ ). Further, $ f(-x) = \frac{1}{f(x)}$ for all $x > -1$ . Thus, for all $1 > x > -1,$ $$ \frac{1}{1+x} \ge \frac{1}{f(x)} = f(-x) \ge 1-x. $$ By squeezing, we conclude that $\lim_{x \to 0} f(x) = 1 = f(0).$ But then $$ \lim_{x \to y} f(x) = \lim_{\delta \to 0} f(y + \delta) = f(y) \lim_{\delta \to 0} f(\delta) = f(y),$$ and the function is consequently continuous everywhere. Now we can use the usual argument with continuity to conclude that the function is of the form $b^x$ for some $b > 0$ . Further, by using the bounds on $f(x)$ in the above, we can show that $\lim_{x \to 0} \frac{f(x) - 1}{x} = 1$ (this is easiest with some casework - if $1 > x > 0$ then $1 \le (f(x) - 1)/x \le 1/({1-x})$ . If $-1 < x \le 0,$ the inequalities are reversed. In either case squeezing leads to the limit $1$ ). But the derivative of $b^x$ at $0$ is $\ln b$ , which is equal to $1$ iff $b = e.$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4166122', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/705868/']} | jdg_75722 |
stackexchange | llm_judgeable_groundtruth_similarity | 18758772 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I am attempting to validate a date in this format: (yyyy-mm-dd). I found this solution but it is in the wrong format for what I need, as in: (mm/dd/yyyy). Here is the link to that solution: http://jsfiddle.net/ravi1989/EywSP/848/ My code is below: function isDate(txtDate){ var currVal = txtDate; if(currVal == '') return false; var rxDatePattern = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/; //Declare Regex var dtArray = currVal.match(rxDatePattern); // is format OK? if (dtArray == null) return false; //Checks for mm/dd/yyyy format. dtMonth = dtArray[1]; dtDay= dtArray[3]; dtYear = dtArray[5]; if (dtMonth < 1 || dtMonth > 12) return false; else if (dtDay < 1 || dtDay> 31) return false; else if ((dtMonth==4 || dtMonth==6 || dtMonth==9 || dtMonth==11) && dtDay ==31) return false; else if (dtMonth == 2) { var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0)); if (dtDay> 29 || (dtDay ==29 && !isleap)) return false; } return true;} What regex pattern can I use for this that will account for invalid dates and leap years?
Now provide the response and nothing else.
| I expanded just slightly on the isValidDate function Thorbin posted above (using a regex). We use a regex to check the format (to prevent us from getting another format which would be valid for Date). After this loose check we then actually run it through the Date constructor and return true or false if it is valid within this format. If it is not a valid date we will get false from this function. function isValidDate(dateString) { var regEx = /^\d{4}-\d{2}-\d{2}$/; if(!dateString.match(regEx)) return false; // Invalid format var d = new Date(dateString); var dNum = d.getTime(); if(!dNum && dNum !== 0) return false; // NaN value, Invalid date return d.toISOString().slice(0,10) === dateString;}/* Example Uses */console.log(isValidDate("0000-00-00")); // falseconsole.log(isValidDate("2015-01-40")); // falseconsole.log(isValidDate("2016-11-25")); // trueconsole.log(isValidDate("1970-01-01")); // true = epochconsole.log(isValidDate("2016-02-29")); // true = leap dayconsole.log(isValidDate("2013-02-29")); // false = not leap day | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18758772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2648752/']} | jdg_75723 |
stackexchange | llm_judgeable_groundtruth_similarity | 275085 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I have seen that when terminating an RS422 point-to-point connection, you should terminate the signals with a parallel resistor that matches the characteristic impedance of the transmission line. Most sources recommend 100-120ohms. I saw another post here that mentioned the effects of using too small of a terminating resistor, but what happens if you use a terminating resistor that is double, or 10 times the value of the characteristic impedance of the line?
Now provide the response and nothing else.
| On an open end, a short pulse will be reflected and travel back the line. On a shorted end, a short pulse will also be reflected, but inverted, too. A resistor dampens this effect, i.e. the amplitude of the reflected signal will be smaller. And for a certain value, the pulse will not be reflected at all. This is the value used for termination. Usually, transmitted signals are not short enough to be reflected completely, but every edge would cause a reflected pulse, which causes all kinds of trouble. See also What and Why's of termination? | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/275085', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/111256/']} | jdg_75724 |
stackexchange | llm_judgeable_groundtruth_similarity | 34633396 |
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 I send a SOAP request to the server it returns following error, though I send similar request using SoapUI and that works. It seems I need to change my SOAP request to the one that I am sending using SoapUI. WSDL is here . [ truncated ] System.Web.Services.Protocols.SoapException : The value of the HTTP header ' SOAPAction ' was not recognized by the server . \ r \ n at System.Web.Services.Protocols.Soap11ServerProtocolHelper.RouteRequest ( ) \ r \ n at System.Web.Servic I am sending following request using Java <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Header/> <SOAP-ENV:Body> <ns2:SearchFlights xmlns:ns2="ElysArres.API"> <ns2:SoapMessage> <ns2:Username>Test</ns2:Username> <ns2:Password>TestPassword</ns2:Password> <ns2:LanguageCode>EN</ns2:LanguageCode> <ns2:Request> <ns2:Departure>ONT</ns2:Departure> <ns2:Destination>EWR</ns2:Destination> <ns2:DepartureDate>2016-01-20</ns2:DepartureDate> <ns2:ReturnDate>2016-01-28</ns2:ReturnDate> <ns2:NumADT>1</ns2:NumADT> <ns2:NumINF>0</ns2:NumINF> <ns2:NumCHD>0</ns2:NumCHD> <ns2:CurrencyCode>EUR</ns2:CurrencyCode> <ns2:WaitForResult>true</ns2:WaitForResult> <ns2:NearbyDepartures>true</ns2:NearbyDepartures> <ns2:NearbyDestinations>true</ns2:NearbyDestinations> <ns2:RROnly>false</ns2:RROnly> <ns2:MetaSearch>false</ns2:MetaSearch> </ns2:Request> </ns2:SoapMessage> </ns2:SearchFlights> </SOAP-ENV:Body></SOAP-ENV:Envelope> I can send following request using SoapUI and it works <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:els="ElsyArres.API"> <soap:Header/> <soap:Body> <els:SearchFlights> <els:SoapMessage> <els:Username>Test</els:Username> <els:Password>TestPassword</els:Password> <els:LanguageCode>EN</els:LanguageCode> <els:Request> <els:Departure>ONT</els:Departure> <els:Destination>EWR</els:Destination> <els:DepartureDate>2016-01-20</els:DepartureDate> <els:ReturnDate>2016-01-28</els:ReturnDate> <els:NumADT>1</els:NumADT> <els:NumINF>0</els:NumINF> <els:NumCHD>0</els:NumCHD> <els:CurrencyCode>EUR</els:CurrencyCode> <els:WaitForResult>true</els:WaitForResult> <els:NearbyDepartures>true</els:NearbyDepartures> <els:NearbyDestinations>true</els:NearbyDestinations> <els:RROnly>false</els:RROnly> <els:MetaSearch>false</els:MetaSearch> </els:Request> </els:SoapMessage> </els:SearchFlights> </soap:Body></soap:Envelope> I am not sure how to make the request that I am creating with Java same as what I am sending with SoapUI. Code SearchFlights @XmlRootElement(name = "SearchFlights")@XmlAccessorType(XmlAccessType.FIELD)public class SearchFlights { @XmlElement(name = "SoapMessage") private SoapMessage soapMessage; getter and setter SoapMessage @XmlRootElement(name = "SoapMessage")@XmlAccessorType(XmlAccessType.FIELD)public class SoapMessage { @XmlElement(name = "Username") private String username; @XmlElement(name = "Password") private String password; @XmlElement(name = "LanguageCode") private String languageCode; @XmlElement(name = "Request") private Request request; getters and setters Request @XmlRootElement(name = "Request")@XmlAccessorType(XmlAccessType.FIELD)public class Request { @XmlElement(name = "Departure") private String departure; @XmlElement(name = "Destination") private String destination; @XmlElement(name = "DepartureDate") private String departureDate; @XmlElement(name = "ReturnDate") private String returnDate; @XmlElement(name = "NumADT") private int numADT; @XmlElement(name = "NumINF") private int numInf; @XmlElement(name = "NumCHD") private int numCHD; @XmlElement(name = "CurrencyCode") private String currencyCode; @XmlElement(name = "WaitForResult") private boolean waitForResult; @XmlElement(name = "NearByDepartures") private boolean nearByDepartures; @XmlElement(name = "NearByDestinations") private boolean nearByDestinations; @XmlElement(name = "RROnly") private boolean rronly; @XmlElement(name = "MetaSearch") private boolean metaSearch;getters and setters package-info.java @XmlSchema( namespace = "ElsyArres.API", elementFormDefault = XmlNsForm.QUALIFIED) package com.myproject.flights.wegolo;import javax.xml.bind.annotation.XmlNsForm;import javax.xml.bind.annotation.XmlSchema; jaxb.index SearchFlightsFlightFlightsLegLegsOutboundRequestResponseSoapMessage Code to send request import javax.xml.soap.MessageFactory;import javax.xml.soap.SOAPConstants;import org.springframework.oxm.jaxb.Jaxb2Marshaller;import org.springframework.stereotype.Service;import org.springframework.web.client.RestClientException;import org.springframework.web.client.RestTemplate;import org.springframework.ws.client.core.WebServiceTemplate;import org.springframework.ws.soap.saaj.SaajSoapMessageFactory;...... // populate searchFlights and other classes to create request try { SaajSoapMessageFactory messageFactory = new SaajSoapMessageFactory( MessageFactory.newInstance()); messageFactory.afterPropertiesSet(); WebServiceTemplate webServiceTemplate = new WebServiceTemplate( messageFactory); Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setContextPath("com.myproject.flights.wegolo"); marshaller.afterPropertiesSet(); webServiceTemplate.setMarshaller(marshaller); webServiceTemplate.afterPropertiesSet(); Response response = (Response) webServiceTemplate .marshalSendAndReceive( "http://www5v80.elsyarres.net/service.asmx", searchFlights); Response msg = (Response) response; System.err.println("Wegolo >>>" + msg.getFlights().getFlight().size()); } catch (Exception s) { s.printStackTrace(); } Update I removed package-info.java and managed to use the suggested code, but it is still sending the same header. Response response = (Response) webServiceTemplate .marshalSendAndReceive( "http://www5v80.elsyarres.net/service.asmx", searchFlights, new WebServiceMessageCallback() { public void doWithMessage(WebServiceMessage message) { ((SoapMessage)message).setSoapAction("http://www5v80.elsyarres.net/searchFlights"); } } );
Now provide the response and nothing else.
| SOAP Version 1.1 requires a HTTP header in your SOAP request to specify the SOAP action. It's not in the actual XML, it's part of the request (in the HTTP header), so that is why you are not seeing any difference between your SoapUI request xml, and the request you're sending using the WebServiceTemplate. Soap 1.2 allows you to set it as an attribute on the media type, but that is not valid for a 1.1 server. Note that according to the specification , the value you use doesn't have to be resolvable. SOAP places no restrictions on the format or specificity of the URI or that it is resolvable. An HTTP client MUST use this header field when issuing a SOAP HTTP Request. Usually, it's specified in your WSDL, something like (taken from here ): <soap:operation soapAction="http://www5v80.elsyarres.net/searchFlights" style="document" /> If that is not in your WSDL, you can add it by using the action annotation in spring in your webservice endpoint class. @Endpointpublic class MyFlightEndpoint{ @Action("http://www5v80.elsyarres.net/searchFlights") public SearchFlights request() { ... }} If it is in your WSDL, you'll want to place that value into your HTTP header on the client side. To do this, you then need to get access to the message on the client side after it's created, but before it's sent in order to add the action header. Spring provides a message callback interface for that, that's described here . What you'll want to do is something like: Response response = (Response) webServiceTemplate .marshalSendAndReceive( "http://www5v80.elsyarres.net/service.asmx", searchFlights, new WebServiceMessageCallback() { public void doWithMessage(WebServiceMessage message) { ((SoapMessage)message).setSoapAction("http://www5v80.elsyarres.net/searchFlights"); } } ); There's a discussion on SOAP action headers here , and the point (or lack of a point) for them if you want to know more. Edit: So looking at the wsdl here: <soap:operation soapAction="ElsyArres.API/SearchFlights" style="document"/> you'll want the following action: ElsyArres.API/searchFlights Now just update the code to read ((SoapMessage)message).setSoapAction("ElsyArres.API/searchFlights"); and you're good to go! Edit 2: I also notice the service you're connecting to accepts SOAP 1.2 connections, while you're using SOAP 1.1. You can force your client to use SOAP 1.2 by setting it in your factory. messageFactory.setSoapVersion(SoapVersion.SOAP_12);messageFactory.afterPropertiesSet(); It looks like the server uses the same endpoint, so that should be the only change. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34633396', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4710417/']} | jdg_75725 |
stackexchange | llm_judgeable_groundtruth_similarity | 3325684 |
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:
Consider the following two generating functions: $$e^x=\sum_{n=0}^{\infty}\frac{x^n}{n!}$$ $$\log\left(\frac{1}{1-x}\right)=\sum_{n=1}^{\infty}\frac{x^n}{n}.$$ If we live in function-land, it's clear enough that there is an inverse relationship between these two things. In particular, $$e^{\log\left(\frac{1}{1-x}\right)}=1+x+x^2+x^3+\ldots$$ If we live in generating-function-land, this identity is really not so obvious. We can figure out that the coefficient of $x^n$ in $e^{\log\left(\frac{1}{1-x}\right)}$ is given as $$\sum_{a_1+\ldots+a_k=n}\frac{1}{a_1\cdot \cdots \cdot a_k}\cdot \frac{1}{k!}$$ where the sum runs over all ways to write $n$ as an ordered sum of positive integers. Supposedly, for each choice of $n$ , this thing sums to $1$ . I really don't see why. Is there a combinatorial argument that establishes this?
Now provide the response and nothing else.
| In your sum, you are distinguishing between the same collection of numberswhen it occurs in different orders. So you'll have separate summands for $(a_1,a_2,a_3,a_4)=(3,1,2,1)$ , $(2,3,1,1)$ , $(1,1,3,2)$ etc. Given a multiset of $k$ numbers adding to $n$ consisting of $t_1$ instancesof $b_1$ up to $t_j$ instances of $b_j$ , that contributes $$\frac{k!}{t_1!\cdot\cdots\cdot t_j!}$$ (a multinomial coefficient) summands to the sum, and so an overallcontributionof $$\frac{1}{t_1!b_1^{t_1}\cdot\cdots\cdot t_j!b_j^{t_j}}$$ to the sum. But that $1/n!$ times the number of permutations with cycle structure $b_1^{t_1}\cdot\cdots\cdots b_j^{t_j}$ . So this identity states thatthe total number of permutations of $n$ objects is $n!$ . | {} | {'log_upvote_score': 6, 'links': ['https://math.stackexchange.com/questions/3325684', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/174927/']} | jdg_75726 |
stackexchange | llm_judgeable_groundtruth_similarity | 7766975 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a problem with the anti CRSF MVC mechanism. The cookie and the form input returned does not match. I'm getting an error every single time, only in one specific page. In the rest of the application it works well. The server is returning HTTP 500 Internal Server Error and I can see on the log this exception: [System.Web.Mvc.HttpAntiForgeryException]: {"A required anti-forgery token was not supplied or was invalid."} This is the hidden input that the server is generating is: <input name="__RequestVerificationToken" type="hidden" value="QK8P7rjyZE6Vm5seY7Fr704YCOoFGdTIMzl1W7R0ZFpXSMjGKLG2T05DfFSYTxvtQCEx7DDT69DGsDB2+ZXFHY8oAjiKz0gw8BhDFywgmfIpoXnGpj7fONNzIIfvbrDrE9WJsMu6Io/0bDLM5WfKs0zktiNjyOWpfYrmnfINYmjW8NLOZFoz74xTcgTptAld"> And this is the Cookie returned: Set-Cookie:__RequestVerificationToken_L2VGbG93=skmTAVI8HCbfxDS+xhioIMIISL3UOBI7qJM1JbHjTtAqKl4W70pDUcTKMm0p3R3mrHDziE8vXw0C0OO4HArzWO1/e6py+v/cFdbe9maFgjl4jMiZ9Wc4YIhC6+IUXkk6yqJDJ8dCIr8qtGaYcD9IX+m7/SlVhu521KQSWJYRcaY=; path=/; HttpOnly When I examine what the server is sending, the cookie is exactly the same, but the payload has different encoding I think: __RequestVerificationToken:QK8P7rjyZE6Vm5seY7Fr704YCOoFGdTIMzl1W7R0ZFpXSMjGKLG2T05DfFSYTxvtQCEx7DDT69DGsDB2%2BZXFHY8oAjiKz0gw8BhDFywgmfIpoXnGpj7fONNzIIfvbrDrE9WJsMu6Io%2F0bDLM5WfKs0zktiNjyOWpfYrmnfINYmjW8NLOZFoz74xTcgTptAld The differences are in two characters that appear encoded: / -> %2F + -> %2B Those are the only differences I can find between the hidden input field, and the post payload. What could be the problem that is causing that ValidateAntiForgeryToken fails in verify the token? Regards.
Now provide the response and nothing else.
| I've had and resolved several issues with ValidateAntiForgeryToken lately, so I'll share my findings with you. Salt : Since you mention this only happens on a single page, my best guess is that you are using different salt values in your calls to Html.AntiForgeryToken(salt) and ValidateAntiForgeryToken(salt) calls. AJAX : as another answer has said, using AJAX may require extra work to ensure the token is included in the POST. Here is my favorite simple, automatic solution to add the token to all AJAX POST requests . In your question though, you state that you have verified that the token is sending. Have you verified that you're only sending the token once? I found out that an AJAX call of mine was sending the token twice, which combined the values, and caused it to fail. Machine Key and Cookies : this issue is ugly, easy to spot (causes exceptions), but not very intuitive. The validation cookies and tokens are encoded and decoded using a unique "machine key". This means that if you have a server farm, or change your server, your cookie will no longer be valid. Closing your browser fixes the issue (because the cookie is a session cookie). However, some people leave their browser windows open in the background for a long time! The solution is to set a "machine key" in your config file. This will tell MVC to use the same key on all servers, ensuring that the cookie will be decryptable everywhere. Encoding Bugs : using a testing utility called jMeter, we attempted to load-test our pages, only to find out that it had a bug that caused our token to have 2 extra " around the value. The solution is to lower your trust in your tools! Test in a browser, and if that works, create a test that extracts the token and cookie values, and set a breakpoint to verify the results. If none of these things work for you, then I'd recommend taking a look at the MVC source code for ValidateAntiForgeryTokenAttribute , specifically the OnAuthorization method. It will help you see the different steps where validation could fail. You might even inspect your error's Exception.StackTrace to determine which part is failing. As a side note , I really dislike the implementation of ValidateAntiForgeryToken in MVC, because: There are about 5 verification steps that can fail, but there is only one generic error message. The class is sealed, so it cannot be extended with additional functionality. The encryption method is weird - it initializes a Page and creates an artificial ViewState to encrypt the tokens and cookies. Seems overkill. So, I grabbed the source code, and created my own specialized subclass, which also turned out to be very helpful in debugging its issues, because I could set breakpoints on the validation methods, and it was really easy to determine which validation step was failing. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/7766975', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/307976/']} | jdg_75727 |
stackexchange | llm_judgeable_groundtruth_similarity | 179233 |
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to use LM78xx for various applications. What I am concerned about is its failure modes. 1. Failure to Short Not shorting Vcc to ground!! I mean shorting V_input to V_output. Assume that you have a delicate and expensive piece of electronic equipment that works with 5V. You are using LM7805 to reduce voltage from 12~13VDC to 5VDC. For some reasons your LM7805 fails to short and your delicate electronic device sees the 12VDC instead of 5VDC and fries. I have seen this all around the web. How to protect against this? 2. Failure to Open It is not as critical as the failure to short. It can happen as a result of over temperature (temporary) or permanent failure. What are the other things that can trigger this? 3. Reverse Bias & Reverse Discharge I have seen that too big an output cap can cause reverse current going back to input. It is recommended to add reverse discharge diode protection. What else can cause this kind of reverse bias voltage? From Various datasheets: With the LM7805, the output capacitor should not exceed 1mf, as largervalues could damage the 7805 due to backfeeding of current when poweris switched off. When a surge voltage exceeding maximum rating is applied to the inputterminal or when a voltage in excess of the input terminal voltage isapplied to the output terminal, the circuit may be destroyed. 4. Flyback Does the diode on the above picture also protect against flyback current of an inductor? Or is it better to add a separate diode across the inductance load? 5. What else? What are the other possible causes of LM78xx failure?
Now provide the response and nothing else.
| Failure to short- crowbar + fused input (a thyristor and trigger circuit) or at least a TVS. The TVS might be able to limit the voltage to something like 8V which your delicate equipment might have a fighting chance of surviving (newer chips with 5.5V abs max supply may not live). An open GND connection will cause the output voltage to rise so make sure the soldering is solid. Failure to open- bad solder connections, destroyed chip. Don't depend on the thermal protection as a matter of course. D1 is unnecessary for a 7805 or 7806, only for higher voltage regulators (and only where the input voltage can be actively discharged). It provides another possible path for failure to short, so I suggest leaving it out unless there is some way the output can (say) get connected to a 12V battery and you don't have a TVS or crowbar on the output. The power supply does not care about load inductance- the inductance will only tend to make the current continue to flow in the same direction. Any flyback voltage appears across the switch so you need a flyback diode to be placed across the switch or the load. You might want to put a reverse-biased diode across the output in case two supplies are connected in series and one is driven negative. If you use a unipolar TVS that can serve both functions with a single part. TL;DR: Put a polyswitch fuse in series with the input (before the capacitor) and add a TVS to the output, and lose D1 (if 7805/6). For extra points mount the polyswitch close to the regulator so it sees the heat. | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/179233', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/72582/']} | jdg_75728 |
stackexchange | llm_judgeable_groundtruth_similarity | 194693 |
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would.
Question:
I see in a lot of the Nagios documentation references to check_nrpe_1arg . Can anyone explain exactly what this is, or does? I see nothing in the Nagios documentation, or anywhere else on the web, that comes right out and says " check_nrpe_1arg does __". At best, it's "you need check_nrpe_1arg here", but without explaining what or why. Thanks!
Now provide the response and nothing else.
| Based off a quick cursory search, check_nrpe_1arg is nothing special compared to check_nrpe, it has a bit of a backstory too. check_nrpe by default does not accept command line arguments to be sent, just the command_name to run on the remote NRPE server host. In order to get NRPE to accept arguments beyond that (if memory serves), you have to enable a compile-time definition, AS WELL AS configure it in check_nrpe as well as the NRPE server nrpe.cfg file. check_nrpe_1arg appears to be a mnemonic that is configured into the core NAGIOS commands.cfg file; specifically, telling the installer that this command will accept only 1 argument (the name of the command to execute on the remote host) and will not honor any additional arguments. It's a weird way to do it, given the default behavior of NAGIOS, but it gained traction nevertheless. The quickest answer to this: check_nrpe_1arg does exactly what it is configured to do in commands.cfg on the core NAGIOS server. In this context, it provides the command name to execute on the remote NRPE server, and nothing additional will be accepted. [edit] Also, it appears to have originated out of the default configs in "Untangle" (a Linux based firewall/routing software package), that or Debian, it's hard to tell without following a handful of links around. | {} | {'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/194693', 'https://serverfault.com', 'https://serverfault.com/users/-1/']} | jdg_75729 |
stackexchange | llm_judgeable_groundtruth_similarity | 11056902 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In a DIV I place some text/html code which get loaded from a database. This text sometimes contains font size definitions (ex: font size="3"). is there a way to override this font size in this specific DIV using CSS. I am grateful for any help.
Now provide the response and nothing else.
| Assuming mark-up similar to the following: <div> <font size="1">Some text at 'size="1"'</font> and natively-sized text, with more at <font size="26">'size="26".'</font></div> Then you can explicitly instruct CSS to inherit the font-size from the parent element: div { font-size: 1.5em;}div font { font-size: inherit;} JS Fiddle demo . Please note, of course, that font is deprecated and should, therefore, not be used (as support for the element can stop without notice, and/or implementations change without warning). Incidentally, while !important will force a declaration to override the usual cascade of styles, it's taking a sledgehammer to crack a nut; and, if it can be avoided (and in this case, it seems, it can be avoided) it should be, since it complicates later debugging of styles, and associated inheritance problems. Further, this is treating the symptom of your problem; the problem you're really facing is the presence of the font tags in your content/database. This should be corrected, by removing the elements, and replacing them with appropriately-styled elements, such as em , span and so forth... References: font element, at the W3.org . font element at the MDN . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11056902', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1306278/']} | jdg_75730 |
stackexchange | llm_judgeable_groundtruth_similarity | 750676 |
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 do something like UPDATE OR REPLACE someTable SET a=1, b=2 WHERE c=3 I expect if it doesnt exist it will be inserted into the DBs. But nothing happens and i get no errors. How can i insert data, replace it if it already exist and use a where for the condition (instead of replacing BC of a unique ID)
Now provide the response and nothing else.
| Careful, INSERT OR REPLACE doesn't have the expected behaviour of an "UPDATE OR REPLACE". If you don't set the values for all fieds, INSERT OR REPLACE is going to replace them with default values, whereas with an UPDATE you expect to keep the old values. See my answer here for an example: SQLite - UPSERT *not* INSERT or REPLACE | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/750676', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_75731 |
stackexchange | llm_judgeable_groundtruth_similarity | 186182 |
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 built a ML classifier, it achieved quite good recall (0.8) but the precision is low (0.3). Is there any way to maintain such recall while improving precision?
Now provide the response and nothing else.
| Precision and recall are a tradeoff. Typically to increase precision for a given model implies lowering recall, though this depends on the precision-recall curve of your model, so you may get lucky. Generally, if you want higher precision you need to restrict the positive predictions to those with highest certainty in your model, which means predicting fewer positives overall (which, in turn, usually results in lower recall). If you want to maintain the same level of recall while improving precision, you will need a better classifier. | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/186182', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/41749/']} | jdg_75732 |
stackexchange | llm_judgeable_groundtruth_similarity | 1865440 |
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 developing WPF applications using MVVM pattern. I have ViewModel with code like this: public bool EditModeEnabled{ get { return _EditModeEnabled; } set { _ModeEditModeEnabled = value; OnPropertyChanged("EditModeEnabled"); OnPropertyChanged("CommentTextBoxVisibility"); }} OnPropertyChanged is virtual method of base class which just raise PropertyChanged event.I want to test PropertyChanged event raising and there my test method: public void EditModeEnabledTest(){ var imageViewModel = TestHelper.GetTestImageViewModel(); var firedEvents = new List<string>(); imageViewModel.PropertyChanged += ((sender, e) => firedEvents.Add(e.PropertyName)); imageViewModel.Mode = true; Assert.AreEqual(firedEvents.Count, 2); Assert.IsTrue(firedEvents.Contains("EditModeEnabled")); Assert.IsTrue(firedEvents.Contains("CommentTextBoxVisibility")); ...} Is it a good way to test ProprtyChanged event?
Now provide the response and nothing else.
| I use a little Fluent API for doing exactly that. It allows you to write tests like this: var imageViewModel = TestHelper.GetTestImageViewModel();imageViewModel.ShouldNotifyOn(s => s.EditModeEnabled) When(s => s.Mode = true); Besides being succinct, I prefer this approach because it's type-safe - no string values to keep in sync with your API. To test that the event is being raised for more than one property, you can just write another test that does this. This will give you many tests, but each will be very small and you avoid Assertion Roulette . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1865440', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/177605/']} | jdg_75733 |
stackexchange | llm_judgeable_groundtruth_similarity | 11389765 |
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 set 777 permission on folder. i need to Set the permission of the following folder to 777:admin\includes\module_installation I do no idea how to set the permission 777 on particular folder in window 7?? Please help me how can I set it? I am using windows 7.
Now provide the response and nothing else.
| 777 is a permission in Unix based system with full read/write/execute permission to owner, group and everyone.. in general we give this permission to assets which are not much needed to be hidden from public on a web server, for example images.. You said I am using windows 7. if that means that your web server is Windows based then you should login to that and right click the folder and set permissions to everyone and if you are on a windows client and server is unix/linux based then use some ftp software and in the parent directory right click and change the permission for the folder. If you want permission to be set on sub-directories too then usually their is option to set permission recursively use that. And, if you feel like doing it from command line the use putty and login to server and go to the parent directory includes and write the following command chmod 0777 module_installation/ for recursive chmod -R 0777 module_installation/ Hope this will help you | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11389765', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1209009/']} | jdg_75734 |
stackexchange | llm_judgeable_groundtruth_similarity | 37441575 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I see some references and tutorials about the commnads of WinDBG.Some of them like this lm , this .echo , this !running , and this nt!_PDB . What is difference between these categories xxx .xxx !xxx xxx!yyy ? They look so confused.
Now provide the response and nothing else.
| There are built-in commands, meta commands (dot commands) and extension commands (bang commands). My personal opinion is that you needn't care too much about the difference of built-in commands compared to meta commands, since there are enough examples where those definitions do not match properly. It's sufficient to know that they are always there and don't need an extension to be loaded. Good examples for built-in commands, which are mainly about controlling and getting information from the debugging target: g - gok - call stack~ - list threads Examples where IMHO this definition does not really match: version - show version of the debuggervercommand - show command line that was used to start the debuggern - set number base Good examples for meta commands, which are thought for only affecting the debugger but not the target: .cls - clear screen.chain - display loaded extensions.effmach - change behavior of the debugger regarding the architecture.prefer_dml - change output format Example where IMHO this definition does not really match: .lastevent - show last exception or event that occurred (in the target).ttime - display thread times (of the target).call - call a function (in the target).dvalloc - allocate memory (in the target) However, it's good to understand that the extension commands are different, especially because the same command may result in different output, depending on which extension is loaded or appears first in the extension list and that you can affect the order (e.g. by .load , .unload , .setdll ). Besides the simple form !command , note that there is also the !extension.command syntax to specify the extension explicitly. I'll use it in the example below. (There's even !c:\path\to\extension.command ) The example of a collision of extension commands is given from a kernel debug session where one !heap does not give any output and the other obviously needs a parameter to work. 0: kd> !ext.heap0: kd> !exts.heapInvalid type information The last format mentioned in your question ( xxx!yyy ) is not a command, but a method or type information where xxx denotes the module (DLL) and yyy denotes the method or type name. Often, this is also seen with an additional offset in bytes for locations inside the method ( xxx!yyy+0xhhh ) | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/37441575', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2533918/']} | jdg_75735 |
stackexchange | llm_judgeable_groundtruth_similarity | 47896 |
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:
The following statements are from Wikipedia page of Keying Keying or digital modulation applies to transmitting a digital signal over an analogue passband channel. When a digital signal is to be transmitted over an analogue baseband channel, the modulation technique is termed line coding. To me, both of the lines seem same. The only difference I see are the terms passband channel and baseband channel . I see both of these terms used interchangeably on the internet because we only care for the message that we get from passband channel which is obtained after filtering baseband channel. So, what's the difference between Line Code and Keying ?
Now provide the response and nothing else.
| I think the Wikipedia definition is limited, and anybody using the terms keying and line coding interchangably is wrong. A line code is an encoding (or mapping) from bits to pulse amplitudes (voltages) whose main purposes are spectral shaping and receiver synchronization . These are some of the things you can acomplish with line coding: Remove DC. Since long transmission lines do not transfer DC very well, and since DC uses power but transmits no information, many systems use line codes that remove it. The simplest example is AMI (alternate mark inversion). In AMI, a bit 0 is mapped to 0 V, and a bit 1 is mapped to +1 V or -1 V in an alternating fashion. Spread the signal energy across the entire bandwidth evenly. This is achieved with a scrambler. Avoid long runs of consecutive '1's or '0's. This helps the receiver synchronize to the received signal; sync algorithmis typically rely on signal transitions. One example is the 8b10b code. This line code substitutes runs of more than 5 symbols by sequences with transitions. Note that the last two are different ways of achieving similar results. It is true DC removal is more commonly used in baseband wireline systems. However, line codes, in one shape or another, are used in all communication systems. Contrast line encoding with other types of codes: source coding compresses the information before transmission, and error control codes add extra information in order to correct and/or detect channel errors. A typical communications system will include all three types of codes. Regarding keying: keying is the process of taking the output of the line coder and mapping it to a carrier. In this sense, keying does imply a passband channel. | {} | {'log_upvote_score': 4, 'links': ['https://dsp.stackexchange.com/questions/47896', 'https://dsp.stackexchange.com', 'https://dsp.stackexchange.com/users/23058/']} | jdg_75736 |
stackexchange | llm_judgeable_groundtruth_similarity | 378132 |
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 there is an n such that $W_n$ = {$2n, . . . , 2n + n^2$} Now I don't know where to start with this question, how can I go about answering it? Would I construct a computable function that has that domain? What is that domain? I'm not sure I understand the question properly. $W_n$ is the domain of a partial computable function with godel number n, is that right? Ok, heres what I have so far with the recursion theorem: define \begin{equation} g(x,y)=\begin{cases} 1, & \text{if $2x\le y \le 2x+x^2$}.\\ ↑, & \text{otherwise}. \end{cases}\end{equation} Say g has an index e, such that $g = \varphi_e$ By S-M-N theorem we have a total computable $\varphi_{s(x)}(y) =\varphi_e(x,y)$. Then we have $\varphi_{s(x)}$ = $\varphi_x$ fixed point by the recursion theorem $\varphi_x$ has domain {$2x,...,2x+x^2$}, therefore such an n=x exists.
Now provide the response and nothing else.
| Expansion of Gerry Myerson/MJD answer. If $x$ is rational but not integer, then $2^x$ is irrational by unique factorization. Now suppose $x$ is irrational. Let's use the "Six Exponentials Theorem" , which states: Let $x_1, x_2, x_3, y_1, y_2$ be complex numbers, assume $x_1, x_2, x_3$ are linearly independent over $\mathbb Q$ and $y_1, y_2$ are linearly independentover $\mathbb Q$. Then at least one of $\exp(x_iy_j)$ is transcendental. Take $x_1 = \log 2, x_2 = \log 3, x_3 = \log 5, y_1 = 1, y_2 = x$. Then $\log 2, \log 3, \log 5$ are linearly independent by unique factorization. And $1,x$ are linearly independent since $x$ is irrational. Conclusion: at least one of$$2, 3, 5, 2^x, 3^x, 5^x$$is transcendental. So, in particular, they are not all rational. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/378132', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/45942/']} | jdg_75737 |
stackexchange | llm_judgeable_groundtruth_similarity | 4278845 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Which is the fastest way to get the lines of an ASCII file?
Now provide the response and nothing else.
| Normally you read files in C using fgets . You can also use scanf("%[^\n]") , but quite a few people reading the code are likely to find that confusing and foreign. Edit: on the other hand, if you really do just want to count lines, a slightly modified version of the scanf approach can work quite nicely: while (EOF != (scanf("%*[^\n]"), scanf("%*c"))) ++lines; The advantage of this is that with the '*' in each conversion, scanf reads and matches the input, but does nothing with the result. That means we don't have to waste memory on a large buffer to hold the content of a line that we don't care about (and still take a chance of getting a line that's even larger than that, so our count ends up wrong unless we got to even more work to figure out whether the input we read ended with a newline). Unfortunately, we do have to break up the scanf into two pieces like this. scanf stops scanning when a conversion fails, and if the input contains a blank line (two consecutive newlines) we expect the first conversion to fail. Even if that fails, however, we want the second conversion to happen, to read the next newline and move on to the next line. Therefore, we attempt the first conversion to "eat" the content of the line, and then do the %c conversion to read the newline (the part we really care about). We continue doing both until the second call to scanf returns EOF (which will normally be at the end of the file, though it can also happen in case of something like a read error). Edit2: Of course, there is another possibility that's (at least arguably) simpler and easier to understand: int ch;while (EOF != (ch=getchar())) if (ch=='\n') ++lines; The only part of this that some people find counterintuitive is that ch must be defined as an int , not a char for the code to work correctly. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4278845', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/122963/']} | jdg_75738 |
stackexchange | llm_judgeable_groundtruth_similarity | 21172889 |
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 simultaneously to render a page and transmit my custom data to browser. As i understood it needs to send two layers: first with template and second with JSON data. I want to handle this data by backbone. As i understood from tutorials express and bb app interact as follows: res.render send a page to browser when document.ready trigger jQuery.get to app.get('/post') app.get('/post', post.allPosts) send data to page This is three steps and how to do it by one? var visitCard = { name: 'John Smit', phone: '+78503569987'};exports.index = function(req, res, next){ res.render('index'); res.send({data: visitCard}); }; And how i should catch this variable on the page- document.card ?
Now provide the response and nothing else.
| I created my own little middleware function that adds a helper method called renderWithData to the res object. app.use(function (req, res, next) { res.renderWithData = function (view, model, data) { res.render(view, model, function (err, viewString) { data.view = viewString; res.json(data); }); }; next();}); It takes in the view name, the model for the view, and the custom data you want to send to the browser. It calls res.render but passes in a callback function. This instructs express to pass the compiled view markup to the callback as a string instead of immediately piping it into the response. Once I have the view string I add it onto the data object as data.view . Then I use res.json to send the data object to the browser complete with the compiled view :) Edit: One caveat with the above is that the request needs to be made with javascript so it can't be a full page request. You need an initial request to pull down the main page which contains the javascript that will make the ajax request. This is great for situations where you're trying to change the browser URL and title when the user navigates to a new page via AJAX. You can send the new page's partial view back to the browser along with some data for the page title. Then your client-side script can put the partial view where it belongs on the page, update the page title bar, and update the URL if needed as well. If you are wanting to send a fully complete HTML document to the browser along with some initial JavaScript data then you need to compile that JavaScript code into the view itself. It's definitely possible to do that but I've never found a way that doesn't involve some string magic. For example: // controller.jsvar someData = { message: 'hi' };res.render('someView', { data: JSON.stringify(someData) });// someView.jadescript. var someData = !{data}; Note: !{data} is used instead of #{data} because jade escapes HTML by default which would turn all the quotation marks into " placeholders. It looks REALLY strange at first but it works. Basically you're taking a JS object on the server, turning it into a string, rendering that string into the compiled view and then sending it to the browser. When the document finally reaches the browser it should look like this: // someSite.com/someView<script type="text/javascript"> var someData = { "message": "hi" };</script> Hopefully that makes sense. If I was to re-create my original helper method to ease the pain of this second scenario then it would look something like this: app.use(function (req, res, next) { res.renderWithData = function (view, model, data) { model.data = JSON.stringify(data); res.render(view, model); }; next();}); All this one does is take your custom data object, stringifies it for you, adds it to the model for the view, then renders the view as normal. Now you can call res.renderWithData('someView', {}, { message: 'hi' }); ; you just have to make sure somewhere in your view you grab that data string and render it into a variable assignment statement. html head title Some Page script. var data = !{data}; Not gonna lie, this whole thing feels kind of gross but if it saves you an extra trip to the server and that's what you're after then that's how you'll need to do it. Maybe someone can think of something a little more clever but I just don't see how else you'll get data to already be present in a full HTML document that is being rendered for the first time. Edit2: Here is a working example: https://c9.io/chevex/test You need to have a (free) Cloud9 account in order to run the project. Sign in, open app.js, and click the green run button at the top. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21172889', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1471681/']} | jdg_75739 |
stackexchange | llm_judgeable_groundtruth_similarity | 1794426 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Most of the applications I've seen that use TCP, do roughly the following to connect to remote host: get the hostname (or address) from the configuration/user input (textual) either resolve the hostname into address and add the port, or use getaddrinfo() from the above fill in the sockaddr_* structure with one of the remote addresses use the connect() to get the socket connected to the remote host. if fails, possibly go to (3) and retry - or just complain about the error (2) is blocking in the stock library implementation, and the (4) seems to be most frequently non-blocking, which seems to give a room for a lot of somewhat similar yet different code that serves the purpose to asynchronously connect to a remote host by its hostname. So the question: what are the good reasons not to have the additional single call like following: int sockfd = connect_by_name(const char *hostname, const char *servicename) ? I can come up with three: historic: because that's what the API is provide for custom per-application policy mechanism for address selection/connection retry: this seems a bit superficial, since for the common case ("get me a tube to talk to remote host") the underlying OS should know better provide the visual feedback to the user about the exact step involved ("name resolution" vs "connection attempt"): this seems rather important, lookup+connection attempt may take time Only the last of them seems to be compelling enough to rewrite the resolve/connect code for every client app (as opposed to at least having and using a widely used library that would implement the connect_by_name() semantics in addition to the existing sockets API), so surely there should be some more reasons that I am missing ? (one of the reasons behind the question is that this kind of API would appear to help the portability to IPv6, as well as possibly to other stream transport protocols significantly) Or, maybe such a library exists and my google-fu failed me ? (edited: corrected the definition to look like it was meant to look, thanks LnxPrgr3)
Now provide the response and nothing else.
| ParseEntry receives a reference to each of the children nodes of the current level. So, you cannot ask the values using the node name, because you already have a child node. The node name is stored in v.first . You can iterate over all the elements at a given level using get_child to select the level and then BOOST_FOREACH to iterate. Each iterator will be a pair representing the name of the node and the node data: using boost::property_tree::wiptree;wiptree &iterationLevel = bifPropTree.get_child(L"VGHL.StringTable");BOOST_FOREACH(wiptree::value_type &v, iterationLevel){ wstring name = v.first; wstring value = v.second.get<wstring>(L""); wcout << L"Name: " << name << L", Value: " << value.c_str() << endl;} This code would print: Name: Language, Value: EN Name: DataPath, Value: ..\\Data\\Resources\\Strings\\stringtable.bst If you do not want to iterate, you can select the node level and then look for the nodes using their name: wiptree &iterationLevel = bifPropTree.get_child(L"VGHL.StringTable");wstring valueLang = iterationLevel.get<wstring>(L"Language");wstring valuePath = iterationLevel.get<wstring>(L"DataPath");wcout << valueLang << endl << valuePath << endl; This code would print: EN ..\\Data\\Resources\\Strings\\stringtable.bst | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1794426', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/120901/']} | jdg_75740 |
Subsets and Splits