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
57653
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: By a semi-simplicial set I mean a simplicial set without degeneracies. In such a thing we can define horns as usual, and thereby "semi-simplicial Kan complexes" which have a filler for every horn. Unlike when degeneracies are present, we have to include 1-dimensional horns: having fillers for 1-dimensional horns means that every vertex is both the source of some 1-simplex and the target of some 1-simplex. I have been told that it is possible to choose degeneracies for any semi-simplicial Kan complex to make it into an ordinary simplicial Kan complex. For instance, to obtain a degenerate 1-simplex on a vertex $x$, we first find (by filling a 1-dimensional 1-horn) a 1-simplex $f\colon x\to y$, then we fill a 2-dimensional 2-horn to get a 2-simplex $f g \sim f$, and we can choose $g\colon x\to x$ to be degenerate. But obviously there are many possible choices of such a $g$. I have three questions: Where can I find this construction written down? Is the choice of degeneracies unique in some "up to homotopy" sense? Ideally, there would be a space of choices which is always contractible. Does a morphism of semi-simplicial Kan complexes necessarily preserve degeneracies in some "up to homotopy" sense? (A sufficiently positive answer to this would imply a corresponding answer to the previous question, by considering the identity morphism.) Now provide the response and nothing else.
The answer to (1) is to be found in Rourke, C. P.; Sanderson, B. J.$\Delta$-sets. I. Homotopy theory. Quart. J. Math. Oxford Ser. (2) 22 (1971), 321–338. It is shown there that a Kan "semi-simplicial" set admits a compatible system of degeneracies. By the way, the term "semi-simplicial" set is not the usual name for this term; it is usually called a "$\Delta$-set." Added: Given Mike's comment below, I realize now that the following sketch doesn't do the job. I haven't looked at this paper recently, but I would imagine the way it goes is as follows:Let $$\Delta^{\text{inj}} = \text{category of finite ordered sets and order preserving injections}$$ $$\Delta = \text{category of finite ordered sets and order preserving maps}$$The we have an inclusion functor $j: \Delta^{\text{inj}} \to \Delta$. Given a"semi-simplicial" set $X$ (i.e., a functor $X: \Delta^{\text{inj}} \to \text{Sets}$) we can form the left Kan extension $j_*X$ and then the restriction$j^*j_*X$ to get a natural map $X \to j^*j_*X$. One can ask whether this is a weak equivalence of simplicial sets. Perhaps what Rourke and Sanderson are doing is showingthis map to be a weak homotopy equivalence, or maybe just so when $X$ is Kan? (I don't have the paper at hand, so this is speculation on my part.) One might argue as follows: Step a): show that $j^\ast j_\ast$ preserves colimits, Step b) show that the map $X \to j^\ast j_\ast X$is a weak equivalence when $X$ is a standard "semi-simplicial" $n$-simplex, Step c)infer the general case by induction on simplices. At any rate, if this is how it goes, then the outcome also provides an answer to (3).
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/57653', 'https://mathoverflow.net', 'https://mathoverflow.net/users/49/']}
jdg_73441
stackexchange
llm_judgeable_groundtruth_similarity
18486837
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 django admin I have 4 users and a super user. I have Users with staff status that have limited access and cannot delete/view/edit users but the admin has authority over every other users and models. I do want the superuser to be able to access the users data and edit/modify/delete them but I do not want the superuser to be able to delete himself/herself. Currently the superuser can delete himself. Is there a way to disable the superuser delete by himself/herself in django?? Any help would be grateful. Thanks Now provide the response and nothing else.
DO NOT USE has_delete_permission() override as it is not being called on every object when you perform delete action from changelist. Use signals to do it. Add this to any models.py from django.db.models.signals import pre_deletefrom django.dispatch.dispatcher import receiverfrom django.contrib.auth.models import Userfrom django.core.exceptions import PermissionDenied@receiver(pre_delete, sender=User)def delete_user(sender, instance, **kwargs): if instance.is_superuser: raise PermissionDenied The only drawback of this method is that nobody will be able to delete any super user. You will have to set users attribute "is_superuser" to False before you can delete it.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18486837', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2659766/']}
jdg_73442
stackexchange
llm_judgeable_groundtruth_similarity
15090829
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 filter a collection of strings based on a rather complex query - in it's "raw" form it looks like this: nano* AND (regulat* OR *toxic* OR ((risk OR hazard) AND (exposure OR release)) ) An example of one of the strings to match against: Workshop on the Second Regulatory Review on Nanomaterials, 30 January 2013, Brussels So, I need to match using AND OR and wildcard characters - so, I presume I'll need to use a regex in JavaScript. I have it all looping correctly, filtering and generally working, but I'm 100% sure my regex is wrong - and some results are being omitted wrongly - here it is: /(nano[a-zA-Z])?(regulat[a-zA-Z]|[a-zA-Z]toxic[a-zA-Z]|((risk|hazard)*(exposure|release)))/i Any help would be greatly appreciated - I really can't abstract my mind correctly to understand this syntax! UPDATE: Few people are point out the importance of the order in which the regex is constructed, however I have no control over the text strings that will be searched, so I need to find a solution that can work regardless of the order or either. UPDATE: Eventually used a PHP solution, due to deprecation of twitter API 1.0, see pastebin for example function ( I know it's better to paste code here, but there's a lot... ): function: http://pastebin.com/MpWSGtHK usage: http://pastebin.com/pP2AHEvk Thanks for all help Now provide the response and nothing else.
A single regex is not the right tool for this, IMO: /^(?=.*\bnano)(?=(?:.*\bregulat|.*toxic|(?=.*(?:\brisk\b|\bhazard\b))(?=.*(?:\bexposure\b|\brelease\b))))/i.test(subject)) would return True if the string fulfills the criteria you set forth, but I find nested lookaheads quite incomprehensible. If JavaScript supported commented regexes, it would look like this: ^ # Anchor search to start of string(?=.*\bnano) # Assert that the string contains a word that starts with nano(?= # AND assert that the string contains... (?: # either .*\bregulat # a word starting with regulat | # OR .*toxic # any word containing toxic | # OR (?= # assert that the string contains .* # any string (?: # followed by \brisk\b # the word risk | # OR \bhazard\b # the word hazard ) # (end of inner OR alternation) ) # (end of first AND condition) (?= # AND assert that the string contains .* # any string (?: # followed by \bexposure\b # the word exposure | # OR \brelease\b # the word release ) # (end of inner OR alternation) ) # (end of second AND condition) ) # (end of outer OR alternation)) # (end of lookahead assertion) Note that the entire regex is composed of lookahead assertions, so the match result itself will always be the empty string. Instead, you could use single regexes: if (/\bnano/i.test(str) && ( /\bregulat|toxic/i.test(str) || ( /\b(?:risk|hazard)\b/i.test(str) && /\b(?:exposure|release)\b/i.test(str) ) )) /* all tests pass */
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/15090829', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/591486/']}
jdg_73443
stackexchange
llm_judgeable_groundtruth_similarity
27175568
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Basically, I'm looking for the cleanest way to modify the styling of some text that i have in the application views without having to reprogram them. I have a lot of section that does not have any tag (text without tag in the view). Is there a way to apply styling to that specific text? (Solution for the short term, before I redefine correctly the tags in the while views) Now provide the response and nothing else.
I got lost somewhere in the middle of your question (and if I've interpreted it incorrectly, please tell me, and I'll dive back into it), but I think this is what you're after: public static Expression ForEach(Expression collection, ParameterExpression loopVar, Expression loopContent){ var elementType = loopVar.Type; var enumerableType = typeof(IEnumerable<>).MakeGenericType(elementType); var enumeratorType = typeof(IEnumerator<>).MakeGenericType(elementType); var enumeratorVar = Expression.Variable(enumeratorType, "enumerator"); var getEnumeratorCall = Expression.Call(collection, enumerableType.GetMethod("GetEnumerator")); var enumeratorAssign = Expression.Assign(enumeratorVar, getEnumeratorCall); // The MoveNext method's actually on IEnumerator, not IEnumerator<T> var moveNextCall = Expression.Call(enumeratorVar, typeof(IEnumerator).GetMethod("MoveNext")); var breakLabel = Expression.Label("LoopBreak"); var loop = Expression.Block(new[] { enumeratorVar }, enumeratorAssign, Expression.Loop( Expression.IfThenElse( Expression.Equal(moveNextCall, Expression.Constant(true)), Expression.Block(new[] { loopVar }, Expression.Assign(loopVar, Expression.Property(enumeratorVar, "Current")), loopContent ), Expression.Break(breakLabel) ), breakLabel) ); return loop;} To use it, you need to supply a collection to iterate over, an expression to substitute into the body of the loop, and a ParameterExpression which is used by the loop body expression, which will be assigned to the loop variable on each loop iteration. I think sometimes examples speak louder than words... var collection = Expression.Parameter(typeof(List<string>), "collection");var loopVar = Expression.Parameter(typeof(string), "loopVar");var loopBody = Expression.Call(typeof(Console).GetMethod("WriteLine", new[] { typeof(string) }), loopVar);var loop = ForEach(collection, loopVar, loopBody);var compiled = Expression.Lambda<Action<List<string>>>(loop, collection).Compile();compiled(new List<string>() { "a", "b", "c" }); EDIT: As Jeroem Mostert correctly points out in the comments, this doesn't quite mirror the "real" behaviour of a foreach loop: this would make sure that it disposes the enumerator. (It would also create a new instance of the loop variable for each iteration, but that doesn't make sense with expressions). Implementing this is just a matter of turning the handle if you feel motivated enough! For anyone watching at home, I've got a similar method for generating 'for' loops: public static Expression For(ParameterExpression loopVar, Expression initValue, Expression condition, Expression increment, Expression loopContent){ var initAssign = Expression.Assign(loopVar, initValue); var breakLabel = Expression.Label("LoopBreak"); var loop = Expression.Block(new[] { loopVar }, initAssign, Expression.Loop( Expression.IfThenElse( condition, Expression.Block( loopContent, increment ), Expression.Break(breakLabel) ), breakLabel) ); return loop;} This is equivalent to the following statement, where the pseudo-variables match the Expressions in the method above: for (loopVar = initValue; condition; increment){ loopContent} Again, loopContent, condition, and increment are Expressions which uses loopVar, and loopVar is assigned on every iteration.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/27175568', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3442206/']}
jdg_73444
stackexchange
llm_judgeable_groundtruth_similarity
234432
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 want to delete the last column of a txt file, while I do not know what the column number is. How could I do this? Example: Input: 1223 1234 1323 ... 2222 1231233 1234 1233 ... 3444 1250000 5553 3455 ... 2334 222 And I want my output to be: 1223 1234 1323 ... 22221233 1234 1233 ... 34440000 5553 3455 ... 2334 Now provide the response and nothing else.
With awk : awk 'NF{NF-=1};1' <in >out or: awk 'NF{NF--};1' <in >out or: awk 'NF{--NF};1' <in >out Although this looks like voodoo, it works. There are three parts to each of these awk commands. The first is NF , which is a precondition for the second part. NF is a variable containing the number of fields in a line. In AWK, things are true if they're not 0 or empty string "" . Hence, the second part (where NF is decremented) only happens if NF is not 0. The second part (either NF-=1 NF-- or --NF ) is just subtracting one from the NF variable. This prevent the last field from being printed, because when you change a field (removing the last field in this case), awk re-construct $0 , concatenate all fields separated by space by default. $0 didn't contain the last field anymore. The final part is 1 . It's not magical, it's just used as a expression that means true . If an awk expression evaluates to true without any associated action, awk default action is print $0 .
{}
{'log_upvote_score': 7, 'links': ['https://unix.stackexchange.com/questions/234432', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/133262/']}
jdg_73445
stackexchange
llm_judgeable_groundtruth_similarity
1264137
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: The SetClipboardData function requires a HANDLE reference; I'm having trouble converting my string for use in the function. Here is my code: char* output = "Test";HLOCAL hMem = LocalAlloc( LHND,1024);char* cptr = (char*) LocalLock(hMem);memcpy( cptr, output, 500 );SetClipboardData(CF_TEXT, hMem);LocalUnlock( hMem );LocalFree( hMem );CloseClipboard(); What am I doing wrong here and what's the proper way to do it? Thanks. Now provide the response and nothing else.
Read the MSDN documentation for the SetClipboardData function. It appears you are missing a few steps and releasing the memory prematurely. First of all, you must call OpenClipboard before you can use SetClipboardData. Secondly, the system takes ownership of the memory passed to the clipboard and it must be unlocked. Also, the memory must be movable, which requires the GMEM_MOVEABLE flag as used with GlobalAlloc (instead of LocalAlloc). const char* output = "Test";const size_t len = strlen(output) + 1;HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, len);memcpy(GlobalLock(hMem), output, len);GlobalUnlock(hMem);OpenClipboard(0);EmptyClipboard();SetClipboardData(CF_TEXT, hMem);CloseClipboard();
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1264137', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_73446
stackexchange
llm_judgeable_groundtruth_similarity
257712
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 $R$ be a regular algebra over a field $k$ of char 0. Let $D$ be its corresponding algebra of differential operators. As in the general setting of non-commutative algebra we can tensor right $D$-modules with left $D$-modules to get $R$-modules. However in this case we have more operations available to us. Let $M$ and $N$ be left $D$-modules. One can define using the leibniz rule a structure of a $D$-module on the tensor product $M \otimes_R N$. The same can be done if we replace one of the factors with a right $D$-modules and flip some signs and similar statements exist for internal Homs over $R$ (i'm not so sure about right tensor right - although I assume that at least in the derived setting one can always use duality to define this structure). Now, my question is rather vague. I'm trying to understand conceptually what properties of $D$ makes it possible to give a $D$-module structure on $M \otimes_R N$ and maybe understand in what way is this construction canonical (since so far all i've seen is a formula in this context). So to summarize: Why do $M \otimes_R N$ and $\mathrm{Hom}_R(M,N)$ have a natural structure of $D$-modules? Edit: After being confused by some conflicting answers I've posted a more detailed and exaustive question here: What kind of algebraic object is $\mathcal{D}_X$? (algebra of diifferential operators). What's special about modules over it? EDIT: Some time has passed and i'm still not satisfied with the my current understanding of this. The original question still remains a mystery: What kind of algebraic object is $\mathcal{D}$? A suitable answer would give a definition of an algebraic object $D$ over a ring $R$ for which all the following holds 1. The opposite $D^{op}$ is canonically morita equivalent to $D$ (Canonically in the sense that the equivalence should be induced from the algebraic structure on $D$). 2. The ability to form tensor products and hom modules over $R$ between left and right $D$-modules except in two cases: Tensor product of a right $D$-module with a right $D$-module. Hom module (over $R$) from a right $D$-module to a left $D$-module 3. The forgetful from $D$-modules to $R$-modules is monoidal w.r.t. above tensor product. Now provide the response and nothing else.
OK, I'll give it a shot. The bi-algebra structure on $D$ is something that I found very confusing too, so I will try to spell it out as best I understand. These ideas were explained to me by Pavel Safronov, and I found these notes by Gabriella Bohm be helpful https://arxiv.org/abs/0805.3806 (though they deal with a more general case than we need here). See also the original papers by Sweedler and Takeuchi from the `70's. The $D$-module set-up Suppose $X$ is a smooth algebraic variety, and $D=D_X$. The situation we have is the following: the category $D-mod$ and the forgetful functor to $\mathcal O-mod$, are equipped with (symmetric) monoidal structures (the duality of $D$-modules will be discussed later). There are many ways to understand why this should be the case, as some of the other answers indicate. For example, the category $D-mod$ can be understood as quasi-coherent sheaves on the de Rham space $X_{dR}$ (and the ring $D$ expresses the descent data on the pullback to quasi-coherent sheaves on $X$). Alternatively, if one thinks of $D$ as a deformation quantization of $T^\ast X$, then the monoidal structure arises from the fact that the cotangent bundle is a symplectic group(oid) acting (trivially) on $X$. One can think of $T^\ast X$ as being a commutative group object in the category of symplectic varieties and lagrangian correspondences (I find this last persepective helpful in unpacking the notion of bialgebroid). However, I think what you are after is not why $D$-modules have this structure, but what structure on the ring $D$ endows $D-mod$ with these structures. The answer (as has already been mentioned) is that $D$ is a bialgebroid over $\mathcal O$. Let me try my best to unpack what that means below. The categorical structure (You can ignore this bit if you don't like it). Consider the following situation: we have monoidal categories $\mathcal C$ and $\mathcal D$ and a monoidal functor$$F:\mathcal D \to \mathcal C$$Suppose also that the functor $F$ is monadic, so that $\mathcal D$ can be expressed as modules for a monad $T$ acting on $\mathcal C$. The monoidal structures on $\mathcal D$, $\mathcal C$ and $F$ must then be reflected in the monad $T$. Such a structure on a monad (acting on a monoidal category $\mathcal C$) is called a bimonad. Rather than saying what this all this means in general, let's consider a special case. Bialgebroids (over a commutative base) Suppose $R$ is a commutative ring, and let $\mathcal C = R-mod$. Then a (colimit preserving) monad acting on $R-mod$ is nothing more than a $R$-ring, i.e. a ring $B$ with a ring homomorphism $R\to B$ (note that $R$ need not be central in $B$). In the case we are interested in $B=D$ and $R=\mathcal O$. Before giving an algebraic definition of a bialgebroid, we note that the point of all this is that a (left) bialgebroid structure on $B$ is exactly equivalent to data of a monoidal structure on $B-mod$ and on the forgetful functor to $R-mod$. Note that if $R$ is central in $B$, this is the usual Tannakian theory, and an $R$-bialgebr oid is just an $R$-bialgebr a . So what is an $R$-bialgebroid? Well, we already know that $B$ is an $R$-ring, so there is a product:$$B_{\bullet} \otimes_{R} {}_\bullet B \to B$$where the dots indicate on which side $R$ is acting on $B$. As one might expect, there is also a coproduct, which tells you how $B$ should act on the tensor product $M \otimes_R N$ of two left $B$-modules, but one has to be careful about which monoidal category the coalgebra structure on $B$ lives in. If you unwind the definitions, you see that the coproduct is given by a map$$B \to {}_\bullet B \otimes_R {}_\bullet B$$Note that, unlike in the product map, $R$ is acting on the left on both factors. This is a little confusing at first, but perhaps not so surprising if you consider that in the category $B-mod$ we want to understand how to tensor two left $B$-modules. Of course, there are some axioms. The one that I found hardest to digest involves something called the Takeuchi product . Let me try to motivate that a bit. Takeuchi Product In the usual theory of bialgebras, there is an axiom which says that the coproduct is an algebra map. This doesn't make sense for bialgebroids as ${}_\bullet B\otimes_R {}_\bullet B$ is not an algebra under componentwise multiplication. The Takeuchi product is a certain subspace of this object, defined by:$$B {}_R \times B := \left\{ \sum b_i \otimes b_i' \in {}_\bullet B\otimes_R {}_\bullet B \mid \sum b_i r \otimes b_i' = b_i \otimes b_i'r \right\}$$Note that the the $r$'s in the condition are acting on the right, whereas the relative tensor product is using multiplication on the left. Note also that if $R$ is central in $B$, then the condition is vacuous. One can check that $B {}_R \times B$ is ring under compoentwise multiplication. One of the axioms of a bialgebroid is that the coproduct map factors through the Takeuchi product and is a ring homomorphism. (There is another interesting bialgebroid axiom, which is about the counit map, but for brevity, I won't discuss that). The Takeuchi product (which in the $R$ commutative case appears to be due to Sweedler?) seemed somewhat mysterious to me until I saw that there is a ring isomorphism:$$B {}_R \times B \simeq End_{B^{op}\otimes B^{op}} (_\bullet B \otimes_R {}_\bullet B )$$Thus, the comultiplication map is nothing more than the structure of a left $B$, right $B\otimes B$ bimodule on ${}_\bullet B\otimes_R {}_\bullet B$. This fits well with the $D$-modules story: the coproduct on $\mathcal D$ is precisely the transfer bimpdule structure on $$ \mathcal D_{X\to X\times X} = {}_\bullet \mathcal D \otimes_{\mathcal O} {}_{\bullet} \mathcal D$$(as it should be, as the transfer bimodule represents the tensor product functor). The D-module structure on Hom Let me come back to this another time...
{}
{'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/257712', 'https://mathoverflow.net', 'https://mathoverflow.net/users/22810/']}
jdg_73447
stackexchange
llm_judgeable_groundtruth_similarity
73138
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: 1 Joule is defined as 1 Watt of power working for 1 second . When the electric bill comes, it says "you've used 5000 Watts, therefore pay us $100". However, from what I understand, if I turn on a 5000 Watt oven for even three seconds, you can say I used 5000 watts. However, for the purpose of measuring how much energy I used, wouldn't it be more correct to say I used 1500 Joules? Why then does the electric company measure in watts when really they are charging you based on a combination of the power used and the amount of time you used it for? Now provide the response and nothing else.
No, the electric bill does NOT say "you have used 5000 Watts". Look at it more closely. It says that you used 5000 kiloWatt-hours . A kilowatt-hour is one kiloWatt (1000 Watts) for one hour. That is a measure of energy, and is the same as charging for Joules. One kiloWatt-hour equals 3.6 MJoules. Or put another way, they do charge by the Joule, just that they express it in more relevant units for most homeowners.
{}
{'log_upvote_score': 6, 'links': ['https://electronics.stackexchange.com/questions/73138', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/20419/']}
jdg_73448
stackexchange
llm_judgeable_groundtruth_similarity
2095697
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 display OpenOffice files, .odt and .odp at client side using a web browser. These files are zipped files. Using Ajax, I can get these files from server but these are zipped files. I have to unzip them using JavaScript , I have tried using inflate.js, http://www.onicos.com/staff/iz/amuse/javascript/expert/inflate.txt , but without success. How can I do this? Now provide the response and nothing else.
I wrote an unzipper in Javascript. It works. It relies on Andy G.P. Na's binary file reader and some RFC1951 inflate logic from notmasteryet . I added the ZipFile class. working example: http://cheeso.members.winisp.net/Unzip-Example.htm (dead link) The source: http://cheeso.members.winisp.net/srcview.aspx?dir=js-unzip (dead link) NB : the links are dead; I'll find a new host soon. Included in the source is a ZipFile.htm demonstration page, and 3 distinct scripts, one for the zipfile class, one for the inflate class, and one for a binary file reader class. The demo also depends on jQuery and jQuery UI. If you just download the js-zip.zip file, all of the necessary source is there. Here's what the application code looks like in Javascript: // In my demo, this gets attached to a click event.// it instantiates a ZipFile, and provides a callback that is// invoked when the zip is read. This can take a few seconds on a// large zip file, so it's asynchronous. var readFile = function(){ $("#status").html("<br/>"); var url= $("#urlToLoad").val(); var doneReading = function(zip){ extractEntries(zip); }; var zipFile = new ZipFile(url, doneReading);};// this function extracts the entries from an instantiated zipfunction extractEntries(zip){ $('#report').accordion('destroy'); // clear $("#report").html(''); var extractCb = function(id) { // this callback is invoked with the entry name, and entry text // in my demo, the text is just injected into an accordion panel. return (function(entryName, entryText){ var content = entryText.replace(new RegExp( "\\n", "g" ), "<br/>"); $("#"+id).html(content); $("#status").append("extract cb, entry(" + entryName + ") id(" + id + ")<br/>"); $('#report').accordion('destroy'); $('#report').accordion({collapsible:true, active:false}); }); } // for each entry in the zip, extract it. for (var i=0; i<zip.entries.length; i++) { var entry = zip.entries[i]; var entryInfo = "<h4><a>" + entry.name + "</a></h4>\n<div>"; // contrive an id for the entry, make it unique var randomId = "id-"+ Math.floor((Math.random() * 1000000000)); entryInfo += "<span class='inputDiv'><h4>Content:</h4><span id='" + randomId + "'></span></span></div>\n"; // insert the info for one entry as the last child within the report div $("#report").append(entryInfo); // extract asynchronously entry.extract(extractCb(randomId)); }} The demo works in a couple of steps: The readFile fn is triggered by a click, and instantiates a ZipFile object, which reads the zip file. There's an asynchronous callback for when the read completes (usually happens in less than a second for reasonably sized zips) - in this demo the callback is held in the doneReading local variable, which simply calls extractEntries , which just blindly unzips all the content of the provided zip file. In a real app you would probably choose some of the entries to extract (allow the user to select, or choose one or more entries programmatically, etc). The extractEntries fn iterates over all entries, and calls extract() on each one, passing a callback. Decompression of an entry takes time, maybe 1s or more for each entry in the zipfile, which means asynchrony is appropriate. The extract callback simply adds the extracted content to an jQuery accordion on the page. If the content is binary, then it gets formatted as such (not shown). It works, but I think that the utility is somewhat limited. For one thing: It's very slow. Takes ~4 seconds to unzip the 140k AppNote.txt file from PKWare. The same uncompress can be done in less than .5s in a .NET program. EDIT : The Javascript ZipFile unpacks considerably faster than this now, in IE9 and in Chrome. It is still slower than a compiled program, but it is plenty fast for normal browser usage. For another: it does not do streaming. It basically slurps in the entire contents of the zipfile into memory. In a "real" programming environment you could read in only the metadata of a zip file (say, 64 bytes per entry) and then read and decompress the other data as desired. There's no way to do IO like that in javascript, as far as I know, therefore the only option is to read the entire zip into memory and do random access in it. This means it will place unreasonable demands on system memory for large zip files. Not so much a problem for a smaller zip file. Also: It doesn't handle the "general case" zip file - there are lots of zip options that I didn't bother to implement in the unzipper - like ZIP encryption, WinZip encryption, zip64, UTF-8 encoded filenames, and so on. ( EDIT - it handles UTF-8 encoded filenames now). The ZipFile class handles the basics, though. Some of these things would not be hard to implement. I have an AES encryption class in Javascript; that could be integrated to support encryption. Supporting Zip64 would probably useless for most users of Javascript, as it is intended to support >4gb zipfiles - don't need to extract those in a browser. I also did not test the case for unzipping binary content. Right now it unzips text. If you have a zipped binary file, you'd need to edit the ZipFile class to handle it properly. I didn't figure out how to do that cleanly. It does binary files now, too. EDIT - I updated the JS unzip library and demo. It now does binary files, in addition to text. I've made it more resilient and more general - you can now specify the encoding to use when reading text files. Also the demo is expanded - it shows unzipping an XLSX file in the browser, among other things. So, while I think it is of limited utility and interest, it works. I guess it would work in Node.js.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2095697', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/69260/']}
jdg_73449
stackexchange
llm_judgeable_groundtruth_similarity
38712772
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 Getting [_WebSafeForwarder forwardInvocation:] and crash report as following on crashlytics. Unable to reproduce the same condition in my code. I added webview.delegate = nil and [webview stopLoading] in each and every -(void)dealloc method where ever UIWebview is present still getting following crash. #0. Crashed: com.apple.main-thread0 libobjc.A.dylib 0x24deba86 objc_msgSend + 51 WebKitLegacy 0x29945e17 -[_WebSafeForwarder forwardInvocation:] + 1902 CoreFoundation 0x25624f4d ___forwarding___ + 3523 CoreFoundation 0x2554f298 _CF_forwarding_prep_0 + 244 CoreFoundation 0x25626664 __invoking___ + 685 CoreFoundation 0x2554b8bd -[NSInvocation invoke] + 2926 WebCore 0x28d6b84b HandleDelegateSource(void*) + 907 CoreFoundation 0x255e39e7 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 148 CoreFoundation 0x255e3569 __CFRunLoopDoSources0 + 3449 CoreFoundation 0x255e193f __CFRunLoopRun + 80610 CoreFoundation 0x255301c9 CFRunLoopRunSpecific + 51611 CoreFoundation 0x2552ffbd CFRunLoopRunInMode + 10812 UIFoundation 0x29bb5837 -[NSHTMLReader _loadUsingWebKit] + 203813 Foundation 0x25e4e887 __NSThreadPerformPerform + 38614 CoreFoundation 0x255e39e7 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 1415 CoreFoundation 0x255e3569 __CFRunLoopDoSources0 + 34416 CoreFoundation 0x255e193f __CFRunLoopRun + 80617 CoreFoundation 0x255301c9 CFRunLoopRunSpecific + 51618 CoreFoundation 0x2552ffbd CFRunLoopRunInMode + 10819 GraphicsServices 0x26b4caf9 GSEventRunModal + 16020 UIKit 0x29c68435 UIApplicationMain + 14421 MyProjectName 0x1446e5 main (main.m:14)22 libdispatch.dylib 0x251dc873 (Missing)--#0. Crashed: com.apple.main-thread0 libobjc.A.dylib 0x24deba86 objc_msgSend + 51 WebKitLegacy 0x29945e17 -[_WebSafeForwarder forwardInvocation:] + 1902 CoreFoundation 0x25624f4d ___forwarding___ + 3523 CoreFoundation 0x2554f298 _CF_forwarding_prep_0 + 244 CoreFoundation 0x25626664 __invoking___ + 685 CoreFoundation 0x2554b8bd -[NSInvocation invoke] + 2926 WebCore 0x28d6b84b HandleDelegateSource(void*) + 907 CoreFoundation 0x255e39e7 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 148 CoreFoundation 0x255e3569 __CFRunLoopDoSources0 + 3449 CoreFoundation 0x255e193f __CFRunLoopRun + 80610 CoreFoundation 0x255301c9 CFRunLoopRunSpecific + 51611 CoreFoundation 0x2552ffbd CFRunLoopRunInMode + 10812 UIFoundation 0x29bb5837 -[NSHTMLReader _loadUsingWebKit] + 203813 Foundation 0x25e4e887 __NSThreadPerformPerform + 38614 CoreFoundation 0x255e39e7 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 1415 CoreFoundation 0x255e3569 __CFRunLoopDoSources0 + 34416 CoreFoundation 0x255e193f __CFRunLoopRun + 80617 CoreFoundation 0x255301c9 CFRunLoopRunSpecific + 51618 CoreFoundation 0x2552ffbd CFRunLoopRunInMode + 10819 GraphicsServices 0x26b4caf9 GSEventRunModal + 16020 UIKit 0x29c68435 UIApplicationMain + 14421 MyProjectName 0x1446e5 main (main.m:14)22 libdispatch.dylib 0x251dc873 (Missing)#2. com.twitter.crashlytics.ios.MachExceptionServer0 MyProjectName 0x157cdd CLSProcessRecordAllThreads + 10150051 MyProjectName 0x157cdd CLSProcessRecordAllThreads + 10150052 MyProjectName 0x157ef5 CLSProcessRecordAllThreads + 10155413 MyProjectName 0x14c52b CLSHandler + 9679794 MyProjectName 0x148249 CLSMachExceptionServer + 9508575 libsystem_pthread.dylib 0x25354c7f _pthread_body + 1386 libsystem_pthread.dylib 0x25354bf3 _pthread_start + 1107 libsystem_pthread.dylib 0x25352a08 thread_start + 8#3. GAIThread0 libsystem_kernel.dylib 0x2529b8a8 mach_msg_trap + 201 libsystem_kernel.dylib 0x2529b6a9 mach_msg + 402 CoreFoundation 0x255e36ad __CFRunLoopServiceMachPort + 1363 CoreFoundation 0x255e1a33 __CFRunLoopRun + 10504 CoreFoundation 0x255301c9 CFRunLoopRunSpecific + 5165 CoreFoundation 0x2552ffbd CFRunLoopRunInMode + 1086 Foundation 0x25d7d42d -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 2687 Foundation 0x25dcbd75 -[NSRunLoop(NSRunLoop) run] + 808 MyProjectName 0x1d58c5 +[GAI threadMain:] + 15300539 Foundation 0x25e4e64d __NSThread__start__ + 114410 libsystem_pthread.dylib 0x25354c7f _pthread_body + 13811 libsystem_pthread.dylib 0x25354bf3 _pthread_start + 11012 libsystem_pthread.dylib 0x25352a08 thread_start + 8#4. com.apple.NSURLConnectionLoader0 libsystem_kernel.dylib 0x2529b8a8 mach_msg_trap + 201 libsystem_kernel.dylib 0x2529b6a9 mach_msg + 402 CoreFoundation 0x255e36ad __CFRunLoopServiceMachPort + 1363 CoreFoundation 0x255e1a33 __CFRunLoopRun + 10504 CoreFoundation 0x255301c9 CFRunLoopRunSpecific + 5165 CoreFoundation 0x2552ffbd CFRunLoopRunInMode + 1086 CFNetwork 0x25b85c47 +[NSURLConnection(Loader) _resourceLoadLoop:] + 4867 Foundation 0x25e4e64d __NSThread__start__ + 11448 libsystem_pthread.dylib 0x25354c7f _pthread_body + 1389 libsystem_pthread.dylib 0x25354bf3 _pthread_start + 11010 libsystem_pthread.dylib 0x25352a08 thread_start + 8#5. com.apple.CFSocket.private0 libsystem_kernel.dylib 0x252afeec __select + 201 CoreFoundation 0x255e8b51 __CFSocketManager + 5722 libsystem_pthread.dylib 0x25354c7f _pthread_body + 1383 libsystem_pthread.dylib 0x25354bf3 _pthread_start + 1104 libsystem_pthread.dylib 0x25352a08 thread_start + 8#6. AFNetworking0 libsystem_kernel.dylib 0x2529b8a8 mach_msg_trap + 201 libsystem_kernel.dylib 0x2529b6a9 mach_msg + 402 CoreFoundation 0x255e36ad __CFRunLoopServiceMachPort + 1363 CoreFoundation 0x255e1a33 __CFRunLoopRun + 10504 CoreFoundation 0x255301c9 CFRunLoopRunSpecific + 5165 CoreFoundation 0x2552ffbd CFRunLoopRunInMode + 1086 Foundation 0x25d7d42d -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 2687 Foundation 0x25dcbd75 -[NSRunLoop(NSRunLoop) run] + 808 MyProjectName 0x29d30f +[AFURLConnectionOperation networkRequestThreadEntryPoint:] (AFURLConnectionOperation.m:168)9 Foundation 0x25e4e64d __NSThread__start__ + 114410 libsystem_pthread.dylib 0x25354c7f _pthread_body + 13811 libsystem_pthread.dylib 0x25354bf3 _pthread_start + 11012 libsystem_pthread.dylib 0x25352a08 thread_start + 8#7. WebThread0 libsystem_kernel.dylib 0x252af998 __psynch_cvwait + 241 libsystem_pthread.dylib 0x253541a5 _pthread_cond_wait + 5362 libsystem_pthread.dylib 0x253550f9 pthread_cond_timedwait + 443 WebCore 0x28d57f57 SendDelegateMessage(NSInvocation*) + 6784 WebKitLegacy 0x29978265 CallFrameLoadDelegate(void (*)(), WebView*, objc_selector*, objc_object*) + 1725 WebKitLegacy 0x29947877 WebFrameLoaderClient::dispatchDidFinishLoad() + 1586 WebCore 0x28d290af WebCore::FrameLoader::checkLoadCompleteForThisFrame() + 3827 WebCore 0x28d28e75 WebCore::FrameLoader::checkLoadComplete() + 2808 WebCore 0x28d55bf1 WebCore::FrameLoader::checkCompleted() + 3169 WebCore 0x28d5504b WebCore::FrameLoader::finishedParsing() + 10210 WebCore 0x28d54f59 WebCore::Document::finishedParsing() + 31211 WebCore 0x28d5270b WebCore::HTMLDocumentParser::prepareToStopParsing() + 11812 WebCore 0x28dddbcb WebCore::HTMLDocumentParser::resumeParsingAfterYield() + 10213 WebCore 0x28cff4a1 WebCore::ThreadTimers::sharedTimerFiredInternal() + 13614 WebCore 0x28cff3f5 WebCore::timerFired(__CFRunLoopTimer*, void*) + 2815 CoreFoundation 0x255e4177 __CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__ + 1416 CoreFoundation 0x255e3da9 __CFRunLoopDoTimer + 93617 CoreFoundation 0x255e1bf5 __CFRunLoopRun + 150018 CoreFoundation 0x255301c9 CFRunLoopRunSpecific + 51619 CoreFoundation 0x2552ffbd CFRunLoopRunInMode + 10820 WebCore 0x28d457b7 RunWebThread(void*) + 42221 libsystem_pthread.dylib 0x25354c7f _pthread_body + 13822 libsystem_pthread.dylib 0x25354bf3 _pthread_start + 11023 libsystem_pthread.dylib 0x25352a08 thread_start + 8#8. JavaScriptCore::Marking0 libsystem_kernel.dylib 0x252af998 __psynch_cvwait + 241 libsystem_pthread.dylib 0x253541a5 _pthread_cond_wait + 5362 libsystem_pthread.dylib 0x253550b9 pthread_cond_wait + 403 libc++.1.dylib 0x24d7469d std::__1::condition_variable::wait(std::__1::unique_lock<std::__1::mutex>&) + 364 JavaScriptCore 0x2891a781 JSC::GCThread::waitForNextPhase() + 1045 JavaScriptCore 0x2891a7ef JSC::GCThread::gcThreadMain() + 626 JavaScriptCore 0x287269e1 WTF::threadEntryPoint(void*) + 1487 JavaScriptCore 0x2872693f WTF::wtfThreadEntryPoint(void*) + 148 libsystem_pthread.dylib 0x25354c7f _pthread_body + 1389 libsystem_pthread.dylib 0x25354bf3 _pthread_start + 11010 libsystem_pthread.dylib 0x25352a08 thread_start + 8#9. NSOperationQueue 0x15e6cc20 :: NSOperation 0x15d230e0 (QOS: USER_INTERACTIVE)0 libsystem_kernel.dylib 0x2529b8f8 semaphore_wait_trap + 81 libsystem_platform.dylib 0x2534f289 _os_semaphore_wait + 122 libdispatch.dylib 0x251bcc6d _dispatch_barrier_sync_f_slow + 3723 MyProjectName 0x27dd8f __69-[SDWebImageManager downloadImageWithURL:options:progress:completed:]_block_invoke98 (SDWebImageManager.m:189)4 MyProjectName 0x275e71 __72-[SDWebImageDownloader downloadImageWithURL:options:progress:completed:]_block_invoke93 (SDWebImageDownloader.m:163)5 MyProjectName 0x27a8fb -[SDWebImageDownloaderOperation connection:didFailWithError:] (SDWebImageDownloaderOperation.m:419)6 CFNetwork 0x25c683a1 __65-[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:]_block_invoke + 567 CFNetwork 0x25c68359 -[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:] + 1848 CFNetwork 0x25c6847d -[NSURLConnectionInternal _withConnectionAndDelegate:] + 369 CFNetwork 0x25c44125 _NSURLConnectionDidFail(_CFURLConnection*, __CFError*, void const*) + 8410 CFNetwork 0x25be3203 ___ZN27URLConnectionClient_Classic17_delegate_didFailEP9__CFErrorU13block_pointerFvvE_block_invoke + 8611 CFNetwork 0x25be1a83 ___ZN27URLConnectionClient_Classic18_withDelegateAsyncEPKcU13block_pointerFvP16_CFURLConnectionPK33CFURLConnectionClientCurrent_VMaxE_block_invoke_2 + 7012 libdispatch.dylib 0x251b3cab _dispatch_client_callout + 2213 libdispatch.dylib 0x251bb543 _dispatch_block_invoke + 45014 CFNetwork 0x25b13e83 RunloopBlockContext::_invoke_block(void const*, void*) + 1815 CoreFoundation 0x2552fc09 CFArrayApplyFunction + 3616 CFNetwork 0x25b13d6b RunloopBlockContext::perform() + 18217 CFNetwork 0x25b13c35 MultiplexerSource::perform() + 21618 CFNetwork 0x25b13ac9 MultiplexerSource::_perform(void*) + 4819 CoreFoundation 0x255e39e7 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 1420 CoreFoundation 0x255e35d7 __CFRunLoopDoSources0 + 45421 CoreFoundation 0x255e193f __CFRunLoopRun + 80622 CoreFoundation 0x255301c9 CFRunLoopRunSpecific + 51623 CoreFoundation 0x25570f23 CFRunLoopRun + 9824 MyProjectName 0x27779b -[SDWebImageDownloaderOperation start] (SDWebImageDownloaderOperation.m:117)25 Foundation 0x25e38b0d __NSOQSchedule_f + 19226 libdispatch.dylib 0x251bde7f _dispatch_queue_drain + 176227 libdispatch.dylib 0x251b6e17 _dispatch_queue_invoke + 28228 libdispatch.dylib 0x251bf20d _dispatch_root_queue_drain + 40029 libdispatch.dylib 0x251bf07b _dispatch_worker_thread3 + 9430 libsystem_pthread.dylib 0x25352e0d _pthread_wqthread + 102431 libsystem_pthread.dylib 0x253529fc start_wqthread + 8#10. com.apple.root.default-qos0 libsystem_kernel.dylib 0x252af998 __psynch_cvwait + 241 libsystem_pthread.dylib 0x253541a5 _pthread_cond_wait + 5362 libsystem_pthread.dylib 0x253550b9 pthread_cond_wait + 403 Foundation 0x25dc840f -[NSCondition wait] + 1944 Foundation 0x25d8f40b -[NSObject(NSThreadPerformAdditions) performSelector:onThread:withObject:waitUntilDone:modes:] + 8505 Foundation 0x25d92be1 -[NSObject(NSThreadPerformAdditions) performSelectorOnMainThread:withObject:waitUntilDone:] + 1366 UIFoundation 0x29bb611f -[NSHTMLReader _load] + 3867 UIFoundation 0x29bb6b21 -[NSHTMLReader attributedString] + 248 UIFoundation 0x29b5ac35 _NSReadAttributedStringFromURLOrData + 53049 UIFoundation 0x29b596f5 -[NSAttributedString(NSAttributedStringUIFoundationAdditions) initWithData:options:documentAttributes:error:] + 11610 MyProjectName 0x19cecf -[MyStaticLibrary handleHTMLCharactersForTitle:] (MyStaticLibrary.m:3132)11 MyProjectName 0x1a8905 __47-[MyNetworkRequest onHTTPSuccessWithResponse:]_block_invoke143 (MyNetworkRequest.m:484)12 libdispatch.dylib 0x251b3cbf _dispatch_call_block_and_release + 1013 libdispatch.dylib 0x251bf6a1 _dispatch_root_queue_drain + 157214 libdispatch.dylib 0x251bf07b _dispatch_worker_thread3 + 9415 libsystem_pthread.dylib 0x25352e0d _pthread_wqthread + 102416 libsystem_pthread.dylib 0x253529fc start_wqthread + 8#11. Thread0 libsystem_kernel.dylib 0x252afffc __semwait_signal + 241 libsystem_c.dylib 0x25203bcd nanosleep + 1722 libc++.1.dylib 0x24db38f5 std::__1::this_thread::sleep_for(std::__1::chrono::duration<long long, std::__1::ratio<1ll, 1000000000ll> > const&) + 1363 JavaScriptCore 0x28ad9b01 bmalloc::Heap::scavenge(std::__1::unique_lock<bmalloc::StaticMutex>&, std::__1::chrono::duration<long long, std::__1::ratio<1ll, 1000ll> >) + 2564 JavaScriptCore 0x28ad98eb bmalloc::Heap::concurrentScavenge() + 785 JavaScriptCore 0x28adb7b7 bmalloc::AsyncTask<bmalloc::Heap, void (bmalloc::Heap::*)()>::entryPoint() + 986 JavaScriptCore 0x28adb751 bmalloc::AsyncTask<bmalloc::Heap, void (bmalloc::Heap::*)()>::pthreadEntryPoint(void*) + 87 libsystem_pthread.dylib 0x25354c7f _pthread_body + 1388 libsystem_pthread.dylib 0x25354bf3 _pthread_start + 1109 libsystem_pthread.dylib 0x25352a08 thread_start + 8#12. Thread0 libsystem_pthread.dylib 0x253529f4 start_wqthread + 14#13. Thread0 libsystem_kernel.dylib 0x252b0864 __workq_kernreturn + 81 libsystem_pthread.dylib 0x25352e19 _pthread_wqthread + 10362 libsystem_pthread.dylib 0x253529fc start_wqthread + 8#14. Thread0 libsystem_kernel.dylib 0x252b0864 __workq_kernreturn + 81 libsystem_pthread.dylib 0x25352e19 _pthread_wqthread + 10362 libsystem_pthread.dylib 0x253529fc start_wqthread + 8#15. PLClientLoggingFlushQueue0 libsystem_platform.dylib 0x2534e96a _platform_memmove + 1051 CoreFoundation 0x2553f0c7 CFStringGetBytes + 6342 CoreFoundation 0x2553f0c7 CFStringGetBytes + 6343 CoreFoundation 0x25677ab9 __writeObject15 + 3244 CoreFoundation 0x2567841d __writeObject15 + 27285 CoreFoundation 0x2567841d __writeObject15 + 27286 CoreFoundation 0x2567841d __writeObject15 + 27287 CoreFoundation 0x2567841d __writeObject15 + 27288 CoreFoundation 0x2567841d __writeObject15 + 27289 CoreFoundation 0x256777ad __CFBinaryPlistWrite15 + 15210 CoreFoundation 0x255729cf _CFXPCCreateXPCMessageWithCFObject + 11811 PowerLog 0x2707ab4f -[PLClientLogger xpcSendMessage:withClientID:withKey:withPayload:] + 8612 PowerLog 0x2707bd85 -[PLClientLogger batchTasksCacheFlush] + 50013 libdispatch.dylib 0x251b3cbf _dispatch_call_block_and_release + 1014 libdispatch.dylib 0x251bd3cf _dispatch_after_timer_callback + 6615 libdispatch.dylib 0x251c65bb _dispatch_source_latch_and_call + 204216 libdispatch.dylib 0x251b5bff _dispatch_source_invoke + 73817 libdispatch.dylib 0x251bd9ed _dispatch_queue_drain + 59218 libdispatch.dylib 0x251b6e17 _dispatch_queue_invoke + 28219 libdispatch.dylib 0x251bf20d _dispatch_root_queue_drain + 40020 libdispatch.dylib 0x251bf07b _dispatch_worker_thread3 + 9421 libsystem_pthread.dylib 0x25352e0d _pthread_wqthread + 102422 libsystem_pthread.dylib 0x253529fc start_wqthread + 8 Now provide the response and nothing else.
I have the same issue, I used [NSAttributedString alloc] initWithData to load the HTML string on a label. My crashes often happened when the app switch between Background mode and Foreground mode.I got some tips from Apple's documentation, I think this might be useful. Following are the discussion on Apple's NSAttributedstring doc: The HTML importer should not be called from a background thread (that is, the options dictionary includes NSDocumentTypeDocumentAttribute with a value of NSHTMLTextDocumentType). It will try to synchronize with the main thread, fail, and time out. Calling it from the main thread works (but can still time out if the HTML contains references to external resources, which should be avoided at all costs). The HTML import mechanism is meant for implementing something like markdown (that is, text styles, colors, and so on), not for general HTML import.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38712772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4090939/']}
jdg_73450
stackexchange
llm_judgeable_groundtruth_similarity
18752409
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: wondering if someone may please explain how openssl works in python2.7.I'm not sure if python got its own openssl or picks it up from local machine/env? let me explain: (if I do this in Python) >>> import ssl>>> ssl.OPENSSL_VERSION'OpenSSL 0.9.8x 10 May 2012' (In terminal) $ openssl versionOpenSSL 0.9.8x 10 May 2012$ which openssl /usr/bin/openssl now I updated openssl (downloaded .) $ cd openssl-1.0.1c$ ./Configure darwin64-x86_64-cc --prefix=/usr --openssldir=/opt/local/etc/openssl shared$ make$ sudo make install this created separate director(as specified), so I copied it to the old path cp -f /usr/local/ssl/bin/openssl /usr/bin/openssl now in terminal openssl version has been updated but not from python! $ openssl versionOpenSSL 1.0.1c 10 May 2012 I did noticed that .dylib is still pointing to old version, how can I change this? $ ls -l /usr/lib/*ssl*-rwxr-xr-x 1 root wheel 411680 Jul 17 2012 /usr/lib/libssl.0.9.7.dylib-rwxr-xr-x 1 root wheel 602800 May 24 03:43 /usr/lib/libssl.0.9.8.dylib-rwxr-xr-x 1 root wheel 390908 Sep 9 17:37 /usr/lib/libssl.1.0.0.dyliblrwxr-xr-x 1 root wheel 18 Jul 17 2012 /usr/lib/libssl.dylib -> libssl.0.9.8.dylib Update : I changed the link still got old version at python. $ ls -l /usr/lib/*ssl*-rwxr-xr-x 1 root wheel 411680 Jul 17 2012 /usr/lib/libssl.0.9.7.dylib-rwxr-xr-x 1 root wheel 602800 May 24 03:43 /usr/lib/libssl.0.9.8.dylib-rwxr-xr-x 1 root wheel 390908 Sep 9 17:37 /usr/lib/libssl.1.0.0.dyliblrwxr-xr-x 1 root wheel 18 Sep 11 15:47 /usr/lib/libssl.dylib -> libssl.1.0.0.dylib Now provide the response and nothing else.
Please refer to http://rkulla.blogspot.kr/2014/03/the-path-to-homebrew.html After upgrading openssl to 1.0.1j by homebrew on MAC, but system python still referred to old version 0.9.8. It turned out the python referred to openssl. So I have installed new python with brewed openssl and finished this issue on Mac, not yet Ubuntu. On Mac OS X version 10.10 and system python version 2.7.6, my procedure is as follows: $ brew update$ brew install openssl Then you can see openssl version 1.0.1j. $ brew link openssl --force $ brew install python --with-brewed-openssl You have to install new python with brewed openssl. Then, you can see /usr/local/Cellar/python/2.7.8_2/bin/python. $ sudo ln -s /usr/local/Cellar/python/2.7.8_2/bin/python /usr/local/bin/python Of course, /usr/local/* should be owned by $USER, not root, which is told by Ryan, but I used 'sudo'. And, before this instruction, I didn't have /usr/local/bin/python. After this instruction, you can use python version 2.7.8 not 2.7.6. Finally, you can see as belows; $ python --version Python 2.7.8$ python -c "import ssl; print ssl.OPENSSL_VERSION"OpenSSL 1.0.1j 15 Oct 2014 Till now, I'm working on it on Ubuntu 12.04. If I have a solution for Ubuntu 12.04, then I will update my answer. I hope this procedure help you.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18752409', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2070446/']}
jdg_73451
stackexchange
llm_judgeable_groundtruth_similarity
67290520
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Before the null safety I could simply mock up the sendRequest(...) method like that: void stubBaseRepositorySendRequestResponse(String response) { when(baseRepository.sendRequest(onGetData: anyNamed('onGetData'))) .thenAnswer((_) { return Future<String>.value(response); }); } where the signature of this method is: Future<T> sendRequest<T>({required Future<T> Function() onGetData}) How can this be done with the new null-safe version of mockito?Can I still maintain the generic character of this stub and allow for any arguments to be passed in? Now provide the response and nothing else.
This can be easily done with mocktail .A lot easier, without the code gen required by mockito. Important to import mocktail first: import 'package:mocktail/mocktail.dart'; then create a mock of the class that we want to mock: class MockBaseRepository extends Mock implements BaseRepository {}void stubBaseRepositorySendRequestResponse(String response) {when(() => baseRepository.sendRequest( onGetData: any(named: 'onGetData', that: isNotNull))).thenAnswer((_) { return Future<String>.value(response); }); }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/67290520', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8643885/']}
jdg_73452
stackexchange
llm_judgeable_groundtruth_similarity
5514887
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there in mvc any opportunity to read a name which will be assigned to html control? For example I use this code: <div> @Html.LabelFor(x => x.Name) @Html.TextBoxFor(x => x.Name) @Html.ValidationMessageFor(x => x.Name) @Html.HiddenFor(x => x.Id) <div> I want to display here a TextBox name </div></div> And I want to get a name of input name. This code is fragment of partial view.Name of element looks like children[1].Name Now provide the response and nothing else.
@Html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName("Name") Or you can use extension method for generic HtmlHelper to use this with Lambda Expressions public static string GetFullHtmlFieldName<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression){ return htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(ExpressionHelper.GetExpressionText(expression));} The use would be (Html.GetFullHtmlFieldName(x => x.Name)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5514887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/677202/']}
jdg_73453
stackexchange
llm_judgeable_groundtruth_similarity
2367162
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Possible Duplicate: SQL Server: Can I Comma Delimit Multiple Rows Into One Column? I have a query like this: SELECT name from users and it's result is a number of records: 1 user12 user23 user3 I want to get all this records in a single line separated by comma: user1, user2, user3 and an empty line if query result is empty. How to get this using T-SQL ? UNPIVOT ? Now provide the response and nothing else.
You can use the COALESCE function to achieve this: declare @result varchar(max)select @result = COALESCE(@result + ', ', '') + namefrom usersselect @result This will work in sql server 2000 and later (probably earlier versions too). Note that you don't have varchar(max) in sql server 2000 though. In later versions of sql server (2005 and later), it is also possible to do this using XML Path() select name + ','from usersfor xml path('')
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2367162', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/41956/']}
jdg_73454
stackexchange
llm_judgeable_groundtruth_similarity
50277504
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Studied the documentation of axios and of ES6 fetch I found than both are quite similar and have experienced a strong influence of $.ajax and its shorthands. Main advantage of axios is browser support. So am I right that if I use babel-polyfill - there is no reasons to use axios? Now provide the response and nothing else.
A few reasons for using Axios over Fetch: Ability to monitor request progress This is more of a question between XMLHttpRequest (which powers axios) or Fetch API. Fetch API currently does not provide any way to get notified of the request progress, a feature which powers feedback mechanism for large file uploads for example. Axios, on the other hand, has this functionality built in: axios.post('/api', data, { onUploadProgress: ({ total, loaded }) => { // update progress }),}) Error handling When your backend returns 500 Internal Server Error response code, fetch will not treat it any different from 200 OK . This is an inconvenience in most cases since all your previous assumptions of what a response would look like are no longer valid. Most often, when receiving an erroneous response from the server you'd want to abort the processing pipeline as soon as possible, and switch to an error handling case. fetch(url) .then(reponse => { if (!(status >= 200 && status < 300)) { return Promise.reject(new Error("Invalid response status")); } return response; }) .then(response => response.json()) .then(/* normal processing */) .catch(/* error handling */); This is not hard to accomplish, but you'd probably want to capture this logic under some abstraction to avoid repetition, and this brings us one step closer to Web API abstraction which is Axios. Axios does a sane thing and rejects the promise if the response returns erroneous status. This behavior is customizable as are most of the things with axios. Testing Axios has moxios , fetch has fetch-mock . Both of those libraries are great but in my experience, fetch-mock required additional setup to get Jest to use mocked fetch over polyfilled one. I also like that moxios.wait() returns a promise which will be resolved after matching the request. Other features that Axios offers For example, you can configure an interceptor which will add api key to all request parameters, or monitor active requests to show a loading screen. Reasons for using one option over the other may vary from actual requirements to convenience. If you need to monitor progress, use Axios (or XMLHttpRequest). If you are writing a service worker, use Fetch. Otherwise, use what's more convenient to you.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/50277504', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2401829/']}
jdg_73455
stackexchange
llm_judgeable_groundtruth_similarity
34460410
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 a question in my book: #include<stdio.h>void main(){ int a=5, b=-7, c=0, d; d = ++a && ++b || ++c; printf("\n%d%d%d%d",a,b,c,d);} The question asks me what is the output of the code. I ran it and the result on the screen is 6-601. I understand why a=6 and b=-6 , but I don't understand why c=0 and d=1 ? Now provide the response and nothing else.
I believe you already got your answer, but just to elaborate a bit step-by-step, let me add one more clarification here. Firstly, to quote the properties of the && and || operators, from C11 standard, chapter §6.5.13 and §6.5.13, respectively, (I) The && operator shall yield 1 if both of its operands compare unequal to 0; otherwise, it yields 0. [...] If the first operand compares equal to 0 , the second operand is not evaluated. and (II) The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0. [...]. If the first operand compares unequal to 0 , the second operand is not evaluated. and they both guarantee left-to-right evaluation. So, comparing your code, d = ++a && ++b || ++c; it happens like d = ((++a && ++b) || ++c ); which evaluates to d = (( 6 && ++b ) || ++c); and then d = ( ( 6 && (-6) ) || ++c); Now in above stage, (I) is fulfilled and it comes down to d = ( 1 || ++c); Now, following the emphasis, which already meets the (II), so no further evaluation of the RHS operand of || is performed (i.e., ++c is not evaluated), and it appears to be d = 1 and the final result, 1, is stored into d . That's how, a == 6 , b == -6 , c == 0 and d ==1 . Having said that, void main() should be changed to int main(void) , at least to conform with the standard.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/34460410', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5715980/']}
jdg_73456
stackexchange
llm_judgeable_groundtruth_similarity
41484323
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 an Error: jsPDF is not defined , I am currenty using following code : import { Component, OnInit, Inject } from '@angular/core';import 'jspdf';declare let jsPDF;@Component({ .... providers: [ { provide: 'Window', useValue: window } ]})export class GenratePdfComponent implements OnInit { constructor( @Inject('Window') private window: Window, ) { } download() { var doc = jsPDF(); doc.text(20, 20, 'Hello world!'); doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.'); doc.save('Test.pdf'); }} I have install npm of jsPDF but don't know how import jspdf and run with angular-cli: 1.0.0-beta.17 Now provide the response and nothing else.
I have done it, after doing lot of R&D , their are few steps to follow as below : Install : npm install jspdf --savetypings install dt~jspdf --global --savenpm install @types/jspdf --save Add following in angular-cli.json: "scripts": [ "../node_modules/jspdf/dist/jspdf.min.js" ] html: <button (click)="download()">download </button> component ts: import { Component, OnInit, Inject } from '@angular/core';import * as jsPDF from 'jspdf'@Component({ ... providers: [ { provide: 'Window', useValue: window } ]})export class GenratePdfComponent implements OnInit { constructor( @Inject('Window') private window: Window, ) { } download() { var doc = new jsPDF(); doc.text(20, 20, 'Hello world!'); doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.'); doc.addPage(); doc.text(20, 20, 'Do you like that?'); // Save the PDF doc.save('Test.pdf'); }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/41484323', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7141386/']}
jdg_73457
stackexchange
llm_judgeable_groundtruth_similarity
2404239
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 currently trying to solve the following: (∃x(¬A(x))) → [∀x (A(x)) → B(z) ] using only the rules of predicate and propositional calculus. I've had a few stabs at the problem. My chief idea has to do with the A(x) statements. I understand that if there exists at least one false A(x), then A(x) is not all true. I understand that falsities can imply anything. How do I join these two ideas together with the proper formal logical notation? For example, I first assume: (∃x(¬A(x))) which means: [∀x (A(x)) → B(z) ] (=> E) [∀x (A(x))] (assume) A(a) (∀E) F So I have proved it's false. Now what? I realise that there is a very good chance I am barking up the wrong tree but I cannot see any other way to prove this. B(z) is totally unrelated to A(z) and while existential elimination will let me arrive at a "q" statement, I do not see how I can get "q" from the other two terms. Now provide the response and nothing else.
You're double (and triple, and quadruple) counting because sometimes one or both of the $2$ cards you choose out of $47$ are lower than a 6. For example, the hand consisting of Ace through 5 of diamonds and the Ace and 2 of hearts is counted 4 times. The hand consisting of Ace through 5 of spades plus both red Aces is counted 3 times. The hand consisting of 2 black Aces and the 2 through 6 of hearts is counted twice. To set this up right, let's partition the cards: 20 cards are less than 6, 32 cards are 6 or more. First let's count all the hands we don't need to double count or half count: $${4 \choose 1}^5{32\choose2}$$ Next let's tackle the hands with 2 of some value below 6 (the value to be doubled is chosen out of five possible values): $${5\choose1}{4\choose2}{4\choose1}^4{32\choose1}$$ Now let's tackle the hands with 3 of some value below 6 (note the 32 choose 0 included for completeness): $${5\choose1}{4\choose3}{4\choose1}^4{32\choose0}$$ Now let's tackle the hands with 2 distinct values below 6 for which there are 2 cards: $${5\choose2}{4\choose2}^2{4\choose1}^3{32\choose0}$$ Adding these figures together, we get 781824, just as stated on the page you linked.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2404239', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/474038/']}
jdg_73458
stackexchange
llm_judgeable_groundtruth_similarity
13618282
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 do this (in my class) public: Entity() { re_sprite_eyes = new sf::Sprite(); re_sprite_hair = new sf::Sprite(); re_sprite_body = new sf::Sprite(); }private: sf::Sprite* re_sprite_hair; sf::Sprite* re_sprite_body; sf::Sprite* re_sprite_eyes; Everything works fine. However, if I change the declarations to this: private: sf::Sprite* re_sprite_hair, re_sprite_body, re_sprite_eyes; I get this compiler error: error: no match for 'operator=' in '((Entity*)this)->Entity::re_sprite_eyes = (operator new(272u), (<statement>, ((sf::Sprite*)<anonymous>))) And then it says candidates for re_sprite_eyes are sf::Sprite objects and/or references. Why does this not work? Aren't the declarations the same? Now provide the response and nothing else.
sf::Sprite* re_sprite_hair, re_sprite_body, re_sprite_eyes; Does not declare 3 pointers - it is one pointer and 2 objects. sf::Sprite* unfortunately does not apply to all the variables declared following it, just the first. It is equivalent to sf::Sprite* re_sprite_hair;sf::Sprite re_sprite_body;sf::Sprite re_sprite_eyes; You want to do: sf::Sprite *re_sprite_hair, *re_sprite_body, *re_sprite_eyes; You need to put one star for each variable. In such cases I prefer to keep the star on the variable's side, rather than the type, to make exactly this situation clear.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/13618282', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_73459
stackexchange
llm_judgeable_groundtruth_similarity
33239959
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 read about signals and I know how to send a signal to a process from the command line. Just do ps -C executable to know the pid of the process, and then kill -s signal pid(number) However, I'd like to find a more interactive and general way to do this if possible. I'd like to send a signal to a specific process from the command line. I'd like to not need to print the PID of the process I want to signal, but rather use a way that the code understands which process should be signaled. Other than that I'd like to understand exacly what the kill command does. Does it kill the process that signals? Does it kill the process where it's called? If it kills a process it means that it's similar to do exit(0) , or does the process resume after the signal is sent back? Now provide the response and nothing else.
As far as I understood your question you want to signal a process by its name, not by its PID. This can easily be achieved by combining the two commands: kill -s signal $(ps -C executable) Does it kill the process that signals? kill can kill. It doesn't necessarily. From man kill : The command kill sends the specified signal to the specified processes or process groups. That means, the kill command is used to **send any signal in general. If it kills a process it means that it's similar to do exit(0) , or does the process resume after the signal is sent back? From here : The SIGKILL signal is used to cause immediate program termination. It cannot be handled or ignored, and is therefore always fatal. It is also not possible to block this signal. If a process receives the SIGKILL signal, it terminates immediately (no destructors called, no cleanup done). The only processes that do not terminate are uninterruptible processes. A full list of signals available on Linux is found here .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33239959', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4921539/']}
jdg_73460
stackexchange
llm_judgeable_groundtruth_similarity
49108242
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 installing WordPress through Xampp. I used to work with MAMP and it basically works the same way. Normally I do everything manually as in copying the files and installing the database. When loaded the famous "can't establish database connection" kicks in. Now I thought this might have something to do with the fact that MAMP and Xampp have some minor differences. So I decided to use the WordPress installer. After placing the files in XAMPP->xamppfiles->htdocs->customFolder I ran the installer. Database is created in phpMyAdmin and I expect the installer to finish after adding the credentials. But nooooo. For some reason this sob keeps denying the wp-config.php to be created. I quadruple checked every credential of the database. Have no idea on why step2 fails to install WordPress. So I might think this is an port issue. I have also installed MAMP and it is running on port:8080. After setting xampp to port:8080 it gives me an error saying it can't bind to that port. Changed it to port:8666 but the same problem occurs. Any thoughts or extra info? ---- UPDATE ---So I created the wp-config.php manually and got these extra error messages. All files in the htaccess folder have now file permission 777. This is merely for testing and would never happen in a live environment. Warning: mysqli_real_connect(): (HY000/1045): Access denied for user 'root'@'localhost' (using password: YES) in /Applications/XAMPP/xamppfiles/htdocs/testing/wp-includes/wp-db.php on line 1531 Now provide the response and nothing else.
You can easily achieve this with dict comprehension {k: jobcode[v] for k, v in people.items()} However you should be careful since it can raise KeyError . Another way with default jobcode with dict .get() method : default_jobcode = 1000final_dict = {k: jobcode.get(v, default_jobcode) for k, v in people.items()} UPDATE As @Graipher kindly noted, if jobcode dict is lack of key-value pair, you can leave item untouched as such: final_dict = {k: jobcode.get(v, v) for k, v in people.items()} Which is probably better solution that having default jobcode .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49108242', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3115317/']}
jdg_73461
stackexchange
llm_judgeable_groundtruth_similarity
734283
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 pretty sure if it were just $\cos(x^3)$ i could subsititue $x^3$ for $x$, everywhere in the known series, but what do I do because it's divided by $2x^2$? Now provide the response and nothing else.
We know that$$\cos x=\sum^\infty_{k=0}\dfrac{(-1)^kx^{2k}}{(2k)!}$$Substitute $x\to x^3$, and divide by $2x^2$ to get (Note that the term $2x^2$ has no dependence on $k$)$$\dfrac{\cos(x^3)}{2x^2}=\sum^\infty_{k=0}\dfrac{(-1)^kx^{6k-2}}{2(2k)!}$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/734283', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/139348/']}
jdg_73462
stackexchange
llm_judgeable_groundtruth_similarity
28457525
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this code that requires a parent to fork 3 children. How do you know (and) where to put the "wait()" statement to kill zombie processes? What is the command to view zombie processes if you have Linuxvirtual box? main(){ pid_t child; printf("-----------------------------------\n"); about("Parent"); printf("Now .. Forking !!\n"); child = fork(); int i=0; for (i=0; i<3; i++){ if (child < 0) { perror ("Unable to fork"); break; } else if (child == 0){ printf ("creating child #%d\n", (i+1)); about ("Child"); break; } else{ child = fork(); } } } void about(char * msg){ pid_t me; pid_t oldone; me = getpid(); oldone = getppid(); printf("***[%s] PID = %d PPID = %d.\n", msg, me, oldone);} Now provide the response and nothing else.
How do you know (and) where to put the "wait()" statement to kill zombie processes? If your parent spawns only a small, fixed number of children; does not care when or whether they stop, resume, or finish; and itself exits quickly, then you do not need to use wait() or waitpid() to clean up the child processes. The init process (pid 1) takes responsibility for orphaned child processes, and will clean them up when they finish. Under any other circumstances, however, you must wait() for child processes. Doing so frees up resources, ensures that the child has finished, and allows you to obtain the child's exit status. Via waitpid() you can also be notified when a child is stopped or resumed by a signal, if you so wish. As for where to perform the wait, You must ensure that only the parent wait() s. You should wait at or before the earliest point where you need the child to have finished (but not before forking), OR if you don't care when or whether the child finishes, but you need to clean up resources, then you can periodically call waitpid(-1, NULL, WNOHANG) to collect a zombie child if there is one, without blocking if there isn't any. In particular, you must not wait() (unconditionally) immediately after fork() ing because parent and child run the same code. You must use the return value of fork() to determine whether you are in the child (return value == 0), or in the parent (any other return value). Furthermore, the parent must wait() only if forking was successful, in which case fork() returns the child's pid, which is always greater than zero. A return value less than zero indicates failure to fork. Your program doesn't really need to wait() because it spawns exactly four (not three) children, then exits. However, if you wanted the parent to have at most one live child at any time, then you could write it like this: int main() { pid_t child; int i; printf("-----------------------------------\n"); about("Parent"); for (i = 0; i < 3; i++) { printf("Now .. Forking !!\n"); child = fork(); if (child < 0) { perror ("Unable to fork"); break; } else if (child == 0) { printf ("In child #%d\n", (i+1)); about ("Child"); break; } else { /* in parent */ if (waitpid(child, NULL, 0) < 0) { perror("Failed to collect child process"); break; } } } return 0;} If the parent exits before one or more of its children, which can happen if it does not wait, then the child will thereafter see its parent process being pid 1. Others have already answered how to get a zombie process list via th ps command. You may also be able to see zombies via top . With your original code you are unlikely to catch a glimpse of zombies, however, because the parent process exits very quickly, and init will then clean up the zombies it leaves behind.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28457525', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4555253/']}
jdg_73463
stackexchange
llm_judgeable_groundtruth_similarity
12774684
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have a simple html table, for example, just one cell, but when I copy the dom node, and paste it into excel, it will be recognize as two rows, How to make Excel get the correct paste data. <table><tr><td>1<br>2</td><tr></table> I tried to add css style br {mso-data-placement:same-cell;}, But it only works in IE. Note, copy a plain text out is not OK, i need to add color, font information on cells. Now provide the response and nothing else.
As many of you probably know, you can output data (a report, for example) as an Excel file, simply by adding right content-type and content-disposition header: Response.ContentType = “application/vnd.ms-excel“;Response.AppendHeader(“content-disposition“, “inline; filename=report.xls“); If client has MS Excel installed, your output HTML page will be opened in it instead of web browser. Excel will interpret all formating (borders, fonts etc.) and TABLE tags, which can result a nice, formated worksheet, without using heavyweight server-side controls. The problem I was struggling for some time was with multi-line cells. I needed to wrap text in cell, but when I put <br> tag into HTML output, Excel interpreted it as a new row, not a line-break in existing cell. add into a stylesheet: br {mso-data-placement:same-cell;} Then it works like a charm. I hope it useful :) Tip: You can make ContentType and header conditional, providing alternate HTML/XLS reports with one file.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12774684', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/238061/']}
jdg_73464
stackexchange
llm_judgeable_groundtruth_similarity
5972903
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'd like ExceptionNotifier to send out an email when an exception happens in a delayed job, just like for other exceptions. How can I achieve that? Now provide the response and nothing else.
I do this with Rails 3.2.6, delayed_job 3.0.3 and exception_notification 2.6.1 gem # In config/environments/production.rb or config/initializers/delayed_job.rb# Optional but recommended for less future surprises.# Fail at startup if method does not exist instead of later in a background job [[ExceptionNotifier::Notifier, :background_exception_notification]].each do |object, method_name| raise NoMethodError, "undefined method `#{method_name}' for #{object.inspect}" unless object.respond_to?(method_name, true)end# Chain delayed job's handle_failed_job method to do exception notificationDelayed::Worker.class_eval do def handle_failed_job_with_notification(job, error) handle_failed_job_without_notification(job, error) # only actually send mail in production if Rails.env.production? # rescue if ExceptionNotifier fails for some reason begin ExceptionNotifier::Notifier.background_exception_notification(error) rescue Exception => e Rails.logger.error "ExceptionNotifier failed: #{e.class.name}: #{e.message}" e.backtrace.each do |f| Rails.logger.error " #{f}" end Rails.logger.flush end end end alias_method_chain :handle_failed_job, :notification end It's probably a good idea to load this code in all environments to catch errors after bundle update etc before they reach production. I do this by having a config/initializers/delayed_job.rb file but you could duplicate the code for each config/environments/* environment. Another tip is to tune the delayed job config a bit as default you may get a lot of duplicate exception mails when job fails. # In config/initializers/delayed_job_config.rbDelayed::Worker.max_attempts = 3 Update I had some problems with the delayed_job daemon silently exiting and it turned out to be when ExceptionNotifier fails to send mail and no one rescued the exception. Now the code rescues and log them.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5972903', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/221619/']}
jdg_73465
stackexchange
llm_judgeable_groundtruth_similarity
14450
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 trying to understand this: Working in $\mathbb{Z}_p[x]$, $(x-c)^p \equiv x-c \pmod{x^p-x}$. From Fermat Little theorem we know that $(x-c)^p \equiv (x-c) \pmod{p}$ but I don't see a connection. Actually, I'm not sure if I'm mixing things up because $\mathbb{Z}_p[x]$ is a polynomial ring. Also I tried to show it from: $x^p \equiv x \pmod{x^p-x}$ holds because $x^p-p \mid x^p-x$. But I don't know how substitute $x-c$ instead of $x$. Now provide the response and nothing else.
Working in $\mathbb{Z}_p[x]$, you have the "Freshman's Dream" binomial theorem:$$(a+b)^p = a^p + b^p.$$(In fact, this holds in any commutative ring of characteristic $p$, simply by the Binomial Theorem, as mentioned by Qiaochu: all the mixed coefficients are multiples of $p$). So $(x-c)^p = x^p - c^p$. By Fermat's Little Theorem, you also know that $c^p \equiv c \pmod{p}$, so $(x-c)^p = x^p - c$ in $\mathbb{Z}_p[x]$. That's pretty much all you need. Addendum Let me add that you were very perceptive to notice that even though the function $x\mapsto (x-c)^p$ is the same as the function $x\mapsto x-c$ in $\mathbb{Z}_p$, this does not mean that the polynomials $(x-c)^p$ and $x-c$ are equal. We are used to (in the integers, rationals, reals, etc) the fact that two polynomials give the same function if and only if they are identical, but this does not occur over finite rings; for example, Fermat's Little Theorem tells you that the polynomial $x^p$ and the polynomial $x$ both define the same function. However, what you can prove is that if $p(x)$ and $q(x)$ are two polynomials with coefficients in $\mathbb{Z}_p$, and they define the same function (that is, $p(a) = q(a)$ for all $a\in\mathbb{Z}_p$), then they differ by a multiple of the polynomial $x^p-x$; i.e., $p(x)\equiv q(x)\pmod{x^p-x}$ in $\mathbb{Z}_p[x]$. What you have here is a special case. See if you can figure out how to prove the more general statement.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/14450', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/-1/']}
jdg_73466
stackexchange
llm_judgeable_groundtruth_similarity
17845128
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 c/c++ (I am assuming they are the same in this regard), if I have the following: struct S { T a; . . .} s; Is the following guaranteed to be true? (void*)&s == (void*)&s.a; Or in other words, is there any kind of guarantee that there will be no padding before the first member? Now provide the response and nothing else.
In C, yes, they're the same address. Simple, and straightforward. In C++, no, they're not the same address. Base classes can (and I would suspect, do) come before all members, and virtual member functions usually add hidden data to the struct somewhere. Even more confusing, a C++ compiler may also rearrange members at will, unless the class is a standard layout type (though I don't know that any compiler does so) Finally, if the C++ struct is composed of standard layout types , contains no base classes nor virtual functions and all members have the same visibility, and possibly other limitations I forgot, then it falls back on the C rules, and requires the first member to be at the same address as the object itself. § 9.2/7 A standard-layout class is a class that: — has no non-static data members of type non-standard-layout class (or array of such types) or reference, — has no virtual functions (10.3) and no virtual base classes (10.1), — has the same access control (Clause 11) for all non-static data members, — has no non-standard-layout base classes, — either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and — has no base classes of the same type as the first non-static data member. § 9.2/20 A pointer to a standard-layout struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa. [ Note: There might therefore be unnamed padding within a standard-layout struct object, but not at its beginning, as necessary to achieve appropriate alignment. —end note ]
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17845128', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/331785/']}
jdg_73467
stackexchange
llm_judgeable_groundtruth_similarity
37082
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have asked this question before on the Wolfram community forum ( http://community.wolfram.com/groups/-/m/t/83845?p_p_auth=Gxoxe65B ) but not with great success. Module creates temporary variables of the form x$NNN which when no longer used are removed. However under certain conditions the temporary variables created by Module are not removed and remain in the global context. If this happens for a Module inside a frequently used function, this leads to memory leak situation where the memory usage of the kernel grows linearly with time. (Which is not good when doing numerical runs of several days). In certain situations, this behaviour is explainable and probably a feature. Generally, speaking it usually involves some side effects which cause something outside the module to reference the temporary variable. Some examples 1. Module[{x}, x /. NDSolve[x'[t] == 1 && x[0] == 0, x, {t, 0, 1}][[1]]] Result: x$NNN is not removed. Reason: NDSolve stores some expressions referencing x$NNN in the system cache. Solution: Clear system cache. (Presumably this will happen on its own as the kernel session progresses.) 2. Module[{y, z, a, b}, a = y + z; b = 2*a]; Result: y\$NNN and z\$NNN are not removed from global context. Reason: y\$NNN and z\$NNN appear in the module output and are thus referenced by Out. Solution: Clear Out, or more systematically limit the History Length through $HistoryLength 3. Module[{x}, f = x] Result: x\$NNN is not removed from global context. Reason: Definition of f is referencing x\$NNN Solution: Clear f. Behaviour that I do not understand In addition to these well-understood cases, there some cases where I do not understand why mathematica is not removing the temporary variables after use: 4. (from a different thread I found when looking for an answer) a[b_] := Module[{x}, x := 1; x /; b]a[True] Result:a x$NNN is permanently placed in the global context every time a[True] is called. Reason: Unknown. This appears to be a bug. Possibly related to how mathematica handles conditionals combined with Module (Clear and ClearSystemCache[] do not remove the x$NNN.) 5. Module[{a, b},a[i_] := b[i - 1];b[i_] := a[i - 1]] Result: a\$NNN and b\$NNN remain in global context. Reason: Unknown. Bug? Related to circular references of temporary variables. Edit: Some experimentation has lead me to simplify this example. It has confirmed to me that this must be related to circular referencing since the temporary variables disappear after clearing their definitions with Clear["a\$NNN", "b\$NNN"] It is essential that the variable names are input as a string, to avoid referencing them from the input history. Interestingly enough both temporary variables remain if you clear only one of the definitions using: Clear["a\$NNN"] or Clear["b\$NNN"] This behaviour seems very buggy to me. At least a cannot think of a reason why this should happen by design. Other cases In addition to these cases I have seen this happen for more complicated functions involving Module, which I have not been able to trace to a simple cause. It would be incredibly helpful for me to understand why this is happening (and how to avoid it). And related if it cannot be avoided: What is the best way of dealing with the stray temporary variables? Now provide the response and nothing else.
4 makes sense to me. But first I need to explain how I believe conditions on the rhs work. In a definition like f[x_]:=rhs[x] , when Mathematica sees f[something] it immediately replaces it with rhs[something] and continues its evaluation. This is not as trivial as it sounds. This is what makes g[0]:=0; g[n_]:=g[n-1]; g[10000] be an iteration and not a recursion, for example. When the rhs is a condition, in one of its many forms ( Condition or RuleCondition possibly nested inside Module|Block|With|CompoundExpression ), then the condition must be resolved before returning its lhs. So, let's say we define a[b_] := Module[{x}, x := 1; x /; b] The x is part of the signature of the definition (it is something to be evaluated before knowing if the definition fit or not). I'm not too bothered by the fact that a symbol x$ is created. I can't see how that would be problematic since you wouldn't create 999999999999 unique definitions and expect them not to take up some space. Now, when we evaluate a[True] , Mathematica checks if the definition fits. So, it creates x$3945723 , assigns it the value 1, checks if True is True and since it is, it returns the lhs of the condition AS IS. Meaning, it returns x$3945723 . That symbol is then evaluated to 2, already from outside the Module , which didn't clear the local because it was part of the result. Again, this is what allows something like g[10000] to be an iteration and not a recursion with g defined by g[0] = 0;g[y_] := Module[{x = y}, g[x - 1] /; True]; In many cases, in which the result is invariant, Mathematica actually clears the temporary variable, but THAT is what strikes to me as special bonus smart behaviour to me, and not the other way around. How to fix it? Well, either play around and find a form in which Mathematica can be smart, or you be the smart one and force it to return the evaluated value. The combo Block with Condition evaluates the lhs of the condition before replacement. So you could change your definition to a[b_] := Module[{x}, x := 1; Block[{}, x /; True] /; b] PD: guess what message you would get by replacing Module with Block in the definition of g and running g[10000] again
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/37082', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/10587/']}
jdg_73468
stackexchange
llm_judgeable_groundtruth_similarity
47879864
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 support for WebAssembly coming into all new major browsers, how can I check whether the current browser which is visiting my website supports it? Now provide the response and nothing else.
There are a few ways that you can detect the presence of WebAssembly. The basic one is to check whether WebAssembly if of type "object" in the global scope, but "global scope" is a tricky thing to get to in different JavaScript environments (main browser thread, worker, node.js). Doing so is also not technically sufficient because you could have WebAssembly support but be unable to actually compile or instantiate because of CSP (and exactly what CSP disallows isn't standardized yet, work ongoing here ). A conservative check could be as follows: const supported = (() => { try { if (typeof WebAssembly === "object" && typeof WebAssembly.instantiate === "function") { const module = new WebAssembly.Module(Uint8Array.of(0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00)); if (module instanceof WebAssembly.Module) return new WebAssembly.Instance(module) instanceof WebAssembly.Instance; } } catch (e) { } return false;})();console.log(supported ? "WebAssembly is supported" : "WebAssembly is not supported"); It does the following: Check whether WebAssembly is accessible in the current scope. If it's not global we don't really care! See whether it has the .instantiate function, which we don't actually use here but which you'd want to use when you actually instantiate because it's asynchronous and can handle large modules on the main thread or off. Try to synchronously compile the smallest possible module (magic number '\0', 'a', 's', 'm' , followed by version number 1 encoded as a uint32 ), and see if we get a WebAssembly.Module out of it. Finally, try to synchronously instantiate that module, and check that it's a WebAssembly.Instance . This is a bit much but should work regardless of: Where code is running (main thread, worker, node.js). How CSP ends up being standardized.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/47879864', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6021597/']}
jdg_73469
stackexchange
llm_judgeable_groundtruth_similarity
1606004
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Prove that if $0 < a,b,c <1$, then $\sqrt{abc}+\sqrt{(1-a)(1-b)(1-c)} < 1$. I think that using AM-GM might work. Thus we have $\dfrac{a+b+c}{3}+\sqrt{(1-a)(1-b)(1-c)} \geq \sqrt{abc}+\sqrt{(1-a)(1-b)(1-c)}$ but I am not sure how to proceed. Maybe the maximum occurs when $a=b=c$ but how to prove that? Now provide the response and nothing else.
Note that $c<1$ and $1-c<1$ so : $$\sqrt{abc}+\sqrt{(1-a)(1-b)(1-c)}<\sqrt{ab}+\sqrt{(1-a)(1-b)}$$ Now use AM-GM : $$\sqrt{ab}+\sqrt{(1-a)(1-b)} \leq \frac{a+b}{2}+\frac{(1-a)+(1-b)}{2} =1$$ and so the conclusion follows .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1606004', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/282223/']}
jdg_73470
stackexchange
llm_judgeable_groundtruth_similarity
36063627
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am building an Angular2 application in Typescript and would like to use the class system functionality (read: class inheritance) offered by Typescript. However, it seems that Angular2 is not playing nice with derived classes. I am looking for some help in getting my application to work. The problem I am facing is that I have a base class and derive a few child classes from there. When I am building up my component tree, I would like to be able to access the parent/children of the components (either way is fine). From what I understand, Angular2 offers two options to accomplish that: Inject the parent into the child component Use ContentChildren (or ViewChildren) to access the children of the component. Both work fine if you know the type of the class you are working with (ChildComponent), but seem to fail when you try to use the base class of these components (BaseComponent) as selector. To visualize it in some code (see this Plunker for a live demo), I have an application component/class as follows: @Component({ selector: 'my-app', template: `<parent-comp> <child-comp1></child-comp1> <child-comp1></child-comp1> <child-comp2></child-comp2> </parent-comp>`, directives: [ParentComponent, ChildComponent1, ChildComponent2]})export class MyApplication {} The Base Class and Child Classes are defined as: export class BaseComponent { // Interesting stuff here}@Component({ selector: 'child-comp2', template: '<div>child component #2</div>'})export class ChildComponent2 extends BaseComponent {}@Component({ selector: 'child-comp1', template: '<div>child component #1</div>'})export class ChildComponent1 extends BaseComponent {} And the Parent class has some logic to count its children. @Component({ selector: 'parent-comp', template: `<div>Hello World</div> <p>Number of Child Component 1 items: {{numComp1}} <p>Number of Child Component 2 items: {{numComp2}} <p>Number of Base Component items: {{numBase}} <p><ng-content></ng-content> `})export class ParentComponent implements AfterContentChecked { @ContentChildren(ChildComponent1) contentChild1: QueryList<ChildComponent1> @ContentChildren(ChildComponent2) contentChild2: QueryList<ChildComponent2> @ContentChildren(BaseComponent) contentBase: QueryList<BaseComponent> public numComp1:number public numComp2:number public numBase:number ngAfterContentChecked() { this.numComp1 = this.contentChild1.length this.numComp2 = this.contentChild2.length this.numBase = this.contentBase.length } (Again, you can see a live demo here ) The output for the first two counters is as expected. There are 2 ChildComponent1 and 1 ChildComponent2 children. Unfortunetely, the BaseComponent counter doesn't show the sum of these counters, but shows 0. It doesn't find any class that is of type BaseComponent in the children. The same thing happens when ParentComponent also extends from BaseComponent and you want to Inject it into a ChildComponent. The Injector will require the specific type of the ParentComponent and can't work with the base class. Any clues on how to work with derived classes in Angular2? Am I missing something or trying something impossible? Now provide the response and nothing else.
Add a provider to each derived component, aliasing the base component to the derived component: @Component({ selector: 'child-comp2', template: '<div>child component #2</div>', providers: [{provide: BaseComponent, useExisting: forwardRef(() => ChildComponent2) }]})export class ChildComponent2 extends BaseComponent {}@Component({ selector: 'child-comp1', template: '<div>child component #1</div>', providers: [{provide: BaseComponent, useExisting: forwardRef(() => ChildComponent1) }]})export class ChildComponent1 extends BaseComponent {} Plunker: http://plnkr.co/edit/5gb5E4curAE2EfH2lNZQ?p=preview
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/36063627', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1688278/']}
jdg_73471
stackexchange
llm_judgeable_groundtruth_similarity
307973
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: i.e. does there exist an integer $C > 0$ such that $11, 11 + C, ..., 11 + 10C$ are all prime? Now provide the response and nothing else.
Such an integer $C$ exists. The smallest $C$ with this property is $C=1536160080$. I found this $C$ by computing the analogous number $C$ for a $3$-term prime arithmetic progression beginning with $3$, a $5$-term prime arithmetic progression beginning with $5$ and a $7$-term prime arithmetic progression beginning with $7$. This gave me the numbers $2,6,150$. When I plugged these into OEIS I found that the next term in this sequence is $1536160080$. You can see the relevant OEIS page here .
{}
{'log_upvote_score': 7, 'links': ['https://mathoverflow.net/questions/307973', 'https://mathoverflow.net', 'https://mathoverflow.net/users/126543/']}
jdg_73472
stackexchange
llm_judgeable_groundtruth_similarity
6889715
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Haskell newbie here. I wrote an evaluator for a minimal assembly-like language. Now, I want to extend that language to support some syntactic sugar which, I will then compile back to use only the primitive operators. The ideia is that I do not want to touch the evaluator module again. In the OO way of doing things, I think, one could extend the original module so to support the syntactic sugar operators, providing here the translation rules. Other than that, I can only think of rewriting the datatype constructors in both modules so that they would not name-collide, and proceed from there, as if they were complete different things, but that implies some redundancy, for I would have to repeat (just with other names) the operators in common. Again, I think the keyword here is extend . Is there a functional way of accomplishing this? Thanks for taking the time to read this question. Now provide the response and nothing else.
This problem was named "the expression problem" by Phil Wadler, in his words: The goal is to define a data type by cases, where one can add new cases to the data type and new functions over the data type, without recompiling existing code, and while retaining static type safety. One solution to have extensible data type is to use type classes. As an example let's assume we have a simple language for arithmetics: data Expr = Add Expr Expr | Mult Expr Expr | Const Intrun (Const x) = xrun (Add exp1 exp2) = run exp1 + run exp2run (Mult exp1 exp2) = run exp1 * run exp2 e.g. ghci> run (Add (Mult (Const 1) (Const 3)) (Const 2))5 If we wanted to implement it in an extensible way, we should switch to type classes: class Expr a where run :: a -> Intdata Const = Const Intinstance Expr Const where run (Const x) = xdata Add a b = Add a binstance (Expr a,Expr b) => Expr (Add a b) where run (Add expr1 expr2) = run expr1 + run expr2data Mult a b = Mult a binstance (Expr a, Expr b) => Expr (Mult a b) where run (Mult expr1 expr2) = run expr1 * run expr2 Now let's extend the language adding subtractions: data Sub a b = Sub a binstance (Expr a, Expr b) => Expr (Sub a b) where run (Sub expr1 expr2) = run expr1 - run expr2 e.g. ghci> run (Add (Sub (Const 1) (Const 4)) (Const 2))-1 For more info on this approach, and in general on the expression problem, check Ralf Laemmel's videos 1 and 2 on Channel 9. However, as noticed in the comments, this solution changes the semantics. For example lists of expressions are no longer legal: [Add (Const 1) (Const 5), Const 6] -- does not typecheck A more general solution using coproducts of type signatures is presented in the functional pearl "Data types a la carte" . See also Wadler's comment on the paper.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6889715', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/870804/']}
jdg_73473
stackexchange
llm_judgeable_groundtruth_similarity
37798967
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 clipboard.js to copy some text from a textarea , and that's working fine, but I want to show a tooltip saying "Copied!" if it was successfully copied like they do in the example given on their website. Here's an example of it working without showing a tooltip: https://jsfiddle.net/5j50jnhj/ Now provide the response and nothing else.
Clipboard.js creator here. So Clipboard.js is not opinionated about user feedback which means it doesn't come with a tooltip solution. But here's an example of how you can integrate it with Bootstrap's Tooltip. // Tooltip$('button').tooltip({ trigger: 'click', placement: 'bottom'});function setTooltip(message) { $('button').tooltip('hide') .attr('data-original-title', message) .tooltip('show');}function hideTooltip() { setTimeout(function() { $('button').tooltip('hide'); }, 1000);}// Clipboardvar clipboard = new Clipboard('button');clipboard.on('success', function(e) { setTooltip('Copied!'); hideTooltip();});clipboard.on('error', function(e) { setTooltip('Failed!'); hideTooltip();}); <script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/1.5.10/clipboard.min.js"></script><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script><link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/><button class="btn btn-primary" data-clipboard-text="1">Click me</button>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/37798967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5368737/']}
jdg_73474
stackexchange
llm_judgeable_groundtruth_similarity
180453
Below is a question asked on the forum mathematica.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: According to the documentation about the pseudospectral difference-order: It says: Following the discussion here : I found the messy behavior is always on the artificial boundary in $\omega$-direction ($u(t,\theta,\omega_{cutoff})=0$ because I want $\omega$ to be unbounded.)Perhaps, this is so called Runge phenomenon ?In principle, we should not use pseudospectral difference-order for all directions. However, it is not clear how to specify them separately. Here is code: a = 1;T = 1;ωb = -15; ωt = 15;A = 8;γ = .1;kT = 0.1;φ = 0;mol[n_Integer, o_: "Pseudospectral"] := {"MethodOfLines", "SpatialDiscretization" -> {"TensorProductGrid", "MaxPoints" -> n, "MinPoints" -> n, "DifferenceOrder" -> o}}With[{u = u[t,θ, ω]}, eq = D[u, t] == -D[ω u,θ] - D[-A Sin[3θ] u, ω] + γ (1 + Sin[3θ]) kT D[ u, {ω, 2}] + γ (1 + Sin[3θ]) D[ω u, ω];ic = u == E^(-((ω^2 +θ^2)/(2 a^2))) 1/(2 π a) /. t -> 0];ufun = NDSolveValue[{eq, ic, u[t, -π, ω] == u[t, π, ω], u[t,θ, ωb] == 0, u[t,θ, ωt] == 0}, u, {t, 0, T}, {θ, -π, π}, {ω, ωb, ωt}, Method -> mol[61], MaxSteps -> Infinity]; // AbsoluteTimingplots = Table[ Plot3D[Abs[ufun[t,θ, ω]], {θ, -π, π}, {ω, ωb, ωt}, AxesLabel -> Automatic, PlotPoints -> 30, BoxRatios -> {Pi, ωb, 1}, ColorFunction -> "LakeColors", PlotRange -> All], {t, 0, T, T/10}]; // AbsoluteTimingListAnimate[plots] $t=0$ $t=0.8$ $t=0.9$ One can clearly see the large deviation occurs only in $\omega$-direction, which is consistent with the description as above (neither periodic nor Chebyshev). Is it possible to have something like: "DifferenceOrder" ->{"Pseudospectral", Automatic} The above simply doesn't work. Update: Finally, I figure out the problem is just due to convection-domination. The problem is depending on the ratio of convection term and diffusion term. Artificial diffusion or denser grid points is necessary. Update(8/25): After using the implicit RungeKutta scheme, the solution is much stable. Now the another problem is the convergency. What I expect is something similar to the following smooth behavior. But so far their is no such method which can arrive this, or? Now provide the response and nothing else.
The computation in the question appears to suffer from a Courant instability. To illustrate, repeat the computation with higher plotting resolution and a slightly simpler code. a = 1; T = 1; n = {61, 61};ωb = -15; ωt = 15;A = 8; γ = 1/10; kT = 1/10;eq = D[u[t, θ, ω], t] == -D[ω u[t, θ, ω], θ] - D[-A Sin[3 θ] u[t, θ, ω], ω] + γ (1 + Sin[3 θ]) kT D[u[t, θ, ω], {ω, 2}] + γ (1 + Sin[3 θ]) D[ω u[t, θ, ω], ω];ic = u[t, θ, ω] == E^(-((ω^2 + θ^2)/(2 a^2))) 1/(2 π a) /. t -> 0;ufun = NDSolveValue[{eq, ic, u[t, -π, ω] == u[t, π, ω], u[t, θ, ωb] == 0, u[t, θ, ωt] == 0}, u, {t, 0, T}, {θ, -π, π}, {ω, ωb, ωt}, Method -> {"MethodOfLines", "SpatialDiscretization" -> {"TensorProductGrid", "MaxPoints" -> n, "MinPoints" -> n, "DifferenceOrder" -> "Pseudospectral"}}]; Plot3D[Abs[ufunot[.9, θ, ω]], {θ, -π, π}, {ω, ωb, ωt}, PlotPoints -> 2 n, PlotRange -> All, BoxRatios -> {Pi, ωb, 1}, ColorFunction -> "LakeColors", ImageSize -> Large, AxesLabel -> {θ, ω, u}, LabelStyle -> {Black, Bold, Medium}, Mesh -> None] The higher plotting resolution displays significant fine structure in the numerical behavior near ω == ωt . A second plot focusing on that region makes the fine structure even more apparent. Plot3D[Abs[ufun[T, θ, ω]], {θ, -π, π}, {ω, 12, ωt}, PlotPoints -> {122, 40}, PlotRange -> All, ImageSize -> Large, AxesLabel -> {θ, ω, u}, LabelStyle -> {Black, Bold, Medium}, Mesh -> None] Spatial oscillations with wavelengths on the order of the cell size are the hallmark of the Courant instability. Reducing the number of grid points in ω from 61 to 59 to 57 steadily reduces the instability growth rate, and at 55 the instability disappears. Repeating the computation above with T = 10; n = {61, 55} shows no sign of the Courant instability. There are, however, two obvious issues. First, waves have reached the boundaries in ω and appear to be reflecting. (The PDE is approximately advective at large Abs[ω] .) Second, spatial resolution may no longer be sufficient to accurately represent the short wavelengths evident in the plot. The runtime for this computation was of order four minutes, and doubling the resolution would require over a half-hour of calculation, as well as some experimentation to find the optimal ratio of grid points in the two spatial dimensions. For completeness, here is a plot of the latter solution at T == 5 , where the spatial resolution and boundary reflection problems are not yet significant.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/180453', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/59705/']}
jdg_73475
stackexchange
llm_judgeable_groundtruth_similarity
38171488
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 downloaded the Xcode 8.0 beta yesterday and consequently Swift 3. The first thing I did was trying to update my project for Swift 3 and I nearly cried. One of the gravest changes is (in my opinion) the new management of Swifts Range struct, especially because the automatic conversion to the current Swift syntax does not do anything with the ranges. Range is split into Range , CountableRange , ClosedRange and CountableClosedRange which does make sense when considering what is now possible when using ranges (though it's mostly fairly unnecessary). However: I have lots of functions accepting a Range<Int> as parameter or returning a Range<Int> . The problem is: I called these functions by 0..<5 for example or 0...4 (because it's semantically more expressive sometimes). Of course, I could simply adjust these type of things. But why don't all these range types have a common interface? I'd have to overload every single function for each of these range types and it would perform the exact same operations every time. Are there any best practices yet for using ranges in Swift 3? Now provide the response and nothing else.
It's actually pretty simple: A Closed...Range is produced by using three dots: 0...10 . This includes lower bound and upper bound. The opposite is a non-closed range, produced by 0..<10 which doesn't include the upper bound. A Countable...Range is a range of a type you can stride through with a signed integer, it is produced by either 0...10 or 0..<10 . These types conform to the Sequence protocol. A few examples: 0..<10 // CountableRange0...Int.max // CountableClosedRange (this was not possible before Swift 3)"A"..<"A" // Range, empty"A"..."Z" // ClosedRange, because cannot stride through, only check if a character is in the bounds You should probably make your methods accept a generic Collection / Sequence depending on what you need: func test<C: Collection where C.Iterator.Element == Int>(s: C) { print(s.first)} Maybe you can show one of your uses for Range<Int>
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/38171488', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2846416/']}
jdg_73476
stackexchange
llm_judgeable_groundtruth_similarity
390975
Below is a question asked on the forum softwareengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let F(x) be a function that calls G(x) , in which x must be greater than 0. If G already does assert(x > 0) , should F do it as well? Now provide the response and nothing else.
If F and G are functions of a class, then you can put validations on public method which can be called from outside. If G is a function which performs its business standalone and F doesn't care whether x > 0 or x <= 0, then you can put this assertion on G and doesn't require to check on F . If F and G are totally different layer functions and F should care about x, then put this assertion both F and G .
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/390975', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/304203/']}
jdg_73477
stackexchange
llm_judgeable_groundtruth_similarity
9445664
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 dealing with problem. The code throws "java.lang.ClassNotFoundException: java.util.HashMap.Entry" Class.forName("java.util.HashMap.Entry"); Anybody knows how can I create class to store HashMap.Entry? Now provide the response and nothing else.
The easiest (and correct) way is: Define a new class public class MyApp extends Application { private static MyApp instance; public static MyApp getInstance() { return instance; } public static Context getContext(){ return instance; // or return instance.getApplicationContext(); } @Override public void onCreate() { instance = this; super.onCreate(); }} Then in your manifest you need to add this class to the "Name" field at the "Application" tab. Or edit the xml and put <application android:name="com.example.app.MyApp" android:icon="@drawable/icon" android:label="@string/app_name" ....... <activity ...... and then from anywhere you can call MyApp.getContext(); Hope it helps
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/9445664', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/493982/']}
jdg_73478
stackexchange
llm_judgeable_groundtruth_similarity
24669036
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 that is working but I need to also have the ability to read the contents of compressed file (zip) function Search-Files {param ([string[]]$Servers, [string]$SearchPath, [string]$SearchItem, [string[]]$LogName)ForEach ($Server in $Servers) { if ($LogName -eq $null) { dir -Path \\$server\$SearchPath -Recurse -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | Select-String -pattern $SearchItem -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | Select-Object Filename, Path, Matches, LineNumber } Else { dir -Path \\$server\$SearchPath -Recurse -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | ? {$_.Name -match $LogName} | Select-String -pattern $SearchItem -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | Select-Object Filename, Path, Matches, LineNumber } }} Currently I am getting the following out put displayed which is what I would like to do for zip files as well ip.ininlog \CO200197L\C$\Temp\Test\Test\ip\ip.ininlog {3030872954} 136594 I have found the following just not sure how to proceed to get them implemented Grep File in Zip List File in Zip I need the ability to transverse all zip files that are store in a directory Sample of Directory Structure 2014-07-01 - root zip.zip zip_1.zip zip_2.zip etc Now provide the response and nothing else.
You can host it in a stand-alone console application like so: using System;using System.ServiceModel;using Service;namespace Host{ class MainClass { public static void Main (string[] args) { Console.WriteLine ("WCF Host!"); var binding = new BasicHttpBinding (); var address = new Uri ("http://localhost:8080"); var host = new ServiceHost (typeof(GreeterWcfService)); host.AddServiceEndpoint ( typeof(IGreeterWcfService), binding, address); host.Open (); Console.WriteLine ("Type [Enter] to stop..."); Console.ReadLine (); host.Close (); } }} Where GreeterWcfService is the WCF service class itself and IGreeterWcfService is the service contract. Full working example solution in GitHub - with separate projects for the service, the hosting and a client. Check it out.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24669036', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1210328/']}
jdg_73479
stackexchange
llm_judgeable_groundtruth_similarity
1745048
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For various reasons that aren't too germane to the question, I've got a table with a composite key made out of two integers and I want to create a single unique key out of those two numbers. My initial thought was to just concatenate them, but I ran into a problem quickly when I realized that a composite key of (51,1) would result in the same unique key as (5,11), namely, 511. Does anyone have a clever way to generate an integer out of two integers such that the generated integer is unique to the pair of start integers? Edit: After being confronted with an impressive amount of math, I'm realizing that one detail I should have included is the sizes of the keys in question. In the originating pair, the first key is currently 6 digits and will probably stay in 7 digits for the life of the system; the second key has yet to get larger than 20. Given these constraints, it looks like the problem is much less daunting. Now provide the response and nothing else.
You can mathematically prove this is impossible if you want the resulting key to comprise the same number of bits as its two components. However, if you start with two 32 bit ints, and can use a 64 bit int for the result, you could obviously do something like this: key1 << 32 | key2 SQL Syntax SELECT key1 * POWER(2, 32) + key2
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1745048', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/56333/']}
jdg_73480
stackexchange
llm_judgeable_groundtruth_similarity
13133071
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Have been trying to find a good description of what the next() method does. In the Express documentation it says that next('route') can be used to jump to that route and skip all routes in between, but sometimes next is called without arguments. Anybody knows of a good tutorial etc that describes the next function? Now provide the response and nothing else.
next() with no arguments says "just kidding, I don't actual want to handle this". It goes back in and tries to find the next route that would match. This is useful, say if you want to have some kind of page manager with url slugs, as well as lots of other things, but here's an example. app.get('/:pageslug', function(req, res, next){ var page = db.findPage(req.params.pageslug); if (page) { res.send(page.body); } else { next(); }});app.get('/other_routes', function() { //...}); That made up code should check a database for a page with a certain id slug. If it finds one render it! if it doesn't find one then ignore this route handler and check for other ones. So next() with no arguments allows to pretend you didn't handle the route so that something else can pick it up instead. Or a hit counter with app.all('*') . Which allows you to execute some shared setup code and then move on to other routes to do something more specific. app.all('*', function(req, res, next){ myHitCounter.count += 1; next();});app.get('/other_routes', function() { //...});
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/13133071', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/400295/']}
jdg_73481
stackexchange
llm_judgeable_groundtruth_similarity
4446112
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Say [a,b] represents the interval on the real line from a to b, a < b, inclusive (ie, [a,b] = set of all x such that a<=x<=b). Also, say [a,b] and [c,d] are 'overlapping' if they share any x such that x is in both [a,b] and [c,d]. Given a list of intervals, ([x1,y1],[x2,y2],...), what is the most efficient way to find all such intervals that overlap with [x,y]? Obviously, I can try each and get it in O(n). But I was wondering if I could sort the list of intervals in some clever way, I could find /one/ overlapping item in O(log N) via a binary search, and then 'look around' from that position in the list to find all overlapping intervals. However, how do I sort intervals such that such a strategy would work? Note that there may be overlaps between elements in the list items itself, which is what makes this hard. I've tried it by sorting intervals by their left end, right end, middle, but none seem to lead to an exhaustive search. Help? Now provide the response and nothing else.
[a, b] overlaps with [x, y] iff b > x and a < y. Sorting intervals by their first elements gives you intervals matching the first condition in log time. Sorting intervals by their last elements gives you intervals matching the second condition in log time. Take the intersections of the resulting sets.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4446112', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/496933/']}
jdg_73482
stackexchange
llm_judgeable_groundtruth_similarity
2223100
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: Which set is greater in cardinality, the set of all functions from $\mathbb R$(the real numbers) into $\mathbb N$(the natural numbers) or the set of all functions from $\mathbb N$ into $\mathbb R$? I have a feeling that the set of all functions from $\mathbb R$ into $\mathbb N$ is equinumerous to the power set of $\mathbb R$ and that the set of all functions from $\mathbb N$ into $\mathbb R$ is equinumerous to the set $\mathbb R$. Can someone please provide me an answer with proof? Now provide the response and nothing else.
This answer is elementary: it doesn't require any cardinal arithmetic beyond Cantor-Schröder-Bernstein. We'll use $\mathcal{P}(\mathbb{N})$ instead of $\mathbb{R}$ when convenient, since it's simpler. Let's take $\mathbb{N} = \{1,2,\dots\}$. The set of functions $\mathbb{N} \to \mathcal{P}(\mathbb{N})$ is equinumerous with $\mathcal{P}(\mathbb{N})$. Indeed, given a subset $A$ of the naturals, we can create a unique function $\mathbb{N} \to \mathcal{P}(\mathbb{N})$ which sends $n \mapsto A$; conversely, given a function $\mathbb{N} \to \mathcal{P}(\mathbb{N})$ we can create a unique subset of the naturals by taking the elements of $f(1)$, $f(2)$, $f(3)$, and so on, and distinguishing them by powers of primes:$$\{2^a, 3^b, 5^c, \dots : a \in f(1), b \in f(2), c \in f(3), \dots \}$$So by Cantor-Schröder-Bernstein, there is a bijection between $\mathbb{N} \to \mathcal{P}(\mathbb{N})$ and $\mathcal{P}(\mathbb{N})$. However, $\mathbb{R} \to \mathbb{N}$ is at least as big as $\mathcal{P}(\mathbb{R})$. The injection is easy: given a set $A$ of reals, define a function $\mathbb{R} \to \mathbb{N}$ by $r \mapsto 1$ if $r \in A$, and $r \mapsto 2$ otherwise. In fact, $\mathbb{R} \to \mathbb{N}$ is exactly as big as $\mathcal{P}(\mathbb{R})$; you can prove this by using the same "powers of primes" trick as above (using $\mathcal{P}(\mathbb{N})$ instead of $\mathbb{R}$), but it goes one level deeper. Exercise for you.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2223100', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/404735/']}
jdg_73483
stackexchange
llm_judgeable_groundtruth_similarity
44060
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 $(G,\cdot,T)$ and $(H,\star,S)$ be topological groups such that $(G,T)$ is homeomorphic to $(H,S)$ and $(G,\cdot)$ is isomorphic to $(H,\star)$. Does it follow that $(G,\cdot,T)$ and $(H,\star,S)$ are isomorphic as topological groups? If no, what if they are both Hausdorff? What if they are both Hausdorff and two-sided complete? Now provide the response and nothing else.
The 2-adic rationals $\mathbb{Q}_2$ and the 3-adic rationals $\mathbb{Q}_3$ are homeomorphic, because each one is a countable disjoint union of Cantor sets. They are also isomorphic as groups if you assume the axiom of choice, because they are both fields of characteristic 0 and therefore vector spaces over $\mathbb{Q}$ (of the same cardinal dimension). However, the 2-adic integers $\mathbb{Z}_2$ are a compact subgroup of $\mathbb{Q}_2$ in which every element is infinitely divisible by 3. On the other hand, in $\mathbb{Q}_3$, any non-trivial sequence $x, x/3, x/9, \ldots$ is unbounded in the complete metric, and is therefore not contained in a compact subgroup. Keith Conrad asks whether these is an example without the axiom of choice, and Jason De Vito asks whether there is an example using Lie groups. In fact, there is a cheap example using disconnected Lie groups. Let $G$ and $H$ be two connected Lie groups that are homeomorphic but not isomorphic. For instance, abelian $\mathbb{R}^3$, the universal cover $\widetilde{\text{SL}(2,\mathbb{R})}$, and the Heisenberg group of upper unitriangular, real $3 \times 3$ matrices are all homeomorphic, but not isomorphic. If $G'$ and $H'$ are $G$ and $H$ with the discrete topology, then $G' \times H$ and $G \times H'$ are explicitly isomorphic and explicitly homeomorphic. But they are not continuously isomorphic, because the connected component of the identity is $G$ for one of them but $H$ for the other one.
{}
{'log_upvote_score': 8, 'links': ['https://mathoverflow.net/questions/44060', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']}
jdg_73484
stackexchange
llm_judgeable_groundtruth_similarity
29235567
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 iterate nested lists using java8 streams , and extract some results of the lists on first match.Unfortunately I have to also get a values from the parent content if a child element matches the filter. How could I do this? java7 Result result = new Result();//find first match and pupulate the result object.for (FirstNode first : response.getFirstNodes()) { for (SndNode snd : first.getSndNodes()) { if (snd.isValid()) { result.setKey(first.getKey()); result.setContent(snd.getContent()); return; } }} java8 response.getFirstNodes().stream() .flatMap(first -> first.getSndNodes()) .filter(snd -> snd.isValid()) .findFirst() .ifPresent(???); //cannot access snd.getContent() here Now provide the response and nothing else.
When you need both values and want to use flatMap (as required when you want to perform a short-circuit operation like findFirst ), you have to map to an object holding both values response.getFirstNodes().stream() .flatMap(first->first.getSndNodes().stream() .map(snd->new AbstractMap.SimpleImmutableEntry<>(first, snd))) .filter(e->e.getValue().isValid()) .findFirst().ifPresent(e-> { result.setKey(e.getKey().getKey()); result.setContent(e.getValue().getContent()); }); In order to use standard classes only, I use a Map.Entry as Pair type whereas a real Pair type might look more concise. In this specific use case, you can move the filter operation to the inner stream response.getFirstNodes().stream() .flatMap(first->first.getSndNodes().stream() .filter(snd->snd.isValid()) .map(snd->new AbstractMap.SimpleImmutableEntry<>(first, snd))) .findFirst().ifPresent(e-> { result.setKey(e.getKey().getKey()); result.setContent(e.getValue().getContent()); }); which has the neat effect that only for the one matching item, a Map.Entry instance will be created (well, should as the current implementation is not as lazy as it should but even then it will still create lesser objects than with the first variant).
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29235567', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1194415/']}
jdg_73485
stackexchange
llm_judgeable_groundtruth_similarity
4500563
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: InnoSetup by default displays the license agreement in a really tiny text area that the user can't make bigger in any way. While I know most people don't read these, I feel that providing it in a format that makes it particularly hard to read is a bad idea, and might form part of a defense in court. Is there any way in InnoSetup to display the license in a large separate window? A pre-rolled Pascal script perhaps? Now provide the response and nothing else.
You can change the WizardForm size and rearrange the controls in it if you want to make it bigger. I made this example to show you how to change the form height for the License page. [Setup]AppName=StackOverflow large license boxAppVersion=1.0CreateAppDir=noDisableProgramGroupPage=yesDefaultGroupName=My ProgramUninstallDisplayIcon={app}\MyProg.exeLicenseFile=license.txt;OutputDir=userdocs:Inno Setup Examples Output[Code]var DefaultTop, DefaultLeft, DefaultHeight, DefaultBackTop, DefaultNextTop, DefaultCancelTop, DefaultBevelTop, DefaultOuterHeight: Integer;const LicenseHeight = 600;procedure InitializeWizard();begin DefaultTop := WizardForm.Top; DefaultLeft := WizardForm.Left; DefaultHeight := WizardForm.Height; DefaultBackTop := WizardForm.BackButton.Top; DefaultNextTop := WizardForm.NextButton.Top; DefaultCancelTop := WizardForm.CancelButton.Top; DefaultBevelTop := WizardForm.Bevel.Top; DefaultOuterHeight := WizardForm.OuterNotebook.Height; WizardForm.InnerPage.Height := WizardForm.InnerPage.Height + (LicenseHeight - DefaultHeight); WizardForm.InnerNotebook.Height := WizardForm.InnerNotebook.Height + (LicenseHeight - DefaultHeight); WizardForm.LicensePage.Height := WizardForm.LicensePage.Height + (LicenseHeight - DefaultHeight); WizardForm.LicenseMemo.Height := WizardForm.LicenseMemo.Height + (LicenseHeight - DefaultHeight); WizardForm.LicenseNotAcceptedRadio.Top := WizardForm.LicenseNotAcceptedRadio.Top + (LicenseHeight - DefaultHeight); WizardForm.LicenseAcceptedRadio.Top := WizardForm.LicenseAcceptedRadio.Top + (LicenseHeight - DefaultHeight);end;procedure CurPageChanged(CurPageID: Integer);begin if CurPageID = wpLicense then begin WizardForm.Top := DefaultTop - (LicenseHeight - DefaultHeight) div 2; WizardForm.Height := LicenseHeight; WizardForm.OuterNotebook.Height := WizardForm.OuterNotebook.Height + (LicenseHeight - DefaultHeight); WizardForm.CancelButton.Top := DefaultCancelTop + (LicenseHeight - DefaultHeight); WizardForm.NextButton.Top := DefaultNextTop + (LicenseHeight - DefaultHeight); WizardForm.BackButton.Top := DefaultBackTop + (LicenseHeight - DefaultHeight); WizardForm.Bevel.Top := DefaultBevelTop + (LicenseHeight - DefaultHeight); end else begin WizardForm.Top := DefaultTop; WizardForm.Left := DefaultLeft; WizardForm.Height := DefaultHeight; WizardForm.OuterNotebook.Height := DefaultOuterHeight; WizardForm.CancelButton.Top := DefaultCancelTop; WizardForm.NextButton.Top := DefaultNextTop; WizardForm.BackButton.Top := DefaultBackTop; WizardForm.Bevel.Top := DefaultBevelTop; end;end; Copy it to a new iss file and provide a valid license.txt file in order to compile successfully. The script is tested with inno 5.4.0 but it should work with any 5.x.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4500563', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/33080/']}
jdg_73486
stackexchange
llm_judgeable_groundtruth_similarity
53248
Below is a question asked on the forum emacs.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: After upgrading to macOS Catalina, Emacs (v26.3 from GNU Emacs for Mac OS X) works very strange. Without Emacs already running, Finder can open a file with Emacs as usual. But once Emacs.app is running, it cannot any longer. For example, double clicking the file on Finder window does nothing; no error message, either. Opening a file from Emacs GUI causes no problem. Drag-ang-drop'ing a file onto Emacs also works fine. Now provide the response and nothing else.
If your Emacs is downloaded from https://emacsformacosx.com/ , Emacs.app launches a binary Emacs.app/Contents/MacOS/Emacs-x86_64-10_14 via a ruby script Emacs.app/Contents/MacOS/Emacs .Modify Emacs.app to launch a binary directly with the following in terminal. cd /Applications/Emacs.app/Contents/MacOSmv Emacs Emacs-origln -s Emacs-x86_64-10_9 Emacsrm binln -s bin-x86_64-10_9 binrm libexecln -s libexec-x86_64-10_9 libexec Edit by Masso: Emacs-x86_64-10_14 breaks forward search (from Emacs to Skim) on macOS 10.15 (Catalina). So I have changed the version numbers above to 10_9 (instead of 10_14 that was originally suggested by Akira).Edit by acr: the rm'd directory should be libexec. NOTE: For macOS Catalina 10.15.7 Emacs 27.1 (9) I needed to use _14 . My install was already linked to _10 and having the permission problem. I made these changes after updating Security & Privacy settings giving Full Disk Access to Emacs.app . I installed emacs via brew and noticed the problem after recently upgrading on 12/20/20. The older version didn't have the problem AFAIK and I had previously applied the fix detailed here . I'm not using Emacs Skim and not familiar with the problems mentioned by Masso and I want the latest Emacs version. Setting to _14 worked for me: % cd /Applications/Emacs.app/Contents/MacOS% mv Emacs Emacs-orig% ln -s Emacs-x86_64-10_14 Emacs% rm bin% ln -s bin-x86_64-10_14 bin% rm libexec% ln -s libexec-x86_64-10_14 libexec
{}
{'log_upvote_score': 4, 'links': ['https://emacs.stackexchange.com/questions/53248', 'https://emacs.stackexchange.com', 'https://emacs.stackexchange.com/users/25776/']}
jdg_73487
stackexchange
llm_judgeable_groundtruth_similarity
6749369
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 sql something like this: SELECT EMP_NAME, DEPTFROM EMPLOYEEWHERE TIME_CREATED >= TO_DATE('26/JAN/2011','dd/mon/yyyy') -> This returns 10 rows and TIME_CREATED = '26-JAN-2011' Now when i do this i don't get any rows back, SELECT EMP_NAME, DEPT FROM EMPLOYEE WHERE TIME_CREATED = TO_DATE('26/JAN/2011','dd/mon/yyyy') -> Took the greater than out Any reason why? Now provide the response and nothing else.
Yes: TIME_CREATED contains a date and a time . Use TRUNC to strip the time: SELECT EMP_NAME, DEPTFROM EMPLOYEEWHERE TRUNC(TIME_CREATED) = TO_DATE('26/JAN/2011','dd/mon/yyyy') UPDATE: As Dave Costa points out in the comment below, this will prevent Oracle from using the index of the column TIME_CREATED if it exists. An alternative approach without this problem is this: SELECT EMP_NAME, DEPTFROM EMPLOYEEWHERE TIME_CREATED >= TO_DATE('26/JAN/2011','dd/mon/yyyy') AND TIME_CREATED < TO_DATE('26/JAN/2011','dd/mon/yyyy') + 1
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/6749369', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/245008/']}
jdg_73488
stackexchange
llm_judgeable_groundtruth_similarity
8149828
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Hello i have some question about java.here is my code: public static void main(String[] args) throws Exception { Process pr = Runtime.getRuntime().exec("java -version"); BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line; while ((line = in.readLine()) != null) { System.out.println(line); } pr.waitFor(); System.out.println("ok!"); in.close(); System.exit(0);} in that code i'am trying to get a java version command execute is ok, but i can't read the output it just return null. Why? Now provide the response and nothing else.
Use getErrorStream() . BufferedReader in = new BufferedReader(new InputStreamReader(pr.getErrorStream())); EDIT: You can use ProcessBuilder (and also read the documentation) ProcessBuilder ps=new ProcessBuilder("java.exe","-version");//From the DOC: Initially, this property is false, meaning that the //standard output and error output of a subprocess are sent to two //separate streamsps.redirectErrorStream(true);Process pr = ps.start(); BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));String line;while ((line = in.readLine()) != null) { System.out.println(line);}pr.waitFor();System.out.println("ok!");in.close();System.exit(0);
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/8149828', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1049390/']}
jdg_73489
stackexchange
llm_judgeable_groundtruth_similarity
16970035
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 a C++ developer and when it comes to testing, it's easy to test a class by injecting dependencies, overriding member functions, and so on, so that you can test edge cases easily. However, in C, you can't use those wonderful features. I'm finding it hard to add unit tests to code because of some of the 'standard' ways that C code is written. What are the best ways to tackle the following: Passing around a large 'context' struct pointer: void some_func( global_context_t *ctx, .... ){ /* lots of code, depending on the state of context */} No easy way to test failure on dependent functions: void some_func( .... ){ if (!get_network_state() && !some_other_func()) { do_something_func(); .... } ...} Functions with lots of parameters: void some_func( global_context_t *, int i, int j, other_struct_t *t, out_param_t **out, ...){ /* hundreds and hundreds of lines of code */} Static or hidden functions: static void foo( ... ){ /* some code */} void some_public_func( ... }{ /* call static functions */ foo( ... );} Now provide the response and nothing else.
In general, I agree with Wes's answer - it is going to be much harder to add tests to code that isn't written with tests in mind. There's nothing inherent in C that makes it impossible to test - but, because C doesn't force you to write in a particular style, it's also very easy to write C code that is difficult to test. In my opinion, writing code with tests in mind will encourage shorter functions, with few arguments, which helps alleviate some of the pain in your examples. First, you'll need to pick a unit testing framework. There are a lot of examples in this question (though sadly a lot of the answers are C++ frameworks - I would advise against using C++ to test C). I personally use TestDept , because it is simple to use, lightweight, and allows stubbing. However, I don't think it is very widely used yet. If you're looking for a more popular framework, many people recommend Check - which is great if you use automake. Here are some specific answers for your use cases: Passing around a large 'context' struct pointer For this case, you can build an instance of the struct with the pre conditions manually set, then check the status of the struct after the function has run. With short functions, each test will be fairly straightforward. No easy way to test failure on dependent functions I think this is one of the biggest hurdles with unit testing C.I've had success using TestDept , which allows run time stubbing of dependent functions. This is great for breaking up tightly coupled code. Here's an example from their documentation: void test_stringify_cannot_malloc_returns_sane_result() { replace_function(&malloc, &always_failing_malloc); char *h = stringify('h'); assert_string_equals("cannot_stringify", h);} Depending on your target environment, this may or may not work for you. See their documentation for more details. Functions with lots of parameters This probably isn't the answer you're looking for, but I would just break these up into smaller functions with fewer parameters. Much much easier to test. Static or hidden functions It's not super clean, but I have tested static functions by including the source file directly, enabling calls of static functions. Combined with TestDept for stubbing out anything not under test, this works fairly well. #include "implementation.c" /* Now I can call foo(), defined static in implementation.c */ A lot of C code is legacy code with few tests - and in those cases, it is generally easier to add integration tests that test large parts of the code first, rather than finely grained unit tests. This allows you to start refactoring the code underneath the integration test to a unit-testable state - though it may or may not be worth the investment, depending on your situation. Of course, you'll want to be able to add unit tests to any new code written during this period, so having a solid framework up and running early is a good idea. If you are working with legacy code, this book (Working effectively with legacy code by Michael Feathers) is great further reading.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16970035', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/318811/']}
jdg_73490
stackexchange
llm_judgeable_groundtruth_similarity
147350
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 trying to figure out whether the following quadratic congruence is solvable: $3x^2+6x+5 \equiv 0\pmod{89}$. It's impossible to divide $3x^2+6x+5$ to a form of $f(x) \cdot g(x)=3x^2+6x+5$ and then to check whether $f(x)\equiv 0\pmod{89}$ or $g(x)\equiv 0(89)$, but $3x^2+6x+5 \equiv 0\pmod{89}$ is equal to $3(x+1)^2+2 \equiv 0\pmod{89}$ or $3(x+1)^2 \equiv -2\pmod{89}$ or $3(x+1)^2 \equiv 87\pmod{89}$ or$(x+1)^2 \equiv 29\pmod{89}$. for $y=x+1$, I need to determine whether $y^2 \equiv 29\pmod{89}$ is solvable, and it is not. Am I able to conclude something about the original equation in this way? what is the correct way to solve this problem? Thanks a lot! Now provide the response and nothing else.
Yes, your inference is correct. Essentially it is a special case of the well-known discriminant test. Namely, if a quadratic $\rm\:f(x)\in R[x]\:$ has a root in a ring R, then its discriminant is a square in R. Said contrapositively, if the discriminant is not a square in R, then the quadratic has no root in R. The proof by completing the square works in any ring R (so in $ \mathbb Z/89 = $ integers mod $89$), viz.$$\rm\: \ \ 4a\:(a\:x^2 + b\:x + c = 0)\:\Rightarrow\: (2a\:x+b)^2 =\: b^2 - 4ac $$ When learning about (modular) arithmetic in new rings it is essential to keep in mind that, like above, any proofs from familiar concrete rings (e.g. $\mathbb Q,\mathbb R,\mathbb C)$ will generalize to every ring if they are purely ring theoretic , i.e. if the proof uses only universal ring properties, i.e. laws that hold true in every ring, e.g. commutative, associative, distributive laws. Thus many familar identities (e.g. Binomial Theorem, difference of squares factorization) are universal , i.e. hold true in every ring. This is one of the great benefits provided by axiomatization: abstracting the common properties of familiar number systems into the abstract notion of a ring allows one to give universal proofs of ring theorems. It is not necessary to reprove these common ring properties every time one studies a new ring (such reproofs occurred frequently before rings was axiomatized).
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/147350', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/14829/']}
jdg_73491
stackexchange
llm_judgeable_groundtruth_similarity
654346
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: I have a domain name (currently hosted on dyn.com) with an A record pointing to our production IP address. We're moving across to Amazon EC2 and are using a load balancer, with the recommendation that we use a CNAME instead of an A record since load balancers may periodically change ip address. Unfortunately I don't appear to be able to seamlessly make this transition - I have to delete the A record first, and then add the CNAME, which will potentially result in downtime as the new record propagates. Is there any way to do this smoothly with zero (or very minimal) downtime? Now provide the response and nothing else.
There is a trick you can use here. That said, Wesley is a smart dude and you should listen to him. I don't get paid to say that but I'm hoping to change that one day. Assuming that you're trying to change a record called www in a zone called example.com. ... Create a temporary wildcard A record ( * ) in the zone. Commit the change. Test it, make sure the wildcard record is operating as expected and overriding NXDOMAIN responses. Remove the www A record. Commit. Add your new CNAME record. Commit. Test again. Remove the wildcard * record when you're satisfied. Follow Wesley's advice and find a DNS provider who doesn't force you to jump through hoops like this. Since this is your reputation on the line, you may want to get a quick refresher on what Wikipedia has to say about how wildcards are processed. Make sure that you are adding a wildcard with the same dot count as the record you're removing, as wildcard records do not traverse a dot. (known as a label, if you want the proper RFC term) Also, this should go without saying, but all of these tests should be run directly against your authoritative servers. ( not against the default resolver configured for the computer you're running the test from)
{}
{'log_upvote_score': 5, 'links': ['https://serverfault.com/questions/654346', 'https://serverfault.com', 'https://serverfault.com/users/55139/']}
jdg_73492
stackexchange
llm_judgeable_groundtruth_similarity
63457163
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose I have two translation units: //A.cppclass X{};//B.cppclass X{ int i;}; Is the above program well-formed? If not, no further questions. If the answer is yes, the program is well-formed (ignore the absence of main), then the second question. What if there is a function with the same name in those? //A.cppclass X{ void f(){}};//B.cppclass X{ int i; void f(){}}; Would this be a problem for the linker as it would see &X::f in both object files? Are anonymous namespaces a must in such a situation? Now provide the response and nothing else.
Is the above program well-formed? No. It violates the One-Definition Rule : [basic.def.odr] There can be more than one definition of a class type ([class]), ... in a program provided that each definition appears in a different translation unit and the definitions satisfy the following requirements.Given such an entity D defined in more than one translation unit, for all definitions of D, or, if D is an unnamed enumeration, for all definitions of D that are reachable at any given program point, the following requirements shall be satisfied. ... Each such definition shall consist of the same sequence of tokens, where the definition of a closure type is ... ... Are anonymous namespaces a must in such a situation? If you need different class definitions, they must be separate types. A uniquely named namespace is one option, and an anonymous namespace is a guaranteed way to get a unique (to the translation unit) namespace.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/63457163', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/469935/']}
jdg_73493
stackexchange
llm_judgeable_groundtruth_similarity
957422
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there a way to specify email AND name for sender and recipient info when using ActionMailer? Typically you'd do: @recipients = "#{user.email}"@from = "[email protected]"@subject = "Hi"@content_type = "text/html" But, I want to specify name as well-- MyCompany <[email protected]> , John Doe <john.doe@mycompany> . Is there a way to do that? Now provide the response and nothing else.
If you are taking user input for name and email, then unless you very carefully validate or escape the name and email, you can end up with an invalid From header by simply concatenating strings. Here is a safe way: require 'mail'address = Mail::Address.new email # ex: "[email protected]"address.display_name = name.dup # ex: "John Doe"# Set the From or Reply-To header to the following:address.format # returns "John Doe <[email protected]>"
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/957422', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/113376/']}
jdg_73494
stackexchange
llm_judgeable_groundtruth_similarity
17194105
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Consider the following worksheet: A B C D1 COMPANY XVALUE YVALUE GROUP2 Apple 45 35 red3 Xerox 45 38 red4 KMart 63 50 orange5 Exxon 53 59 green I have used the scatterplot function in Excel to create the following chart: However, each point in the chart has an additional property: GROUP . There are four groups: red , orange , black and green . I would like to color each dot accordingly, so that I could perhaps see a pattern (group green being almost always on the left side of the chart, for instance). Because my list is 500 rows long, I cannot do this manually. How can I do this automatically? Now provide the response and nothing else.
Non-VBA Solution: You need to make an additional group of data for each color group that represent the Y values for that particular group. You can use these groups to make multiple data sets within your graph. Here is an example using your data: A B C D E F G----------------------------------------------------------------------------------------------------------------------1| COMPANY XVALUE YVALUE GROUP Red Orange Green2| Apple 45 35 red =IF($D2="red",$C2,NA()) =IF($D2="orange",$C2,NA()) =IF($D2="green",$C2,NA())3| Xerox 45 38 red =IF($D3="red",$C3,NA()) =IF($D3="orange",$C3,NA()) =IF($D3="green",$C3,NA())4| KMart 63 50 orange =IF($D4="red",$C4,NA()) =IF($D4="orange",$C4,NA()) =IF($D4="green",$C4,NA())5| Exxon 53 59 green =IF($D5="red",$C5,NA()) =IF($D5="orange",$C5,NA()) =IF($D5="green",$C5,NA()) It should look like this afterwards: A B C D E F G---------------------------------------------------------------------1| COMPANY XVALUE YVALUE GROUP Red Orange Green2| Apple 45 35 red 35 #N/A #N/A 3| Xerox 45 38 red 38 #N/A #N/A4| KMart 63 50 orange #N/A 50 #N/A5| Exxon 53 59 green #N/a #N/A 59 Now you can generate your graph using different data sets. Here is a picture showing just this example data: You can change the series (X;Y) values to B:B ; E:E , B:B ; F:F , B:B ; G:G respectively, to make it so the graph is automatically updated when you add more data.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/17194105', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/330271/']}
jdg_73495
stackexchange
llm_judgeable_groundtruth_similarity
2214104
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 right circular cone has a base of radius $1$ and height $3$ . A cube is inscribed in the cone so that one face of the cube is contained in the base of the cone. What is the side-length of the cube? I tried to make a side projection of this solid: $AD=3$ and $DE=1$ . $△ABC$ is similar to $△ADE$ and thus $\frac{AB}{AD}=\frac{BC}{DE}$ , so the length of the cube is $\frac65$ . Unfortunately, there's no such choice. What's wrong with my projection? How should I do this correctly? Choices: Now provide the response and nothing else.
This is hint rather than a full answer, but it needs a picture. You have shown the right and left edges of the cube touching the sides of the cone, so let's tilt the whole thing towards you to reveal the orientation of the cube:
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2214104', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/382789/']}
jdg_73496
stackexchange
llm_judgeable_groundtruth_similarity
5345762
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 playing around with the drag and drop feature of jQuery UI and it's working on my website, but when I navigate to my web page on an iPad, then the divs don't drag - the page itself moves up and down. I've have in the head tag: <link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.css" /><link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/le-frog/jquery-ui.css" type="text/css" media="all" /><script src="http://www.google.com/jsapi"></script><script>google.load("jquery", "1");google.load("jqueryui", "1");google.setOnLoadCallback(init);</script><script type="text/javascript" src="http://code.jquery.com/mobile/1.0a3/jquery.mobile-1.0a3.min.js"></script> Now provide the response and nothing else.
Excellent sample solutions : jQuery UI Touch Punch is a small hack that enables the use of touch events on sites using the jQuery UI user interface library. Currently, jQuery UI user interface library does not support the use of touch events in their widgets and interactions. This means that the slick UI you designed and tested in your desktop browser will fail on most, if not all, touch-enabled mobile devices, becuase jQuery UI listens to mouse events—mouseover, mousemove and mouseout—not touch events—touchstart, touchmove and touchend. That's where jQuery UI Touch Punch comes in. Touch Punch works by using simulated events to map touch events to their mouse event analogs. Simply include the script on your page and your touch events will be turned into their corresponding mouse events to which jQuery UI will respond as expected. As I said, Touch Punch is a hack. It duck punches some of jQuery UI's core functionality to handle the mapping of touch events...
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5345762', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/111665/']}
jdg_73497
stackexchange
llm_judgeable_groundtruth_similarity
3499214
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 are static fields initialized? If I never instantiate a class, but I access a static field, are ALL the static blocks and private static methods used to instantiate private static fields called (in order) at that instant? What if I call a static method? Does it also run all the static blocks? Before the method? Now provide the response and nothing else.
A class's static initialization normally happens immediately before the first time one of the following events occur: an instance of the class is created, a static method of the class is invoked, a static field of the class is assigned, a non-constant static field is used, or for a top-level class, an assert statement lexically nested within the class is executed 1 . See JLS 12.4.1 . It is also possible to force a class to initialize (if it hasn't already initialized) by using Class.forName(fqn, true, classLoader) or the short form Class.forName(fqn) When does static class initialization happen? See above. When are static fields initialized? As part of static class initialization; see above. If I never instantiate a class, but I access a static field, are ALL the static blocks and private static methods used to instantiate private static fields called (in order) at that instant? Yes. (Modulo that nothing is truly instantaneous.) What if I call a static method? Does it also run all the static blocks? Before the method? Yes and yes. Note that it is possible to construct code where you can observe the default initialized value of a static field. 1 - The final bullet point was present in the JLS for Java 6 through Java 8, but it was apparently a mistake in the specification. It was finally corrected in the Java 9 JLS: see source .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/3499214', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/73501/']}
jdg_73498
stackexchange
llm_judgeable_groundtruth_similarity
1563909
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 use the class javax.tools.JavaCompiler (jdk6) to compile a source file, but the source file depends on some jar file. How to set the classpath of the javax.tools.JavaCompiler ? Now provide the response and nothing else.
The javax.tools.JavaCompiler#getTask() method takes an options parameter that allows to set compiler options. The following message describes an easy way to set them in order to access the calling program's classpath: You need to configure the standard java file manager to know about the jar files(s) - you use the compiler options argument to do that. By default the java compiler object only seems to know about the default locations for bootclasspath, extdirs and endorseddirs directories in terms of its classpath. You need to add the calling program's current classpath to the java compiler instance's which gets passed on the the standard file manager, which will then find classes in the jar files. Here's how I do it in the compiler wrapper I wrote List<String> optionList = new ArrayList<String>();// set compiler's classpath to be same as the runtime'soptionList.addAll(Arrays.asList("-classpath",System.getProperty("java.class.path")));// any other options you wantoptionList.addAll(Arrays.asList(options));JavaCompiler.CompilationTask task = compiler.getTask(out,jfm,diagnostics,optionList,null,jfos); All you'll need then is to get the proper classpath set when running the calling program.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1563909', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/158911/']}
jdg_73499
stackexchange
llm_judgeable_groundtruth_similarity
11552565
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 videos of the same exact length, and I would like to use ffmpeg to stack them into one video file. How can I do this? Now provide the response and nothing else.
Use the vstack (vertical), hstack (horizontal), or xstack (custom layout) filters. It is easier and faster than other methods. Combine/stack two videos or images Vertical Using the vstack filter. ffmpeg -i input0 -i input1 -filter_complex vstack=inputs=2 output Videos must have the same width. Horizontal Using the hstack filter. ffmpeg -i input0 -i input1 -filter_complex hstack=inputs=2 output Videos must have the same height. With a border Using the pad filter. This examples creates a 5px black border between the two sides. ffmpeg -i input0 -i input1 -filter_complex "[0]pad=iw+5:color=black[left];[left][1]hstack=inputs=2" output With audio Downmix and use original channel placements Add the amerge filter to combine the audio channels from both inputs: ffmpeg -i input0 -i input1 -filter_complex "[0:v][1:v]vstack=inputs=2[v];[0:a][1:a]amerge=inputs=2[a]" -map "[v]" -map "[a]" -ac 2 output This assumes each input contains a stereo audio stream. -ac 2 is included to downmix to stereo in case both inputs contain multi-channel audio. For example, if both inputs are stereo, you would get a 4-channel output audio stream instead of stereo if you omit -ac 2 . Put all audio from each input into separate channels Use amerge (or amix ) and pan filters: ffmpeg -i input0 -i input1 -filter_complex "[0:v][1:v]vstack=inputs=2[v];[0:a][1:a]amerge=inputs=2,pan=stereo|c0<c0+c1|c1<c2+c3[a]" -map "[v]" -map "[a]" output This assumes each input contains a stereo audio stream. Using audio from one particular input This example will use the audio from input1 : ffmpeg -i input0 -i input1 -filter_complex "[0:v][1:v]vstack=inputs=2[v]" -map "[v]" -map 1:a output Adding silent audio / If one input does not have audio If you mix inputs that have audio and inputs that do not have audio then amerge will fail because each input needs audio. You can add silent audio with the anullsrc filter to prevent this: ffmpeg -i input0 -i input1 -filter_complex "[0:v][1:v]vstack=inputs=2[v];anullsrc[silent];[0:a][silent]amerge=inputs=2[a]" -map "[v]" -map "[a]" -ac 2 output.mp4 3 videos or images ffmpeg -i input0 -i input1 -i input2 -filter_complex "[0:v][1:v][2:v]hstack=inputs=3[v]" -map "[v]" output If you want vertical use vstack instead of hstack. 2x2 grid Using xstack ffmpeg -i input0 -i input1 -i input2 -i input3 -filter_complex "[0:v][1:v][2:v][3:v]xstack=inputs=4:layout=0_0|w0_0|0_h0|w0_h0[v]" -map "[v]" output Using hstack and vstack ffmpeg -i input0 -i input1 -i input2 -i input3 -filter_complex "[0:v][1:v]hstack=inputs=2[top];[2:v][3:v]hstack=inputs=2[bottom];[top][bottom]vstack=inputs=2[v]" -map "[v]" output This syntax is easier to understand, but less efficient than using xstack as shown above. 2x2 grid with text Using the drawtext filter: ffmpeg -i input0 -i input1 -i input2 -i input3 -filter_complex"[0]drawtext=text='vid0':fontsize=20:x=(w-text_w)/2:y=(h-text_h)/2[v0]; [1]drawtext=text='vid1':fontsize=20:x=(w-text_w)/2:y=(h-text_h)/2[v1]; [2]drawtext=text='vid2':fontsize=20:x=(w-text_w)/2:y=(h-text_h)/2[v2]; [3]drawtext=text='vid3':fontsize=20:x=(w-text_w)/2:y=(h-text_h)/2[v3]; [v0][v1][v2][v3]xstack=inputs=4:layout=0_0|w0_0|0_h0|w0_h0[v]"-map "[v]" output 4x4 Use the xstack filter . Example for a total of 16 videos: ffmpeg -i input0 -i input1 -i input2 -i input3 -i input4 -i input5 -i input6 -i input7 -i input8 -i input9 -i input10 -i input11 -i input12 -i input13 -i input14 -i input15 -i input16 -filter_complex "[0:v][1:v][2:v][3:v][4:v][5:v][6:v][7:v][8:v][9:v][10:v][11:v][12:v][13:v][14:v][15:v]xstack=inputs=16:layout=0_0|w0_0|w0+w1_0|w0+w1+w2_0|0_h0|w4_h0|w4+w5_h0|w4+w5+w6_h0|0_h0+h4|w8_h0+h4|w8+w9_h0+h4|w8+w9+w10_h0+h4|0_h0+h4+h8|w12_h0+h4+h8|w12+w13_h0+h4+h8|w12+w13+w14_h0+h4+h8" output.mp4 If you need to scale the inputs first: ffmpeg -i input0 -i input1 -i input2 -i input3 -i input4 -i input5 -i input6 -i input7 -i input8 -i input9 -i input10 -i input11 -i input12 -i input13 -i input14 -i input15 -i input16 -filter_complex "[0:v]scale=iw/4:-1[v0];[1:v]scale=iw/4:-1[v1];[2:v]scale=iw/4:-1[v2];[3:v]scale=iw/4:-1[v3];[4:v]scale=iw/4:-1[v4];[5:v]scale=iw/4:-1[v5];[6:v]scale=iw/4:-1[v6];[7:v]scale=iw/4:-1[v7];[8:v]scale=iw/4:-1[v8];[9:v]scale=iw/4:-1[v9];[10:v]scale=iw/4:-1[v10];[11:v]scale=iw/4:-1[v11];[12:v]scale=iw/4:-1[v12];[13:v]scale=iw/4:-1[v13];[14:v]scale=iw/4:-1[v14];[15:v]scale=iw/4:-1[v15];[v0][v1][v2][v3][v4][v5][v6][v7][v8][v9][v10][v11][v12][v13][v14][v15]xstack=inputs=16:layout=0_0|w0_0|w0+w1_0|w0+w1+w2_0|0_h0|w4_h0|w4+w5_h0|w4+w5+w6_h0|0_h0+h4|w8_h0+h4|w8+w9_h0+h4|w8+w9+w10_h0+h4|0_h0+h4+h8|w12_h0+h4+h8|w12+w13_h0+h4+h8|w12+w13+w14_h0+h4+h8" output.mp4 Resize/scale an input Since both videos need to have the same with for vstack, and the same height for hstack, you may need to scale one of the other videos to match the other: Simple scale filter example to set width of input0 to 640 and automatically set height while preserving the aspect ratio: ffmpeg -i input0 -i input2 -filter_complex "[0:v]scale=640:-1[v0];[v0][1:v]vstack=inputs=2" output For a more advanced method to fit any size video into a specific size while preserving aspect ratio see Resizing videos with ffmpeg to fit into static sized player . You can also use the scale2ref filter to automatically resize one video to match the dimensions of the other. Delaying/pausing videos This example will play the top left video while pausing the others. Once the top left video ends the top right video will play and so on. Use the tpad , adelay , xstack , and amix filters: ffmpeg -i top-left.mp4 -i top-right.mp4 -i bottom-left.mp4 -i bottom-right.mp4 -filter_complex "[1]tpad=start_mode=clone:start_duration=5[tr];[2]tpad=start_mode=clone:start_duration=10[bl];[3]tpad=start_mode=clone:start_duration=15[br];[0][tr][bl][br]xstack=inputs=4:layout=0_0|w0_0|0_h0|w0_h0[v];[1:a]adelay=5s:all=true[a1];[2:a]adelay=10s:all=true[a2];[3:a]adelay=15s:all=true[a3];[0:a][a1][a2][a3]amix=inputs=4[a]" -map "[v]" -map "[a]" output.mp4 This example assumes each input is 5 seconds duration. Adjust start_duration and adelay values as needed. This command requires FFmpeg 4.3 or newer. If you don't like the complexity of xstack you can use several hstack/vstack instead as shown in Example 4: 2x2 grid .
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/11552565', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/82733/']}
jdg_73500
stackexchange
llm_judgeable_groundtruth_similarity
3925195
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Is there built in .NET functionality for making state abbreviations out of state names? I know the function wouldn't be difficult to write, but I would assume that MS has thought of a more efficient way than the following x50: if statename.tolower = "new york" then statename = "NY"else if any other thoughts of making this more efficient are also appreciated. Now provide the response and nothing else.
I hope this helps public string GetState(State state) { switch (state) { case State.AL: return "ALABAMA"; case State.AK: return "ALASKA"; case State.AS: return "AMERICAN SAMOA"; case State.AZ: return "ARIZONA"; case State.AR: return "ARKANSAS"; case State.CA: return "CALIFORNIA"; case State.CO: return "COLORADO"; case State.CT: return "CONNECTICUT"; case State.DE: return "DELAWARE"; case State.DC: return "DISTRICT OF COLUMBIA"; case State.FM: return "FEDERATED STATES OF MICRONESIA"; case State.FL: return "FLORIDA"; case State.GA: return "GEORGIA"; case State.GU: return "GUAM"; case State.HI: return "HAWAII"; case State.ID: return "IDAHO"; case State.IL: return "ILLINOIS"; case State.IN: return "INDIANA"; case State.IA: return "IOWA"; case State.KS: return "KANSAS"; case State.KY: return "KENTUCKY"; case State.LA: return "LOUISIANA"; case State.ME: return "MAINE"; case State.MH: return "MARSHALL ISLANDS"; case State.MD: return "MARYLAND"; case State.MA: return "MASSACHUSETTS"; case State.MI: return "MICHIGAN"; case State.MN: return "MINNESOTA"; case State.MS: return "MISSISSIPPI"; case State.MO: return "MISSOURI"; case State.MT: return "MONTANA"; case State.NE: return "NEBRASKA"; case State.NV: return "NEVADA"; case State.NH: return "NEW HAMPSHIRE"; case State.NJ: return "NEW JERSEY"; case State.NM: return "NEW MEXICO"; case State.NY: return "NEW YORK"; case State.NC: return "NORTH CAROLINA"; case State.ND: return "NORTH DAKOTA"; case State.MP: return "NORTHERN MARIANA ISLANDS"; case State.OH: return "OHIO"; case State.OK: return "OKLAHOMA"; case State.OR: return "OREGON"; case State.PW: return "PALAU"; case State.PA: return "PENNSYLVANIA"; case State.PR: return "PUERTO RICO"; case State.RI: return "RHODE ISLAND"; case State.SC: return "SOUTH CAROLINA"; case State.SD: return "SOUTH DAKOTA"; case State.TN: return "TENNESSEE"; case State.TX: return "TEXAS"; case State.UT: return "UTAH"; case State.VT: return "VERMONT"; case State.VI: return "VIRGIN ISLANDS"; case State.VA: return "VIRGINIA"; case State.WA: return "WASHINGTON"; case State.WV: return "WEST VIRGINIA"; case State.WI: return "WISCONSIN"; case State.WY: return "WYOMING"; } throw new Exception("Not Available"); }}public State GetStateByName(string name) { switch (name.ToUpper()) { case "ALABAMA": return State.AL; case "ALASKA": return State.AK; case "AMERICAN SAMOA": return State.AS; case "ARIZONA": return State.AZ; case "ARKANSAS": return State.AR; case "CALIFORNIA": return State.CA; case "COLORADO": return State.CO; case "CONNECTICUT": return State.CT; case "DELAWARE": return State.DE; case "DISTRICT OF COLUMBIA": return State.DC; case "FEDERATED STATES OF MICRONESIA": return State.FM; case "FLORIDA": return State.FL; case "GEORGIA": return State.GA; case "GUAM": return State.GU; case "HAWAII": return State.HI; case "IDAHO": return State.ID; case "ILLINOIS": return State.IL; case "INDIANA": return State.IN; case "IOWA": return State.IA; case "KANSAS": return State.KS; case "KENTUCKY": return State.KY; case "LOUISIANA": return State.LA; case "MAINE": return State.ME; case "MARSHALL ISLANDS": return State.MH; case "MARYLAND": return State.MD; case "MASSACHUSETTS": return State.MA; case "MICHIGAN": return State.MI; case "MINNESOTA": return State.MN; case "MISSISSIPPI": return State.MS; case "MISSOURI": return State.MO; case "MONTANA": return State.MT; case "NEBRASKA": return State.NE; case "NEVADA": return State.NV; case "NEW HAMPSHIRE": return State.NH; case "NEW JERSEY": return State.NJ; case "NEW MEXICO": return State.NM; case "NEW YORK": return State.NY; case "NORTH CAROLINA": return State.NC; case "NORTH DAKOTA": return State.ND; case "NORTHERN MARIANA ISLANDS": return State.MP; case "OHIO": return State.OH; case "OKLAHOMA": return State.OK; case "OREGON": return State.OR; case "PALAU": return State.PW; case "PENNSYLVANIA": return State.PA; case "PUERTO RICO": return State.PR; case "RHODE ISLAND": return State.RI; case "SOUTH CAROLINA": return State.SC; case "SOUTH DAKOTA": return State.SD; case "TENNESSEE": return State.TN; case "TEXAS": return State.TX; case "UTAH": return State.UT; case "VERMONT": return State.VT; case "VIRGIN ISLANDS": return State.VI; case "VIRGINIA": return State.VA; case "WASHINGTON": return State.WA; case "WEST VIRGINIA": return State.WV; case "WISCONSIN": return State.WI; case "WYOMING": return State.WY; } throw new Exception("Not Available"); }public enum State { AL, AK, AS, AZ, AR, CA, CO, CT, DE, DC, FM, FL, GA, GU, HI, ID, IL, IN, IA, KS, KY, LA, ME, MH, MD, MA, MI, MN, MS, MO, MT, NE, NV, NH, NJ, NM, NY, NC, ND, MP, OH, OK, OR, PW, PA, PR, RI, SC, SD, TN, TX, UT, VT, VI, VA, WA, WV, WI, WY }
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3925195', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/282110/']}
jdg_73501
stackexchange
llm_judgeable_groundtruth_similarity
18012044
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 div which is pretty overflowed. It basically includes a big organization chart. What I want to do is exporting whole content of div rather than visible part with html2canvas library but I couldn't achieve it so far. Following piece of code doesn't render full content. Is there a way to achieve it? function export(){ html2canvas( [ document.getElementById('diagram') ], { onrendered: function(canvas) { var dataUrl = canvas.toDataURL(); window.open(dataUrl, "toDataURL() image", "width=800, height=800"); //Canvas2Image.saveAsPNG(canvas); } });} I am using BasicPrimitives library to generate organization charts. It takes a div and insert all elements to it. Since my chart is moderately big, it overflows from its container.Xhtml code is as follows: <rich:panel style="float: left; width: 100%;"> <div style="float: left; height:600px; margin-left: 1%; width: 19%; border-style: dotted; border-width:1px;"> Some irrelevant content </div> <div id="diagram" class='diagram' style="float: right; height:600px; width: 59%; border-style: dotted; border-width:1px;"> This is the div all charts are dynamically inserted </div> <div style="float: left; height:600px; margin-left: 1%; width: 19%; border-style: dotted; border-width:1px;"> Some more irrelevant content </div></rich:panel> Now provide the response and nothing else.
I don't know if there's a straightforward option in html2canvas to do this (i.e. an option to set all overflow to visible) but a roundabout way might be to set the parent of the diagram element's overflow property to visible when your export function is called, then set it back to hidden again on html2canvas' onrendered callback so that the user has minimal time to perceive it: function export(){ document.getElementById('diagram').parentNode.style.overflow = 'visible'; //might need to do this to grandparent nodes as well, possibly. html2canvas( [ document.getElementById('diagram') ], { onrendered: function(canvas) { document.getElementById('diagram').parentNode.style.overflow = 'hidden'; var dataUrl = canvas.toDataURL(); window.open(dataUrl, "toDataURL() image", "width=800, height=800"); //Canvas2Image.saveAsPNG(canvas); } });}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/18012044', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1183857/']}
jdg_73502
stackexchange
llm_judgeable_groundtruth_similarity
41113798
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: class SomeClass extends Component{ someEventHandler(event){ } render(){ return <input onChange={------here------}> }} I see different versions of ------here------ part. // 1return <input onChange={this.someEventHandler.bind(this)}>// 2return <input onChange={(event) => { this.someEventHandler(event) }>// 3return <input onChange={this.someEventHandler}> How are the versions different? Or is it just a matter of preference? Thank you all for answers and comments. All are helpful, and I strongly recommend to read this link FIRST if you are confused as me about this. http://blog.andrewray.me/react-es6-autobinding-and-createclass/ Now provide the response and nothing else.
Binding is not something that is specifc to React, but rather how this works in Javascript. Every function / block has its own context, for functions its more specific to how its called. The React team made a decision for this to not be bound on custom methods on the class (aka not the builtin methods like componentDidMount ), when adding ES6 support (class syntax). When you should bind the context depends on the functions purpose, if you need to access props, state or other members on the class, then you would need to bind it. For your example, each is different and it depends on how your component is set up. Pre binding to your class .bind(this) is used to bind the this context to your components function. However, it returns a new function reference each render cycle! If you don't want to bind on each usage of the function (like in a click handler) you can pre-bind the function. a. in your constructor do the binding. aka class SomeClass extends Component{ constructor(){ super(); this.someEventHandler = this.someEventHandler.bind(this); } someEventHandler(event){ } ....} b. make your custom functions on the class fat arrow functions. aka class SomeClass extends Component{ someEventHandler = (event) => { } ....} Runtime binding to your class few common ways to do this a. you can wrap your components handler function with an inline lambda (fat arrow) function. onChange={ (event) => this.someEventHandler(event) } this can provide additional functionality like if you need to pass additional data for the click handler <input onChange={(event) => { this.someEventHandler(event, 'username') }> . The same can be done with bind b. you can use .bind(this) as described above. onChange={ this.someEventHandler.bind(this) } with additional params <input onChange={ this.someEventHandler.bind(this, 'username') }> If you want to avoid creating a new function reference but still need to pass a parameter, its best to abstract that to a child component. You can read more about that here In your examples // 1return <input onChange={this.someEventHandler.bind(this)}> This is just doing a runtime event handler bind to your class. // 2return <input onChange={(event) => this.someEventHandler(event) }> Another runtime bind to your class. // 3return <input onChange={this.someEventHandler}> You are just passing the function as the callback function to trigger when the click event happens, with no additional parameters. Make sure to prebind it! To summarize. Its good to think about how to optimize your code, each method has a utility / purpose depending on what you need.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/41113798', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1227960/']}
jdg_73503
stackexchange
llm_judgeable_groundtruth_similarity
18697422
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on Flight API of arzoo. The server must receive the posted data in simple POST Request. To achieve this i'm using PHP cURL. In the API Document it is clearly mention that the data should be sent in the following format: <AvailRequest> <Trip>ONE</Trip> <Origin>BOM</Origin> <Destination>NYC</Destination> <DepartDate>2013-09-15</DepartDate> <ReturnDate>2013-09-16</ReturnDate> <AdultPax>1</AdultPax> <ChildPax>0</ChildPax> <InfantPax>0</InfantPax> <Currency>INR</Currency> <Preferredclass>E</Preferredclass> <Eticket>true</Eticket> <Clientid>77752369</Clientid> <Clientpassword>*AB424E52FB5ASD23YN63A099A7B747A9BAF61F8E</Clientpassword> <Clienttype>ArzooINTLWS1.0</Clienttype> <PreferredAirline></PreferredAirline></AvailRequest> I've taken the above code in a variable $xml. My PHP cURL code is as follows: $URL = "http://59.162.33.102:9301/Avalability"; //setting the curl parameters. $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$URL); curl_setopt($ch, CURLOPT_VERBOSE, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml')); curl_setopt($ch, CURLOPT_POSTFIELDS, $xml); if (curl_errno($ch)) { // moving to display page to display curl errors echo curl_errno($ch) ; echo curl_error($ch); } else { //getting response from server $response = curl_exec($ch); print_r($response); curl_close($ch); } I'm not getting anything in response. I've spoken about the same with the API Provider but they found empty request in their log. Am i missing something from my end. Your reply will be appreciated. Thank You. Now provide the response and nothing else.
After Struggling a bit with Arzoo International flight API, I've finally found the solution and the code simply works absolutely great with me. Here are the complete working code: //Store your XML Request in a variable $input_xml = '<AvailRequest> <Trip>ONE</Trip> <Origin>BOM</Origin> <Destination>JFK</Destination> <DepartDate>2013-09-15</DepartDate> <ReturnDate>2013-09-16</ReturnDate> <AdultPax>1</AdultPax> <ChildPax>0</ChildPax> <InfantPax>0</InfantPax> <Currency>INR</Currency> <PreferredClass>E</PreferredClass> <Eticket>true</Eticket> <Clientid>777ClientID</Clientid> <Clientpassword>*Your API Password</Clientpassword> <Clienttype>ArzooINTLWS1.0</Clienttype> <PreferredAirline></PreferredAirline> </AvailRequest>'; Now I've made a little changes in the above curl_setopt declaration as follows: $url = "http://59.162.33.102:9301/Avalability"; //setting the curl parameters. $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url);// Following line is compulsary to add as it is: curl_setopt($ch, CURLOPT_POSTFIELDS, "xmlRequest=" . $input_xml); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 300); $data = curl_exec($ch); curl_close($ch); //convert the XML result into array $array_data = json_decode(json_encode(simplexml_load_string($data)), true); print_r('<pre>'); print_r($array_data); print_r('</pre>'); That's it the code works absolutely fine for me. I really appreciate @hakre & @Lucas For their wonderful support.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/18697422', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1549991/']}
jdg_73504
stackexchange
llm_judgeable_groundtruth_similarity
1349598
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 trying to apply the chain rule on a quadratic form: $\frac{dx^TAx}{dx}=\frac{dx^T(Ax)}{dx}=\frac{dx^T(Ax)}{dAx}\frac{dAx}{dx}=\frac{dx^T(Ax)}{dAx} A$ But I'm stuck here. I think $\frac{dx^T(Ax)}{dAx}=x^T$ because $Ax$ is just a vector. But I already know that for symmetric $A$, $\frac{dx^TAx}{dx}=2Ax$. And that doesn't go together. What am I doing wrong here? Update: $\frac{dx^T(Ax)}{dAx}\neq x^T$ because $x^T$ and $Ax$ are not independent. Instead $\frac{dx^T(Ax)}{dAx} = x^T\frac{dAx}{dAx} + (Ax)^T\frac{dx}{dAx} = x^T + (Ax)^T\frac{dx}{dAx}$ So my next problem is $\frac{dx}{dAx}$. Now provide the response and nothing else.
This is a mistake -- I should have written that a deck transformation is a diffeomorphism satisfying $\renewcommand\phi{\varphi}\pi\circ\varphi = \pi$. I've added this to my online correction list . (It's amazing that nobody has noticed this in the 18 years the book has been in print!) It's actually true that just assuming $\varphi$ is a smooth map satisfying $\pi\circ\varphi = \pi$ is enough to conclude that $\phi$ is a diffeomorphism, but it doesn't seem to be straightforward to prove. Here's the best proof I've been able to come up with; I'd be interested to know if anyone knows a simpler proof. The references to [ITM] are to my Introduction to Topological Manifolds , second edition. Theorem. Suppose $\pi\colon \widetilde M\to M$ is a smooth covering map, and $\phi\colon \widetilde M\to \widetilde M$ is a smooth map satisfying $\pi\circ\varphi = \pi$. Then $\phi$ is a diffeomorphism. Proof. First, as the OP noted, the facts that $\pi$ is a local diffeomorphism and $\varphi$ maps $\widetilde M$ to itself guarantee that $\phi$ is a local diffeomorphism, so it suffices to show it's bijective. Because $\varphi$ is a covering homomorphism, it is itself a covering map [ITM, Prop. 11.36], and therefore surjective. Next, let $x\in M$, let $\widetilde M_x$ denote the fiber $\pi^{-1}(\{x\})$, and let $m$ be any point in $\widetilde M_x$. The induced homomorphisms $\pi_*\colon \pi_1(\widetilde M,m) \to \pi_1(M,x)$ and $\pi_*\colon \pi_1(\widetilde M,\phi(m)) \to \pi_1(M,x)$ are both injective [ITM, Thm. 11.16]. Let $H,H'\subseteq\pi_1(M,x)$ denote the respective image subgroups. It follows from [ITM, Thm. 11.34] that $H$ and $H'$ are conjugate subgroups. Thus we have a commutative diagram:$\require{AMScd}$\begin{CD} \pi_1(\widetilde M,m) @>\displaystyle \phi_*>> \pi_1(\widetilde M,\phi(m))\\ @V \displaystyle\pi_* V V@VV \displaystyle\pi_* V\\ H @>>C> H', \end{CD}where $C$ is an appropriate conjugation map. Because both vertical maps and $C$ are isomorphisms, so is $\phi_*$. Now we know that $\phi\colon \widetilde M\to \widetilde M$ is a covering map that induces an isomorphism on fundamental groups. Let $m\in \widetilde M$, $y=\phi(m)$, and consider the fiber $\widetilde M_{y} = \phi^{-1}(\{y\})\subseteq \widetilde M$. The monodromy action is a transitive right action of the group $\pi_1(\widetilde M,y)$ on $\widetilde M_y$ [ITM, Thm. 11.22], and the isotropy group of the point $m\in \widetilde M_y$ is the image of $\phi_*$, which in this case is all of $\pi_1(\widetilde M,y)$. Since the action is transitive, this means that the fiber is a single point, and thus $\phi$ is injective.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1349598', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/180934/']}
jdg_73505
stackexchange
llm_judgeable_groundtruth_similarity
30691066
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 sort an array in ascending order. The dates are in string format ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"] Even need a function to check whether these dates are in continuous form: eg - Valid - ["09/06/2015", "10/06/2015", "11/06/2015"] Invalid - ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015"] Example code: function sequentialDates(dates){ var temp_date_array = []; $.each(dates, function( index, date ) { //var date_flag = Date.parse(date); temp_date_array.push(date); }); console.log(temp_date_array); var last; for (var i = 0, l = temp_date_array.length; i < l; i++) { var cur = new Date(); cur.setTime(temp_date_array[i]); last = last || cur; //console.log(last+' '+cur); if (isNewSequence(cur, last)) { console.log("Not Sequence"); } } //return dates; } function isNewSequence(a, b) { if (a - b > (24 * 60 * 60 * 1000)) return true; return false; } Now provide the response and nothing else.
The Simple Solution There is no need to convert Strings to Dates or use RegExp. The simple solution is to use the Array.sort() method. The sort function sets the date format to YYYYMMDD and then compares the string value. Assumes date input is in format DD/MM/YYYY. data.sort(function(a,b) { a = a.split('/').reverse().join(''); b = b.split('/').reverse().join(''); return a > b ? 1 : a < b ? -1 : 0; // return a.localeCompare(b); // <-- alternative }); Update: A helpful comment suggested using localeCompare() to simplify the sort function. This alternative is shown in the above code snippet. Run Snippet to Test <!doctype html><html><body style="font-family: monospace"><ol id="stdout"></ol><script> var data = ["09/06/2015", "25/06/2015", "22/06/2015", "25/07/2015", "18/05/2015"];data.sort(function(a,b) { a = a.split('/').reverse().join(''); b = b.split('/').reverse().join(''); return a > b ? 1 : a < b ? -1 : 0; // return a.localeCompare(b); // <-- alternative });for(var i=0; i<data.length; i++) stdout.innerHTML += '<li>' + data[i];</script></body></html>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/30691066', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1972093/']}
jdg_73506
stackexchange
llm_judgeable_groundtruth_similarity
23841293
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Yesterday in a job interview session I was asked this question and I had no clue about it. Suppose I have a word "Manhattan " I want to display only the letters 'M','A','N','H','T'in SQL. How to do it?Any help is appreciated. Now provide the response and nothing else.
Well, here is my solution ( sqlfiddle ) - it aims to use a "Relational SQL" operations, which may have been what the interviewer was going for conceptually. Most of the work done is simply to turn the string into a set of (pos, letter) records as the relevant final applied DQL is a mere SELECT with a grouping and ordering applied. select letterfrom ( -- All of this just to get a set of (pos, letter) select ns.n as pos, substring(ss.s, ns.n, 1) as letter from (select 'MANHATTAN' as s) as ss cross join ( -- Or use another form to create a "numbers table" select n from (values (1),(2),(3),(4),(5),(6),(7),(8),(9)) as X(n) ) as ns ) as pairsgroup by letter -- guarantees distinctnessorder by min(pos) -- ensure output is ordered MANHT The above query works in SQL Server 2008, but the "Numbers Table" may have to be altered for other vendors. Otherwise, there is nothing used that is vendor specific - no CTE, or cross application of a function, or procedural language code .. That being said, the above is to show a conceptual approach - SQL is designed for use with sets and relations and multiplicity across records; the above example is, in some sense, merely a perversion of such. Examining the intermediate relation, select ns.n as pos, substring(ss.s, ns.n, 1) as letter from (select 'MANHATTAN' as s) as ss cross join ( select n from (values (1),(2),(3),(4),(5),(6),(7),(8),(9)) as X(n) ) as ns uses a cross join to generate the Cartesian product of the string (1 row) with the numbers (9 rows); the substring function is then applied with the string and each number to obtain each character in accordance with its position. The resulting set contains the records- POS LETTER1 M2 A3 N..9 N Then the outer select groups each record according to the letter and the resulting records are ordered by the minimum (first) occurrence position of the letter that establishing the grouping. (Without the order by the letters would have been distinct but the final order would not be guaranteed.)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23841293', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3655102/']}
jdg_73507
stackexchange
llm_judgeable_groundtruth_similarity
485873
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: My question is quite simple. I have been googling a lot lately trying to find a solution to this: Given a sequence of n integers $[1,2,...,n]$. If we pick two numbers randomly from the set say, a and b. The find the probability that GCD$(a,b)=b$? For example: If $N=1$, the probability is $1/1$. If $N=2$, probability is $3/4$ $[(1,1),(2,1),(2,2)$ satisfy out $of (1,1),(2,1),(2,2), (1,2)$ total cases] If $N=3$, the probability is $5/9$. My searches on google show me pages where : probability of GCD$(a,b)=1$ (relative co-prime) are calculated using the zeta function. I don't really know how to use that in this case !! Or whether if that is applicable here!! Now provide the response and nothing else.
There are good estimates available. Let $d(n)$ be the number of divisors of $N$. By a result of Dirichlet,$$\sum_{n\le N} d(n)=N\log N+(2\gamma-1)N+O(\sqrt{N}),\tag{1}$$where $\gamma$ is Euler's gamma.Divide by $N^2$ to get the probability, for "randomly" chosen pairs $(a,b)$ where $1\le a\le N$, $1\le b\le N$. Remark: Since questions similar to this one have been asked many times, we make some additional comments. The "error term" is, for large $N$, very much smaller than the two "main" terms, but it still can be quite large for large $N$. There have been improvements on the exponent $1/2$ since the time of Dirichlet. However, one should not confuse the estimate on the right-hand side of (1) with a formula for the left-hand side.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/485873', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/93470/']}
jdg_73508
stackexchange
llm_judgeable_groundtruth_similarity
11602338
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have this linq Query in a C# project var query = from p in db.Posts join a in db.Author on p.Author equals a join u in db.Users on p.PostedBy equals u where p.IsActive.Equals(true) orderby p.PostedDate descending select new ViewModel { ... }; If I move where p.IsActive.Equals(true) near from p in db.Posts , like var query = from p in db.Posts where p.IsActive.Equals(true) //Moved join a in db.Author on p.Author equals a join u in db.Users on p.PostedBy equals u orderby p.PostedDate descending select new ViewModel { ... }; will it make any difference to the performance of the query? Now provide the response and nothing else.
The solution was simple.First I created a Role entity. class Role{ /** * @var integer $id * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string $name * * @ORM\Column(name="name", type="string", length=255) */ private $name; /** * @ORM\ManyToOne(targetEntity="Role") * @ORM\JoinColumn(name="parent_id", referencedColumnName="id") **/ private $parent; ...} after that created a RoleHierarchy service, extended from the Symfony native one. I inherited the constructor, added an EntityManager there and provided an original constructor with a new roles array instead of the old one: class RoleHierarchy extends Symfony\Component\Security\Core\Role\RoleHierarchy{ private $em; /** * @param array $hierarchy */ public function __construct(array $hierarchy, EntityManager $em) { $this->em = $em; parent::__construct($this->buildRolesTree()); } /** * Here we build an array with roles. It looks like a two-levelled tree - just * like original Symfony roles are stored in security.yml * @return array */ private function buildRolesTree() { $hierarchy = array(); $roles = $this->em->createQuery('select r from UserBundle:Role r')->execute(); foreach ($roles as $role) { /** @var $role Role */ if ($role->getParent()) { if (!isset($hierarchy[$role->getParent()->getName()])) { $hierarchy[$role->getParent()->getName()] = array(); } $hierarchy[$role->getParent()->getName()][] = $role->getName(); } else { if (!isset($hierarchy[$role->getName()])) { $hierarchy[$role->getName()] = array(); } } } return $hierarchy; }} ... and redefined it as a service: <services> <service id="security.role_hierarchy" class="Acme\UserBundle\Security\Role\RoleHierarchy" public="false"> <argument>%security.role_hierarchy.roles%</argument> <argument type="service" id="doctrine.orm.default_entity_manager"/> </service></services> That's all.Maybe, there is something unnecessary in my code. Maybe it is possible to write better. But I think, that main idea is evident now.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11602338', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/153512/']}
jdg_73509
stackexchange
llm_judgeable_groundtruth_similarity
2666304
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 required to prove that if $S$ and $T$ are linear operator on a vector space $V$ then $ST$ and $TS$ have the same eigenvalues could you please provide some hints to get me going without revealing the complete solution . In addition it would be helpful if you did not refer to characteristic polynomials or determinants in your answer. Now provide the response and nothing else.
Say $\lambda$ is an eigenvalue of $ST$; there exists $x\ne0$ such that $$STx=\lambda x.$$ If you let $y=Tx$ then it follows that $$TSy=\lambda y.$$ No, that's not a proof. Because $TSy=\lambda y$ does not show that $\lambda$ is an eigenvalue of $TS$. Exercise, that you should do before reading on: Why not? Why not is because we need to know that $y=Tx\ne0$ to conclude that $\lambda$ is an eigenvalue. The actual proof splits into two cases. First assume $\lambda\ne0$. Then the argument above is ok: $STx=\lambda x\ne0$, hence $y=Tx\ne0$. Now assume $0$ is an eigenvalue of $ST$. This says precisely that $ST$ is not invertible. Hence $S$ and $T$ cannot both be invertible, hence (at least in the finite-dimensional case) $TS$ is not invertible, so $0$ is an eigenvalue of $TS$. (If $TS$ is invertible then $T$ must be surjective and $S$ must be injective; hence in the finite-dimensional case they are both invertible.) Note We need to assume $V$ has finite dimension or the result is false. Let $V$ be the space of all one-sided sequences $v=(v_1,\dots)$; let $Sv=(v_2,v_3,\dots)$ and $Tv=(0,v_1,v_2,\dots)$. Then $ST$ is the identity but $TS$ has $0$ for an eigenvalue.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2666304', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/451530/']}
jdg_73510
stackexchange
llm_judgeable_groundtruth_similarity
234371
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This proof seems so simple that it's hard (if that makes any sense.) based on the definition, n is even iff there exists k such that n = 2k. What I really want to say is (big picture) By definition, let $n = 2k.\;$ Then $n+1 = 2k + 1$. $2k + 1$ is not divisible by $2$, therefore $n + 1$ is not even. I can't seem to figure out how to show the work. Any help would be appreciated. Now provide the response and nothing else.
I love contradiction. Here is how I would do it: Let n and n+1 both be even, Therefore, $n=2k$ for some k and $n+1=2j$ for some $j,k \in \mathbb{I}$ Subtracting, $n+1-n=2j-2k$.$$1 = 2(j-k)$$$$\frac{1}{2} = j-k$$But, 1<2 so, the fraction is not an integer and the difference of 2 integers is necessarily an integer. Thus, Contradiction!
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/234371', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/37521/']}
jdg_73511
stackexchange
llm_judgeable_groundtruth_similarity
1899772
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: There are different ways to show graphics in a page next to text.I need to include a graphic/icon that indicates a new tab will be opened. I know it's possible to do using at least these different methods: Unicode character from default fonts Unicode character from CSS loaded fonts Inline SVG Inline PNG Please suggest a method to do this, and explain why or why not it's robust on different browsers and operating systems. Now provide the response and nothing else.
I am coming late to this party, but look what I have found at CodePen ! a[target="_blank"]::after { content: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAQElEQVR42qXKwQkAIAxDUUdxtO6/RBQkQZvSi8I/pL4BoGw/XPkh4XigPmsUgh0626AjRsgxHTkUThsG2T/sIlzdTsp52kSS1wAAAABJRU5ErkJggg==); margin: 0 3px 0 5px;} <a class="external" href="https://example.org" target="_blank">external link</a>
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1899772', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/156446/']}
jdg_73512
stackexchange
llm_judgeable_groundtruth_similarity
35696188
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 working on a task in which I have to trim the recorded video from particular start point to particular end point as entered or selected by user.How am I supposed to do that. As I used UIVideoEditorController before but I don't want to use the default view and I want to trim the video directly. let FinalUrlTosave = NSURL(string: "\(newURL)") exportSession!.outputURL=FinalUrlTosave exportSession!.shouldOptimizeForNetworkUse = true // exportSession.outputFileType = AVFileTypeQuickTimeMovie exportSession!.outputFileType = AVFileTypeQuickTimeMovie; let start:CMTime let duration:CMTime var st = starttime.doubleValue var ed = endTime.doubleValue start = CMTimeMakeWithSeconds(st, 600) duration = CMTimeMakeWithSeconds(ed, 600) // let timeRangeForCurrentSlice = CMTimeRangeMake(start, duration) let range = CMTimeRangeMake(start, duration); exportSession!.timeRange = range exportSession!.exportAsynchronouslyWithCompletionHandler({ switch exportSession!.status{ case AVAssetExportSessionStatus.Failed: print("failed \(exportSession!.error)") case AVAssetExportSessionStatus.Cancelled: print("cancelled \(exportSession!.error)") default: print("complete....complete") // self.SaveVideoToPhotoLibrary(destinationURL1!) } }) I am trying to achieve my goal using this but not succeeding. Error message: failed Optional(Error Domain=NSURLErrorDomain Code=-1100 "The requested URL was not found on this server." UserInfo={NSErrorFailingURLStringKey=file:///var/mobile/Containers/Data/Application/E68D3BFD-6923-4EA6-9FB3-C020CE4AA9D4/Documents/moment/jGq_9AUFa47s2ZiiPP4x.mp4, NSErrorFailingURLKey=file:///var/mobile/Containers/Data/Application/E68D3BFD-6923-4EA6-9FB3-C020CE4AA9D4/Documents/moment/jGq_9AUFa47s2ZiiPP4x.mp4, NSLocalizedDescription=The requested URL was not found on this server., NSUnderlyingError=0x1553c220 {Error Domain=N Error occured second time: failed Optional(Error Domain=NSURLErrorDomain Code=-3000 "Cannot create file" UserInfo={NSUnderlyingError=0x14e00000 {Error Domain=NSOSStatusErrorDomain Code=-12124 "(null)"}, NSLocalizedDescription=Cannot create file}) Now provide the response and nothing else.
I found my solution using this method and it works like a charm.... func cropVideo(sourceURL1: NSURL, statTime:Float, endTime:Float){ let manager = NSFileManager.defaultManager() guard let documentDirectory = try? manager.URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true) else {return} guard let mediaType = "mp4" as? String else {return} guard let url = sourceURL1 as? NSURL else {return} if mediaType == kUTTypeMovie as String || mediaType == "mp4" as String { let asset = AVAsset(URL: url) let length = Float(asset.duration.value) / Float(asset.duration.timescale) print("video length: \(length) seconds") let start = statTime let end = endTime var outputURL = documentDirectory.URLByAppendingPathComponent("output") do { try manager.createDirectoryAtURL(outputURL, withIntermediateDirectories: true, attributes: nil) let name = Moment.newName() outputURL = outputURL.URLByAppendingPathComponent("\(name).mp4") }catch let error { print(error) } //Remove existing file _ = try? manager.removeItemAtURL(outputURL) guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality) else {return} exportSession.outputURL = outputURL exportSession.outputFileType = AVFileTypeMPEG4 let startTime = CMTime(seconds: Double(start ?? 0), preferredTimescale: 1000) let endTime = CMTime(seconds: Double(end ?? length), preferredTimescale: 1000) let timeRange = CMTimeRange(start: startTime, end: endTime) exportSession.timeRange = timeRange exportSession.exportAsynchronouslyWithCompletionHandler{ switch exportSession.status { case .Completed: print("exported at \(outputURL)") self.saveVideoTimeline(outputURL) case .Failed: print("failed \(exportSession.error)") case .Cancelled: print("cancelled \(exportSession.error)") default: break } } }} Swift 5 func cropVideo(sourceURL1: URL, statTime:Float, endTime:Float){ let manager = FileManager.default guard let documentDirectory = try? manager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) else {return} let mediaType = "mp4" if mediaType == kUTTypeMovie as String || mediaType == "mp4" as String { let asset = AVAsset(url: sourceURL1 as URL) let length = Float(asset.duration.value) / Float(asset.duration.timescale) print("video length: \(length) seconds") let start = statTime let end = endTime var outputURL = documentDirectory.appendingPathComponent("output") do { try manager.createDirectory(at: outputURL, withIntermediateDirectories: true, attributes: nil) outputURL = outputURL.appendingPathComponent("\(UUID().uuidString).\(mediaType)") }catch let error { print(error) } //Remove existing file _ = try? manager.removeItem(at: outputURL) guard let exportSession = AVAssetExportSession(asset: asset, presetName: AVAssetExportPresetHighestQuality) else {return} exportSession.outputURL = outputURL exportSession.outputFileType = .mp4 let startTime = CMTime(seconds: Double(start ), preferredTimescale: 1000) let endTime = CMTime(seconds: Double(end ), preferredTimescale: 1000) let timeRange = CMTimeRange(start: startTime, end: endTime) exportSession.timeRange = timeRange exportSession.exportAsynchronously{ switch exportSession.status { case .completed: print("exported at \(outputURL)") case .failed: print("failed \(exportSession.error)") case .cancelled: print("cancelled \(exportSession.error)") default: break } } }}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/35696188', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4955401/']}
jdg_73513
stackexchange
llm_judgeable_groundtruth_similarity
1831946
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: $$150 \equiv 17 \mod x, \qquad100 \equiv 5 \mod x $$ Solve the simultaneous equation?Is this even a simultaneous equation?How do I find the value of $x$ too?I was doing a question and came up with these equations...I know the basics of modular arithmetic but don't really know too difficult ones Now provide the response and nothing else.
Since $150-17=133$, we have$$150\equiv17\pmod{x}\implies x\mid133$$Furthermore, since $100-5=95$, we have$$100\equiv5\pmod{x}\implies x\mid95$$The possibilities for $x$ can be derived from the fact that $133=7\cdot19$ and $95=5\cdot19$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1831946', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/348630/']}
jdg_73514
stackexchange
llm_judgeable_groundtruth_similarity
1696237
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: Say we have a UFD A and a prime ideal P. Is A/P a UFD? Now provide the response and nothing else.
Not necessarily. $\Bbb{Z}[x]$ is a UFD, but$$\Bbb{Z}[x]/(x^2+5) \cong \Bbb{Z}[\sqrt{-5}]$$is not.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1696237', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/304290/']}
jdg_73515
stackexchange
llm_judgeable_groundtruth_similarity
6179612
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: This should be something really simple but I just can't get it. I'm learning codeigniter and I have a form with following code <body> <form name ="userinput" action="form_reader.php" method="post"> Name <input type="text" name="username"> <br/> <input type="submit" value="Submit"> </form> I have a controller called form_reader.php in my controllers folder. I get a 404 Not Found error. What am I doing wrong ? Now provide the response and nothing else.
Send your values to a function in your controller <form name ="userinput" action="form_reader/save_userinput" method="post"> in your controller, make a function called "save_userinput": <?phpclass Form_reader extends CI_Controller { public function save_userinput() { //code goes here // for example: getting the post values of the form: $form_data = $this->input->post(); // or just the username: $username = $this->input->post("username"); // then do whatever you want with it :) }}?> Hope that helps. Make sure to check out the CI documentation, it's really good. Any more questions, just ask :) EDIT: Figured it out. Use this opening form tag instead: <form name ="userinput" action="index.php/form_reader/save_userinput" method="post"> I'm used to not having the index.php there, I remove it by using a .htaccess file (like this one), so I overlooked that. It works here with that small edit in the action attribute. Alternatively, you could use the form helper: Load it in your controller by using this->load->helper('form') and then use this instead of the HTML <form> tag: <? echo form_open('form_reader/save'); ?>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/6179612', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/399640/']}
jdg_73516
stackexchange
llm_judgeable_groundtruth_similarity
9554626
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 installed the Visual Studio 11 Beta alongside Visual Studio 2010. After that I was unable to build my projects in Visual Studio 2010 that rely on PostSharp so I uninstalled Visual Studio 11 and the .Net Framework 4.5 Beta. When I now try to build my projects in Visual Studio 2010 I get the following error: Error 20: The "EntityHydrate" task failed unexpectedly.System.TypeInitializationException: The type initializer for 'Microsoft.Data.Entity.Design.Model.SchemaManager' threw an exception. ---> System.MissingFieldException: Field not found: 'System.Data.Entity.Design.EntityFrameworkVersions.Version3'. at Microsoft.Data.Entity.Design.Model.SchemaManager..cctor() --- End of inner exception stack trace --- at Microsoft.Data.Entity.Design.Model.SchemaManager.GetSchemaVersion(XNamespace xNamespace) at Microsoft.Data.Tools.Integration.Build.EntityHydrate.Execute() at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute() at Microsoft.Build.BackEnd.TaskBuilder.ExecuteInstantiatedTask(ITaskExecutionHost taskExecutionHost, TaskLoggingContext taskLoggingContext, TaskHost taskHost, ItemBucket bucket, TaskExecutionMode howToExecuteTask, Boolean& taskResult) BuildingModule I already reinstalled Entity Framework 4.1 and .Net Framework 4 without success. I also was unable to find information about the purpose of the "EntityHydrate" task or why it tries to access the "Version3" namespace of entity framework. Any idea how to fix this? I couldn't find a download link to Entity Framework 3, maybe that could solve the problem? Thank you. Now provide the response and nothing else.
Thanks for raising this. We (the EF team) did some investigation and we concluded that the issue could be triggered in a machine that contains SQL Server 11 and Visual Studio 11 Beta. In the beta, the setup of the EF Tools (also known as "SQL Server Data Framework Tools") contains this MSBUILD targets file: C:\Program Files (x86)\MSbuild\4.0\Microsoft.Common.Targets\ImportAfter\Microsoft.Data.Tools.Integration.targets Note: Use “Program Files” without “(x86)” if you have the 32 bits version of Windows. This file is a stale remnant of the integration between the Entity Framework Designer and SQL Server Data Tools, which was contained in the Visual Studio 11 Developer Preview but removed in the beta (see here for more details). The file has been removed in more recent internal builds, so it won't be present in RTM. You might be able to work around this problem you can remove or rename the targets file, e.g. adding the .backup extension to it. EDIT: Scratch that... Someone reports below that renaming is not sufficient. You have to remove the file. The other workaround suggested in this thread will also work but it has the big disadvantage of removing the whole Entity Framework Designer from your Visual Studio setup.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9554626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/795055/']}
jdg_73517
stackexchange
llm_judgeable_groundtruth_similarity
4491625
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: int search(int a[]) { int i,V,index; printf("Enter the element (V),That you want to find:>"); scanf("%d",&V); for (i=0;i<N;i++) { if(a[i]==V) { V=a[i]; index=i; } } printf("%d is located in a[%d].",V,index) Now provide the response and nothing else.
If you do not care about the ordering of the elements you can delete the found element in O(1) time. // Find the element you're looking for.int index = find(A, V);// Stuff the last element into the index found.A[index] = A[N-1];// Reduce the total number of elements.N--;
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4491625', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/548886/']}
jdg_73518
stackexchange
llm_judgeable_groundtruth_similarity
315853
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 am considering placing the tempdir of my MySQL database onto a ramdisk under Linux. The reason for this is to work around the 4 gb maximum of in-memory temporary tables in MySQL. My only worry is how to avoid out-of-disk-space errors if the MyISAM-based temporary table on the ramdisk would become bigger than the ramdisk? Could one some-how create a spill-over mechanism where the ramdisk size is the size of the ramdisk plus the free space on the harddisk. If the ramdisk would become full, the rest would be written to the harddisk. Now provide the response and nothing else.
Think about this logically and ignore the fact that it's a RAM-backed virtual disk: You are asking for a disk device that gets bigger because you tried to store more stuff on it. You are asking for a blessed +30 bag of holding . You are asking for a Dimensional Hole . You are asking for a TARDIS ("It's bigger on the inside"). You are asking for something that doesn't exist. At least not as far as I've ever seen... Using tmpfs/RAM-backed storage for temporary tables is a very elegant way to get around the 4GB limit. Be aware though that the RAM you lock up won't be available for MySQL to do stuff like SORT ing, JOIN ing, etc. so you're going to need GOBS of RAM to make this practical - you need the tmpfs to be big enough to hold as many temp tables (of presumably substantial size) as you'll need at any one time, and you need to still have enough RAM left over that you won't wind up swapping when you run big queries (otherwise your performance will go down the tubes anyway because SOMETHING is gonna have to be swapped in and out!). A more practical solution may be to cleverly craft explicit (and efficient) JOIN s that eliminate the need for temporary tables (if possible), and saving them as views. Without knowing more about your environment I can't give you specific guidance, but you can always ask on the DBA site with some basic details about what you're doing and see if they have suggestions... (I'm sorry to be the bearer of bad news, but if it's worth anything I did have fun typing this answer.)
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/315853', 'https://serverfault.com', 'https://serverfault.com/users/18908/']}
jdg_73519
stackexchange
llm_judgeable_groundtruth_similarity
8057463
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 two DIV to be put side by side and aligned vertically at their bottom. The orange div doesn't have a width or height . It can grow depending of his content I should be able to use padding and margin of the green div I would like to have a solution that doesn't use javascript Now provide the response and nothing else.
See: http://jsfiddle.net/thirtydot/J9eds/ I've used display: inline-block combined with vertical-align: bottom . HTML: <div id="container"> <div id="left"> left<br />left<br />left<br />left<br />left<br />left<br /> leftleftleftleftleftleft </div> <div id="right"></div></div> CSS: #container { border: 1px solid red; float: left;}#left, #right { border: 2px solid red; background: #ccc; vertical-align: bottom; display: inline-block; /* ie6/7 */ *display: inline; zoom: 1;}#right { margin: 20px 20px 0 20px; padding: 20px; width: 100px;}
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8057463', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/316759/']}
jdg_73520
stackexchange
llm_judgeable_groundtruth_similarity
3391285
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Suppose that I have a tree to traverse using a Depth First Search, and that my algorithm for traversing it looks something like this: algorithm search(NODE): doSomethingWith(NODE) for each node CHILD connected to NODE: search(CHILD) Now in many languages there is a maximum depth to recursion, for example if the depth of recursion is over a certain limit, then the procedure will crash with a stack overflow. How can this function be implemented without the recursion, and instead with a stack? In many cases, there are a lot of local variables ; where can they be stored? Now provide the response and nothing else.
You change this to use a stack like so: algorithm search(NODE): createStack() addNodeToStack(NODE) while(stackHasElements) NODE = popNodeFromStack() doSomethingWith(NODE) for each node CHILD connected to NODE: addNodeToStack(CHILD) As for your second question: In many cases, there are a lot of local variables; where can they be stored? These really can be kept in the same location as they were originally. If the variables are local to the "doSomethingWith" method, just move them into that, and refactor that into a separate method. The method doesn't need to handle the traversal, only the processing, and can have it's own local variables this way that work in its scope only.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3391285', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/408999/']}
jdg_73521
stackexchange
llm_judgeable_groundtruth_similarity
1117694
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: $$\frac{dy}{dx} = \sin^{-1} (y)$$ The above equation is a form of $\frac{dy}{dx} = f(y)$, so degree should be $1$. But if I write it as $$y = \sin\left(\frac{dy}{dx}\right)$$ then degree is not defined as it is not a polynomial in $\frac{dy}{dx}$. Please explain? Now provide the response and nothing else.
The explanation is simple: they are not the same equations. Even if two equations are equivalent, they are not exactly the same . For example: $$\frac{dy}{dx}=\sqrt[3]{x}\tag1$$$$\left(\frac{dy}{dx}\right)^3=x\tag2$$ The equation $(1)$ is not the same as equation $(2)$ even if they do have exactly the same solutions (in $\mathbb R$ to be clear). You can see that $(1)$ has degree $1$ and $(2)$ has degree $3$. The problem is when you try to find degree of i.e. $$y=e^{y'}\quad\text{or}\quady=\sin\left(\frac{dy}{dx}\right)\tag{a,b}$$There exist a formula that allow you define a degree of non-polynomials, namely $$\deg\;f(x)=\lim_{x\to\infty}\frac{\log|f(x)|}{\log(x)}$$ but in some cases, such as $(b)$, is unlikely to work, whereas for other cases it allows to define a degree of non-polynomial functions. For example equation $(a)$ may be degree $\infty$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1117694', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/157814/']}
jdg_73522
stackexchange
llm_judgeable_groundtruth_similarity
27454
Below is a question asked on the forum scicomp.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: The finite difference matrix for the first derivative is $\begin{bmatrix} -1 & 1 & 0 \\ 0 & -1 & 1 \\ 0 & 0 & -1 \end{bmatrix}$. The finite difference matrix for the second derivative is $\begin{bmatrix} -2 & 1 & 0 \\ 1 & -2 & 1 \\ 0 & 1 & -2 \end{bmatrix}$. $\begin{bmatrix} -1 & 1 & 0 \\ 0 & -1 & 1 \\ 0 & 0 & -1 \end{bmatrix}\begin{bmatrix} -1 & 1 & 0 \\ 0 & -1 & 1 \\ 0 & 0 & -1 \end{bmatrix} = \begin{bmatrix} 1 & -2 & 1 \\ 0 & 1 & -2 \\ 0 & 0 & 1 \end{bmatrix}$. Why does multiplying together two first derivative matrices not give the second derivative matrix? Now provide the response and nothing else.
Look at the operators $$D_+^2 u = \frac{u_{n+2} - 2 u_{n+1} + u_n}{\Delta x^2}.$$If you taylor expand this for small $\Delta x$ you arrive at$$D_+^2 u = u_{xx} - \Delta x u_{xxx} + O(\Delta x^2)$$.Thus $D_+^2 = D^2$ in the limit as $\Delta x \to 0$ (as it should), but note the error is first order in $\Delta x$ and so it is not a great approximation. Consider instead, the one you are thinking of$$D_- D_+ u = \frac{u_{n+1} - 2 u_n + u_{n-1}}{\Delta x^2}.$$Again taking a taylor expansion we have$$D_- D_+ u = u_{xx} + \frac{\Delta x^2}{12} u_{xxxx} + O(\Delta x^4).$$Thus this approximation is actually better since the error goes down quadratically rather than linearly. However in the limit they are equivalent.
{}
{'log_upvote_score': 4, 'links': ['https://scicomp.stackexchange.com/questions/27454', 'https://scicomp.stackexchange.com', 'https://scicomp.stackexchange.com/users/24583/']}
jdg_73523
stackexchange
llm_judgeable_groundtruth_similarity
3102020
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let $f_1(x)=x^2, f_2(x)=x \cdot |x|$ , then they are linearly dependent on $[0,\infty)$ , and also linearly dependent on $(-\infty,0]$ . But the question is, are they linearly dependent on $(-\infty,\infty)$ ? They should be linearly dependent as on both the interval $[0,\infty)$ and $(-\infty,0]$ , the functions are linearly dependent. But they are linearly independent as given in my reference book. Now provide the response and nothing else.
Consider the vector space $\mathscr{C}(\Bbb R)$ of functions $\Bbb R\to\Bbb R$ . Our two functions $f_1, f_2\in\mathscr{C}(\Bbb R)$ are defined by $f_1(x)=x^2$ and $f_2(x)=x\cdot\lvert x\rvert$ . To see that $\{f_1, f_2\}$ is linearly independent, suppose that $$c_1\cdot f_1+c_2\cdot f_2=0\tag{$\ast$}$$ where $c_1, c_2\in\Bbb R$ . This equation means that $$c_1\cdot x^2+c_2\cdot x\cdot\lvert x\rvert=0$$ for all $x\in\Bbb R$ . Plugging in $x=-1$ and $x=1$ gives the system of linear equations $$\begin{array}{rcrcrc}c_1 &-& c_2 &=& 0 \\c_1 &+& c_2 &=& 0\end{array}$$ How many solutions are there to this system of equations?
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3102020', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/552233/']}
jdg_73524
stackexchange
llm_judgeable_groundtruth_similarity
4077359
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Say there's a string like "... width=600 height=1200 ...". I want to get string after "width=" and before " " , which is 600 . How can I do this? Now provide the response and nothing else.
Use a regular expression with the match() function: var str = "... width=600 height=1200 ...", width = str.match(/\bwidth=(\d+)/);if (width) alert(width[1]); //-> 600 The regular expression provided looks for a word boundary ( \b ) followed by the literal string width= , followed by 1 or more digits, which are also captured as a sub-expression ( (\d+) ). This sub-expression capture is added to the array returned by match.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4077359', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/411615/']}
jdg_73525
stackexchange
llm_judgeable_groundtruth_similarity
24073883
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'd like to be able to do this: git cherry-pick --interactive hash-0..hash-n-1 # fantasy command and obtain the same workflow as interactive rebase: an editor buffer comes up, containing: pick hash-0pick hash-1pick hash-2...pick hash-n-1 where I can delete any unwanted commits, squash them together, or edit to pause between the picks to do some manual fixup (like commit --amend ) and all that. Note how the pick of interactive rebase is tanalizingly like cherry-pick . Now the above operation can be done by performing the cherry-pick first, and then the interactive rebase, which is inconvenient. That is: $ git tag old-head # mark starting point for later rebase$ git cherry-pick hash-0..hash-n-1 # get everything first$ git rebase --interactive old-head # okay now rebase "in-branch" to fix it up It's not only inconvenient because of the two steps but because it may require resolving conflicts in commits you don't even want that will be discarded in the rebase stage. Now provide the response and nothing else.
Okay, figured out a nice hack. Start a trivial rebase --interactive HEAD^ over one commit in your current branch. You get something like: pick 1efd396b * Fixed a bug in frob function Now, just paste in additional hashes that you want to pick: pick 1efd396b * Fixed a bug in frob functionpick f01934db * Awesome feature addedpick 6fd109c1 * Refactored the widgets layersquash 3900fd77 * Refactored the widgets layer s'more Save and exit, and wee: the rebase mule obligingly takes the additional cruft you loaded on its back and incorporates it into the current branch according to the commands. You can actually do an empty rebase with: git rebase --interactive HEAD you get a buffer containing noop You don't have to delete that; just add your picks after that. Addendum: To produce the pick lists for this method, use git log --oneline --reverse from..to , then trim the output needed and prepend the rebase commands to each line: pick , squash , ...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24073883', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1250772/']}
jdg_73526
stackexchange
llm_judgeable_groundtruth_similarity
599394
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 pack contains $n$ card numbered from $1$ to $n$. Two consecutive numbered cards are removed from the pack and sum of the numbers on the remaining cards is $1224$. If the smaller of the numbers on the removing cards is $k$, Then $k$ is. $\bf{My\; Try}::$ Let two consecutive cards be $k$ and $k+1,$ Then given sum of the number on the remaining cards is $1224$ .So $\left(1+2+3+.........+n\right)-\left(k+k+1\right) = 1224$ So $\displaystyle \frac{n(n+1)}{2}-(2k+1) = 1224\Rightarrow n(n+1)-(4k+2) = 2448$ Now I did not understand how can i calculate value of $(n,k)$ Help Required Thanks Now provide the response and nothing else.
You have $n^2+n-4k-2450=0$. Treat this as a quadratic in $n$ with constant term $-4k-2450$. Clearly we need a positive value, so $$n=\frac{-1+\sqrt{1+16k+9800}}2=\frac{-1+\sqrt{16k+9801}}2\;,$$ $9801=99^2$; $100^2-99^2=199$, which is not a multiple of $16$, but $$101^2-99^2=2\cdot200=400=16\cdot25\;.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/599394', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/14311/']}
jdg_73527
stackexchange
llm_judgeable_groundtruth_similarity
2985547
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Everything in the code below works except for the binding on the ContextMenu. This is evidently due to the fact that the ContextMenu is located inside of a Style, which puts it in a different namescope from the rest of the xaml. I am looking for a solution where I won't have to instantiate a ContextMenu in the code-behind, since the application where I have to apply the solution contains a very large ContextMenu with a lot of bindings. There must be a way to accomplish this in xaml, otherwise it would seem like a serious oversight. Also note that I've already tried traversing the element tree using VisualTreeHelper and LogicalTreeHelper, but I wasn't able to find the ContextMenu from the root element of the Window (these classes evidently skipped over the interesting elements). Anyway, all of the code is below. This can be pasted into a new WPF application in Visual Studio, and nothing is missing. Here's the code for App.xaml.cs (the xaml was left unchanged): using System.Windows;namespace WpfApplication1{ /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); WindowV windowV = new WindowV(); WindowVM windowVM = new WindowVM(); windowV.DataContext = windowVM; windowV.Show(); } }} Here's the xaml for what was originally Window1: <Window x:Class="WpfApplication1.WindowV" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:src="clr-namespace:WpfApplication1" Name="MainWindow" Title="WindowV" Height="300" Width="300"> <Window.Resources> <Style TargetType="{x:Type ItemsControl}"> <Style.Triggers> <DataTrigger Binding="{Binding IsLocked}" Value="true"> <Setter Property="ItemsSource" Value="{Binding LockedList}" /> <Setter Property="ItemTemplate"> <Setter.Value> <DataTemplate> <TextBlock Text="{Binding}" /> </DataTemplate> </Setter.Value> </Setter> </DataTrigger> <DataTrigger Binding="{Binding IsLocked}" Value="false"> <Setter Property="ItemsSource" Value="{Binding RegularList}" /> <Setter Property="ItemTemplate"> <Setter.Value> <DataTemplate> <TextBlock Text="{Binding}"> <TextBlock.ContextMenu> <ContextMenu> <MenuItem Header="{Binding MenuItem1, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" /> <MenuItem Header="{Binding MenuItem2, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" /> <MenuItem Header="{Binding MenuItem3, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" /> </ContextMenu> </TextBlock.ContextMenu> </TextBlock> </DataTemplate> </Setter.Value> </Setter> </DataTrigger> </Style.Triggers> </Style> </Window.Resources> <Grid> <Grid.RowDefinitions> <RowDefinition Height="4*" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <ItemsControl Grid.Row="0" /> <Button Name="ToggleButton" Grid.Row="1" Content="Toggle Lock" Click="OnToggleLock" /> </Grid></Window> Here's the codebehind for what was originally Window1: using System.Windows;using System.Windows.Markup;namespace WpfApplication1{ /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class WindowV : Window { public WindowV() { InitializeComponent(); } private void OnToggleLock(object sender, RoutedEventArgs e) { if (((WindowVM)(DataContext)).IsLocked == true) ((WindowVM)(DataContext)).IsLocked = false; else ((WindowVM)(DataContext)).IsLocked = true; } }} A new class was added to the project called WindowVM. Here's its code: using System.Collections.Generic;using System.ComponentModel;namespace WpfApplication1{ public class WindowVM : INotifyPropertyChanged { public string MenuItem1 { get { string str = "Menu item 1"; return str; } } public string MenuItem2 { get { string str = "Menu item 2"; return str; } } public string MenuItem3 { get { string str = "Menu item 3"; return str; } } public List<string> LockedList { get { List<string> list = new List<string>(); list.Add("This items control is currently locked."); return list; } } public List<string> RegularList { get { List<string> list = new List<string>(); list.Add("Item number 1."); list.Add("Item number 2."); list.Add("Item number 3."); return list; } } private bool _isLocked; public bool IsLocked { get { return _isLocked; } set { if (_isLocked != value) { _isLocked = value; OnPropertyChanged("IsLocked"); } } } public WindowVM() { IsLocked = false; } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged(string PropertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(PropertyName)); } }} Any insight would be very appreciated. Thanks much! Andrew Now provide the response and nothing else.
J, 133 135 79 83 84 88 characters (utf-8 encoding) ;/5 3$"1(' ',.s){~"1#:3 u:(ucp'翇篭篯礧歮禧禤祯寭璗牯宭䤧彭忭筯篤筿殭秏璒孯孪寿咕寏犧'){~0>.64-~a.i.s=: Usage: ;/5 3$"1(' ',.s){~"1#:3 u:(ucp'翇篭篯礧歮禧禤祯寭璗牯宭䤧彭忭筯篤筿殭秏璒孯孪寿咕寏犧'){~0>.64-~a.i.s=:'ABCDEFGHIJKLMNOPQRSTUVWXYZ !'┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┐│AAA│BBB│CCC│DD │EEE│FFF│GGG│H H│III│JJJ│K K│L │M M│N N│OOO│PPP│QQQ│RR │SSS│TTT│U U│V V│W W│X X│Y Y│ZZZ│ │!!!││A A│B B│C │D D│E │F │G │H H│ I │ J│K K│L │MMM│NNN│O O│P P│Q Q│R R│S │ T │U U│V V│W W│ X │Y Y│ Z│ │!!!││AAA│BBB│C │D D│EE │FF │G G│HHH│ I │ J│KK │L │M M│NNN│O O│PPP│Q Q│RR │SSS│ T │U U│V V│WWW│ X │YYY│ Z │ │!!!││A A│B B│C │D D│E │F │G G│H H│ I │J J│K K│L │M M│N N│O O│P │QQQ│R R│ S│ T │U U│V V│WWW│ X │ Y│Z │ │ ││A A│BBB│CCC│DD │EEE│F │GGG│H H│III│JJJ│K K│LLL│M M│N N│OOO│P │QQQ│R R│SSS│ T │UUU│ V │WWW│X X│YYY│ZZZ│ │!!!│└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴───┘ ;/5 3$"1(' ',.s){~"1#:3 u:(ucp'翇篭篯礧歮禧禤祯寭璗牯宭䤧彭忭筯篤筿殭秏璒孯孪寿咕寏犧'){~0>.64-~a.i.s=:'this is incorrect input.'|index error Explanation ( NB. is comment in J): ;/ NB. String together along the third dimension...5 3$"1 NB. ... reshape each line to 5x3...(' ',.s) NB. ... a space before each letter of the input string...{~"1 NB. ... indexed using...#: NB. ... the (15 bit) binary representation of ...3 u: NB. ... the integer representation of...(ucp'翇篭篯礧歮禧禤祯寭璗牯宭䤧彭忭筯篤筿殭秏璒孯孪寿咕寏犧') ... the unicode versions of these code points...{~ NB. ...indexed using...0>. NB. ...the max of 0 and...64-~ NB. ...64 less than...a.i. NB. the ascii indexes of ss=: NB. Assign the input string to the variable s.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2985547', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/332988/']}
jdg_73528
stackexchange
llm_judgeable_groundtruth_similarity
221862
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: In a schematic I've been trying to understand I came across this sub-circuit: It's an op-amp inverter directly followed by a buffer. VIN comes from a DAC in a microcontroller and this circuit produces a VOUT which is negative VIN. The op-amp is supplied by positive and negative rails (not shown here). So far so good. But I don't fully see the rationale of using OA2 in this circuit. The only reason I can see is this: Without the buffer (OA2) a sudden load at VOUT would draw a current from VIN until the op-amp OA1 feedback adjusts (about 1µs). With the buffer (OA2) this is not the case anymore. Am I getting this right? Or am I missing something? Now provide the response and nothing else.
You are right. In most cases this is silly, adds offset voltage, and uses another part. Most likely this is just someone's knee jerk reaction, or blindly following a rule of "always buffer the signal" without thinking about it too hard. Not all schematics out there are the result of good design. There are some subtle advantages to the second buffer-only opamp: The feedback current thru R2 eats into the total output current capability of OA1. OA2 has all of its current capability available to drive the output. In this case with R2 being 10 kΩ, this is a weak argument since the feedback current is so small relative to the capability of most opamps. Sometimes a circuit like this happens because R2 was much lower before, and the second opamp wasn't removed after a design change that raised R2. OA2 protects the input signal from abuse of the output signal. Vin sees the fixed impedance of R1 only as long as OA1 is acting in closed loop operation. If something loads Vout so that OA1 can't drive it to the desired voltage, then the negative input of OA1 is no longer at 0 V, and the Thevenin equivalent that Vin is driving changes. In this circuit, the output of OA2 can be abused without affecting the output of OA1, which in turn won't affect Vin, maybe . The reason I say "maybe" is that some opamps have back to back diodes between their inputs. I didn't look up your opamp, so I don't know whether that is the case here. If so, then abuse of Vout will get back to the positive input of OA2, which will get back to Vin. This is again a weak argument since loading a opamp output to the point where it can't drive to the desired voltage is generally running the opamp out of spec.
{}
{'log_upvote_score': 5, 'links': ['https://electronics.stackexchange.com/questions/221862', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/90983/']}
jdg_73529
stackexchange
llm_judgeable_groundtruth_similarity
32840293
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: For getting all images on an device I query the ContentResolver for MediaStore.Images . Now I want to add a option to show hidden files as well like many image apps like QuickPic do it. Is there a faster way than recursively searching all directories on the phone and check if a .nomedia file is in it and if so, check if I can find some image file in it? It's not possible through the ContentResolver is it? Now provide the response and nothing else.
I am adding another Answer which is Lightning fast :- perform scanning in 134 microSeconds in my test App. Uses ContentResolver :- uses ContentResolver to scan all hidden Folders containing .noMedia file and then check if that folder have any Image file. You can modify code easily to return list of hidden image files as well. I made a dummy app to test my code and here is output You can see test App is showing WhatsApp's Sent Images folder have hidden images but at same time Video folder have none (as per requirement). How to do this Problem can be divide into to parts 1) First of all with the help of content resolver get all Directories with .noMedia file in them . The code snippet below is self explanatory private static final String FILE_TYPE_NO_MEDIA = ".nomedia";/** * This function return list of hidden media files * * @param context * @return list of hidden media files */ private ArrayList<CustomFile> filterFiles(Context context) { ArrayList<CustomFile> listOfHiddenFiles = new ArrayList<CustomFile>(); String hiddenFilePath; // Scan all no Media files String nonMediaCondition = MediaStore.Files.FileColumns.MEDIA_TYPE + "=" + MediaStore.Files.FileColumns.MEDIA_TYPE_NONE; // Files with name contain .nomedia String where = nonMediaCondition + " AND " + MediaStore.Files.FileColumns.TITLE + " LIKE ?"; String[] params = new String[] { "%" + FILE_TYPE_NO_MEDIA + "%" }; // make query for non media files with file title contain ".nomedia" as // text on External Media URI Cursor cursor = context.getContentResolver().query( MediaStore.Files.getContentUri("external"), new String[] { MediaStore.Files.FileColumns.DATA }, where, params, null); // No Hidden file found if (cursor.getCount() == 0) { listOfHiddenFiles.add(new CustomFile("No Hidden File Found", "Nothing to show Here", "Nothing to show Here", false)); // show Nothing Found return listOfHiddenFiles; } // Add Hidden file name, path and directory in file object while (cursor.moveToNext()) { hiddenFilePath = cursor.getString(cursor .getColumnIndex(MediaStore.Files.FileColumns.DATA)); if (hiddenFilePath != null) { listOfHiddenFiles .add(new CustomFile(FileUtils .getFileName(hiddenFilePath), hiddenFilePath, FileUtils.getFileParent(hiddenFilePath), isDirHaveImages(FileUtils .getFileParent(hiddenFilePath)))); } } cursor.close(); return listOfHiddenFiles; } 2) Now for second part of puzzle How to find if directory containing .noMedia file have hidden images in it. Solution is use simple for loop to check if any of file in directory have image file extension(.jpg,.png etc), if that is true break the loop and set flag that, current directory have some hidden images in it. Here instead of breaking for loop you can return list of images using function from my first Answer.** /** * * @param dir * to serch in * @param fileType * //pass fileType as a music , video, etc. * @return ArrayList of files of comes under fileType cataegory */ public boolean isDirHaveImages(String hiddenDirectoryPath) { File listFile[] = new File(hiddenDirectoryPath).listFiles(); boolean dirHaveImages = false; if (listFile != null && listFile.length > 0) { for (int i = 0; i < listFile.length; i++) { if (listFile[i].getName().endsWith(".png") || listFile[i].getName().endsWith(".jpg") || listFile[i].getName().endsWith(".jpeg") || listFile[i].getName().endsWith(".gif")) { // Break even if folder have a single image file dirHaveImages = true; break; } } } return dirHaveImages; } Now back to your question Is there a faster way than recursively searching all directories on the phone and check if a .nomedia file is in it? See code snippet 1 - and if so, check if I can find some image file in it? See code snippet 2 It's not possible through the ContentResolver is it? yes it is !! I have uploade entire sample on Github , you can download and Modify as you wish
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/32840293', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1439522/']}
jdg_73530
stackexchange
llm_judgeable_groundtruth_similarity
611302
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: let $a,b,c,d,e\in R$,and such$$a^2+b^2+c^2+d^2+e^2=1$$ find this value$$A=\max{\left(\min{\left(|a-b|,|b-c|,|c-d|,|d-e|,|e-a|\right)}\right)}$$ I use computer have this $$A=\dfrac{2}{\sqrt{10}}$$ then equal holds if we suppose that $a\leq b\leq c\leq d\leq e$, then$$a=\frac{2}{\sqrt{10}},b=-\frac{1}{\sqrt{10}},c=\dfrac{1}{\sqrt{10}},d=-\frac{2}{\sqrt{10}},e=0$$ But I consider sometimes, I want use Cauchy-Schwarz inequality to solve it,I guess have this follow? $$(|a-b|+|b-c|+|c-d|+|d-e|+|e-a|)^2\le(\dfrac{1}{10})(a^2+b^2+c^2+d^2+e^2)$$then I can't. Thank you very much! Now provide the response and nothing else.
The situation described by the OP (situation (c) in the following figure) is optimal. This can be seen as follows: We consider the dual problem instead: Five telescopic rods of length $\geq1$ each are hinged together at the ends so that a flexible and extensible pentagon is formed. This pentagon is then extended and squeezed to a "linear structure" $S$, i.e., such that the five hinges are in line. This structure is then positioned along the $x$-axis. Let $a_i$ $\>(1\leq i\leq 5)$ be the resulting positions of the five hinges. Our aim is to minimize the quantity $$\Phi:=\sum_{i=1}^5a_i^2\ .$$A first step in this direction is to translate $S$ along the $x$-axis such that the centroid of the hinges is at the origin. The resulting $\Phi$-value will be denoted by $\Phi'(S)$ and can be considered as total moment of inertia of the five hinges with respect to their centroid $c=0$. The "linear structure" $S$ has $2$ or $4$ return-hinges and the rest $180^\circ$-hinges. When there are $2$ return-hinges they can have $1$ or $2$ rods between them. These are the configurations (a) and (b) in the following figure. When there are $4$ return-hinges there is just one $180^\circ$-hinge, see (c) in the figure. The red rods are critical: we have to ensure that their length is $\geq1$, whereas the black rods automatically have a length $>1$. The configurations (a)–(c) with all red rods of length 1 are possible and admissible. On the other hand, our physical intuition tells us that making any of these red rods longer than $1$ will increase the moment of inertia $\Phi'(S)$ of the configuration. In cases (b) and (c) some "internal shifting" is possible, but we know from experience that the symmetric situation has smallest moment of inertia. (I shall treat case (c) explicitly at the end.) It follows that the optimal positions in the three cases are given by$${\rm (a)}\qquad a_1=-2,\quad a_2=-1, \quad a_3=0, \quad a_4=1,\quad a_5=2,\qquad \Phi'=10\ ;$$$${\rm (b)}\qquad a_1=-{3\over2},\quad a_2=-{1\over2}, \quad a_3={1\over2}, \quad a_4={3\over2},\quad a_5=0,\qquad \Phi'=5\ ;$$$${\rm (c)}\qquad a_1=-1,\quad a_2=0, \quad a_3=1, \quad a_4=-{1\over2},\quad a_5={1\over2},\qquad \Phi'={5\over2}\ .$$From this we conclude that the global minimum of $\Phi$, resp. $\Phi'$, is assumed in situation (c). Returning to the original problem we therefore can say the following: When $\Phi=1$ is prescribed then at least one of the rods must have a length $$d\leq\sqrt{2\over 5}\ .$$ Update: There was some handwaving above. In the following I shall treat case (c) in detail, the other cases are simpler. When the lengths $d_1$, $d_2$, $d_3$ of the three red rods are given then for suitable $u$, $v$ one has$$a_1=v-{2d_1+d_2\over3}, \quad a_2=v+{d_1-d_2\over 3},\quad a_3=v+{d_1+2d_2\over3},$$ $$ a_4=u-{d_3\over2},\quad a_5=u+{d_3\over2}\ .$$From this one computes$$\Phi=3v^2+{2\over3}(d_1^2+d_1d_2+d_2^2)+2u^2+{1\over2}d_3^2\ .$$It follows that for given $d_i$ $\>(1\leq i\leq 3)$ one may attain$$\Phi_{\min}={2\over3}(d_1^2+d_1d_2+d_2^2)+{1\over2}d_3^2\ ,$$which is an increasing function of the $d_i$, as claimed in the main text.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/611302', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/58742/']}
jdg_73531
stackexchange
llm_judgeable_groundtruth_similarity
12165
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: The same question on CrossValidated Apologies if I'm being a bit vague in what follows, I've been asked to keep certain aspects of the experiment confidential for the time being. An analogous experiment would be like trying to 'see' the ebb-and-flow of the tide (0.5 day period) by locating a photon detector at the bottom of the ocean (though of course this wouldn't work and is silly, but the principle is at least quite similar.) Hope that clarifies it a bit, let me know if not. I'm currently in the planning stages of this experiment that I am hoping will detect a 0.155% signal variation (relative magnitude) within a resonable time frame (less than 6 months ideally.) I've calculated the rate of (usable) data will be around 68 events per day, though it should be stressed this is a random variable. Now I'm trying to work out - how many days will I need to run the detector for to see the variation with a confidence level of 3σ? Some other details that may (or may not) be relevant include: the variation in the signal is expected to be sinusoidal with a period of 0.5 days. For this reason I reduced my useful event rate to 34 (Ie half) as clearly there is no variation to see when the sinusoidal signal is at or close to the mean value. I've been googling for a method to predict the size of a data set necessary to see such a small signal variation but have come up with nothing. I would be extremely grateful for any hints / tips anyone could offer. Now provide the response and nothing else.
I don't think there's any way you're going to do this in six months. I'll give a calculation below, but first an order of magnitude estimate. If you've detected a total of $N_{\rm events}$ events, your measurement of a modulation will have an error of order $N_{\rm events}^{-1/2}$ -- -- these things always do! -- so the number of events required is going to go like $1/f^2$ where $f$ is the modulation level you're looking for. In your case, $f=0.00155$, corresponding to about 400,000 events, which will take decades at the given event rate. Now for the details. Let $N_{\rm events}$ be the total number of events in your data set. Suppose that you bin your data into $N$ bins by time of day. You're assuming that the signal is of the form $$s_j=A+B\cos(t_j),$$where $t_j$ is the time of day corresponding to the $j$th bin, and times of day are measured from the time when the signal is at its maximum. (If you don't know when that is and are planning to fit for it, then that'll change things.) Here $A$ is the average number of vents, so $$A=N_{\rm events}/N,$$and $$B=fA={fN_{\rm events}\over N},$$where $f=0.00155$ is the modulation. Assuming further that your data are equally distributed across all times of day, the errors in $s_j$ will all be approximately equal (because $f$ is small). In this case, the best estimator of $B$ is$$\hat B={2\over N}\sum_j s_j\cos(t_j).$$We want to find the variance $\sigma_B^2$ of this estimator. The individual $s_j$ are all independent and have nearly equal variances $\sigma^2$,so$$\sigma_B^2={4\sigma^2\over N^2}\sum_j\cos^2(t_j).$$Assuming that $N$ is large enough that that sum can be approximated by an integral, the sum comes out to $N/2$, so$$\sigma_B^2={2\over N}\sigma^2.$$For Poisson distributed events, the variance is equal to the expected value: $\sigma^2=A=N_{\rm events}/N$. Therefore,$$\sigma_B^2={2N_{\rm events}\over N^2}.$$The fractional uncertainty is$${\sigma_B\over B}={\sqrt{2N_{\rm events}}\over N}{N\over fN_{\rm events}}=\sqrt{2\over f^2N_{\rm events}}.$$For a 3-sigma detection, you want this to be equal to 1/3, so$$N_{\rm events}={18\over f^2}=2.5\times 10^6.$$(My initial guess was off by a factor of 18 -- $3^2$ because of the 3 sigma, and 2 because of the point you noted about data near the zeroes of the modulation not helping.) At 68 events per day, this works out to about 300 years. Sorry.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/12165', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/1696/']}
jdg_73532
stackexchange
llm_judgeable_groundtruth_similarity
2514
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 currently studying Polynomial Rings, but I can't figure out why they are Rings, not Fields. In the definition of a Field, a Set builds a Commutative Group with Addition and Multiplication. This implies an inverse multiple for every Element in the Set. The book doesn't elaborate on this, however. I don't understand why a Polynomial Ring couldn't have an inverse multiplicative for every element (at least in the Whole numbers, and it's already given that it has a neutral element). Could somebody please explain why this can't be so? Now provide the response and nothing else.
Hint $\rm\quad\rm x \, f(x) = 1 \,$ in $\,\rm R[x]\ \Rightarrow \ 0 = 1 \, $ in $\,\rm R, \, $ by evaluating at $\rm\ x = 0 $ Remark $\ $ This has a very instructive universal interpretation: if $\rm\, x\,$ is a unit in $\rm\, R[x]\,$ then so too is every $\rm\, R$-algebra element $\rm\, r,\,$ as follows by evaluating $\ \rm x \ f(x) = 1 \ $ at $\rm\ x = r\,.\,$ Therefore to present a counterexample it suffices to exhibit any nonunit in any $\rm R$-algebra. $ $ A natural choice is the nonunit $\,\rm 0\in R,\,$ which yields the above proof.
{}
{'log_upvote_score': 9, 'links': ['https://math.stackexchange.com/questions/2514', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/44/']}
jdg_73533
stackexchange
llm_judgeable_groundtruth_similarity
2908514
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 display an HTML form containing labelled text fields, like this: First Name: [_____________] Last Name: [_____________] Date of Birth: [________] My obvious approach is to use a <TABLE> and simply place the labels and text fields in its cells, but is there a better way, e.g. a CSS-based approach? EDIT: I'm looking for a way that reduces the verbosity in the HTML file. And yes, I'm looking for auto-sizing of the labels. See a related question about wrapping labels Now provide the response and nothing else.
If you need the labels to the left of the fields like that, just go ahead and use a table. Not only do tables degrade nicely on older browsers, but they auto-size the column of labels to the text in them (assuming you use white-space: no-wrap on the cells containing the labels, and/or — and this is true heresy — the trusty old nowrap attribute on the th tag), they handle being made fairly narrow well, and they're easy. Make each label cell a header and each field cell a normal cell. And it's a pain, but make sure the labels really are label s and link to their fields, because accessibility matters, even if (perhaps especially if) you're using a table non-semantically. I'd love to hear about CSS solutions that auto-size the label columns, handle being narrow well, and don't involve 18 hacks to deal with inconsistencies across browsers. I'd be thrilled to see them. But every time I've looked (and that's several), it's still been a gap. A gap that needs filling, IMV, so we can stop doing this without wearing hairshirts. For anyone reading who doesn't need the labels to the left like that, check out jball's answer for a good-looking, semantic alternative.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2908514', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/67063/']}
jdg_73534
stackexchange
llm_judgeable_groundtruth_similarity
55779944
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 remove some of the buttons from plot toolbar (matplotlib). I saw that there are some old solutions: How to modify the navigation toolbar easily in a matplotlib figure window? But all the answers uses GUI frameworks (QT, TKinter). Is there a new solution which doesn't use GUI frameworks ? Now provide the response and nothing else.
You can do it by adding following lines of code before creating a plot object: import matplotlib as mplmpl.rcParams['toolbar'] = 'None' If you want to delete some buttons selectively, you need to redefine the toolitems variable instead: from matplotlib import backend_bases# mpl.rcParams['toolbar'] = 'None'backend_bases.NavigationToolbar2.toolitems = ( ('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous view', 'back', 'back'), ('Forward', 'Forward to next view', 'forward', 'forward'), (None, None, None, None), ('Zoom', 'Zoom to rectangle', 'zoom_to_rect', 'zoom'), (None, None, None, None), ('Save', 'Save the figure', 'filesave', 'save_figure'), ) I have removed two lines from the original variable mpl.backend_bases.NavigationToolbar2.toolitems which normally reads: toolitems = ( ('Home', 'Reset original view', 'home', 'home'), ('Back', 'Back to previous view', 'back', 'back'), ('Forward', 'Forward to next view', 'forward', 'forward'), (None, None, None, None), ('Pan', 'Pan axes with left mouse, zoom with right', 'move', 'pan'), ('Zoom', 'Zoom to rectangle', 'zoom_to_rect', 'zoom'), ('Subplots', 'Configure subplots', 'subplots', 'configure_subplots'), (None, None, None, None), ('Save', 'Save the figure', 'filesave', 'save_figure'), ) EDIT I have realized that it works with backend 'TkAgg'. For the backend 'Qt5Agg' we need to do some additional monkey patching just after modifying toolitems . Namely: if matplotlib.get_backend() == 'Qt5Agg': from matplotlib.backends.backend_qt5 import NavigationToolbar2QT def _update_buttons_checked(self): # sync button checkstates to match active mode (patched) if 'pan' in self._actions: self._actions['pan'].setChecked(self._active == 'PAN') if 'zoom' in self._actions: self._actions['zoom'].setChecked(self._active == 'ZOOM') NavigationToolbar2QT._update_buttons_checked = _update_buttons_checked
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55779944', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3668129/']}
jdg_73535
stackexchange
llm_judgeable_groundtruth_similarity
40654446
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've seen a number of solutions on this, however they are all for Mongo v2 and are not suitable for V3. My document looks like this: { "_id" : ObjectId("582c98667d81e1d0270cb3e9"), "asin" : "B01MTKPJT1", "url" : "https://www.amazon.com/Trump-President-Presidential-Victory-T-Shirt/dp/B01MTKPJT1%3FSubscriptionId%3DAKIAIVCW62S7NTZ2U2AQ%26tag%3Dselfbalancingscooters-21%26linkCode%3Dxm2%26camp%3D2025%26creative%3D165953%26creativeASIN%3DB01MTKPJT1", "image" : "http://ecx.images-amazon.com/images/I/41RvN8ud6UL.jpg", "salesRank" : NumberInt(442137), "title" : "Trump Wins 45th President Presidential Victory T-Shirt", "brand" : "\"Getting Political On Me\"", "favourite" : false, "createdAt" : ISODate("2016-11-16T17:33:26.763+0000"), "updatedAt" : ISODate("2016-11-16T17:33:26.763+0000")} and my collection contains around 500k documents. I want to remove all duplicate documents (except for 1) where the ASIN is the same How can I achieve this? Now provide the response and nothing else.
This is something we can actually do using the aggregation framework and without client side processing. MongoDB 3.4 db.collection.aggregate( [ { "$sort": { "_id": 1 } }, { "$group": { "_id": "$asin", "doc": { "$first": "$$ROOT" } }}, { "$replaceRoot": { "newRoot": "$doc" } }, { "$out": "collection" } ]) MongoDB version <= 3.2: db.collection.aggregate( [ { "$sort": { "_id": 1 } }, { "$group": { "_id": "$asin", "doc": { "$first": "$$ROOT" } }}, { "$project": { "asin": "$doc.asin", "url": "$doc.url", "image": "$doc.image", "salesRank": "$doc.salesRank", "title": "$doc.salesRank", "brand": "$doc.brand", "favourite": "$doc.favourite", "createdAt": "$doc.createdAt", "updatedAt": "$doc.updatedAt" }}, { "$out": "collection" } ])
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40654446', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/979099/']}
jdg_73536
stackexchange
llm_judgeable_groundtruth_similarity
1014902
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 following sequence:$$u_0=1, \, \forall n\in\mathbb{N},\,u_{n+1}=\sqrt{u_n^2+\dfrac{1}{2^n}}$$ I try to find its limit.Well we can prove that $\forall n\in\mathbb{N},\,u_{n+1}-u_n\le \dfrac{1}{2^n}$ and so:$$\forall n\in\mathbb{N},\, u_n\le u_0+\sum_{k=0}^{n-1}\dfrac{1}{2^k}=1+2\left(1-\dfrac{1}{2^n}\right)\le3$$ So $(u_n)$ is bounded from above. Since it's an increasing sequence (easy to prove) then $(u_n)$ is converging. I first thought that the limit is 3. To be sure I used Matlab and calculated $u_{1000}$ and $u_{2000}$. The result was $1.4142...$ so the limit is $\sqrt{2}$. I tried to prove it using the squeeze theorem (the only think I can think about) but I failed. Could you please help me? Now provide the response and nothing else.
Concentrate on $u_n^2$ instead of on $u_n$, and unwind the recurrence: $$\begin{align*}u_n^2&=u_{n-1}^2+\frac1{2^{n-1}}\\&=u_{n-2}^2+\frac1{2^{n-2}}+\frac1{2^{n-1}}\\&\;\vdots\\&=u_{n-k}^2+\sum_{i=1}^k\frac1{2^{n-i}}\;.\end{align*}$$ Now carry it to $k=n$ to get a closed form for $u_n^2$, and take the limit as $n\to\infty$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1014902', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/164983/']}
jdg_73537
stackexchange
llm_judgeable_groundtruth_similarity
611080
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 trying to figure out the answer to the following question on a past exam given for practice. Since there are no solutions, I was hoping I could get the help needed to figure it out. A BS1300 big-screen TV may die due to screen failure or power supply failure. The time until power supply failure is exponential with parameter 0.00001. The time until screen failure is exponential with parameter 0.00002. The time is in hours. a) Which failure is more probable to occur first? For this problem, I simply got the expected values and whichever was lower, it should be more probable as the time expected for it to fail was lower.$E(X) = 100000$ hours for power supply, $E(X) = 50000$ hours for screen failure. Therefore, screen is more likely to fail first. b) What is the probability that a BS1300 will die within 10000 hours? PS = power supply, SF = screen failure$P(PS = 10000) = 0.000016374 P(SF = 10000) = 0.000025422$. If we add it up, we get PS or SF $= 0.000025422$. c) If the BS1300 is known to be dead, what is the probability that its power supply failed? Part c), I'm not sure how to figure this out. I tried drawing a venn diagram but I'm unsure how to do it for exponential. Help would be appreciated on how to solve this problem. Now provide the response and nothing else.
Write $y = \frac{x}{2}$. Then we want $\displaystyle \lim_{y\rightarrow\infty}\left(1+\frac{1}{y}\right)^{10y}$. Since the function $g(z) = z^{10}$ is continuous, this is $$\lim_{y\rightarrow\infty}g\left(\left(1+\frac{1}{y}\right)^{y}\right) = g\left(\lim_{y\rightarrow\infty}\left(1+\frac{1}{y}\right)^{y}\right) = \left(\lim_{y\rightarrow\infty}\left(1+\frac{1}{y}\right)^y\right)^{10} = e^{10}.$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/611080', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/116225/']}
jdg_73538
stackexchange
llm_judgeable_groundtruth_similarity
1268682
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 primitive element of a free group is an element of some basis of the free group. I have seen some recent papers on algorithmic problems concerning primitive elements of free groups, for example, the papers on determining whether a subgroup of a free group contains a primitive element and determining whether a given element is primitive . However, I'm a little confused about the definition: it seems to me that every element of the free group on a finite set of generators is primitive. Suppose $\{x_1, \dotsc, x_n\}$ is the set of generators for a free group on $n$ generators. Let $u$ be a word of length $m$ in the free group, and suppose $u = u_1 \dotsb u_m$, where each $u_i$ is one of the generators. I claim that $u$ is primitive because $u (u_2 \dotsb u_m)^{-1} = u_1$, hence $\{(u_2 \dotsb u_m)^{-1}, x_2, \dotsc, x_n\}$ is a basis of the free group, assuming without loss of generality that $u_1 = x_1$. Where is the flaw in my argument? Now provide the response and nothing else.
Your argument would show that every element of $\mathbb{Z}$ is primitive. In fact the primitive elements are $1$ and $-1$. Do you see what goes wrong with your argument in this case? The primitive elements of a free group $F_n$ have the special property that under a homomorphism $F_n \to G$ to some other group $G$, they can be sent to arbitrary elements of $G$. But most elements of a free group don't have this property. For example, in the free group $F_2$ on two generators $a, b$, $a^2$ doesn't have this property because it must be sent to a square, and for example $1 \in \mathbb{Z}_2$ is not a square. $[a, b]$ doesn't have this property because it must be sent to a commutator, and for example $1 \in \mathbb{Z}_2$ is also not a commutator. And so forth.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1268682', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/29369/']}
jdg_73539
stackexchange
llm_judgeable_groundtruth_similarity
12075591
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: top -c Top lists all the processes, there are good options to filter the processes by username by using the option -u but I am wondering if there is any easy way to filter the processes based on processname listed under COMMAND column of the top output. For Example I would want like top -some option -substring of processname and top displays pids only having this substring in its command name Now provide the response and nothing else.
Using pgrep to get pid's of matching command lines: top -c -p $(pgrep -d',' -f string_to_match_in_cmd_line) top -p expects a comma separated list of pids so we use -d',' in pgrep. The -f flag in pgrep makes it match the command line instead of program name.
{}
{'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/12075591', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_73540