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
1050561
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: There is a positive integer $N$. $N$ is made up of only two distinct digits- $2$ and $3$. $N+18$ is divisible by $37$. What is the minunum amount of times the number $2$ can appear in $N$? I'm pretty sure the answer is only one time. But how can I prove this? Now provide the response and nothing else.
Let's start with a simple observation: The number $37$ plays very nicely with powers of $10$... The value $10^m$ can only have three possible remainders modulo $37$: $1$, $10$ and $26$. If $N+18$ is divisible by $37$, $N$ must be congruent to $19$ modulo $37$. This observation will be quite useful in subsequent thoughts. The number $N=2323323$ satisfies the given conditions and contains three twos. In order to show that we cannot satisfy the conditions given with fewer twos, we need to consider three cases: Numbers consisting solely of digit $3$: An $m$-digit number of this form is equal to $$\frac{3}{9}(10^m-1)=\frac{1}{3}(10^m-1)$$Using the observation mentioned above, we find that such numbers produce remainders $0$, $3$ and $33$ modulo $37$; none of which is equal to the desired $19$. Numbers having exactly one occurrence of $2$: They can be obtained by the numbers in the preceding group by subtracting number of the form $10^k$ with $k\leq m$. The observation allows us to quickly conclude that the only remainders of such numbers modulo $37$ are $2$,$7$, $11$, $14$, $23$, $27$, $30$, $32$ and $36$. Numbers having exactly two occurrences of $2$ are just as easy to deal with; there are just more remainders to cover... but still no $19$ among them.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1050561', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/114495/']}
jdg_85441
stackexchange
llm_judgeable_groundtruth_similarity
14129278
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 customize the color of text in IPython, but am not sure how to do it. I know that in Python, I can do this by ending sys.ps1 and sys.ps2 with an ANSI color code such as sys.ps1=">>> \001\033[0m\033[34m\002" But the corresponding approach, using PromptManager.in_template , does not work for IPython. For example c = get_config()c.PromptManager.in_template = 'In [{count}] : {color.Blue}' has no effect on the color of text after the prompt. Is there a way to change the color of text in IPython? Now provide the response and nothing else.
Colorize and Syntax Style in IPython First you have to create a ipython profile ~/.iphyton/ipython_config.py in your home directory. ipython_config.py . The easiest way to do so is to run the following command: ipython profile create In case you are using ipython3 start ipython3 profile create This will install a profile_default directory and some scripts in your ~/.ipython ; otherwise find this file on your machine and duplicate it in your ~/.ipython/profile_default/ directory. Make a backup of this file with: cp ~/.ipython/profile_default/ipython_config.py{,_backup} Open the ~/.ipython/profile_default/ipython_config.py with an text editor of your choice and search for following settig and comment it out if you like it (delete the '#'): c.InteractiveShell.color_info = True c.InteractiveShell.colors = 'Linux' c.TerminalInteractiveShell.highlighting_style = 'monokai' c.TerminalInteractiveShell.highlight_matching_brackets = True and so on. There are many usefull settings which are disabled by default; you have only to comment them out (deleting the `#' ). Style Files On Ubuntu/Debian you have to install the pygments package sudo apt install python3-pygments or sudo pip3 install pygments The style files can be found in following directory: /path/to/your/python/ site-packages/pygments/styles/ , e.g. /usr/lib/python3/dist-packages/pygments/styles/monokai.py Alternatively, you can also list your installed styles with pygmentize : pygmentize -L styles
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14129278', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/656912/']}
jdg_85442
stackexchange
llm_judgeable_groundtruth_similarity
1256704
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 python script which process a file line by line, if the linematches a regex, it calls a function to handle it. My question is is there a better write to refactor my script. Thescript works, but as it is, i need to keep indent to the right of theeditor as I add more and more regex for my file. Thank you for any idea.Now my code end up like this: for line in fi.readlines(): result= reg1.match(line) if result: handleReg1(result) else: result = reg2.match(line) if result: handleReg2(result) else: result = reg3.match(line) if result: handleReg3(result) else: result = reg4.match(line) if result: handleReg4(result) else: result = reg5.match(line) if result: handleReg5(result) Now provide the response and nothing else.
I'd switch to using a data structure mapping regexes to functions. Something like: map = { reg1: handleReg1, reg2: handleReg2, etc } Then you just loop through them: for reg, handler in map.items(): result = reg.match(line) if result: handler(result) break If you need the matches to happen in a particular order you'll need to use a list instead of a dictionary, but the principal is the same.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1256704', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/125440/']}
jdg_85443
stackexchange
llm_judgeable_groundtruth_similarity
450369
Below is a question asked on the forum unix.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have the following command: python -c 'import crypt; print(crypt.crypt("$Password", crypt.mksalt(crypt.METHOD_SHA512)))' Where $Password is a shell variable. How do I correctly expand it as a variable, and not have it treated as a literal? Now provide the response and nothing else.
Don't as that would be a code injection vulnerability and also avoid passing passwords in arguments to commands, as they then become public by showing in the output of ps and they are sometimes logged in some audit logs. Using environment variables is usually better: PASSWORD="$Password" python3 -c 'import os, cryptprint(crypt.crypt(os.getenv("PASSWORD"), crypt.mksalt(crypt.METHOD_SHA512)))' (here using the VAR=value cmd syntax as opposed to export VAR so the environment variable is passed only to that one command invocation).
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/450369', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/293979/']}
jdg_85444
stackexchange
llm_judgeable_groundtruth_similarity
4900923
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: If I expose an IEnumerable<T> as a property of a class, is there any possibility that it can be mutated by the users of a class, and if so what is the best way of protecting against mutation, while keeping the exposed property's type IEnumerable<T> ? Now provide the response and nothing else.
It depends on what you're returning. If you return (say) a mutable List<string> then the client could indeed cast it back to List<string> and mutate it. How you protect your data depends on what you've got to start with. ReadOnlyCollection<T> is a good wrapper class, assuming you've got an IList<T> to start with. If your clients won't benefit from the return value implementing IList<T> or ICollection<T> , you could always do something like: public IEnumerable<string> Names{ get { return names.Select(x => x); }} which effectively wraps the collection in an iterator. (There are various different ways of using LINQ to hide the source... although it's not documented which operators hide the source and which don't. For example calling Skip(0) does hide the source in the Microsoft implementation, but isn't documented to do so.) Select definitely should hide the source though.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4900923', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']}
jdg_85445
stackexchange
llm_judgeable_groundtruth_similarity
52086
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: What is the difference between indistinguishable particles and identical particles ? Now provide the response and nothing else.
If I create an electron on earth and someone else creates an electron on Andromeda, they're identical particles. They have the same quantum numbers, they're both excitations of the electron field. However they're distinguishable by means of their spatial separation. Their wavefunctions don't overlap. Edit: perhaps I should add that not everyone uses the two words in this strict sense. Sometimes they're used interchangeably, but blurring them carries with it the danger of taking seriously the entanglement implied by antisymmetrizing across all existing electrons.
{}
{'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/52086', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/4521/']}
jdg_85446
stackexchange
llm_judgeable_groundtruth_similarity
450226
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: Just wondering if this: if [ "$first_arg" == "major" ] || [ "$first_arg" == "minor" ]; then exit 1;fi is the same as this: if [ "$first_arg" == "major" || "$first_arg" == "minor" ]; then exit 1;fi Now provide the response and nothing else.
They're not the same. In fact [ "$first_arg" == "major" || "$first_arg" == "minor" ] is not even a valid expression. This is because [ is a command that's equivalent to test and they can't use the || alternative, which operates on the inter-command level. What could be historically considered correct for alternative is -o , but it's now marked as obsolete by POSIX 1 , which advises to rewrite test "$1" -o "$2" into test "$1" || test "$2" Apart from the test and [ constructs, there's also the "modern" [[ test command, which in turn doesn't accept -o altogether, but instead accepts || . Thus all of these are valid and equivalent: One [[ test: if [[ $first_arg == major || $first_arg == minor ]]; then exit 1;fi Two [[ tests: if [[ $first_arg == major ]] || [[ $first_arg == minor ]]; then exit 1;fi Two [ tests (the standard equivalent): if [ "$first_arg" = major ] || [ "$first_arg" = minor ]; then exit 1;fi Double quotes aroung $first_arg are not necessary inside [[ , as there's no word splitting nor pathname expansion in there. The quotes should be used with [ , however. And there's no point in quoting minor nor major either. Not just here, but with test or [ too. That's because they're simple strings. 1. See APPLICATION USAGE.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/450226', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/113238/']}
jdg_85447
stackexchange
llm_judgeable_groundtruth_similarity
29873677
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 from skeleton like below @using (Html.BeginForm("Preapprove", "Preapproval", FormMethod.Post, new { name = "form1", id = "form1", enctype = "multipart/form-data", @class = "form-horizontal" })){ ......<input name="submit" type="button" value="Submit" id="Sub" class="btn btn-success" style="margin-left:950px" /> } And in jquery im submitting this form on the click even of the button id Sub $(document).ready(function () { $('#Sub').click(function (e) { var error_flag = 0; if (d_row_count == 1) { error_flag = 1; } else if (d_row_count > 1) { if (code == null || code.trim() == '') { error_flag = 1; } else if (s_row_count == 1) { error_flag = 1; } } if (error_flag != 1) { alert("submitting"); $("#form1").submit(); } }); When all the validation passed the error_flag will be 0 and it is getting inside the if condition and giving me the alert "Submitting" but the form is not getting submitted. Anything im missing on the code? Now provide the response and nothing else.
You need to change the name of the input button from "submit" to something else. Having an element named "submit" causes the form's submit method to no longer work, which means the form cannot be submitted via JavaScript (at least, not easily). The reason for this is because an input element named "submit" can be referenced by its name like this: form1.submit . That is, the input element is added as a property of the form object, with the property name being the name of the input element. That basically hides the submit function that is on the form's prototype. I say "not easily" above, because the following still works (at least in Firefox): HTMLFormElement.prototype.submit.call($("#form1")[0]);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/29873677', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2706726/']}
jdg_85448
stackexchange
llm_judgeable_groundtruth_similarity
2911330
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: Finding the slopes of internal or external angle bisectors, when given the slopes of the sides of a triangle, it's a simple question, the one you can easily find in any textbook of analytic geometry. But the reverse problem : finding the slopes of the sides of a triangle, when only given the slopes of internal angle bisectors. Is it possible? Is there a straightforward formula for that? Now provide the response and nothing else.
First, let's observe that $[P_i(x)]+4\cdot[P_{iv}(x)]=1+3\cdot[P_{iv}(x)]$. We can check three cases: $x<3$: Our equation becomes $x=1+3\cdot(x\%2)$ where $\%$ is the mod operator. Clearly, no even number can satisfy this equation, and neither can an odd number. So, $x\geq3$. $3\leq x<6$ We can convert the equation to $x=3+3\cdot(x\%2)$. Again, no even or odd numbers can satisfy this equation, so we move on to case three. $x\geq6$ Since we know any solution must satisfy this, we can convert the equation to $6+3\cdot(x\%2)$. So, $x=6$ and $x=9$ are solutions. Hence, there are $\color{red}{2}$ solutions to this equation.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2911330', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/591638/']}
jdg_85449
stackexchange
llm_judgeable_groundtruth_similarity
16377926
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to generate a hashCode() method for my simple class but i'm not getting anywhere with it. I would appreciate any help. I've implemented the equals() method, which looks as follows, and would also like to know if I need to implement compareTo() method. I've imported java.lang.Character to use character.hashCode() but it doesn't seem to work. private class Coord{ private char row; private char col; public Coord(char x, char y){ row = x; col = y; } public Coord(){}; public char getX(){ return row; } public char getY(){ return col; } public boolean equals(Object copy){ if(copy == null){ throw new NullPointerException("Object entered is empty"); } else if(copy.getClass()!=this.getClass()){ throw new IllegalArgumentException("Object entered is not Coord"); } else{ Coord copy2 = (Coord)copy; if(copy2.row==this.row && copy2.col==this.col) return true; else return false; } }} Thanks in advance... The comparTo() method that is giving me java.lang.Comparable casting error.. public int compareTo(Object copy){ if(copy==null){ throw new NullPointerException("Object entered is empty"); } else if(copy.getClass()!=this.getClass()){ throw new IllegalArgumentException("Object entered is not Coord"); } else{ Coord copy2 = (Coord)copy; if(copy2.row==this.row && copy2.col==this.col){ return 0; } else if(copy2.col < this.col){ return -1; } else{ return 1; } } } thanks... Now provide the response and nothing else.
To implement hashCode, you override the default implementation from Object: @Overridepublic int hashCode(){ return row ^ col;} This isn't really an ideal hash, since its results are very predictable and it is easy for two different Coord objects to return the same value. A better hash would make use of the built-in Arrays class from java.util ( http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html ): @Overridepublic int hashCode(){ return Arrays.hashCode(new Object[]{new Character(row), new Character(col)});} You can use this method to generate a pretty good hash with any number of fields. To implement compareTo, you'll want your class to implement Comparable : public class Coord implements Comparable<Coord> Once you've done this, you can make compareTo take an argument of type Coord rather than type Object , which will save you the trouble of checking its type.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16377926', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1114931/']}
jdg_85450
stackexchange
llm_judgeable_groundtruth_similarity
47247952
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 on ubuntu 16.04. I have a (testing) docker (docker-compose) container running php 5.6 and apache 2.4. On the production platform (without docker) the mail is sent with sendmail. How to send test email on docker container (with sendmail)? Thanks in advance for responses. Now provide the response and nothing else.
It works. In Dockerfile : # sendmail config############################################RUN apt-get install -q -y ssmtp mailutils# root is the person who gets all mail for userids < 1000RUN echo "[email protected]" >> /etc/ssmtp/ssmtp.conf# Here is the gmail configuration (or change it to your private smtp server)RUN echo "mailhub=smtp.gmail.com:587" >> /etc/ssmtp/ssmtp.confRUN echo "[email protected]" >> /etc/ssmtp/ssmtp.confRUN echo "AuthPass=yourGmailPass" >> /etc/ssmtp/ssmtp.confRUN echo "UseTLS=YES" >> /etc/ssmtp/ssmtp.confRUN echo "UseSTARTTLS=YES" >> /etc/ssmtp/ssmtp.conf# Set up php sendmail configRUN echo "sendmail_path=sendmail -i -t" >> /usr/local/etc/php/conf.d/php-sendmail.ini For testing inside php sendmail container : echo "Un message de test" | mail -s "sujet de test" [email protected] I succeed with the help of this two documents : https://unix.stackexchange.com/questions/36982/can-i-set-up-system-mail-to-use-an-external-smtp-server https://github.com/cmaessen/docker-php-sendmail/blob/master/Dockerfile
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/47247952', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1768583/']}
jdg_85451
stackexchange
llm_judgeable_groundtruth_similarity
1700917
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: see also " WCF push to client through firewall " I need to have a WCF client that connect to a WCF server, then when some of the data changes on the server the clients need to update its display. As there is likely to be a firewall between the clients and the server. All communications must be over HTTP The server can not make an (physical) outgoing call to the client. As I am writing both the client and the server I do not need to limit the solution to only using soap etc. I am looking for built in surport for " long polling " / " Comet " etc Thanks for the most informative answer from Drew Marsh on how to implement long polling in WCF. However I thought the main “selling point” of WCF was that you could do this sort of thing just by configuring the channels to be used in the config file. E.g I want a channel that logically two way but physically incoming only. Now provide the response and nothing else.
It sounds to me like you already know the answer: use long polling. :) So I guess the only thing left to explain is how you might be able to accomplish this with WCF and in the most efficient manner possible. The basics: First, decide how long you want each "long poll" to be. For argument's sake I'm going to choose 5min timeouts. On the client side binding, change the sendTimeout="00:05:00" . Just like using XmlHttpRequest (XHR) for long polling, when the timeout does actually occur, you will need to detect it and re-issue the next polling request. This is quite easy in WCF because there is a specific exception, TimeoutException , that you can catch to easily detect this was the issue vs. some other exception. Depending on how you're hosting your WCF service, you will need to make sure to configure yourself to allow processing for up to 5mins. From a pure WCF perspective you'll want to make sure you set the receiveTimeout="00:05:00" . However, if you're hosting inside of ASP.NET you will also need to configure the ASP.NET runtime to have a higher timeout which is done using the <httpRuntime executionTimeout="300" /> ( note: the measurements are in seconds for this attribute). Being efficient in the client If you just setup your client to synchronously call the service and the client blocks for 5mins while waiting for a response, that's not a very efficient use of system resources. You could put these calls on background threads, but that's still going to chew up a thread resource while the call is outstanding. The most efficient way to deal with this is to use async operations. If you're creating your service contracts by hand, I would suggest checking out this section on MSDN on OperationContractAttribute.AsyncPattern for details on how to add a BeginXXX / EndXXX async method pair for each of your calls. However, if you're using svcutil to generate your operation contracts for you, all you need to do to have async methods generated is pass the /async option on the command line. For more details on this topic, check out the Synchronous and Asynchronous topic on MSDN . Now that you've go your async operations define, the pattern is very much like working with XHR. You call the BeginXXX method to which you pass an AsyncCallback delegate . The BeginXXX method will return you an IAsyncResult , which you can either hold onto if you wanted to be able to wait on the operation (in more advanced scenarios) or ignore, and then the WCF infrastructure will asynchronously send the request to the server and wait for a response behind the scenes. When a response is received or an exception occurs, the callback you passed into the BeginXXX method will be invoked. Inside of this callback method you need to call the corresponding EndXXX method passing in the IAsyncResult that is handed to you. During the call to the EndXXX method you need to employ exception handling to deal with any kind of logical fault that may have occurred while calling the method, but this is also where you'd now be able to catch the TimeoutException we talked about earlier. Assuming you got a good response, the data will be the returned from the EndXXX call and you can react to that data in whatever way makes sense. NOTE: One thing to keep in mind about this pattern is the nature of the threading. The async callbacks from WCF will be received on a thread from the managed thread pool . If you're planning on updating the UI in a technology such as WPF or WinForms, you need to make sure you marshal the calls back to the UI thread using the Invoke or BeginInvoke methods. Being efficient on the server If we're going to be worried about efficiency in the client, we should be doubly so when it comes to the server. Obviously this type of approach puts more demand on the server side because a connection must remain open and pending until there is a reason to send notification back to the client. The challenge here is that you only want to tie the WCF runtime up with the processing of those clients who are actually being sent an event. Everything else should just be asleep, waiting for the event to occur. Luckily the same async pattern we just used on the client side also works on the servers side. However, there is now a major difference: now you must return the IAsyncResult (and thus a WaitHandle ) from the BeginXXX method which the WCF runtime will then wait to be signaled on before calling your EndXXX method. You will not find much in the way of documentation inside of MSDN other than the links I've already provided earlier and, unfortunately, their samples on writing an async-service are less than useful. That said, Wenlong Dong wrote a piece about scaling WCF services with the async model some time ago that I highly recommend you check out. Beyond this, I honestly I can't give too much advice on how best to implement the asynchronous model on the server side for you bcause it depends entirely on what kind of data source your events will be coming from in the first place. File I/O? A message queue? A database? Some other proprietary software with its own messaging service that you're trying to provide a façade over? I don't know, but they should all offer an async models of their own on which you can piggy back your own service to make it as efficient as possible. Updated Prescription Since this seems to be a popular answer, I figured I should come back here and provide an update given the recent changes in the landscape. At this point there is now a .NET library called SignalR which provides this exact functionality and is definitely how I would recommend implementing any such communication with the server.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1700917', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/57159/']}
jdg_85452
stackexchange
llm_judgeable_groundtruth_similarity
2955968
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: When we consider a vector space $V$ over some field $F$ , I know that when the $F=\mathbb{R}$ or $ =\mathbb{C}$ , by setting $\|x\|=\left\langle{x,x}\right\rangle^\frac{1}{2}$ we get a norm. However, since the inner product is a function with its image in $F$ , what happens if we consider any $V$ over the rational numbers? For example, if we take $\mathbb{Q}^2$ over $\mathbb{Q}$ with the dot product, then $v=(1,1)$ has norm $\sqrt{2}$ , which is not rational. How can one obtain a norm from a given inner product in such cases? Now provide the response and nothing else.
An ordered field where $a^2+b^2$ is always a square is called a Pythagorean field . As you observe, not every ordered field is Pythagorean, but eachordered field has a Pythagorean extension. If you really want $L^2$ -normsyou could always extend your ground field to a Pythagorean extension field.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2955968', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/393965/']}
jdg_85453
stackexchange
llm_judgeable_groundtruth_similarity
36938976
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Quoting the Spark DataFrames, Datasets and SQL manual : A handful of Hive optimizations are not yet included in Spark. Some of these (such as indexes) are less important due to Spark SQL’s in-memory computational model. Others are slotted for future releases of Spark SQL. Being new to Spark, I'm a bit baffled by this for two reasons: Spark SQL is designed to process Big Data, and at least in my usecase the data size far exceeds the size of available memory.Assuming this is not uncommon, what is meant by "Spark SQL’sin-memory computational model"? Is Spark SQL recommended only forcases where the data fits in memory? Even assuming the data fits in memory, a full scan over a very large dataset can take a long time. I read this argument against indexing in in-memory database, but I was not convinced. The example there discusses a scan of a 10,000,000 records table, but that's not really big data. Scanning a table with billions of records can cause simple queries of the "SELECT x WHERE y=z" type take forever instead of returning immediately. I understand that Indexes have disadvantages like slower INSERT/UPDATE, space requirements, etc. But in my use case, I first process and load a large batch of data into Spark SQL, and then explore this data as a whole, without further modifications. Spark SQL is useful for the initial distributed processing and loading of the data, but the lack of indexing makes interactive exploration slower and more cumbersome than I expected it to be. I'm wondering then why the Spark SQL team considers indexes unimportant to a degree that it's off their road map. Is there a different usage pattern that can provide the benefits of indexing without resorting to implementing something equivalent independently? Now provide the response and nothing else.
Indexing input data The fundamental reason why indexing over external data sources is not in the Spark scope is that Spark is not a data management system but a batch data processing engine. Since it doesn't own the data it is using it cannot reliably monitor changes and as a consequence cannot maintain indices. If data source supports indexing it can be indirectly utilized by Spark through mechanisms like predicate pushdown. Indexing Distributed Data Structures : standard indexing techniques require persistent and well defined data distribution but data in Spark is typically ephemeral and its exact distribution is nondeterministic. high level data layout achieved by proper partitioning combined with columnar storage and compression can provide very efficient distributed access without an overhead of creating, storing and maintaining indices.This is a common pattern used by different in-memory columnar systems. That being said some forms of indexed structures do exist in Spark ecosystem. Most notably Databricks provides Data Skipping Index on its platform. Other projects, like Succinct (mostly inactive today) take different approach and use advanced compression techniques with with random access support. Of course this raises a question - if you require an efficient random access why not use a system which is design as a database from the beginning. There many choices out there, including at least a few maintained by the Apache Foundation. At the same time Spark as a project evolves, and the quote you used might not fully reflect future Spark directions.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/36938976', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/524283/']}
jdg_85454
stackexchange
llm_judgeable_groundtruth_similarity
148027
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: This is a bit of a repost from an old question, but it doesn't seem like it was fully answered before and this is a bit of an abstraction from that post. I'm trying to show the following: Let $f(z)$ be an entire function such that $f(z)=f(z+1)$ for all $z$ . If there exists $c\in(0,1)$ such that $|f(z)|\le e^{c|z|}$ for all $z$ , then $f(z)=0$ . The previous post was here: Entire "periodic" function I've tried using Zarrax's method in that post: The periodicity of $f(z)$ allows us to write $f(z)=g(e^{2\pi i z})$ , since $e^{2\pi i (x+iy)}=e^{2\pi i (x+1+iy)}$ . Now we have: $$\left|g(e^{2\pi i z})\right|\le e^{c|z|}$$ Now make a change of variables, re-writing $z=(2\pi i)^{-1}\log z$ : $$\left|g(z)\right|\le e^{c\left|\frac{\log z}{2\pi i}\right|}$$ Now assume $|z|\ge 1$ : $$\left|g(z)\right|\le e^{\frac{c}{2\pi}(\log |z|+2\pi)}=|z|^\frac{c}{2\pi}e^c$$ So now I would say that this implies $g(z)$ has to be a polynomial, but I don't really see how I can derive a contradiction from that. Now provide the response and nothing else.
We will prove that $p$ does not divide $\dbinom{n}{k}$ for any $k \in \{0,1,2,\ldots,n\}$ iff $ n = p^m-1$. Write $n$ in base $p$ as $$n = \sum_{i=0}^{l} n_i p^i$$ The highest power of $p$ that divides $n!$ is $$\left \lfloor \frac{n}{p} \right \rfloor + \left \lfloor \frac{n}{p^2} \right \rfloor + \cdots + \left \lfloor \frac{n}{p^l} \right \rfloor = \sum_{i=1}^{l} n_i p^{i-1} + \sum_{i=2}^{l} n_i p^{i-2} + \cdots + \sum_{i=l}^{l} n_i p^{i-l}\\ = \sum_{i=1}^{l} n_i \left( p^{i-1} + p^{i-2} + \cdots + 1\right) = \sum_{i=0}^{l} n_i \left( p^i - 1 \right) = n - \sum_{i=0}^{l} n_i$$ The power of $p$ that divides the binomial coefficient $\dbinom{n}{k}$ is nothing but $$(n - \sum_{i=0}^{l} n_i) - (k - \sum_{i=0}^{l} k_i) - (n -k - \sum_{i=0}^{l} (n-k)_i) = \sum_{i=0}^{l} k_i + \sum_{i=0}^{l} (n-k)_i - \sum_{i=0}^{l} n_i$$ Hence, $p \not \vert \dbinom{n}{k}$ if and only if $$\sum_{i=0}^{l} k_i + \sum_{i=0}^{l} (n-k)_i - \sum_{i=0}^{l} n_i = 0$$ i.e. $$\sum_{i=0}^{l} n_i = \sum_{i=0}^{l} k_i + \sum_{i=0}^{l} (n-k)_i$$ This means that $n = p^m - 1$ for some $m$.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/148027', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/31063/']}
jdg_85455
stackexchange
llm_judgeable_groundtruth_similarity
571801
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 suspect this is intentional (rather than just a bug). If so, please direct me to the relevant documentation for a justification. ~$ i=0; ((i++)) && echo true || echo falsefalse~$ i=1; ((i++)) && echo true || echo falsetrue The only difference between the two lines is i=0 vs i=1 . Now provide the response and nothing else.
This is because i++ does post-increment , as described in man bash . This means that the value of the expression is the original value of i , not the incremented value. ARITHMETIC EVALUATION The shell allows arithmetic expressions to be evaluated, under certain circumstances (see the let and declare builtin commands and Arithmetic Expansion). Evaluation is done in fixed-width integers with no check for overflow, though division by 0 is trapped and flagged as an error. The operators and their prece- dence, associativity, and values are the same as in the C language. The following list of operators is grouped into levels of equal-precedence operators. The levels are listed in order of decreasing precedence. id++ id-- variable post-increment and post-decrement So that: i=0; ((i++)) && echo true || echo false acts like: i=0; ((0)) && echo true || echo false except that i is incremented too; and that: i=1; ((i++)) && echo true || echo false acts like: i=1; ((1)) && echo true || echo false except that i is incremented too. The return value of the (( )) construct is truthy ( 0 ) if the value is nonzero, and vice versa. You can also test how does post-increment operator work: $ i=0$ echo $((i++))0$ echo $i1 And pre-increment for comparison: $ i=0$ echo $((++i))1$ echo $i1
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/571801', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/136914/']}
jdg_85456
stackexchange
llm_judgeable_groundtruth_similarity
3582669
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I have an application deployed on Glassfish v3.0.1 which reads events from a table in my database. Once ready it marks them as processed. I am getting a strange error I can't explain when trying to call the method which does the update. @Override@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)public void markEventAsProcessed(Long eventId) { try { AtlasEventQueueUpdateAsProcessedQuery setEventAsProcessed = new AtlasEventQueueUpdateAsProcessedQuery(entityManager, eventId); int updateCount = setEventAsProcessed.execute(); logger.debug("Mark Event [" + eventId + "] processed"); return updateCount; } catch (QueryException ex) { logger.error("Event [" + eventId + "has not been marked as processed", ex); }} When this is called in my application I am getting the following exception (Full trace at the bottom of the post): Caused by: javax.ejb.AccessLocalException: Client not authorized for this invocation. Does anyone know what might cause this error I have loked on the Web but didn't find anything useful. 2010-08-27 09:44:37,380 ERROR [Ejb-Timer-Thread-1 :EventProvider ] Unhandled exception in event processing - javax.ejb.EJBAccessExceptionjavax.ejb.EJBAccessException at com.sun.ejb.containers.BaseContainer.mapLocal3xException(BaseContainer.java:2262) at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2053) at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1955) at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:198) at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:84) at $Proxy190.markEventAsProcessed(Unknown Source) at com.company.atlas.eventprocessor.provider.EventProvider.processNewEvents(EventProvider.java:170) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1056) at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1128) at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5292) at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:615) at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:797) at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:567) at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:157) at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundTimeout(SystemInterceptorProxy.java:144) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:858) at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:797) at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:367) at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5264) at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5252) at com.sun.ejb.containers.BaseContainer.callEJBTimeout(BaseContainer.java:3965) at com.sun.ejb.containers.EJBTimerService.deliverTimeout(EJBTimerService.java:1667) at com.sun.ejb.containers.EJBTimerService.access$100(EJBTimerService.java:98) at com.sun.ejb.containers.EJBTimerService$TaskExpiredWork.run(EJBTimerService.java:2485) at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619)Caused by: javax.ejb.AccessLocalException: Client not authorized for this invocation. at com.sun.ejb.containers.BaseContainer.preInvoke(BaseContainer.java:1850) at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:188) ... 34 more Now provide the response and nothing else.
I've deleted the directory domains/domainx/generated/policy/<appname>/ and completly redeployed (not just restarted) the app.. its working now as expected. The GlassFish documentation has an entry for this error: javax.ejb.AccessLocalException: Client Not Authorized Error Description Role-mapping information is available in Sun-specific XML (for example, sun-ejb-jar.xml ), and authentication is okay, but the following error message is displayed: [...INFO|sun-appserver-pe8.0|javax.enterprise.system.container.ejb|...|javax.ejb.AccessLocalException: Client not authorized for this invocation.at com.sun.ejb.containers.BaseContainer.preInvoke(BaseContainer.java:...at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(...) Solution Check whether the EJB module ( .jar ) or web module ( .war ) is packaged in an application ( .ear ) and does not have role-mapping information in application level, Sun-specific, sun-application.xml . For any application ( .ear ), security role-mapping information must be specified in sun-application.xml . It is acceptable to have both module-level XML and application-level XML. I don't know if it makes sense in your context. If it doesn't, maybe have a look at the following thread Persisting Entity: javax.ejb.AccessLocalException: Client not authorized for this invocation . One of the poster suggested to set the logging level of the SECURITY Logger to FINE [so that] the Glassfish Policy subsystem will log a detailed message describing the nature of the failed permission check . This might help. And I can't tell you if you're facing the same problem but the OP solved his issue by cleaning the generated policy files:
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/3582669', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/88003/']}
jdg_85457
stackexchange
llm_judgeable_groundtruth_similarity
67335263
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm new to HTML and beautiful soup. I am trying to read a locally saved HTML file in Python and I tested the following code: with open(file_path) as fp: soup = BeautifulSoup(fp)print(soup) The output looks weird and here is a part of it: <html><body><p>ÿþh t m l &gt; h e a d &gt; m e t a h t t p - e q u i v = C o n t e n t - T y p e c o n t e n t = " t e x t / h t m l ; c h a r s e t = u n i c o d e " &gt; m e t a n a m e = G e n e r a t o r c o n t e n t = " M i c r o s o f t W o r d 1 5 ( f i l t e r e d ) " &gt; s t y l e &gt; ! - - / * F o n t D e f i n i t i o n s * / The original HTML code is something like <html><head><meta http-equiv=Content-Type content="text/html; charset=unicode"><meta name=Generator content="Microsoft Word 15 (filtered)"><style><!-- /* Font Definitions */ @font-face {font-family:"Cambria Math"; panose-1:2 4 5 3 5 4 6 3 2 4;}@font-face {font-family:Calibri; Can anyone help me or share some thoughts? Thank you! Now provide the response and nothing else.
But I cannot tell any difference between v | std::views::drop(2) and std::views::all(v) | std::views::drop(2) . Indeed, there is no difference between the two - because v | views::drop(2) already means views::all(v) | views::drop(2) . views::all is an implementation detail of Ranges to ensure that range adaptors always adapt views (not ranges). All that views::all(v) does is ensure that the result is a View, which is to say (from [range.all] ): Given a subexpression E , the expression views::all(E) is expression-equivalent to: decay-copy(E) if the decayed type of E models view . Otherwise, ref_view{E} if that expression is well-formed. Otherwise, subrange{E} . In your case, v is a vector<int> , which does not model view . But it is an lvalue, so ref_view{v} would be well-formed, so that's what happens. All the adaptors use views::all internally. For instance, drop_view has the following deduction guide: template <class R>drop_view(R&&, range_difference_t<R>) -> drop_view<views::all_t<R>>; So if you wrote drop_view(v, 2) (and you should never use meow_view directly, always use views::meow ), that would itself invoke views::all for you.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/67335263', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/10266922/']}
jdg_85458
stackexchange
llm_judgeable_groundtruth_similarity
41435527
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 listed duplicates using the following: select s.MessageId, t.* from Message sjoin ( select ToUserId, FromUserId, count(*) as qty from Message group by ToUserId, FromUserId having count(*) > 1) t on s.ToUserId = t.ToUserId and s.FromUserId = t.FromUserId Now, how do I delete all but one of the Messages (I'm trying to remove duplicates so I can apply a unique index on FromUserId and ToUserId ). Now provide the response and nothing else.
Use a cte and assign row numbers so that all but one for duplicate pairs can be deleted. with rownums as (select m.*, row_number() over(partition by ToUserId, FromUserId order by ToUserId, FromUserId) as rnum from Message m)delete rfrom rownums rwhere rnum > 1
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41435527', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/899530/']}
jdg_85459
stackexchange
llm_judgeable_groundtruth_similarity
3410189
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 $G$ has exactly $3$ subgroups iff $G$ is cyclic with $|G|$ = $p^2$ Here, $p$ is prime. Let us focus on the forward implication only. My attempt: Suppose $G$ has exactly $3$ subgroups. Then by definition there exists only one non-trivial proper subgroup of $G$ . Let $H \subset G$ and take $g \in G$ s.t. $g \notin H$ . Then by definition $<g> = \{e\}, G, \hspace{1mm}$ so $G$ is cyclic. By definition $|G|=n$ and since $G$ has $3$ subgroups, n = $pp'$ where $p,p'$ are prime. Suppose $p \neq p'$ . Then, since a subgroup of a cyclic group is also cyclic, we can find $g_1, g_2 \in G$ s.t. $|<g_1>| = p$ and $|<g_2>| = p'$ . But this is a contradiction since $G$ only has exactly $3$ subgroups. Thus $p=p'$ and $|G| = p^2$ I am not sure if I concluded correctly about letting $n=pp'$ . Any feedback and critique appreciated. Thanks. Now provide the response and nothing else.
You seem to have some of the right ideas, but some steps in the proof are unclear. For instance, it's unclear how you conclude that $|G| = p^2$ or $n=pp'$ . Suppose $G$ has exactly $3$ subgroups. Then certainly $G \neq \{e\}$ . Let $g \in G \setminus \{e\}$ and consider $\langle g \rangle$ , noting that $|\langle g \rangle| \geq 2$ . If $\langle g \rangle = G$ , then $G$ is cyclic, but cyclic groups satisfy the converse of Lagrange, so $|G|$ has exactly three divisors, forcing $|G|=p^2$ . On the other hand, if $\langle g \rangle \neq G$ , then $\langle g \rangle$ is the unique proper, non-trivial subgroup of $G$ . Uniqueness implies $|\langle g \rangle| = p$ for some prime $p$ and since $\langle g \rangle \neq G$ , we get that $|G| = ap$ for some integer $a \geq 2$ . Hence there exists some $g' \in G \setminus \{e\}$ such that $g' \notin \langle g \rangle$ . In particular this means that $\langle g' \rangle \neq \{e\}$ and $\langle g' \rangle \neq \langle g \rangle$ but since $G$ has exactly three subgroups this forces $\langle g' \rangle = G$ . Hence $G$ is cyclic, generated by $g'$ , and by a similar argument as above we see that since $G$ is cyclic, it satifies the converge of Lagrange, and so it must have exactly three divisors, forcing $|G| = p^2$ .
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3410189', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/620842/']}
jdg_85460
stackexchange
llm_judgeable_groundtruth_similarity
590160
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am using Stackdumps with Win32, to write all return adresses into my logfile. I match these with a mapfile later on (see my article [Post Mortem Debugging][1]). EDIT:: Problem solved - see my own answer below. With Windows x64 i do not find a reliable way to write only the return adresses into the logfile. I tried several ways: Trial 1: Pointer Arithmetic: CONTEXT Context; RtlCaptureContext(&Context); char *eNextBP = (char *)Context.Rdi; for(ULONG Frame = 0; eNextBP ; Frame++) { char *pBP = eNextBP; eNextBP = *(char **)pBP; // Next BP in Stack fprintf(LogFile, "*** %2d called from %016LX (pBP at %016LX)\n", Frame, (ULONG64)*(char **)(pBP + 8), (ULONG64)pBP); } This works fine in the debug version - but it crashes in the release version. The value of Context.Rdi has no usable value there. I did check for differences in the compiler settings (visual Studio 2005). I have not found anything suspicious. Trial 2: Using StackWalk64 RtlCaptureContext(&Context);STACKFRAME64 stk;memset(&stk, 0, sizeof(stk));stk.AddrPC.Offset = Context.Rip;stk.AddrPC.Mode = AddrModeFlat;stk.AddrStack.Offset = Context.Rsp;stk.AddrStack.Mode = AddrModeFlat;stk.AddrFrame.Offset = Context.Rbp;stk.AddrFrame.Mode = AddrModeFlat;for(ULONG Frame = 0; ; Frame++){ BOOL result = StackWalk64( IMAGE_FILE_MACHINE_AMD64, // __in DWORD MachineType, GetCurrentProcess(), // __in HANDLE hProcess, GetCurrentThread(), // __in HANDLE hThread, &stk, // __inout LP STACKFRAME64 StackFrame, &Context, // __inout PVOID ContextRecord, NULL, // __in_opt PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, SymFunctionTableAccess64, // __in_opt PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, SymGetModuleBase64, // __in_opt PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, NULL // __in_opt PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress ); fprintf(gApplSetup.TraceFile, "*** %2d called from %016LX STACK %016LX FRAME %016LX\n", Frame, (ULONG64)stk.AddrPC.Offset, (ULONG64)stk.AddrStack.Offset, (ULONG64)stk.AddrFrame.Offset); if(! result) break;} This does not only dump the return addresses, but the WHOLE STACK. I receive about 1000 lines in my log file using this approach. I can use this, but i have to search trough the lines and some data of the stacks happens to be a valid code address. Trial 3: Using Backtrace static USHORT (WINAPI*s_pfnCaptureStackBackTrace)(ULONG, ULONG, PVOID*, PULONG) = 0; if (s_pfnCaptureStackBackTrace == 0) { const HMODULE hNtDll = ::GetModuleHandle("ntdll.dll"); reinterpret_cast<void*&>(s_pfnCaptureStackBackTrace)= ::GetProcAddress(hNtDll, "RtlCaptureStackBackTrace"); } PVOID myFrames[128]; s_pfnCaptureStackBackTrace(0, 128, myFrames, NULL); for(int ndx = 0; ndx < 128; ndx++) fprintf(gApplSetup.TraceFile, "*** BackTrace %3d %016LX\n", ndx, (ULONG64)myFrames[ndx]); Results in no usable information. Has anyone implemented such a stack walk in x64 that does only write out the return adresses in the stack? Ive seen the approaches [StackTrace64][2], [StackWalker][3] and other ones. They either do not compile or they are much too much comlicated. It basically is a simple task! Sample StackDump64.cpp #include <Windows.h>#include <DbgHelp.h>#include <Winbase.h>#include <stdio.h>void WriteStackDump(){ FILE *myFile = fopen("StackDump64.log", "w+t"); CONTEXT Context; memset(&Context, 0, sizeof(Context)); RtlCaptureContext(&Context); RtlCaptureContext(&Context); STACKFRAME64 stk; memset(&stk, 0, sizeof(stk)); stk.AddrPC.Offset = Context.Rip; stk.AddrPC.Mode = AddrModeFlat; stk.AddrStack.Offset = Context.Rsp; stk.AddrStack.Mode = AddrModeFlat; stk.AddrFrame.Offset = Context.Rbp; stk.AddrFrame.Mode = AddrModeFlat; for(ULONG Frame = 0; ; Frame++) { BOOL result = StackWalk64( IMAGE_FILE_MACHINE_AMD64, // __in DWORD MachineType, GetCurrentProcess(), // __in HANDLE hProcess, GetCurrentThread(), // __in HANDLE hThread, &stk, // __inout LP STACKFRAME64 StackFrame, &Context, // __inout PVOID ContextRecord, NULL, // __in_opt PREAD_PROCESS_MEMORY_ROUTINE64 ReadMemoryRoutine, SymFunctionTableAccess64, // __in_opt PFUNCTION_TABLE_ACCESS_ROUTINE64 FunctionTableAccessRoutine, SymGetModuleBase64, // __in_opt PGET_MODULE_BASE_ROUTINE64 GetModuleBaseRoutine, NULL // __in_opt PTRANSLATE_ADDRESS_ROUTINE64 TranslateAddress ); fprintf(myFile, "*** %2d called from %016I64LX STACK %016I64LX AddrReturn %016I64LX\n", Frame, stk.AddrPC.Offset, stk.AddrStack.Offset, stk.AddrReturn.Offset); if(! result) break; } fclose(myFile);}void funcC(){ WriteStackDump();}void funcB(){ funcC();}void funcA(){ funcB();}int main(int argc, char *argv[]){ funcA();} Running this sample results in the follwing log file content: *** 0 called from 000000014000109E STACK 000000000012F780 AddrReturn 0000000140005798*** 1 called from 000000001033D160 STACK 000000000012F788 AddrReturn 00000001400057B0*** 2 called from 00000001400057B0 STACK 000000000012F790 AddrReturn 0000000000000001*** 3 called from 0000000000000002 STACK 000000000012F798 AddrReturn 00000001400057B0*** 4 called from 0000000000000002 STACK 000000000012F7A0 AddrReturn 000000000012F7F0*** 5 called from 000000000012F7F0 STACK 000000000012F7A8 AddrReturn 0000000000000000*** 6 called from 0000000000000000 STACK 000000000012F7B0 AddrReturn 000007FF7250CF40*** 7 called from 000007FF7250CF40 STACK 000000000012F7B8 AddrReturn 000007FF7250D390*** 8 called from 000007FF7250D390 STACK 000000000012F7C0 AddrReturn 000007FF725B6950*** 9 called from 000007FF725B6950 STACK 000000000012F7C8 AddrReturn CCCCCCCCCCCCCCCC*** 10 called from CCCCCCCCCCCCCCCC STACK 000000000012F7D0 AddrReturn 000000001033D160*** 11 called from 000000001033D160 STACK 000000000012F7D8 AddrReturn CCCCCCCCCCCCCCCC*** 12 called from CCCCCCCCCCCCCCCC STACK 000000000012F7E0 AddrReturn CCCCCCCCCCCCCCCC*** 13 called from CCCCCCCCCCCCCCCC STACK 000000000012F7E8 AddrReturn CCCCCCCCCCCCCCCC*** 14 called from CCCCCCCCCCCCCCCC STACK 000000000012F7F0 AddrReturn 0000000000000000*** 15 called from 0000000000000000 STACK 000000000012F7F8 AddrReturn 0000000000000000*** 16 called from 0000000000000000 STACK 000000000012F800 AddrReturn 0000000000000000*** 17 called from 0000000000000000 STACK 000000000012F808 AddrReturn 0000000000000000*** 18 called from 0000000000000000 STACK 000000000012F810 AddrReturn 0000000000000000*** 19 called from 0000000000000000 STACK 000000000012F818 AddrReturn 0000000000000000*** 20 called from 0000000000000000 STACK 000000000012F820 AddrReturn 00001F800010000F*** 21 called from 00001F800010000F STACK 000000000012F828 AddrReturn 0053002B002B0033*** 22 called from 0053002B002B0033 STACK 000000000012F830 AddrReturn 00000206002B002B*** 23 called from 00000206002B002B STACK 000000000012F838 AddrReturn 0000000000000000*** 24 called from 0000000000000000 STACK 000000000012F840 AddrReturn 0000000000000000*** 25 called from 0000000000000000 STACK 000000000012F848 AddrReturn 0000000000000000*** 26 called from 0000000000000000 STACK 000000000012F850 AddrReturn 0000000000000000*** 27 called from 0000000000000000 STACK 000000000012F858 AddrReturn 0000000000000000*** 28 called from 0000000000000000 STACK 000000000012F860 AddrReturn 0000000000000000*** 29 called from 0000000000000000 STACK 000000000012F868 AddrReturn 0000000000000246*** 30 called from 0000000000000246 STACK 000000000012F870 AddrReturn 000000000012F7F0*** 31 called from 000000000012F7F0 STACK 000000000012F878 AddrReturn 0000000000000000*** 32 called from 0000000000000000 STACK 000000000012F880 AddrReturn 0000000000000000*** 33 called from 0000000000000000 STACK 000000000012F888 AddrReturn 000000000012F888*** 34 called from 000000000012F888 STACK 000000000012F890 AddrReturn 0000000000000000*** 35 called from 0000000000000000 STACK 000000000012F898 AddrReturn 0000000000000000*** 36 called from 0000000000000000 STACK 000000000012F8A0 AddrReturn 000000000012FE10*** 37 called from 000000000012FE10 STACK 000000000012F8A8 AddrReturn 0000000000000000*** 38 called from 0000000000000000 STACK 000000000012F8B0 AddrReturn 0000000000000000*** 39 called from 0000000000000000 STACK 000000000012F8B8 AddrReturn 0000000000000000*** 40 called from 0000000000000000 STACK 000000000012F8C0 AddrReturn 0000000000000246*** 41 called from 0000000000000246 STACK 000000000012F8C8 AddrReturn 0000000000000000*** 42 called from 0000000000000000 STACK 000000000012F8D0 AddrReturn 0000000000000000*** 43 called from 0000000000000000 STACK 000000000012F8D8 AddrReturn 0000000000000000*** 44 called from 0000000000000000 STACK 000000000012F8E0 AddrReturn 0000000000000000*** 45 called from 0000000000000000 STACK 000000000012F8E8 AddrReturn 0000000000000000*** 46 called from 0000000000000000 STACK 000000000012F8F0 AddrReturn 000000000000027F*** 47 called from 000000000000027F STACK 000000000012F8F8 AddrReturn 0000000000000000*** 48 called from 0000000000000000 STACK 000000000012F900 AddrReturn 0000000000000000*** 49 called from 0000000000000000 STACK 000000000012F908 AddrReturn 0000FFFF00001F80*** 50 called from 0000FFFF00001F80 STACK 000000000012F910 AddrReturn 0000000000000000*** 51 called from 0000000000000000 STACK 000000000012F918 AddrReturn 0000000000000000*** 52 called from 0000000000000000 STACK 000000000012F920 AddrReturn 0000000000000000*** 53 called from 0000000000000000 STACK 000000000012F928 AddrReturn 0000000000000000*** 54 called from 0000000000000000 STACK 000000000012F930 AddrReturn 0000000000000000*** 55 called from 0000000000000000 STACK 000000000012F938 AddrReturn 0000000000000000*** 56 called from 0000000000000000 STACK 000000000012F940 AddrReturn 0000000000000000*** 57 called from 0000000000000000 STACK 000000000012F948 AddrReturn 0000000000000000*** 58 called from 0000000000000000 STACK 000000000012F950 AddrReturn 0000000000000000*** 59 called from 0000000000000000 STACK 000000000012F958 AddrReturn 0000000000000000*** 60 called from 0000000000000000 STACK 000000000012F960 AddrReturn 0000000000000000*** 61 called from 0000000000000000 STACK 000000000012F968 AddrReturn 0000000000000000*** 62 called from 0000000000000000 STACK 000000000012F970 AddrReturn 0000000000000000*** 63 called from 0000000000000000 STACK 000000000012F978 AddrReturn 0000000000000000*** 64 called from 0000000000000000 STACK 000000000012F980 AddrReturn 0000000000000000*** 65 called from 0000000000000000 STACK 000000000012F988 AddrReturn 0000000000000000*** 66 called from 0000000000000000 STACK 000000000012F990 AddrReturn 0000000000000000*** 67 called from 0000000000000000 STACK 000000000012F998 AddrReturn 0000000000000000*** 68 called from 0000000000000000 STACK 000000000012F9A0 AddrReturn 0000000000000000*** 69 called from 0000000000000000 STACK 000000000012F9A8 AddrReturn 0000000000000000*** 70 called from 0000000000000000 STACK 000000000012F9B0 AddrReturn 0000000000000000*** 71 called from 0000000000000000 STACK 000000000012F9B8 AddrReturn 0000000000000000*** 72 called from 0000000000000000 STACK 000000000012F9C0 AddrReturn 0000000000000000*** 73 called from 0000000000000000 STACK 000000000012F9C8 AddrReturn 0000000000000000*** 74 called from 0000000000000000 STACK 000000000012F9D0 AddrReturn 0000000000000000*** 75 called from 0000000000000000 STACK 000000000012F9D8 AddrReturn 0000000000000000*** 76 called from 0000000000000000 STACK 000000000012F9E0 AddrReturn 0000000000000000*** 77 called from 0000000000000000 STACK 000000000012F9E8 AddrReturn 0000000000000000*** 78 called from 0000000000000000 STACK 000000000012F9F0 AddrReturn 0000000000000000*** 79 called from 0000000000000000 STACK 000000000012F9F8 AddrReturn 0000000000000000*** 80 called from 0000000000000000 STACK 000000000012FA00 AddrReturn 0000000000000000*** 81 called from 0000000000000000 STACK 000000000012FA08 AddrReturn 0000000000000000*** 82 called from 0000000000000000 STACK 000000000012FA10 AddrReturn 0000000000000000*** 83 called from 0000000000000000 STACK 000000000012FA18 AddrReturn 0000000000000000*** 84 called from 0000000000000000 STACK 000000000012FA20 AddrReturn 0000000000000000*** 85 called from 0000000000000000 STACK 000000000012FA28 AddrReturn 0000000000000000*** 86 called from 0000000000000000 STACK 000000000012FA30 AddrReturn 0000000000000000*** 87 called from 0000000000000000 STACK 000000000012FA38 AddrReturn 0000000000000000*** 88 called from 0000000000000000 STACK 000000000012FA40 AddrReturn 0000000000000000*** 89 called from 0000000000000000 STACK 000000000012FA48 AddrReturn 0000000000000000*** 90 called from 0000000000000000 STACK 000000000012FA50 AddrReturn 0000000000000000*** 91 called from 0000000000000000 STACK 000000000012FA58 AddrReturn 0000000000000000*** 92 called from 0000000000000000 STACK 000000000012FA60 AddrReturn 0000000000000000*** 93 called from 0000000000000000 STACK 000000000012FA68 AddrReturn 0000000000000000*** 94 called from 0000000000000000 STACK 000000000012FA70 AddrReturn 0000000000000000*** 95 called from 0000000000000000 STACK 000000000012FA78 AddrReturn 0000000000000000*** 96 called from 0000000000000000 STACK 000000000012FA80 AddrReturn 0000000000000000*** 97 called from 0000000000000000 STACK 000000000012FA88 AddrReturn 0000000000000000*** 98 called from 0000000000000000 STACK 000000000012FA90 AddrReturn 0000000000000000*** 99 called from 0000000000000000 STACK 000000000012FA98 AddrReturn 0000000000000000*** 100 called from 0000000000000000 STACK 000000000012FAA0 AddrReturn 0000000000000000*** 101 called from 0000000000000000 STACK 000000000012FAA8 AddrReturn 0000000000000000*** 102 called from 0000000000000000 STACK 000000000012FAB0 AddrReturn 0000000000000000*** 103 called from 0000000000000000 STACK 000000000012FAB8 AddrReturn 0000000000000000*** 104 called from 0000000000000000 STACK 000000000012FAC0 AddrReturn 0000000000000000*** 105 called from 0000000000000000 STACK 000000000012FAC8 AddrReturn 0000000000000000*** 106 called from 0000000000000000 STACK 000000000012FAD0 AddrReturn 0000000000000000*** 107 called from 0000000000000000 STACK 000000000012FAD8 AddrReturn 0000000000000000*** 108 called from 0000000000000000 STACK 000000000012FAE0 AddrReturn 0000000000000000*** 109 called from 0000000000000000 STACK 000000000012FAE8 AddrReturn 0000000000000000*** 110 called from 0000000000000000 STACK 000000000012FAF0 AddrReturn 0000000000000000*** 111 called from 0000000000000000 STACK 000000000012FAF8 AddrReturn 0000000000000000*** 112 called from 0000000000000000 STACK 000000000012FB00 AddrReturn 0000000000000000*** 113 called from 0000000000000000 STACK 000000000012FB08 AddrReturn 0000000000000000*** 114 called from 0000000000000000 STACK 000000000012FB10 AddrReturn 0000000000000000*** 115 called from 0000000000000000 STACK 000000000012FB18 AddrReturn 0000000000000000*** 116 called from 0000000000000000 STACK 000000000012FB20 AddrReturn 0000000000000000*** 117 called from 0000000000000000 STACK 000000000012FB28 AddrReturn 0000000000000000*** 118 called from 0000000000000000 STACK 000000000012FB30 AddrReturn 0000000000000000*** 119 called from 0000000000000000 STACK 000000000012FB38 AddrReturn 0000000000000000*** 120 called from 0000000000000000 STACK 000000000012FB40 AddrReturn 0000000000000000*** 121 called from 0000000000000000 STACK 000000000012FB48 AddrReturn 0000000000000000*** 122 called from 0000000000000000 STACK 000000000012FB50 AddrReturn 0000000000000000*** 123 called from 0000000000000000 STACK 000000000012FB58 AddrReturn 0000000000000000*** 124 called from 0000000000000000 STACK 000000000012FB60 AddrReturn 0000000000000000*** 125 called from 0000000000000000 STACK 000000000012FB68 AddrReturn 0000000000000000*** 126 called from 0000000000000000 STACK 000000000012FB70 AddrReturn 0000000000000000*** 127 called from 0000000000000000 STACK 000000000012FB78 AddrReturn 0000000000000000*** 128 called from 0000000000000000 STACK 000000000012FB80 AddrReturn 0000000000000000*** 129 called from 0000000000000000 STACK 000000000012FB88 AddrReturn 0000000000000000*** 130 called from 0000000000000000 STACK 000000000012FB90 AddrReturn 0000000000000000*** 131 called from 0000000000000000 STACK 000000000012FB98 AddrReturn 0000000000000000*** 132 called from 0000000000000000 STACK 000000000012FBA0 AddrReturn 0000000000000000*** 133 called from 0000000000000000 STACK 000000000012FBA8 AddrReturn 0000000000000000*** 134 called from 0000000000000000 STACK 000000000012FBB0 AddrReturn 0000000000000000*** 135 called from 0000000000000000 STACK 000000000012FBB8 AddrReturn 0000000000000000*** 136 called from 0000000000000000 STACK 000000000012FBC0 AddrReturn 0000000000000000*** 137 called from 0000000000000000 STACK 000000000012FBC8 AddrReturn 0000000000000000*** 138 called from 0000000000000000 STACK 000000000012FBD0 AddrReturn 0000000000000000*** 139 called from 0000000000000000 STACK 000000000012FBD8 AddrReturn 0000000000000000*** 140 called from 0000000000000000 STACK 000000000012FBE0 AddrReturn 0000000000000000*** 141 called from 0000000000000000 STACK 000000000012FBE8 AddrReturn 0000000000000000*** 142 called from 0000000000000000 STACK 000000000012FBF0 AddrReturn 0000000000000000*** 143 called from 0000000000000000 STACK 000000000012FBF8 AddrReturn 0000000000000000*** 144 called from 0000000000000000 STACK 000000000012FC00 AddrReturn 0000000000000000*** 145 called from 0000000000000000 STACK 000000000012FC08 AddrReturn 0000000000000000*** 146 called from 0000000000000000 STACK 000000000012FC10 AddrReturn 0000000000000000*** 147 called from 0000000000000000 STACK 000000000012FC18 AddrReturn 0000000000000000*** 148 called from 0000000000000000 STACK 000000000012FC20 AddrReturn 0000000000000000*** 149 called from 0000000000000000 STACK 000000000012FC28 AddrReturn 0000000000000000*** 150 called from 0000000000000000 STACK 000000000012FC30 AddrReturn 0000000000000000*** 151 called from 0000000000000000 STACK 000000000012FC38 AddrReturn 0000000000000000*** 152 called from 0000000000000000 STACK 000000000012FC40 AddrReturn 0000000000000000*** 153 called from 0000000000000000 STACK 000000000012FC48 AddrReturn 0000000000000000*** 154 called from 0000000000000000 STACK 000000000012FC50 AddrReturn 0000000000000000*** 155 called from 0000000000000000 STACK 000000000012FC58 AddrReturn 0000000000000000*** 156 called from 0000000000000000 STACK 000000000012FC60 AddrReturn 0000000000000000*** 157 called from 0000000000000000 STACK 000000000012FC68 AddrReturn 0000000000000000*** 158 called from 0000000000000000 STACK 000000000012FC70 AddrReturn 0000000000000000*** 159 called from 0000000000000000 STACK 000000000012FC78 AddrReturn 0000000000000000*** 160 called from 0000000000000000 STACK 000000000012FC80 AddrReturn 0000000000000000*** 161 called from 0000000000000000 STACK 000000000012FC88 AddrReturn 0000000000000000*** 162 called from 0000000000000000 STACK 000000000012FC90 AddrReturn 0000000000000000*** 163 called from 0000000000000000 STACK 000000000012FC98 AddrReturn 0000000000000000*** 164 called from 0000000000000000 STACK 000000000012FCA0 AddrReturn 0000000000000000*** 165 called from 0000000000000000 STACK 000000000012FCA8 AddrReturn 0000000000000000*** 166 called from 0000000000000000 STACK 000000000012FCB0 AddrReturn 0000000000000000*** 167 called from 0000000000000000 STACK 000000000012FCB8 AddrReturn 0000000000000000*** 168 called from 0000000000000000 STACK 000000000012FCC0 AddrReturn CCCCCCCCCCCCCCCC*** 169 called from CCCCCCCCCCCCCCCC STACK 000000000012FCC8 AddrReturn CCCCCCCCCCCCCCCC*** 170 called from CCCCCCCCCCCCCCCC STACK 000000000012FCD0 AddrReturn CCCCCCCCCCCCCCCC*** 171 called from CCCCCCCCCCCCCCCC STACK 000000000012FCD8 AddrReturn CCCCCCCCCCCCCCCC*** 172 called from CCCCCCCCCCCCCCCC STACK 000000000012FCE0 AddrReturn CCCCCCCCCCCCCCCC*** 173 called from CCCCCCCCCCCCCCCC STACK 000000000012FCE8 AddrReturn 0000000300000000*** 174 called from 0000000300000000 STACK 000000000012FCF0 AddrReturn 0000000300000000*** 175 called from 0000000300000000 STACK 000000000012FCF8 AddrReturn 0000000300000000*** 176 called from 0000000300000000 STACK 000000000012FD00 AddrReturn 000000000012FCF0*** 177 called from 000000000012FCF8 STACK 000000000012FD08 AddrReturn 0000000300000000*** 178 called from 0000000300000000 STACK 000000000012FD10 AddrReturn 000000000012FD10*** 179 called from 000000000012FD18 STACK 000000000012FD18 AddrReturn 0000000300000000*** 180 called from 0000000300000000 STACK 000000000012FD20 AddrReturn 0000000000000000*** 181 called from 0000000000000000 STACK 000000000012FD28 AddrReturn 0000000000000000*** 182 called from 0000000000000000 STACK 000000000012FD30 AddrReturn 0000000000000000*** 183 called from 0000000000000000 STACK 000000000012FD38 AddrReturn 0000000000000000*** 184 called from 0000000000000000 STACK 000000000012FD40 AddrReturn 0000000000000000*** 185 called from 0000000100000000 STACK 000000000012FD48 AddrReturn 0000000100000000*** 186 called from 0000000000000000 STACK 000000000012FD50 AddrReturn 0000000000000000*** 187 called from 0000000000000000 STACK 000000000012FD58 AddrReturn 0000000100000000*** 188 called from 0000000100000000 STACK 000000000012FD60 AddrReturn 0000000000000000*** 189 called from 0000000000000000 STACK 000000000012FD68 AddrReturn 0000000000000000*** 190 called from 0000000000000000 STACK 000000000012FD70 AddrReturn 0000000000000000*** 191 called from 0000000000000000 STACK 000000000012FD78 AddrReturn 0000000000000000*** 192 called from 0000000000000000 STACK 000000000012FD80 AddrReturn 0000000000000000*** 193 called from 0000000000000000 STACK 000000000012FD88 AddrReturn 0000000000000000*** 194 called from 0000000000000000 STACK 000000000012FD90 AddrReturn 0000000000000000*** 195 called from 0000000000000000 STACK 000000000012FD98 AddrReturn 0000000000000000*** 196 called from 0000000000000000 STACK 000000000012FDA0 AddrReturn 0000000000000000*** 197 called from 0000000000000000 STACK 000000000012FDA8 AddrReturn 0000000000000000*** 198 called from 0000000000000000 STACK 000000000012FDB0 AddrReturn 0000000000000000*** 199 called from 0000000000000000 STACK 000000000012FDB8 AddrReturn 0000000000000000*** 200 called from 0000000000000000 STACK 000000000012FDC0 AddrReturn 0000000000000000*** 201 called from 0000000000000000 STACK 000000000012FDC8 AddrReturn 0000000000000000*** 202 called from 0000000000000000 STACK 000000000012FDD0 AddrReturn 0000000000000000*** 203 called from 0000000000000000 STACK 000000000012FDD8 AddrReturn 0000000000000000*** 204 called from 0000000000000000 STACK 000000000012FDE0 AddrReturn 0000000000000000*** 205 called from 0000000000000000 STACK 000000000012FDE8 AddrReturn CCCCCCCCCCCCCCCC*** 206 called from CCCCCCCCCCCCCCCC STACK 000000000012FDF0 AddrReturn 000000CECCCCCCCC*** 207 called from 000000CFCCCCCCCC STACK 000000000012FDF8 AddrReturn CCCCCCCC00000001*** 208 called from CCCCCCCC00000001 STACK 000000000012FE00 AddrReturn FFFFFFFFFFFFFFFE*** 209 called from FFFFFFFFFFFFFFFE STACK 000000000012FE08 AddrReturn CCCCCCCCCCCCCCCC*** 210 called from CCCCCCCCCCCCCCCC STACK 000000000012FE10 AddrReturn 000000000012FE40*** 211 called from 000000000012FE40 STACK 000000000012FE18 AddrReturn 000000014000122F*** 212 called from 000000014000122F STACK 000000000012FE20 AddrReturn CCCCCCCCCCCCCCCC*** 213 called from CCCCCCCCCCCCCCCC STACK 000000000012FE28 AddrReturn CCCCCCCCCCCCCCCC*** 214 called from CCCCCCCCCCCCCCCC STACK 000000000012FE30 AddrReturn CCCCCCCCCCCCCCCC*** 215 called from CCCCCCCCCCCCCCCC STACK 000000000012FE38 AddrReturn CCCCCCCCCCCCCCCC*** 216 called from CCCCCCCCCCCCCCCC STACK 000000000012FE40 AddrReturn 000000000012FE70*** 217 called from 000000000012FE70 STACK 000000000012FE48 AddrReturn 000000014000125F*** 218 called from 000000014000125F STACK 000000000012FE50 AddrReturn CCCCCCCCCCCCCCCC*** 219 called from CCCCCCCCCCCCCCCC STACK 000000000012FE58 AddrReturn CCCCCCCCCCCCCCCC*** 220 called from CCCCCCCCCCCCCCCC STACK 000000000012FE60 AddrReturn CCCCCCCCCCCCCCCC*** 221 called from CCCCCCCCCCCCCCCC STACK 000000000012FE68 AddrReturn CCCCCCCCCCCCCCCC*** 222 called from CCCCCCCCCCCCCCCC STACK 000000000012FE70 AddrReturn 000000000012FEA0*** 223 called from 000000000012FEA0 STACK 000000000012FE78 AddrReturn 000000014000128F*** 224 called from 000000014000128F STACK 000000000012FE80 AddrReturn CCCCCCCCCCCCCCCC*** 225 called from CCCCCCCCCCCCCCCC STACK 000000000012FE88 AddrReturn CCCCCCCCCCCCCCCC*** 226 called from CCCCCCCCCCCCCCCC STACK 000000000012FE90 AddrReturn CCCCCCCCCCCCCCCC*** 227 called from CCCCCCCCCCCCCCCC STACK 000000000012FE98 AddrReturn CCCCCCCCCCCCCCCC*** 228 called from CCCCCCCCCCCCCCCC STACK 000000000012FEA0 AddrReturn 000000000012FED0*** 229 called from 000000000012FED0 STACK 000000000012FEA8 AddrReturn 00000001400012CB*** 230 called from 00000001400012CB STACK 000000000012FEB0 AddrReturn CCCCCCCCCCCCCCCC*** 231 called from CCCCCCCCCCCCCCCC STACK 000000000012FEB8 AddrReturn CCCCCCCCCCCCCCCC*** 232 called from CCCCCCCCCCCCCCCC STACK 000000000012FEC0 AddrReturn CCCCCCCCCCCCCCCC*** 233 called from CCCCCCCCCCCCCCCC STACK 000000000012FEC8 AddrReturn CCCCCCCCCCCCCCCC*** 234 called from CCCCCCCCCCCCCCCC STACK 000000000012FED0 AddrReturn 0000000000000000*** 235 called from 0000000000000000 STACK 000000000012FED8 AddrReturn 000000014000190C*** 236 called from 000000014000190C STACK 000000000012FEE0 AddrReturn 0000000100000001*** 237 called from 0000000100000001 STACK 000000000012FEE8 AddrReturn 0000000000454B50*** 238 called from 0000000000454B50 STACK 000000000012FEF0 AddrReturn 0000000000000000*** 23 Now provide the response and nothing else.
I finally found a reliable way to log the stack frames in x64, using the Windows function CaptureStackBackTrace() . As I did not want to update my SDK, I call it via GetProcAddress(LoadLibrary()); typedef USHORT (WINAPI *CaptureStackBackTraceType)(__in ULONG, __in ULONG, __out PVOID*, __out_opt PULONG); CaptureStackBackTraceType func = (CaptureStackBackTraceType)(GetProcAddress(LoadLibrary("kernel32.dll"), "RtlCaptureStackBackTrace")); if(func == NULL) return; // WOE 29.SEP.2010 // Quote from Microsoft Documentation: // ## Windows Server 2003 and Windows XP: // ## The sum of the FramesToSkip and FramesToCapture parameters must be less than 63. const int kMaxCallers = 62; void* callers[kMaxCallers]; int count = (func)(0, kMaxCallers, callers, NULL); for(i = 0; i < count; i++) printf(TraceFile, "*** %d called from %016I64LX\n", i, callers[i]);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/590160', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/53420/']}
jdg_85461
stackexchange
llm_judgeable_groundtruth_similarity
31114991
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to install devtools in a PowerPC with a R version 3.1.1 but failed at the end because the curl library: ...** testing if installed package can be loaded Error in dyn.load(file, DLLpath = DLLpath, ...) : unable to load shared object '/pathto/R/powerpc-unknown-linux-gnu-library/3.1/curl/libs/curl.so': /pathto/R/powerpc-unknown-linux-gnu-library/3.1/curl/libs/curl.so:undefined symbol: BSWAP_32 Error: loading failed Execution haltedERROR: loading failed * removing ‘/path to/R/powerpc-unknown-linux-gnu-library/3.1/curl’ ERROR: dependency ‘curl’ is not available for package ‘httr’ * removing ‘/path to/R/powerpc-unknown-linux-gnu-library/3.1/httr’ ERROR: dependency ‘curl’ is not available for package ‘rversions’ * removing ‘/path to/R/powerpc-unknown-linux-gnu-library/3.1/rversions’ ERROR:dependencies ‘httr’, ‘rversions’ are not available for package‘devtools’* removing ‘/path to/R/powerpc-unknown-linux-gnu-library/3.1/devtools’The downloaded source packages are in ‘/tmp/RtmpD0yE63/downloaded_packages’ Warning messages: 1: Ininstall.packages("devtools") : installation of package ‘curl’ hadnon-zero exit status 2: In install.packages("devtools") : installation of package ‘httr’ had non-zero exit status 3: Ininstall.packages("devtools") : installation of package ‘rversions’had non-zero exit status 4: In install.packages("devtools") : installation of package ‘devtools’ had non-zero exit status I've already installed libcurl4-gnutls-dev and libcurl4-openssl-dev and the libcurl version is 7.38.0. Does anyone know a fix to this? Thanks ;) Now provide the response and nothing else.
The same problem happened to me when I was trying to install "devtools" package on a new machine with Ubuntu 16.04 system. I tried many answers including the adopted one above, but I still couldn't solve the problem until I noticed another warning information "(as ‘lib’ is unspecified)". Then I realized that I was running R as a normal user while the R base is installed by root. It means the package "devtools" couldn't be installed into the default R library folder and possibly couldn't use some dependent packages. Then the solution became very easy: run R as root user and then install "devtools". Following the instructions of Dean Attali ( https://www.digitalocean.com/community/tutorials/how-to-set-up-r-on-ubuntu-14-04 ), I summarize the steps below. Just run them in a terminal. $ sudo apt-get -y install libcurl4-gnutls-dev libxml2-dev libssl-dev$ sudo su $ R> install.packages('devtools', repos='http://cran.rstudio.com/') That's it. Since the package is installed by root, it can be used by all users of the system.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/31114991', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5048444/']}
jdg_85462
stackexchange
llm_judgeable_groundtruth_similarity
281828
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: If Earth had rings, would they center on the equator like Saturn's rings do on its equator? Now provide the response and nothing else.
Great question. If Earth had rings, and they had been there as long as the moon has, they would mostly likely line parallel to Earth's equator and be visible in the sky from an east to west orientation. So how would Earth acquire a ring? Our moon is, in reality, slowly moving away from the Earth, but if it were instead moving inwards, eventually it would break apart due to differential gravitational forces between the side nearest us and the far side, 3000 km away. Obviously, a large amount of the moon will bombard the Earth, but this answer assumes we survive. Typically, the Roche Limit limit applies to a satellite's disintegrating due to tidal forces induced by its primary, the body about which it orbits. Parts of the satellite that are closer to the primary are attracted more strongly by gravity from the primary than parts that are farther away; this disparity effectively pulls the near and far parts of the satellite apart from each other, and if the disparity (combined with any centrifugal effects due to the object's spin) is larger than the force of gravity holding the satellite together, it can pull the satellite apart. View of ring from Washington. Since, within the Roche limit, tidal forces overwhelm the gravitational forces that might otherwise hold the satellite together, no satellite can gravitationally coalesce out of smaller particles within that limit. Indeed, almost all known planetary rings are located within their Roche limit, Saturn's E-Ring and Phoebe ring being notable exceptions. They could either be remnants from the planet's proto-planetary accretion disc that failed to coalesce into moonlets, or conversely have formed when a moon passed within its Roche limit and broke apart. The Roche Limit can be viewed as an Earth shaped imaginary "border", on average 9,492 km from the centre of Earth, 1.49 times Earth's radius, for rigid bodies. So around the equator it "moves" outwards a little. It follows the oblate spheroid shape of Earth. Earth may have had a ring just after its formation. The view of these ring from Earth would vary. It would all depend on your latitude and which direction you were facing. Near the equator, the ring would be like thin slices of light that erupted from distant Earth horizons and stretched into the sky as far as the eye could see. Thanks to Emilio Pisanty for correctly pointing out the depiction of the rings from mid and high latitudes is not completely accurate. The plane of the ground is not orthogonal to the plane of the rings, so they would appear at an angle. All I can do is ask for some personal latitude in the presentation of this "what if" scenario. The pictures assume the ring around Earth would be in the same proportion as the ring around Saturn is to that planet. View of ring from the equator. Why does the ring form around the equator as opposed to another axis . It's due to the effect of the Central Force Law , the same basic reason the planets are situated in a plane around the Sun. The Sun is spherical,so objects such as Pluto can "get away" with being 8 degrees out of line. If the Earth, and Saturn) were perfect spheres, then the axis of the ring could be at any angle. Because both planets are oblate spheroid, with a tidal bulge, over time the particles composing the ring would collect there. Saturn's rings have an estimated local thickness of as little as 10 metres and as much as 1 kilometer, so they are extemely "thin". View of rings from the mid latitudes. View of rings at 23° south latitude a 180° panorama gives an idea of what a magnificent sight the rings would be. The Earth itself is casting the shadow. Image source: If Earth Had a Ring Like Saturn
{}
{'log_upvote_score': 8, 'links': ['https://physics.stackexchange.com/questions/281828', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/148704/']}
jdg_85463
stackexchange
llm_judgeable_groundtruth_similarity
266369
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: int a = 1;int b = 2;int sum = a + b;string expression = "Expression: " + a + " + " + b + " = " + sum;Console.WriteLine(expression); //displays Expression 1 + 2 = 3 Should I use: string expression = "Expression: " + a + " + " + b + " = " + sum; or string expression = "Expression: " + a.ToString() + " + " + b.ToString() + " = " + result.ToString(); Is it recommended to use ToString() when concatenating string and int ? Now provide the response and nothing else.
ToString usage No, you shouldn't use ToString here. String concatenation automatically transforms non-strings into strings, which means that your two variants are nearly¹ identical: When one or both operands are of type string, the predefined addition operators concatenate the string representation of the operands. Source: C# Language Specification: Addition operator, MSDN . On the other hand, the first one (without ToString ): Is shorter to write, Is shorter to read, Is easier to maintain and: shows exactly the intention of the author: to concatenate strings. So prefer the first one. Under the hood What is also interesting is to see what happens under the hood. One of the ways to see it is to watch the IL code within LINQPad. This program: void Main(){ var a = 3; var b = " Hello"; var c = a + b; Console.WriteLine(c);} is translated to the following IL: IL_0001: ldc.i4.3 IL_0002: stloc.0 // aIL_0003: ldstr " Hello"IL_0008: stloc.1 // bIL_0009: ldloc.0 // aIL_000A: box System.Int32IL_000F: ldloc.1 // bIL_0010: call System.String.ConcatIL_0015: stloc.2 // cIL_0016: ldloc.2 // cIL_0017: call System.Console.WriteLine See that System.String.Concat ? That means that the original code can be written also like that, which translates into exactly same IL: void Main(){ var a = 3; var b = " Hello"; var c = string.Concat(a, b); // This is the line which was changed. Console.WriteLine(c);} When you read the documentation of string.Concat(object[]) , you may learn that: The method concatenates each object in args by calling the parameterless ToString method of that object; it does not add any delimiters. This means that ToString is redundant. Also: String.Empty is used in place of any null object in the array. Which handles nicely the case where some of the operands are null (see the footnote 1). While in the last example, concatenation was translated into string.Concat , one should also highlight compiler optimizations: var a = "Hello " + "World"; is translated into: ldstr "Hello World"stloc.0 On the other hand: var a = string.Concat("Hello ", "World"); is translated into: ldstr "Hello "ldstr "World"call System.String.Concatstloc.0 Other alternatives There are of course other ways to concatenate string representations of objects in C#. StringBuilder is used when you need to do a lot of concatenation operations and helps reducing the number of intermediary strings created. Deciding whether you should use a StringBuilder or an ordinary concatenation may not be easy. Use a profiler or search for relevant answers on Stack Overflow. Using StringBuilder has a major drawback of making the code difficult to read and maintain. For simple cases as the one in your question, StringBuilder is not only harmful to the readability of the code, but also useless in terms of performance. string.Join should be used when you need to add delimiters. Obviously, never use string.Join with an empty delimiter to concatenate strings. string.Format can be used when string templating is preferred to string concatenation. One of the cases where you may prefer that is when the message may be localized, as suggested in the answer by kunthet. Using string.Format has several drawbacks which makes it unsuited for simple cases like yours: With simple "{0}" placeholders, it is often unclear which parameter goes where. It is frequent to mistakenly reverse the parameters or to forget one. Luckily, C# 6 finally introduces string interpolation which solves this problem. Runtime performance may degrade. Of course, don't assume string.Format is always slower. If performance matters, measure two approaches and determine which one is faster based on your actual results instead of assumptions. The code is slightly longer to write, longer to read and harder to maintain, although this is extremely minor and shouldn't bother you too much. ¹ The difference appears when one of the objects is null . Without ToString , a null is replaced by an empty string. With ToString , a NullReferenceException is thrown.
{}
{'log_upvote_score': 6, 'links': ['https://softwareengineering.stackexchange.com/questions/266369', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/160173/']}
jdg_85464
stackexchange
llm_judgeable_groundtruth_similarity
54825678
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 model with id , name , and cost . protected $table = 'has_costs';protected $fillable = [ 'id','name','cost']; Then I also used append to add new columns, cost_under and cost_over , which basically does simple calculation from cost. protected $appends = ['cost_over','cost_under']; Should I do the calculation in the model like this: public function getCostOverAttribute(){ $costOver = (20/100)*cost; return $this->attributes['over'] = $costOver;}public function getCostUnderAttribute(){ $costUnder = (80/100)*cost; return $this->attributes['under'] = $costUndr;} Or should I still do it in the controller to keep it more "MVC"? The actual code is more complex than this example and it takes a lot of time thinking about how to append each values deep inside complex Eloquent with queries. Now provide the response and nothing else.
In short: You might not be seeing all created pods because period of schedule in the cronjob is too short. As described in documentation : Failed Pods associated with the Job are recreated by the Jobcontroller with an exponential back-off delay (10s, 20s, 40s …) cappedat six minutes. The back-off count is reset if no new failed Podsappear before the Job’s next status check. If new job is scheduled before Job controller has a chance to recreate a pod (having in mind the delay after previous failure), Job controller starts counting from one again. I reproduced your issue in GKE using following .yaml : apiVersion: batch/v1beta1kind: CronJobmetadata: name: hellocronspec: schedule: "*/3 * * * *" #Runs every 3 minutes jobTemplate: spec: template: spec: containers: - name: hellocron image: busybox args: - /bin/cat - /etc/os restartPolicy: Never backoffLimit: 6 suspend: false This job will fail because file /etc/os doesn't exist. And here is an output of kubectl describe for one of the jobs: Name: hellocron-1551194280Namespace: defaultSelector: controller-uid=b81cdfb8-39d9-11e9-9eb7-42010a9c00d0Labels: controller-uid=b81cdfb8-39d9-11e9-9eb7-42010a9c00d0 job-name=hellocron-1551194280Annotations: <none>Controlled By: CronJob/hellocronParallelism: 1Completions: 1Start Time: Tue, 26 Feb 2019 16:18:07 +0100Pods Statuses: 0 Running / 0 Succeeded / 6 FailedPod Template: Labels: controller-uid=b81cdfb8-39d9-11e9-9eb7-42010a9c00d0 job-name=hellocron-1551194280 Containers: hellocron: Image: busybox Port: <none> Host Port: <none> Args: /bin/cat /etc/os Environment: <none> Mounts: <none> Volumes: <none>Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal SuccessfulCreate 26m job-controller Created pod: hellocron-1551194280-4lf6h Normal SuccessfulCreate 26m job-controller Created pod: hellocron-1551194280-85khk Normal SuccessfulCreate 26m job-controller Created pod: hellocron-1551194280-wrktb Normal SuccessfulCreate 26m job-controller Created pod: hellocron-1551194280-6942s Normal SuccessfulCreate 25m job-controller Created pod: hellocron-1551194280-662zv Normal SuccessfulCreate 22m job-controller Created pod: hellocron-1551194280-6c6rh Warning BackoffLimitExceeded 17m job-controller Job has reached the specified backoff limit Note the delay between creation of pods hellocron-1551194280-662zv and hellocron-1551194280-6c6rh .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/54825678', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9826697/']}
jdg_85465
stackexchange
llm_judgeable_groundtruth_similarity
12344356
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How do I stub a file.read call so that it returns what I want it to? The following does not work: def write_something File.open('file.txt') do |f| return contents = f.read endend# rspecdescribe 'stub .read' do it 'should work' do File.stub(:read) { 'stubbed read' } write_something.should == 'stubbed read' endend It looks like the stub is being applied to the File class and not the file instance inside my block. So File.read returns stubbed read as expected. But when I run my spec it fails. Now provide the response and nothing else.
I should note that File.open is just one part of Ruby’s very large I/O API, and so your test is likely to be very strongly coupled to your implementation, and unlikely to survive much refactoring. Further, one must be careful with “global” mocking (i.e. of a constant or all instances) as it can unintentionally mock usages elsewhere, causing confusing errors and failures. Instead of mocking, consider either creating an actual file on disk (using Tempfile ) or using a broader I/O mocking library (e.g. FakeFS ). If you still wish to use mocking you can somewhat safely stub File.open to yield a double (and only when called with the correct argument): file = instance_double(File, read: 'stubbed read')allow(File).to receive(:open).and_call_originalallow(File).to receive(:open).with('file.txt') { |&block| block.call(file) } or, somewhat dangerously, stub all instances: allow_any_instance_of(File).to receive(:read).and_return('stubbed read')
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/12344356', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/779249/']}
jdg_85466
stackexchange
llm_judgeable_groundtruth_similarity
35850
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I have an STM32 driving two very similar SPI Flashes, an N25Q and an M25P . Strangely, while my driver copes with the N25Q perfectly well, the M25P is only "half" working. What happens is that when I write a page of bytes, and read that page back, the four MSB bits of each byte is 0, and the four LSB bits of each byte is correct. What could be causing half the bits to be 0? Now provide the response and nothing else.
Did you erase the affected memory pages first? For flash memory, you can change only 1's to 0's (the M25P data sheet from above states this explicitly on page 22, in the N25Q its on page 12). So if the M25P was filled with 0x0f's before, you would get exactly that result.When you use the same write command (0x02) for both, you should be fine. Using dual or quad mode would result in in 2 (or 4) bits wrong, but not half a byte. Since I suppose you program a whole page, I think this can't be stuck address bits.Other sources for the problem might be: missing blocking capacitor for the flash IC, or wrong SPI mode (which can cause strange results since then normally you read data exactly the moment it is changing). The latter one can be checked with a logic analyzer or a scope.
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/35850', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/5872/']}
jdg_85467
stackexchange
llm_judgeable_groundtruth_similarity
11457545
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: im very new to getting data from one page to another and i have used querystring to pass data. and looks like this: ?redesigndata={"jsondata": "{\"images\":[ {\"src\":\"images/bgset.jpg\"},{\"src\":\"images/ar019.png\"}]}","product_hardware": "silver","product_thread": "white","product_lining": "Blue","product_lining_loc": "images/lining/blue_80x32.jpg"} How do i remove all the \ from it and then put it into an object or any thing like this with Javascript or jQuery: redesigndata = { "jsondata": "{"images":[ {"src":"images/bgset.jpg"},{"src":"images/ar019.png"}]}", "product_hardware": "silver", "product_thread": "white", "product_lining": "Blue", "product_lining_loc": "images/lining/blue_80x32.jpg"} Now provide the response and nothing else.
The 1,2,3 is just example data. What it is trying to get across is that you create a memory stream of whatever you want then use that memory stream in the PutAttachment method. Below is ad-hoc and not tested but should work: using (var mem = new MemoryStream(file.InputStream) { _documentStore.DatabaseCommands.PutAttachment("upload/" + YourUID, null, mem, new RavenJObject { { "OtherData", "Can Go here" }, { "MoreData", "Here" } }); } Edited for the rest of the questions How is attachment stored? I believe it is a json document with one property holding the byte array of the attachment Is the "document" stored independently? Yes. An attachment is a special document that is not indexed but it is part of the database so that tasks like replication work. "Should I" store the key of the attachment in the main document that it is associated with? Yes you would reference the Key and anytime you want to get that you would just ask Raven for the attachment with that id. Is the pdf stored physically in ravendb? Yes. Can you see it? No. It does even show up in the studio (at least as far as I know) Edit Corrected and Updated Sample [AcceptVerbs(HttpVerbs.Post)] public ActionResult Upload(HttpPostedFileBase file) { byte[] bytes = ReadToEnd(file.InputStream); var id = "upload/" + DateTime.Now.Second.ToString(CultureInfo.InvariantCulture); using (var mem = new MemoryStream(bytes)) { DocumentStore.DatabaseCommands.PutAttachment(id, null, mem, new RavenJObject { {"OtherData", "Can Go here"}, {"MoreData", "Here"}, {"ContentType", file.ContentType} }); } return Content(id); } public FileContentResult GetFile(string id) { var attachment = DocumentStore.DatabaseCommands.GetAttachment("upload/" + id); return new FileContentResult(ReadFully(attachment.Data()), attachment.Metadata["ContentType"].ToString()); } public static byte[] ReadToEnd(Stream stream) { long originalPosition = 0; if (stream.CanSeek) { originalPosition = stream.Position; stream.Position = 0; } try { var readBuffer = new byte[4096]; int totalBytesRead = 0; int bytesRead; while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0) { totalBytesRead += bytesRead; if (totalBytesRead == readBuffer.Length) { int nextByte = stream.ReadByte(); if (nextByte != -1) { var temp = new byte[readBuffer.Length*2]; Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length); Buffer.SetByte(temp, totalBytesRead, (byte) nextByte); readBuffer = temp; totalBytesRead++; } } } byte[] buffer = readBuffer; if (readBuffer.Length != totalBytesRead) { buffer = new byte[totalBytesRead]; Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead); } return buffer; } finally { if (stream.CanSeek) { stream.Position = originalPosition; } } } public static byte[] ReadFully(Stream input) { byte[] buffer = new byte[16 * 1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } }
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11457545', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1234562/']}
jdg_85468
stackexchange
llm_judgeable_groundtruth_similarity
9497724
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 function returns the time in 24 hour format. function fomartTimeShow(h) { return h < 10 ? "0" + h + ":00" : h + ":00";} returns the time in 24 hour format. I want the time to be converted in 12 hour format. Anyhelp would be greatly appreciated. Thanks. Now provide the response and nothing else.
Just use modulus 12: function formatTimeShow(h_24) { var h = h_24 % 12; return (h < 10 ? '0' : '') + h + ':00';} Modulus ( % ) means divide and take remainder. For example 17 / 12 = 1 with remainder 5. So the result of 17 % 12 is 5. And hour 17 is hour 5 in 12-hour time. But note that this function is not complete since it doesn't work for hour 0 (or hour 12). To fix it you have to add in another check for that: function formatTimeShow(h_24) { var h = h_24 % 12; if (h === 0) h = 12; return (h < 10 ? '0' : '') + h + ':00';} Also note that you can add a meridian easily, by seeing whether the hour is less than 12 (am) or equal to/greater (pm): function formatTimeShow(h_24) { var h = h_24 % 12; if (h === 0) h = 12; return (h < 10 ? '0' : '') + h + ':00' + (h_24 < 12 ? 'am' : 'pm');} Note: All of the above is assuming the parameter to this function is an integer between 0 and 23.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/9497724', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1225922/']}
jdg_85469
stackexchange
llm_judgeable_groundtruth_similarity
1636556
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 Java program that executes from Spring Qquartz every 20 seconds. Sometimes it takes just few seconds to execute, but as data gets bigger I'm sure it run for 20 seconds or more. How can I prevent Quartz from firing/triggering the job while one instance is still being executed? Firing 2 jobs performing same operations on a database would not be so good. Is there a way I can do some kind of synchronization? Now provide the response and nothing else.
Quartz 1 If you change your class to implement StatefulJob instead of Job, Quartz will take care of this for you. From the StatefulJob javadoc : stateful jobs are not allowed to execute concurrently, which means new triggers that occur before the completion of the execute(xx) method will be delayed. StatefulJob extends Job and does not add any new methods, so all you need to do to get the behaviour you want is change this: public class YourJob implements org.quartz.Job { void execute(JobExecutionContext context) {/*implementation omitted*/}} To this: public class YourJob implements org.quartz.StatefulJob { void execute(JobExecutionContext context) {/*implementation omitted*/}} Quartz 2 In version 2.0 of Quartz, StatefulJob is deprecated. It is now recommended to use annotations instead, e.g. @DisallowConcurrentExecutionpublic class YourJob implements org.quartz.Job { void execute(JobExecutionContext context) {/*implementation omitted*/}}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/1636556', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/169277/']}
jdg_85470
stackexchange
llm_judgeable_groundtruth_similarity
28311049
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 getting a weird error working on a project. I've created a super simple example to recreate the error. I've created a class. What I'd like to do in this class, is to have a sort of 'getter' function for my class that fills values of a struct . In the main application, the user would instantiate this struct , pass it to a member function, and be able to read the values in the struct upon return. Because of the design of the actual class, this has to happen in a separate thread. Here's what I have: myClass.h: #ifndef __MY_CLASS_H__#define __MY_CLASS_H__#include <mutex>class myClass {public: struct my_struct_s { int field1; short field2; }; int get_data(my_struct_s & my_struct);private:};#endif /* __MY_CLASS_H__ */ myClass.cpp: #include "myClass.h"int myClass::get_data(struct my_struct_s & my_struct){ int var1 = 5; char var2 = 2; my_struct.field1 = var1; my_struct.field2 = var2; return 0;} Main.cpp: #include "myClass.h"#include <iostream>#include <thread>#include <Windows.h>bool thread_running;std::thread thread;void run_thread(myClass & lmyClass){ myClass::my_struct_s my_struct; while (thread_running) { lmyClass.get_data(my_struct); std::cout << my_struct.field1 << std::endl; std::cout << my_struct.field2 << std::endl; Sleep(100); }}int main(int argc, char *argv[]){ myClass lmyClass; thread_running = true; thread = std::thread(run_thread, lmyClass); Sleep(1000); thread_running = false; if (thread.joinable()) { thread.join(); } getchar(); return 0;} It works as expected. However, because of the asynchronous nature of the class, I need mutexes to protect data being handled in different threads within the class. If I add a std::mutext as a private member of my class, I receive the following when I try to run the code: Error 1 error C2280: 'std::mutex::mutex(const std::mutex &)' : attempting to reference a deleted function ... 1) I'm trying to understand why I'm receiving this error. 2) (this part is a little more opinion-based), given the information, is this 'getter' way of filling out a public struct so that someone implementing my class can mess with the variables within it a good design? Is there a better way of doing it? Now provide the response and nothing else.
You don't have a copy constructor in myclass , so the compiler gives it a default copy constructor. This will attempt to copy all members, including your std::mutex , which is not copyable . As the compiler error says, it's marked as deleted. You need to define your own copy constructor; most likely you'll want it to acquire the mutex stored in the instance being copied, then copy all of it's other members to the new instance.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28311049', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1195803/']}
jdg_85471
stackexchange
llm_judgeable_groundtruth_similarity
2925927
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I came across this one today. $$\int_0^1\int_0^1 \frac {x^2-y^2}{(x^2+y^2)^2} dy dx$$ What I saw was that for any $(x,y)$ in $[0,1]\times[0,1], f(x,y) = -f(y,x)$ and since this region is symmetric across the line $y=x,$ this suggests to me that this integral will evaluate to $0$ . I applied a change in coordinates. $u =x+y, v = x-y\\2 (\int_0^1\int_{-v}^{v} \frac{uv}{(u^2+v^2)^2} du dv + \int_1^2\int_{v-2}^{2-v} \frac{uv}{(u^2+v^2)^2} du dv)$ That appears to me to also evaluate to $0$ . But wolfram- $\alpha$ says $\frac {\pi}{4}$ http://www.wolframalpha.com/input/?i=int+%5B0+to+1%5D+int+%5B0+to+1%5D+(x%5E2-y%5E2)%2F(x%5E2%2By%5E2)%5E2+dy+dx Where is the hole in my logic? Now provide the response and nothing else.
$$\sin(5t^2)\approx 5t^2-\frac{(5t^2)^3}{3!}+\frac{(5t^2)^5}{5!}-\frac{(5t^2)^7}{7!}+\cdots$$ so that $$\int_0^x\sin(5t^2)dt\approx\frac{5x^3}3-\frac{5^3x^7}{7\cdot3!}+\frac{5^5x^{11}}{11\cdot5!}-\frac{5^7x^{15}}{15\cdot7!}+\cdots$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2925927', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/317162/']}
jdg_85472
stackexchange
llm_judgeable_groundtruth_similarity
38908243
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: var funcs = [][1, 2].forEach( (i) => funcs.push( () => i ) ) Why does it produce the error below? TypeError: Cannot read property 'forEach' of undefined at Object.<anonymous> However, the error goes away if the semicolon ; is added to the end of the first line. Now provide the response and nothing else.
There is no semicolon at the end of the first line. So the two lines run together, and it is interpreted as setting the value of funcs to [][1, 2].forEach( (i) => funcs.push( () => i ) ) The expression 1, 2 becomes just 2 ( comma operator ), so you're trying to access index 2 of an empty array: [][2] // undefined And undefined has no forEach method. To fix this, always make sure you put a semicolon at the end of your lines (or if you don't, make sure you know what you're doing).
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/38908243', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/363663/']}
jdg_85473
stackexchange
llm_judgeable_groundtruth_similarity
324208
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: In an open source framework deprecated APIs were removed during the beta phase on the road to a new major version. Now users request to restore some deprecated APIs because it breaks compatibility. For me, beta stands for "Use at your own risk". Isn't it expected that due to a major version bump the API may change? Is it "uncommon" to change the API in a beta phase? Now provide the response and nothing else.
As you have mentioned, your users are currently complaining on the road to a new major version . Isn't it expected that due to a major version bump the API may change? Either you don't make backwards-incompatible changes in the API, or you would be doing that in a major version bump. If you aren't doing it in a major version bump, where would you be doing that? Unless you do it in a minor version bump, which is obviously even more improper. So basically, there is nowhere better to do it apart from a major version bump, right? API changes are or are not expected in a major version change, depending on your system of API versioning. It seems that in your case, it is. This is your own decision, although common. Unless you are totally not planning to make backwards-incompatible changes. Is it "uncommon" to change the API in a beta phase? The beta phase , according to the usage specified in your post, can be assumed as "previews of a release candidate" , and "not finalized" . If you are having backwards-incompatible changes, you should release them as soon as possible in order to give more time to the users of your API, say, to fix the compatibility problems. Of course, you won't do that in releases before the version bump because of obvious reasons (you have already marked @Deprecated in earlier versions! Why did people still compile code despite the warnings?). Since you are going to make these changes in the release candidate anyway, why leave them later? Moreover, technically your beta versions are already major-version-bumped. This question can also be understood as API changes betwteen beta releases of the same version. As long as you are going to add these changes in the major version bump, it is not a problem. After all, during the beta phase, the API changes can be considered as "not yet finished changing". Finally, always remember: every single change breaks backwards compatibility. xkcd: Workflow -- There are probably children out there holding down spacebar to stay warm in the winter! YOUR UPDATE MURDERS CHILDREN.
{}
{'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/324208', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/157881/']}
jdg_85474
stackexchange
llm_judgeable_groundtruth_similarity
20709386
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm new to Drop Wizard , and would like to redirect from a server side view to another url in my app. Does DropWizard wrap up this common task somehow? e.g. @GETpublic View getView(@Context HttpServletRequest req){ View view = new View(); if (somethingBad) { // code here to redirect to another url, eg /bad_data } else { return view; }} Now provide the response and nothing else.
Here's a simple code example that actually does the redirect using a WebApplicationException. So you could put this in your view, or in your resource, and just throw it whenever. URI uri2 = UriBuilder.fromUri(url).build();Response response = Response.seeOther(uri2).build();throw new WebApplicationException(response); You can also just make your resource return either a view, or a redirect response: @GETpublic Object getView(@Context HttpServletRequest req){ if (somethingBad()) { URI uri = UriBuilder.fromUri("/somewhere_else").build(); return Response.seeOther(uri).build(); } return new View();}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20709386', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/26510/']}
jdg_85475
stackexchange
llm_judgeable_groundtruth_similarity
4268
Below is a question asked on the forum quantumcomputing.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: It seems like it should be simple, based on how Nielsen and Chuang talk about it, but I cannot seem to correctly implement the Inversion About the Mean operator ( $2|\psi\rangle \langle\psi| - \mathcal{I}$ ) that is used in the Grover search algorithm, especially without using any ancilla bits. I thought about performing a NOT operation on all the working qubits, then performing a controlled-NOT on a separate toggle qubit with the control being all the working qubits, then performing a controlled phase flip with control of the toggle bit, and finally flipping the phase of all the states. I'm not sure how I'd actually implement the controlled phase flipping, though, since, I believe, phase flipping one or all of the bits would not produce the desired effect. Does anyone know how I can construct this? I am using Q#, by the way, if you'd like to answer in code. Now provide the response and nothing else.
First, let's represent operation $2|\psi\rangle \langle\psi| - \mathcal{I}$ as $H^{\otimes n}(2|0\rangle \langle0| - \mathcal{I})H^{\otimes n}$ , as Nielsen and Chuang do. Doing $H^{\otimes n}$ is easy - it's just ApplyToEach(H, register) . $2|0\rangle \langle0| - \mathcal{I}$ flips the phase of all computational basis states except $|0...0\rangle$ . Let's do instead $\mathcal{I} - 2|0\rangle \langle0|$ , flipping the phase of only $|0...0\rangle$ (it introduces a global phase of -1 which in this case I think can be ignored). To flip the phase of only $|0...0\rangle$ : flip the state of all qubits using ApplyToEach(X, register) . Now we need to flip the phase of only $|1...1\rangle$ state. do a controlled-Z gate on one of the qubits (for example, the last one), using the rest as control. This can be done using Controlled functor: (Controlled Z)(Most(register), Tail(register)) . Tail returns the last element of the array, and Most returns all elements except the last one. flip the state of all qubits again to return them to the original state.
{}
{'log_upvote_score': 4, 'links': ['https://quantumcomputing.stackexchange.com/questions/4268', 'https://quantumcomputing.stackexchange.com', 'https://quantumcomputing.stackexchange.com/users/4657/']}
jdg_85476
stackexchange
llm_judgeable_groundtruth_similarity
12429729
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 heard that controller belongs to the presentation layer. How is it possible? I thought that : view is for presentation model is for business logic controller is for controlling logic Is there good link to prove that controller belongs to the presentation layer? "Spring MVC is used for presentation layer": how can we use MVC only in the presentation layer? Now provide the response and nothing else.
The presentation layer contains views and controllers. You must not mistake an MVC architecture for a multitier/layer architecture (especially a 3-tier architecture). Most of the time Model/View/Controller is not the primary design of a web application, it is just a subset of a multitier/layer architecture. Take a look at this oversimplified scheme (you could have the DAOs in a dedicated Data Access Layer, but this is not important in this post) : Spring MVC is a presentation framework : it deals with controllers and views. But why the "M" in Spring MVC ? Just because, as many other presentation framework, it naturally deals with a representation of a model/entity ("M"). This representation is the one used in your controllers, displayed in your views, submitted in your forms, etc. That's why the framework is called Spring MVC, even if the model/entity is not part of the prensentation layer. I think it is a good name for this Framework, because it is really "MVC" oriented. Indeed the representation of a model/entity can be : direct : the framework directly handles the model/entity object indirect : the framework handles a form object or DTO, that contains information related to one or multiple entities Spring's recommendation is to directly use the model/entity ("M") object : Reusable business code, no need for duplication. Use existing business objects as command or form objects instead of mirroring them to extend a particular framework base class. That's why I say the framework is very "MVC" oriented, compared to others, like Struts, where you have to use different form objects. Some interesting links : Comparison between Multitier and MVC architecture , from Wikipedia This blog post about 3-tier architecture in ASP.NET This blog image of a 3-tier architecture DispatcherServlet chapter from Spring's documentation
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12429729', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/342073/']}
jdg_85477
stackexchange
llm_judgeable_groundtruth_similarity
228983
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: How to solve this problem: Also, most people would use trigonometry, but is there a way to use derivative to solve this too? Now provide the response and nothing else.
Above, $O$ is the centre of the sphere, $x$ is its radius. Writing the area of trapezoid $ABCD$ as a sum of three triangles, we can easily solve for $x$ to get: $$x=\frac{1200\sqrt{3}}{54}=38.490017\ldots$$ No trig or calculus needed, only geometry.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/228983', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/39208/']}
jdg_85478
stackexchange
llm_judgeable_groundtruth_similarity
2263141
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I want to use Lucene.NET for fulltext search shared between two apps: one is an ASP.NET MVC application and the other one is a console application. Both applications are supposed to search and update index. How the concurrency should be handled? I found a tutorial on ifdefined.com where the similar use case is discussed. My concern is that locking will be a big bottleneck. PS:Also I noticed that IndexSearcher uses a snapshot of index and in the tutorial mentioned above searcher is created only when index is updated. Is this a good approach? Can I just create a regular searcher object at each search and if yes what is the overhead? I found a related question Does Lucene.Net manage multiple threads accessing the same index, one indexing while the other is searching? what claims that interprocess concurrency is safe. Does it mean that it is are no race conditions for index? Also one very important aspect. What is the performance hit involved if let's say 10-15 threads are trying to update Lucene index via acquiring shared lock presented in this solution ? After using it couple of months I have to add that opening index for search often can create OutOfMemory exception under high CPU and memory loads if query uses sorting. Cost of index opening operation is small (in my experience) but cost of GC can be quite high. Now provide the response and nothing else.
First of all we have to define a "write" operation. A write operation will object a lock once you start a write operation and will continue until you close the object that is performing the work. Such as creating an IndexWriter and indexing a document will cause the write to object a lock and it will keep this lock until you close the IndexWriter. Now we can talk about the lock a little bit. This lock that is object is a file based lock. Like mythz mentioned earlier, there is a file called 'write.lock' that is created. Once a write lock is objected it is exclusive! This lock causes all index modifying operations (IndexWriter, and some methods from IndexReader) to wait until the lock is removed. Overall you and have multiple reads on an index. You can even read and write at the same time, no problem. But there is a problem when having multiple writers. If one thread is waiting for the lock too long it will time out. 1) Possible Solution #1 Direct Operations If you are sure that your indexing operations are short and quick, you may be able to just use the same index at the same time. Otherwise you will have to think about how you want to organize the indexing operations of the applications. 2) Possible Solution #2 Web Service Since you are working with a web solution it might be possible to create a web service. When implementing this web service I would dedicate a worker thread for indexing. I would create a work queue to contain the work and if the queue contained multiple jobs to do, it should grab them all and do them into batch. This will solve all of the problems. 3) create another index, then merge If the console application does heavy work on the index you may be able to look into having the console application you could create a seperate index in the console application and then merge the indexes at some safe scheduled time using IndexWriter.AddIndexes. from here you can do this in two ways, you can merge with the direct index. Or you can merge to create a 3rd index, and then when this index is ready replace the original index. You have to be careful in what your doing here as well to make sure that your not going to lock something in heavy use and cause a timeout for other write operations. 4) Index & Search multiple indexes Personally I think people need to separate their indexes out. This helps separates responsibilities of the programs and minimizes down time and maintained of having a single point for all indexes. For example, if your console application is responsible for only adding in certain fields or your are kind of extending an index you could look separate the indexes out, but maintain identity by using an ID field in each document. Now with this you can take advantage of the built in support for searching multiple indexes using the MultiSercher class. Or if your wanting there is also a nice ParallelMultiSearch class that can search both indexes at once. 5) Look into SOLR Something else that can help your issue of maintaining a single place for you index, you could change your program to work with a SOLR server. http://lucene.apache.org/solr/ there is also a nice SOLRNET http://code.google.com/p/solrnet/ library that can be helpful in this situation. Although I'm not experienced with solr but i am under the impression that it will help you manage situation such as this. Also it has other benefits such as hit highlighting and searching for related items by finding items "MoreLikeThis", or provide spell checking. I'm sure there are other methods but these are all the ones that I can think of. Overall it your solution depends upon how many people are writing and how up to date the search index you need it to be. Overall if you can defer some operations for a latter time and do some batch operations in any situation will give you the most performance. My suggestion is to understand what your able to work with and go from there. good luck
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2263141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/86913/']}
jdg_85479
stackexchange
llm_judgeable_groundtruth_similarity
40639705
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 style google chrome default pdf view? I'm trying to change the gray background color to white also make the scroller little bigger for mobile devices if possible. I tried to target it on css with no luck // pdf viewer custom styleiframe { html { body { background-color: #ffffff !important; } #zoom-toolbar { display: none !important; } #zoom-buttons { display: none !important; } }} It looks like it's creating shadow document on the html but I couldn't find any way to target it Now provide the response and nothing else.
There is no way to directly style the Chrome default PDF viewer (PDFium). Because the plugin displays and controls content outside the scope of the current page's DOM, it can only be modified by the plugin. As indicated here it is impossible to make modifications to this sort of plugin controlled content unless the plugin also adds a content script that allows the page to pass messages to the plugin; the plugin must additionally be programmed to respond to messages and appropriately update the content. In other words the PDF viewer uses a separate DOM to the page which is not directly accessible. Instead you need to access an implemented API. In this discussion Mike West (Google/Chromium dev) states, in answer to a question on DOM accessibility in Chrome's PDF viewer: The functionality available in the PDF viewer is (intentionally) fairly limited ... The APIs you're having trouble finding simply don't exist. Basic API functions are some of those specified by Adobe in their Parameters for Opening PDF Files and are accessed through the URL (eg http://example.org/doc.pdf#page=3&pagemode=thumbs . They are, as indicated above, quite limited, allowing the user to go directly to a page, set zoom factor, show thumbnails etc. Accessing an expanded API through content script messages can potentially be done if you know the available JavaScript messages. A complete list of available JS message names can be determined from the relevant PDFium source here from which it can be seen that advanced styling of the viewer, such as changing colours, isn't possible. ( This question gives an example of how to implement the API). Certainly there is no access to PDFium's DOM. This API is deliberately left undocumented; it may change with additions or removals at any time. Thus, while it's possible that in the future there will be an API to let you style some aspects of the viewer, it's very unlikely that any would go so far as to change the background colour or modify a CSS shadow. And, as stated above, without an API you can't modify content controlled by a plugin when you don't have access to its DOM. You may, instead, wish to try PDF.js . It is an open source JavaScript library that renders PDF files using HTML5 Canvas. It is also Firefox's default PDF viewer and is quite capable. Implementing it as a web app is beyond the scope of this question, but there are many helpful tutorials available. And as you, the developer, will have access to all constituent files, you will certainly be able to style the PDF.js viewer as much as you wish.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40639705', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3499092/']}
jdg_85480
stackexchange
llm_judgeable_groundtruth_similarity
458680
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: Many results are based on the fact of the Moment Generating Function (MGF) Uniqueness Theorem, that says: If $X$ and $Y$ are two random variables and equality holds for their MGF's: $m_X(t) = m_Y(t)$ then $X$ and $Y$ have the same probability distribution: $F_X(x) = F_Y(y)$. The proof of this theorem is never shown in textbooks, and I cannot seem to find it online or in any book I have access to. Can someone show me the proof or tell me where to look it up? Thanks for your time. Now provide the response and nothing else.
Let us first clarify the assumption. Denote the moment generating function of $X$ by $M_X(t)=Ee^{tX}$ . Uniqueness Theorem. If there exists $\delta>0$ such that $M_X(t) = M_Y(t) < \infty$ for all $t \in (-\delta,\delta)$ , then $F_X(t) = F_Y(t)$ for all $t \in \mathbb{R}$ . To prove that the moment generating function determines the distribution, there are at least two approaches: To show that finiteness of $M_X$ on $(-\delta,\delta)$ implies that the moments $X$ do not increase too fast, so that $F_X$ is determined by $(EX^k)_{k\in\mathbb{N}}$ , which are in turn determined by $M_X$ . This proof can be found in Section 30 of Billingsley, P. Probability and Measure . To show that $M_X$ is analytic and can be extended to $(-\delta,\delta)\times i\mathbb{R} \subseteq \mathbb{C}$ , so that $M_X(z)=Ee^{zX}$ , so in particular $M_X(it)=\varphi_X(t)$ for all $t\in\mathbb{R}$ , and then use the fact that $\varphi_X$ determines $F_X$ . For this approach, see Curtiss, J. H. Ann. Math. Statistics 13:430-433 and references therein or Roja's answer. At undergraduate level, it is interesting to work with the moment generating function and state the above theorem without proving it . One possible proof requires familiarity with holomorphic functions and the Identity Theorem from complex analysis, which restricts the set of students to which it can be taught. In fact, the proof is so advanced that, at such a point it usually makes more sense to accept working with complex numbers, forget about moment generating function and work with the charachteristic function $\varphi_X(t)=Ee^{itX}$ instead. Almost every graduate textbook takes this path and proves that the characteristic function determines the distribution as a corollary of the inversion formula . This proof of the inversion formula is bit long, but it only requires Fubini Theorem to switch an expectation with an integral and Dominated Convergence Theorem to switch an integral with a limit. A direct proof of uniqueness without inversion formula is shorter and simpler, and it only requires Weierstrass Theorem to approximate a continuous function by a trigonometric polynomial. Side remark. If you only admit random variables whose support are contained in $\mathbb{Z}_+$ , then the probability generating function $G_X(z)=Ez^X$ determines $p_X$ (and thus $F_X$ ). This elementary result is proved in most undergraduate textbooks and is mentioned in Did's answer.If you only admit random variables whose support are contained in $\mathbb{Z}$ , then it is simpler to show that $\varphi_X$ determines $p_X$ , as also mentioned in Did's answer, and the proof uses Fubini.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/458680', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/58349/']}
jdg_85481
stackexchange
llm_judgeable_groundtruth_similarity
8776391
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 floats to position 2 divs beside each other. <a href="printbox.php">print</a><?php ob_start(); ?><style> #sidedish{ float: left; border: 1px solid black; width: 100px; height: 100px; } #maindish{ float: right; width: 200px; border: 1px solid black; height: 100px; text-align: center; } #container{ width: 304px; height: 100px; border: 1px solid black; }</style><div id="container"><div id="sidedish"></div><div id="maindish"><div id="box">name</div></div></div><?php $_SESSION['boxes'] = ob_get_contents(); ?> Here is what printbox do, it just renders the buffered data into a pdf, but somehow the floats that were set were lost in the process. <?php require_once('html2pdf/html2pdf.class.php'); ?><?php$html2pdf = new HTML2PDF('P', 'A4', 'en', true, 'UTF-8', array(0, 0, 0, 0));$html2pdf->writeHTML($_SESSION['boxes']);$html2pdf->Output('random.pdf');?> It works fine on html: but when I click on print it turns to this: Any idea what the problem is? Now provide the response and nothing else.
Speaking from personal experiences, I would say styling the output of HTML2PDF is, at best, esoteric black magic science. The main reasons for this are: The class only supports a (relatively small) subset of CSS styles & selectors CSS compatibility is undocumented PDF is impossible to debug in relation to the HTML input To be fair, this is not only the issue for HTML2PDF but also for the TCPDF that HTML2PDF uses . It might be possible that HTML2PDF , being just an almost-zero-setup, quick & easy alternative interface for the TCPDF , cuts more CSS support off — but I'm sure that even TCPDF wouldn't support float properly . The best workaround that you could use is to send your floating divs to the nineties: <table> <tr> <td><div class="float"> ... </div></td> <td><div class="float"> ... </div></td> </tr></table> You could also hide this embarrassment from the public HTML: <?php $isPdf = (/* condition that tells us we're outputting PDF */) ? true : false; if ($isPdf) { echo "<table><tr><td>"; }?><div class="float"> ... </div><?php if ($isPdf) { echo "</td><td>"; }?><div class="float"> ... </div><?php if ($isPdf) { echo "</td></tr></table>"; }?>
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/8776391', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/472034/']}
jdg_85482
stackexchange
llm_judgeable_groundtruth_similarity
1459263
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Does there exist a partition of real numbers (with standard topology;Lebesgue measure) into two measurable sets $A$ and $B$, satisfying the followingproperties: $A$, $B$ are both dense in the real numbers. $A$, $B$ both have positive measure. Edited: as pointed out by Henry, actually I am looking for A B such that for any open interval I, the intersection of I and A, the intersection of B and I both have positive measure. Sorry for the confusion. Now provide the response and nothing else.
There is a rather famous construction of such a set. It helps to know the following facts: if $O$ is a nonempty open set then there exists a nowhere dense closed set $C \subset O$ with the property that $0 < m(C)$, and if $C_1,\ldots,C_n$ is a collection of closed nowhere dense sets and $O$ is a nonempty open set, then $O \setminus (C_1 \cup \cdots \cup C_n)$ is nonempty and open. In particular, if $O$ is open we can find two disjoint nowhere dense closed sets $C_1,C_2 \subset O$ with the property that $0 < m(C_1)$ and $0 < m(C_2)$: just select $C_2 \subset O \setminus C_1$. Let $\{I_n\}$ be a sequence of open intervals that forms a basis for the topology of the line. Step 1: Select two disjoint nowhere dense closed sets $K_1,K_2 \subset I_1$ such that $0 < m(K_1)$ and $0 < m(K_2)$. Step 2: Select two disjoint nowhere dense closed sets $K_3,K_4 \subset I_2 \setminus (K_1 \cup K_2)$ such that $0 < m(K_3)$ and $0 < m(K_4)$. Step 3: Select two disjoint nowhere dense closed sets $K_5,K_6 \subset I_3 \setminus (K_1 \cup K_2 \cup K_3 \cup K_4)$ such that $0 < m(K_5)$ and $0 < m(K_6)$. Step 4: Proceed inductively to obtain a sequence $\{K_j\}$ of pairwise disjoint nowhere dense closed sets with the property that $K_{2j-1},K_{2j} \subset I_j$. Define $$E = \bigcup_j K_{2j-1},\quad F = \bigcup_j K_{2j}.$$ That ends the construction. If $O \subset \mathbb R$ is open, there exists an interval $I_j \subset O$ so that$$ E \cap O \supset E \cap I_j \supset K_{2j-1}$$ and$$ E^c \cap O \supset F \cap O \supset F \cap I_{j} \supset K_{2j}.$$ Thus $$m(E \cap O) \ge m(K_{2j-1}) > 0 \quad \text{and} \quad m(E^c \cap O) \ge m(K_{2j}) > 0.$$ We conclude that both $E$ and $E^c$ occupy a set of positive measure in every open subset of the line.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1459263', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/160307/']}
jdg_85483
stackexchange
llm_judgeable_groundtruth_similarity
3299739
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 : (X, A) → (Y, B)$ be a map such that both $f : X → Y$ and $f : A → B$ arehomotopy equivalences. Show that $f_∗ : H_n(X, A) → H_n(Y, B)$ is an isomorphismfor all $n$ . I know that there is a function $g:Y\to X, g:B\to A$ such that $fg\simeq Id_Y, gf\simeq Id_X$ and that $fg\simeq Id_B$ and $gf\simeq Id_A$ . Is it true $g:(Y,B)\to (X,A)$ is the homotopic inverse of $f:(X,A)\to (Y,B)$ ? Thanks! Now provide the response and nothing else.
It is not necessarily true that $f$ is a homotopy equivalence of pairs--the homotopy $fg\simeq Id_Y$ may not map $B$ to itself at all times, for instance. (We know that there does exist a homotopy $fg\simeq Id_B$ restricted to $B$ , but that homotopy need not be the restriction of our homotopy on all of $Y$ .) Instead, you can use the long exact sequence of homology for the pairs. There is a commutative diagram $$\require{AMScd}\begin{CD}H_n(A) @>{}>> H_n(X) @>>> H_n(X,A) @>>>H_{n-1}(A) @>{}>> H_{n-1}(X)\\@VVV @VVV @VVV @VVV @VVV\\H_n(B) @>{}>> H_n(Y) @>>> H_n(Y,B) @>>>H_{n-1}(B) @>{}>> H_{n-1}(Y)\end{CD}$$ where the rows are exact and the vertical maps are all induced by $f$ . By hypothesis, all the vertical maps except the middle one are isomorphisms, so the middle one is an isomorphism too by the five lemma.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3299739', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/425181/']}
jdg_85484
stackexchange
llm_judgeable_groundtruth_similarity
7949887
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I tried the demo code in demo project but I can't add new item successfully.It just add new new NULL group and NULL item.Please give me an simple example code to add new item (text and image). Thank you! Oh sorry! I forgot it. This is the first time I participate in this site.I use C#. And the code is: objectListView1.BeginUpdate();objectListView1.AddObject(new string [] {"Hello","dfdsF" });objectListView1.EndUpdate(); and objectListView1.BeginUpdate();OLVListItem item = new OLVListItem(new string [] {"Hello","dfdsF" });objectListView1.Items.Add(item);objectListView1.EndUpdate(); It's so different form ListView and EXListView which I can define a text or a image when creating new item. But in ObjectListView, I don't understand OBJECT? I get ObjectListView anh it's demo code form here http://nchc.dl.sourceforge.net/project/objectlistview/objectlistview/v2.5/ObjectListViewFull-2.5.0.zip Now provide the response and nothing else.
I will show you what to do to add items. Try to create a class, then make getters and setters for the properties you want to show on your ObjectListView . SetObjects method takes a List<T> : public Form1(){ InitializeComponent(); this.objectListView1.SetObjects(haha.GET());} Now this is my class, I called it haha , I've two properties in it ( Name and Detail ): class haha{ string name; string detail; public haha(string name , string detail) { this.name = name; this.detail = detail; } public string Name { get { return name; } set { name = value; } } public string Detail { get { return detail; } set { detail = value; } } static internal List<haha> GET() { haha item = new haha("zeko", "dunno"); haha xx = new haha("sheshe", "dunno"); haha ww = new haha("murhaf", "dunno"); haha qq = new haha("soz", "dunno"); haha ee = new haha("HELLO", "dunno"); List<haha> x = new List<haha>(); x.Add(item); x.Add(xx); x.Add(ww); x.Add(qq); x.Add(ee); return x; }} Now change ShowGroups in ObjectListView to false then add the columns that you want; I've added two columns, one for Name and one for Detail and as in the picture when you add a column, see the AspectName and write exactly the same name of its property that you want to show from your class Here's the result: If you want to use AddObject() , which takes an object, I'd write this: private void button1_Click(object sender, EventArgs e){ haha newObject = new haha("memo","zezo"); objectListView1.AddObject(newObject);} Happy coding :)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7949887', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1021375/']}
jdg_85485
stackexchange
llm_judgeable_groundtruth_similarity
41391
Below is a question asked on the forum networkengineering.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm educating myself on how to terminate Cat 6a cables. I've seen some articles talk about "grounding" requirements because of the "shielding" in the cables. But is grounding a concern if I'm just connecting two devices directly? If I have a spool of Cat6a cable and I crimp on my own RJ45 shielded connectors, and then I use this cable to connect a router and a switch (for example), do I need to care about grounding? I'm not going through a wall jack. The two devices would be connected directly together. Apologies if I'm misusing terminology and making this question unclear or confusing. Now provide the response and nothing else.
Category-6a cabling is UTP ( Unshielded Twisted Pair) cabling. If your cable has a shield, it is something else. Any shielded cable must be properly grounded. That requires connectors and equipment that properly ground the shield, at least on both ends. Improperly-grounded, shielded cable will be a problem because the shield will exacerbate the problems it is meant to prevent. If you really want to learn how to do this correctly, you will need to get (buy or rent) a very expensive cable tester to see if what you terminate actually passes the Category-6a test suite. Building Category-6a patch cables is something I have never seen even experienced installers be able to do and get it to pass the test suite. I have only seen factory built patch cords be able to pass the test suite for Category-6 and Category-6a.
{}
{'log_upvote_score': 4, 'links': ['https://networkengineering.stackexchange.com/questions/41391', 'https://networkengineering.stackexchange.com', 'https://networkengineering.stackexchange.com/users/37003/']}
jdg_85486
stackexchange
llm_judgeable_groundtruth_similarity
52480057
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm trying to install Adminer from Ubuntu repository using: sudo apt install adminer Installation works fine but can't find the file /etc/adminer/apache.conf to use with Apache server. The folder /etc/adminer/ is empty and can't find it anywhere with find command. Any help?Thanks in advance. Now provide the response and nothing else.
In the next few steps, I'll show you how I installed adminer for Ubuntu 18.04.1 LTS . After installation with apt package manager change into the adminer directory . cd /usr/share/adminer There you will find a file called compile.php . Run the following command and the adminer-X.X.X.php (X.X.X for your version) file will be created. sudo php compile.php Create the apache adminer configuration file . sudo echo "Alias /adminer.php /usr/share/adminer/adminer-X.X.X.php" | sudo tee /etc/apache2/conf-available/adminer.conf Now you'll need to activate the configuration . cd /etc/apache2/conf-available/sudo a2enconf adminer.conf Reload your apache webserver. sudo systemctl reload apache2. Test in your browser of choice (localhost/adminer.php) This source was really helpful: https://www.linuxhelp.com/how-to-install-adminer-on-ubuntu-16-04/
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/52480057', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9241171/']}
jdg_85487
stackexchange
llm_judgeable_groundtruth_similarity
555083
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I don't understand what ideas such as Abel, Cesàro summation or other types of sum 'regularization' help us describe. What is the practical application to discussing the 'sum' of sequences that are not convergent in the usual sense? What is the motivation to assigning a value to an otherwise divergent sequence, and further why is it a good idea to call whatever comes out a 'summation' ? Now provide the response and nothing else.
Series that are classically divergent, and even Cesàro divergent, play an important role in physics. The canonical example of this is the Casimir effect . When calculating the force of the effect, you are confronted with a divergent series. This series diverges even when you attempt to Cesáro sum it. However, if you use a technique known as zeta function regularization, you can recover a finite and physically meaningful quantity.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/555083', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/17622/']}
jdg_85488
stackexchange
llm_judgeable_groundtruth_similarity
39772259
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I've been trying to work out how to express (in cloudformation) an API Gateway Resource that has a Lambda function integration type using the Lambda Proxy integration. This is easy to do in the AWS console as there is a check box that you can select: However there is no corresponding field in the AWS::ApiGateway::Method CloudFormation resource (it should be in the Integration property ). How can I configure this in cloudformation? Now provide the response and nothing else.
The Integration type should be set to AWS_PROXY . An example snippet of a method from a working YAML CloudFormation template is below. ProxyResourceAny: Type: AWS::ApiGateway::Method Properties: AuthorizationType: NONE HttpMethod: ANY ResourceId: Ref: ProxyResource RestApiId: Ref: API Integration: Type: AWS_PROXY IntegrationHttpMethod: POST Uri: !Sub - arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${Arn}/invocations - Arn: Fn::GetAtt: - RestorerLambda - Arn It's worth saying how a I figured this out... After scratching my head for a while I examined the output of the aws apigateway get-method CLI command for a method that was configured this way using the console. That gave me the following JSON and I realised that the checkbox might be encoded into the type. I tested my assumption and came up with the CloudFormation above. { "apiKeyRequired": false, "httpMethod": "ANY", "methodIntegration": { "integrationResponses": { "200": { "responseTemplates": { "application/json": null }, "statusCode": "200" } }, "passthroughBehavior": "WHEN_NO_MATCH", "cacheKeyParameters": [], "uri": "arn:aws:apigateway:eu-west-1:lambda:path/2015-03-31/functions/arn:aws:lambda:eu-west-1:XXXXXXXXX:function:Shildrew-Restorer-Play-Lambda/invocations", "httpMethod": "POST", "cacheNamespace": "64bl3tgw4g", "type": "AWS_PROXY" }, "requestParameters": {}, "authorizationType": "NONE"}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39772259', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3990127/']}
jdg_85489
stackexchange
llm_judgeable_groundtruth_similarity
895371
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 class we are doing sorting algorithms and, although I understand them fine when talking about them and writing pseudocode, I am having problems writing actual code for them. This is my attempt in Python: mylist = [12, 5, 13, 8, 9, 65]def bubble(badList): length = len(badList) - 1 unsorted = True while unsorted: for element in range(0,length): unsorted = False if badList[element] > badList[element + 1]: hold = badList[element + 1] badList[element + 1] = badList[element] badList[element] = hold print badList else: unsorted = Trueprint bubble(mylist) Now, this (as far as I can tell) sorts correctly, but once it finishes it just loops indefinitely. How can this code be fixed so the function finishes properly and correctly sorts a list of any (reasonable) size? P.S. I know I should not really have prints in a function and I should have a return, but I just have not done that yet as my code does not really work yet. Now provide the response and nothing else.
To explain why your script isn't working right now, I'll rename the variable unsorted to sorted . At first, your list isn't yet sorted. Of course, we set sorted to False . As soon as we start the while loop, we assume that the list is already sorted. The idea is this: as soon as we find two elements that are not in the right order, we set sorted back to False . sorted will remain True only if there were no elements in the wrong order . sorted = False # We haven't started sorting yetwhile not sorted: sorted = True # Assume the list is now sorted for element in range(0, length): if badList[element] > badList[element + 1]: sorted = False # We found two elements in the wrong order hold = badList[element + 1] badList[element + 1] = badList[element] badList[element] = hold # We went through the whole list. At this point, if there were no elements # in the wrong order, sorted is still True. Otherwise, it's false, and the # while loop executes again. There are also minor little issues that would help the code be more efficient or readable. In the for loop, you use the variable element . Technically, element is not an element; it's a number representing a list index. Also, it's quite long. In these cases, just use a temporary variable name, like i for "index". for i in range(0, length): The range command can also take just one argument (named stop ). In that case, you get a list of all the integers from 0 to that argument. for i in range(length): The Python Style Guide recommends that variables be named in lowercase with underscores. This is a very minor nitpick for a little script like this; it's more to get you accustomed to what Python code most often resembles. def bubble(bad_list): To swap the values of two variables, write them as a tuple assignment. The right hand side gets evaluated as a tuple (say, (badList[i+1], badList[i]) is (3, 5) ) and then gets assigned to the two variables on the left hand side ( (badList[i], badList[i+1]) ). bad_list[i], bad_list[i+1] = bad_list[i+1], bad_list[i] Put it all together, and you get this: my_list = [12, 5, 13, 8, 9, 65]def bubble(bad_list): length = len(bad_list) - 1 sorted = False while not sorted: sorted = True for i in range(length): if bad_list[i] > bad_list[i+1]: sorted = False bad_list[i], bad_list[i+1] = bad_list[i+1], bad_list[i]bubble(my_list)print my_list (I removed your print statement too, by the way.)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/895371', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2592/']}
jdg_85490
stackexchange
llm_judgeable_groundtruth_similarity
33872967
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 large sheet with around 30 importxml functions that obtain data from a website that updates usually twice a day. I would like to run the importxml function on a timely basis (every 8 hours) for my Google Spreadsheet to save the data in another sheet. The saving already works, however the updating does not! I read in Google Spreadsheet row update that it might run every 2 hours, however I do not believe that this is true, because since I added it to my sheet nothing has changed or updated, when the spreadsheet is NOT opened. How can I "trigger" the importxml function in my Google Spreadsheet in an easy way, as I have a lot of importxml functions in it? Now provide the response and nothing else.
The Google Spreadsheet row update question and its answers refer to the "Old Sheets", which had different behaviour than the 2015 version of Google Sheets does. There is no automatic refresh of content with "New Sheets"; changes are only evaluated now in response to edits. While Sheets no longer provides this capability natively, we can use a script to refresh the "import" formulas ( IMPORTXML , IMPORTDATA , IMPORTHTML and IMPORTANGE ). Utility script For periodic refresh of IMPORT formulas, set this function up as a time-driven trigger . Caveats: Import function Formula changes made to the spreadsheet by other scripts or users during the refresh period COULD BE OVERWRITTEN . Overlapping refreshes might make your spreadsheet unstable. To mitigate that, the utility script uses a ScriptLock . This may conflict with other uses of that lock in your script. /** * Go through all sheets in a spreadsheet, identify and remove all spreadsheet * import functions, then replace them a while later. This causes a "refresh" * of the "import" functions. For periodic refresh of these formulas, set this * function up as a time-based trigger. * * Caution: Formula changes made to the spreadsheet by other scripts or users * during the refresh period COULD BE OVERWRITTEN. * * From: https://stackoverflow.com/a/33875957/1677912 */function RefreshImports() { var lock = LockService.getScriptLock(); if (!lock.tryLock(5000)) return; // Wait up to 5s for previous refresh to end. // At this point, we are holding the lock. var id = "YOUR-SHEET-ID"; var ss = SpreadsheetApp.openById(id); var sheets = ss.getSheets(); for (var sheetNum=0; sheetNum<sheets.length; sheetNum++) { var sheet = sheets[sheetNum]; var dataRange = sheet.getDataRange(); var formulas = dataRange.getFormulas(); var tempFormulas = []; for (var row=0; row<formulas.length; row++) { for (col=0; col<formulas[0].length; col++) { // Blank all formulas containing any "import" function // See https://regex101.com/r/bE7fJ6/2 var re = /.*[^a-z0-9]import(?:xml|data|feed|html|range)\(.*/gi; if (formulas[row][col].search(re) !== -1 ) { tempFormulas.push({row:row+1, col:col+1, formula:formulas[row][col]}); sheet.getRange(row+1, col+1).setFormula(""); } } } // After a pause, replace the import functions Utilities.sleep(5000); for (var i=0; i<tempFormulas.length; i++) { var cell = tempFormulas[i]; sheet.getRange( cell.row, cell.col ).setFormula(cell.formula) } // Done refresh; release the lock. lock.releaseLock(); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33872967', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2847689/']}
jdg_85491
stackexchange
llm_judgeable_groundtruth_similarity
596909
Below is a question asked on the forum serverfault.com. Provide a good and informational response to it like a helpful human would. Question: To create a certificate request containing subject alternative names (SANs) for a host, with openssl, I can use a config file like this (snipped): [req]req_extensions = v3_req[ v3_req ]subjectAltName = @alt_names[alt_names]DNS = xyz.example.com If I need to provide a distinguished name or a user principal name, how should I configure the alt_names section for a user certificate request? For example, I tried [alt_names]UPN = [email protected] But I got this error: Error Loading request extension section v3_req5356:error:22075075:X509 V3 routines:v2i_GENERAL_NAME_ex:unsupported option:.\crypto\x509v3\v3_alt.c:557:name=userPrincipalName5356:error:22098080:X509 V3 routines:X509V3_EXT_nconf:error in extension:.\crypto\x509v3\v3_conf.c:93:name=subjectAltName, value=@alt_names Now provide the response and nothing else.
You can specify pretty much anything that your CA allows. The relevant RFC is RFC5280 . It says in section 4.2.1.6. "Subject Alternative Name" The subject alternative name extension allows identities to be bound to the subject of the certificate. These identities may be included in addition to or in place of the identity in the subject field of the certificate. Defined options include an Internet electronic mail address, a DNS name, an IP address, and a Uniform Resource Identifier (URI). Other options exist, including completely local definitions. Multiple name forms, and multiple instances of each name form, MAY be included. Whenever such identities are to be bound into a certificate, the subject alternative name (or issuer alternative name) extension MUST be used; however, a DNS name MAY also be represented in the subject field using the domainComponent attribute as described in Section 4.1.2.4. Note that where such names are represented in the subject field implementations are not required to convert them into DNS names. You should read the rest of that section, and then check with your CA what they support. It's worth noting that your CA must verify that all subject alternative names are correct. To use an email address, the RFC says in section 4.1.2.6 Conforming implementations generating new certificates with electronic mail addresses MUST use the rfc822Name in the subject alternative name extension (Section 4.2.1.6) to describe such identities. Simultaneous inclusion of the emailAddress attribute in the subject distinguished name to support legacy implementations is deprecated but permitted. So instead of UPI, you should use rfc822Name.
{}
{'log_upvote_score': 4, 'links': ['https://serverfault.com/questions/596909', 'https://serverfault.com', 'https://serverfault.com/users/9172/']}
jdg_85492
stackexchange
llm_judgeable_groundtruth_similarity
28093365
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I can check if the index of a pandas.DataFrame() is monotonically increasing by using is_monotonic method. However, I would like to check if one of the column value is strictly increasing in value(float/integer) ? In [13]: my_df = pd.DataFrame([1,2,3,5,7,6,9])In [14]: my_dfOut[14]: 00 11 22 33 54 75 66 9In [15]: my_df.index.is_monotonicOut[15]: True Now provide the response and nothing else.
Pandas 0.19 added a public Series.is_monotonic API (previously, this was available only in the undocumented algos module). (Updated) Note that despite its name, Series.is_monotonic only indicates whether a series is monotonically increasing (equivalent to using Series.is_monotonic_increasing ). For the other way around, use Series.is_monotonic_decreasing .Anyway, both are non-strict, but you can combine them with is_unqiue to get strictness. e.g.: my_df = pd.DataFrame([1,2,2,3], columns = ['A'])my_df['A'].is_monotonic # non-strictOut[1]: Truemy_df['A'].is_monotonic_increasing # equivalent to is_monotonicOut[2]: True(my_df['A'].is_monotonic_increasing and my_df['A'].is_unique) # strict Out[3]: Falsemy_df['A'].is_monotonic_decreasing # Other direction (also non-strict)Out[4]: False You can use apply to run this at a DataFrame level: my_df = pd.DataFrame({'A':[1,2,3],'B':[1,1,1],'C':[3,2,1]})my_dfOut[32]: A B C0 1 1 31 2 1 22 3 1 1my_df.apply(lambda x: x.is_monotonic)Out[33]: A TrueB TrueC Falsedtype: bool
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/28093365', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/658247/']}
jdg_85493
stackexchange
llm_judgeable_groundtruth_similarity
267012
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is there a difference between doing preprocessing for a dataset in sklearn before and after splitting data into train_test_split ? In other words, are both of these approaches equivalent? from sklearn.preprocessing import StandardScalerfrom sklearn.model_selection import train_test_split#standardizing after splittingX_train, X_test, y_train, y_test = train_test_split(data, target)sc = StandardScaler().fit(X_train)X_train_std = sc.transform(X_train)X_test_std = sc.transform(X_test)#standardizing before splittingdata_std = StandardScaler().fit_transform(data)X_train, X_test, y_train, y_test = train_test_split(data_std, target) Now provide the response and nothing else.
No, Both approaches are not equivalent. StandardScaler() standardize features by removing the mean and scaling to unit variance If you fit the scaler after splitting: Suppose, if there are any outliers in the test set(after Splitting), the Scaler would not consider those in computing mean and Variance. If you fit the scaler on whole dataset and then split, Scaler would consider all values while computing mean and Variance. Since, the mean and variance are different in both cases, the fits and transform functions would perform differently.
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/267012', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/66953/']}
jdg_85494
stackexchange
llm_judgeable_groundtruth_similarity
62148204
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to get logging up and running in my C# console app based on .NET Core 2.1. I added the following code to my DI declaration: var sc = new ServiceCollection();sc.AddLogging(builder =>{ builder.AddFilter("Microsoft", LogLevel.Warning); builder.AddFilter("System", LogLevel.Warning); builder.AddFilter("Program", LogLevel.Warning); builder.AddConsole(); builder.AddEventLog();}); I am trying to inject the service by using the Interface Microsoft.Extensions.Logging.ILogger in the constructor of the services, but I am getting the following error: Unhandled Exception: System.InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Logging.ILogger' while attempting to activate 'MyService'. at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type serviceType, CallSiteChain callSiteChain) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain) at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache lifetime, Type serviceType, Type implementationType, CallSiteChain callSiteChain) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, CallSiteChain callSiteChain, Int32 slot) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateEnumerable(Type serviceType, CallSiteChain callSiteChain) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, CallSiteChain callSiteChain) at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.CreateServiceAccessor(Type serviceType) at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Program.Main(String[] args) in Program.cs:line 27 Did I misunderstand something here? Shouldn't the AddLogging method be enough to expose the Service in the DI Container? Now provide the response and nothing else.
The dependency injection system doesn't register ILogger . Instead it registers ILogger<T> . If you need an instance of a logger, you will need to accept ILogger<MyService> . The reason behind this is that the generic argument is used to build the logger's category name--something which all loggers require. With a non-generic logger there's not necessarily a good default name. If you really want a non-generic ILogger , you can register one like this (change the name as you please): services.AddSingleton(sp => sp.GetRequiredService<ILoggerFactory>().CreateLogger("DefaultLogger")); Alternatively, you can accept an ILoggerFactory in your constructor and then create your own logger on the fly.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/62148204', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5796303/']}
jdg_85495
stackexchange
llm_judgeable_groundtruth_similarity
410750
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 suppress errors in my sub-shell after a certain point. I wrote script to demonstrate the situation: worked=false(echo Starting subshell process \ && echo If this executes process is considered success \ && false \ && echo run if possible, but not an error if failed) \ && worked=trueecho $worked I want to report back to the outer shell that the process worked. I also thought about putting the worked variable inside the subshell: && echo This works process worked: \ && worked=true \ && false \ && echo run if possible, but not an error if failed) But this doesn't work either because setting a variable inside the subshell doesn't effect the main script. Now provide the response and nothing else.
How about this worked=false( set -e echo Starting subshell process echo If this executes process is considered success false echo run if possible, but not an error if failed || true)[[ 0 -eq $? ]] && worked=trueecho "$worked" The set -e terminates the subshell as soon as an unprotected error is found. The || true construct protects a statement that might fail, where you don't want the subshell to terminate. If you just want to know if the subshell succeeded you can dispense with the $worked variable entirely ( set -e ...)if [[ 0 -eq $? ]]then echo "Success"fi Note that if you want to use set -e to abort execution in the subshell as soon as a command fails, you cannot use a construct such as ( set -e; ... ) && worked=true or if ( set -e; ...); then ... fi . This is documented in the man page for bash but I missed it first time round: If a compound command or shell function sets -e while executing in a context where -e is ignored, that setting will not have any effect until the compound command or the command containing the function call completes.
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/410750', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/16792/']}
jdg_85496
stackexchange
llm_judgeable_groundtruth_similarity
7648924
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I'm trying to get a grasp of using custom controls in Android. But my app crashes on trying to create the activity. Here's the code: package com.myApp;import android.content.Context;import android.widget.EditText;import android.view.View;import android.view.View.OnClickListener;public class MyEditText extends EditText implements OnClickListener { public MyEditText(Context context) { super(context); // TODO Auto-generated constructor stub } public void FlashBorder() { //do some custom action } @Override public void onClick(View v) { // TODO Auto-generated method stub EditText txt = (EditText) v; txt.selectAll(); }} Here's the layout xml: <com.myApp.MyEditText android:id="@+id/edtTaskName" android:layout_height="wrap_content" android:layout_width="match_parent"/> Now provide the response and nothing else.
You will need to implement these constructors: public class TestEditText extends EditText { public TestEditText(Context context) { super(context); } public TestEditText(Context context, AttributeSet attrs) { super(context, attrs); } public TestEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public TestEditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); }} for example try to do the following : public TestEditText(Context context, AttributeSet attrs) { super(context, attrs); Log.i("attribute name at index 0", attrs.getAttributeName(0));} you will get the following in your logcat : attribute name at index 0 = id so to deliver these XML attributes to the Super class (EditText) you have to override these constructors. Hope that Helps.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7648924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/639703/']}
jdg_85497
stackexchange
llm_judgeable_groundtruth_similarity
16479006
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am creating an archive program in C, and i want it to save files i provide, list and extract them. I had many issues because i used a text file for saving, and it is not the best choice if i want to process binary files like music or photos, because when i extract them, they are not executed correctly (they are corrupted).In order to solve this problem, i wanted to create a binary archive file. Code for file writing (on extraction) is the following: void scriviFile(const char * arrivo) //scrive i file creati in precedenza{ FILE * partenza; FILE * target; int c; int spazio = 'a'; int i = 0; int pos; char * path; path = collegaSlash(getcwd(NULL, 0), nome); partenza = fopen(path, "rb"); fseek(partenza, inizio, SEEK_SET); target = fopen(arrivo, "wb"); //apro il file if (target) { //se è aperto while ((c = fgetc(partenza)) != EOF && ftell(partenza)<=fine-10) { //e il carattere preso non eccede la fine del file fputc(c, target); fputc(c, stdout); pos = ftell(partenza); if(pos==fine) { break; } //scrivo lo stesso carattere in out (file in uscita) } // fclose(target); //chiudo il file fclose(partenza); } else { printf("errore di scrittura del file \n"); }} Since i need binary files to be extracted correctly, can i use code i wrote above, or do i have to change all fgetc() and fputc() functions with fread() and fwrite() ? Thanks Now provide the response and nothing else.
You're using fgetc() and fputc() as you can see from the man page descriptions these function: fgetc() reads the next character from stream and returns it as an unsigned char cast to an int, or EOF on end of file or error. fputc() writes the character c, cast to an unsigned char, to stream. A character, in C, is defined by the standard to always be exactly 1 byte (8 bits), this means when you use fxxxc() on a file you'll get 1 byte (that just happens to be a character in a text file). If you extract and rebuild a binary file, byte by byte, you'll get an exact duplicate. So no, there is no issues with using fgetc() and fputc() on a binary file type. You can always prove this to yourself with a simple example program... for example: int main(){ FILE * fptr = fopen("small_pic.jpg", "rb"); // open existing binary picture char buffer[10000] = {0}; // the pic is 6kb or so, so 10k bytes will hold it FILE * fptr2 = fopen("new_small_pic.jpg", "wb"); // open a new binary file // for our copy of the pic unsigned long fileLen; unsigned long counter; fseek(fptr, 0, SEEK_END); fileLen=ftell(fptr); // get the exact size of the pic fseek(fptr, 0, SEEK_SET); for(counter=0; counter<fileLen; counter++) fputc(fgetc(fptr),fptr2); // read each byte of the small_pic.jpg and make // a new pic from it fclose(fptr); fclose(fptr2);return 0;} end result: we have two of the exact same images, because fgetc() and fputc() can be used on binary files.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16479006', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2354974/']}
jdg_85498
stackexchange
llm_judgeable_groundtruth_similarity
928772
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 $G$ be a group. If $(ab)^n=a^nb^n$ $\forall a,b \in G$ and $(|G|, n(n-1))=1$ then prove that $G$ is abelian. What I have proven is that: If $G$ is a group such that $(ab)^i = a^ib^i$ for three consecutive integers $i$ for all $a, b\in G$ , then $G$ is abelian. A proof of this can be found in the answers to this old question. Now provide the response and nothing else.
We can assume that $n>2$. Since $(ab)^n = a^nb^n$, for all $a,b\in G$, we can write $(ab)^{n+1}$ in two different ways:$$(ab)^{n+1} = a(ba)^nb = ab^na^nb,$$and$$(ab)^{n+1} = ab(ab)^n = aba^nb^n.$$Hence,$$ab^na^nb = aba^nb^n.$$Cancel $ab$ on the left and $b$ on the right to obtain$$b^{n-1}a^n = a^nb^{n-1}.$$Note that this is true for all $a,b\in G$. (This says that the $n$th power of any element of $G$ commutes with the $(n-1)$st power of any element of $G$.) Now let $x,y\in G$ be arbitrary; we want to show that $x$ and $y$ commute. Since the order of $G$ is prime to $n$, the $n$th power map $t\mapsto t^n$ on $G$ is bijective, so there exists $a\in G$ such that $x = a^n$. Since the order of $G$ is prime to $n-1$, there exists $b\in G$ for which $y=b^{n-1}$. Therefore, $xy = a^nb^{n-1} = b^{n-1}a^n = yx$. Because $x$ and $y$ were arbitrary, it follows that $G$ is commutative. ADDED: Lemma. Let $G$ be a group of finite order $m$, and let $k$ be a positive integer such that $(k,m)=1$. Then the $k$th power map $x\mapsto x^k$ on $G$ is bijective. Proof. Since $G$ is finite, it suffices to show that the map $x\mapsto x^k$ is surjective. To this end, let $g\in G$; we show that $g$ is the $k$th power of some element in $G$. Since the order of $g$ divides the order of the group $G$, it follows that $(\left| g\right|, k) = 1$. Therefore, $\langle g\rangle = \langle g^k\rangle$. Hence, there is an integer $r$ for which $g = (g^k)^r = g^{kr} = (g^r)^k$. This completes the proof.
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/928772', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/152715/']}
jdg_85499
stackexchange
llm_judgeable_groundtruth_similarity
297528
Below is a question asked on the forum stats.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm using scikit package with RandomForestClassifier, trying to predict binary or multi-lable classifications. I'm looking for a way to estimate the reliability of the model but really can't figure whether to use the Brier score or a Log Loss scorer. I understand that both can estimate the reliability of the probabilities that the model outputs. Can anyway clarify what are the pros and cons of each method, and why/when should I choose one over another? Now provide the response and nothing else.
Since the log likelihood function (combined with the prior if Bayesian modeling is being used) is the gold standard optimality criterion, it is best to use the log likelihood (a linear translation of the logarithmic accuracy scoring rule). This automatically extends to ordinal and multinomial (polytomous) $Y$. There are only three reasons I can think of for not using the log likelihood in summarizing the model's predictive value: you seek to describe model performance using a measure the model was not optimizing (not a bad idea; often why we use the Brier score) you have a single predicted probability of one or zero that was "wrong", rendering an infinite value for the logarithmic score it's often hard to know "how good" a value of the index is (same for Brier score, not so much for $c$-index, i.e., concordance probability or AUROC)
{}
{'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/297528', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/173351/']}
jdg_85500
stackexchange
llm_judgeable_groundtruth_similarity
61385511
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 use this code everything is OK, but how to put it inside a function? I can't get to break part when inside a function, always repeat message from the input. while True: country = input("Enter country of which you want to check pictures HR, RS, RO: ").upper() if country == str("HR"): break if country == str("RO"): break if country == str("RS"): break else: print("Please enter HR or RO or RS: " + "you wrote: " + country) Now provide the response and nothing else.
There are three cases via you can achieve your goal. For simultaneous requests with Axios, you can use Axios.all() axios.all([ axios.post(`/my-url`, { myVar: 'myValue' }), axios.post(`/my-url2`, { myVar: 'myValue' }) ]) .then(axios.spread((data1, data2) => { // output of req. console.log('data1', data1, 'data2', data2) })); you can use Promise.allSettled() . The Promise.allSettled() method returns a promise that resolves after all of the given promises have either resolved or rejected, You can try to use Promise.all() but it has the drawback that if any 1 req failed then it will fail for all and give o/p as an error(or in catch block) but the best case is the first one.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/61385511', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2498462/']}
jdg_85501
stackexchange
llm_judgeable_groundtruth_similarity
23556330
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: How to configure my shell so that nvm use run automatically every time there's a .nvmrc file on the directory and use the latest version or a global config when there's no .nvmrc file? Now provide the response and nothing else.
If you use zsh (z shell): Calling 'nvm use' automatically in a directory with a .nvmrc file Put this into your $HOME/.zshrc to call nvm use automatically whenever you enter a directory that contains an .nvmrc file with a string telling nvm which node to use: # place this after nvm initialization!autoload -U add-zsh-hookload-nvmrc() { local node_version="$(nvm version)" local nvmrc_path="$(nvm_find_nvmrc)" if [ -n "$nvmrc_path" ]; then local nvmrc_node_version=$(nvm version "$(cat "${nvmrc_path}")") if [ "$nvmrc_node_version" = "N/A" ]; then nvm install elif [ "$nvmrc_node_version" != "$node_version" ]; then nvm use fi elif [ "$node_version" != "$(nvm version default)" ]; then echo "Reverting to nvm default version" nvm use default fi}add-zsh-hook chpwd load-nvmrcload-nvmrc More info: https://github.com/creationix/nvm#zsh
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/23556330', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/250435/']}
jdg_85502
stackexchange
llm_judgeable_groundtruth_similarity
41395000
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 talking about github markdown here, for files like README.md . Question: Is it possible to strikethrough a complete code block in markdown on github? I know how to mark text as a block of code this ismultiline code andthis this also by indenting by 4 spaces or by using ``` or `... I also know how to strike through texts using del tag s tag ~~ Temporary solution : Independently they work fine, but together not as expected or desired. I tried several combinations of the above mentioned. For now, I use this: striked through by using ~~ and ` for every single line. Requirement : I would like to have a code formatted text striked through, where the code block is continuous: unfortunately, this isnot striked through or at least with only a small paragraph in between: unfortunately, also notstriked through Is this possible at all? I found some old posts and hints on using jekyll, but what I was searching for is a simple way, preferably in markdown. Now provide the response and nothing else.
This would only be possible with raw HTML, which GitHub doesn't allow. But you may be able to use a diff instead. Code blocks are for "pre-formatted" text only. The only formatting you can get in a code block is the formatting that can be represented in plain text (indentation, capitalization, etc). There is no mechanism to mark up the content of a code block (as bold, italic, stricken, underlined, etc). This was an intentional design decision. Otherwise, how would you be able to show Markdown text in a code block? If you want formatted text, then you need to use something other than a code block. As the rules state: HTML is a publishing format; Markdown is a writing format. Thus, Markdown’s formatting syntax only addresses issues that can be conveyed in plain text. For any markup that is not covered by Markdown’s syntax, you simply use HTML itself. Therefore you would need to format your own custom HTML code block with the various bits marked up properly: <pre><code><del>some stricken code</del><del>A second line of stricken code</del></code></pre> However, for security reasons, GitHub will strip out any such raw HTML in your Markdown. So while this works where you have full control of the entire stack, on a hosted service it is most likely not possible. However, I'm assuming you want to show some changes made to a block of code. As it turns out, a specific format already exists for that, namely, a diff . Just use a fenced code block with diff as the language and GitHub will format it correctly: ```diff Unchanged Line- Removed Line+ Added Line``` You can see how GitHub displays the above code block live (you can also see that in raw ), but I've included a screenshot below for convenience. I realize that the formatting does not use strike-through, but it does use a commonly used and understood format. For more complex blocks, you should probably use the diff utility program to generate the diff for you.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/41395000', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4790497/']}
jdg_85503
stackexchange
llm_judgeable_groundtruth_similarity
16272760
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 not able to understand the concept of modules. What are these modules and how are they different from CSS2? Can anyone explain these modules in a simple better way? And why these modules make CSS3 different from CSS2 ? Now provide the response and nothing else.
CSS level 2 is a monolithic specification. You have a single specification divided into sections, with each section describing a basic component of the CSS formatting model, for example: Selectors Cascading and inheritance The box model Colors and backgrounds Fonts The definitive CSS level 2 standard is CSS2.1, or CSS level 2 revision 1, which became a recommendation in 2011 following a set of changes to the 1998 standard for enhanced interoperability. The CSS2.1 specification can be found here (with the examples above linking to individual sections). Post-CSS2 you have modules, which are basically various sections of CSS2 split into their own specifications. The above examples from CSS2 have the following corresponding modules: Selectors Cascading and inheritance The box model Colors and backgrounds (yes, that's one section split into two modules) Fonts This means you have multiple specifications that all pertain to CSS, each with its own independent development path. This consequently means that different modules can progress toward implementation and standardization at different rates, without having to depend on the rest of CSS as a language (which was the primary cause of CSS2.1 taking so long to become a recommendation following CSS2's standardization). These specifications are collectively known as CSS3, or "CSS level 3" , although each goes through levels on its own, making it somewhat of a misnomer. CSS3 and its modularization system are explained in greater detail in this other answer .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/16272760', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2091061/']}
jdg_85504
stackexchange
llm_judgeable_groundtruth_similarity
126379
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 find myself extremely confused about how Placed works with plot legends. I want my legend to partially hang over one edge of the plot. But Plot[Sin[x], {x, -1, 1}, PlotLegends -> Placed[{"Sine"}, {.975, .75}]] produces which is no good because the label gets cut off. As soon as I increase the first coordinate up to 1, it works okay, but space is really tight in my desired application and I can't afford to waste all that white space under the curve. I've tried using the optional second pair of coordinates in Placed , but I can't figure out how they work - When I hold the first pair fixed and change the values of the second pair, they seem to be moving my legend in the opposite direction as I would expect (e.g. changing the coordinates to {{1, .75}, {2, 0}} moves the legend to the left ), and I also have no idea what's setting the scaling of the second pair of coordinates. I found the question Legend placement explanation , but I can't follow the example because it has so much extraneous crap in it and the answers don't go into enough detail. Not much detail in the documentation for Placed either. Would this maybe be a job for Show , Inset , or Overlay ? I'm not really sure about their relative advantages. Finally, I noticed that using Placed changes the legend's text from left-aligned to centered. How do I change it back? Edit: Regarding my last question, the easiest way to change the text alignment of the legend is to change {"Sine"} to LineLegend[{"Sine"}, LabelStyle -> {TextAlignment -> Left}] . Now provide the response and nothing else.
tl;dr Use Plot[Sin[x], {x, -1, 1}, PlotLegends -> Placed[{"Sine"}, {{1, .75}, {0.7, 0.5}}]] , where {1, 0.75} must be a point outside the $((0,1),(0,1))$ box. {0.7, 0.5} is the scaled position of this point within the legend. The explanation for this behaviour is tricky and non-obvious. Graphics with legends have the (possibly nested) structure Legended[graphics, legend] . See this answer for more details. The Legended expression doesn't evaluate to something, it is simply displayed in a certain way. However, the display/formatting can happen in two very different ways: if the legend is within the boundaries of the graphics, then the object that is produced is just a single graphics in box representation. The legend is contained within. If the legend is outside, then there will be two separate notebook objects joined together by something which behaves like Grid . I am not 100% certain that all this is correct, but I am convinced that something very similar to this is happening. The main point is that the result behaves in a different way depending on whether the legend is considered to be inside or outside of the graphics area. You want an overlapping legend. Now is that inside or outside? You are using scaled coordinates, and both the x and y coordinates fall within $0..1$. That counts as inside. So the legend will be inside. By default, anything beyond the graphics frame is clipped. This is controlled by PlotRangeClipping . You can set it to False and see that less of the legend is clipped. To allow all of it to show, you would need to manually set ImagePadding to leave enough space. But this is a lot of trouble and not the easiest way to achieve your goal, so I won't bother fussing with the padding values and posting the full code ... Let's do something else instead. Look up Placed , expand the Details section and check the Placed[expr, {pos,epos}] syntax. pos is the (scaled) coordinates of a point in the main graphics and epos is the (scaled) coordinates of the same point in the legend. We can achieve an overlapping look by putting epos in the middle of the legend. Plot[Sin[x], {x, -1, 1}, PlotLegends -> Placed[{"Sine"}, {{1, .75}, {0.5, 0.5}}]] Now try to move pos just slightly into the $0..1$ interval and see how the clipping happens due to Legended switching to a different rendering mode. Plot[Sin[x], {x, -1, 1}, PlotLegends -> Placed[{"Sine"}, {{0.999, .75}, {0.7, 0.5}}]]
{}
{'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/126379', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/30780/']}
jdg_85505
stackexchange
llm_judgeable_groundtruth_similarity
861262
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If you think about Fourier Transform, in the classical cases, say on the real line, what it is? Just a waded sum. Right? You take a function $f$, and you take it's Fourier Transform at particular frequency k, then it’s going to be something like integral over the real line of this exponential factor$$\int_{R}^{}{e^{ik}\cdot{f(x)}}dx$$So $f$ is a general complex value function. One way to think about Fourier Transform in the classical case is that if you take the space of all functions that you apply their Fourier Transform to. To take the space of functions that it defines way in to separate that space into subspaces, which are independently effected by translation, right? But how to describe the Fast Fourier Transform? What is difference? Also I need to know is there another kind of Fourier Transform excluding FFT and Discrete Fourier Transform? Thank you anyway! Now provide the response and nothing else.
The Fast Fourier Transform is a particularly efficient way of computing a DFT and its inverse by factorization into sparse matrices. The wiki page does a good job of covering it. To answer your last question, let's talk about time and frequency. You are right in saying that the Fourier transform separates certain functions (the question of which functions is actually interesting) into their frequency components. For example, the function $f(t) = \cos(6πt) e^{−2πt}$ taken from Wiki has a Fourier transform with maxima corresponding to frequencies at $3$ Hz (supposing we're in seconds). But, imagine you had a more complex signal and you were interested not just in the frequency components, but when those components occurred in time. To localize in time, you'd need something like a short-time Fourier transform or "windowed" transform. Performing this transform produces a two-variable function in time and frequency. It looks like this $$X(\omega, \tau) = \int_{\mathbb{R}} w(t - \tau) f(t)e^{-2\pi i t \omega} \ dt$$ The resolution that one can know the frequency depends on the width of the windowing function $w$. You might be interested to know how good the resolution can get. Unfortunately, because of the Uncertainty Principle, if we define the variance about zero of the function and its STFT as $D_0(f(t))$ and $D_0(\hat{f}(\omega))$. Then $$ D_0(f)D_0(\widehat{f}) \geq \frac{1}{16\pi}.$$ Hence, the resolution has some type minimum granularity. However, there is a whole field of study devoted to improved time and frequency localization. If you are interested in transforms besides the FT and FFT, then you may want to investigate wavelet analysis. Wavelets in general have better time-frequency resolution than the FT since the "windows" they use are of variable width. In wavelet analysis, $L^2$ is broken up into a nested sequence of subspaces called a multiresolution analysis (MRA) each with a basis consisting of a special scaling function. From this construction, we can build a so-called mother wavelet whose various dilations and translations form a basis for all of $L^2$. The ability to slide and stretch these functions and the diversity of possible mother wavelets yields many different ways of examining a signal in time and scale, beyond those offered by the traditional Fourier transform.
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/861262', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/46313/']}
jdg_85506
stackexchange
llm_judgeable_groundtruth_similarity
555043
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm writing my third app, and I already have an app in the App Store, but I still don't get this App ID business. I created the App IDs for my first two applications like this: XXXXXXXXXX.me.cbg.FirstAppYYYYYYYYYY.me.cbg.SecondApp but then Apple introduced the App ID wizard, which I used to create the App ID and provisioning profiles for my third application: ZZZZZZZZZZ.* So my question is: What is the "proper" way of creating App IDs for three completely independent apps? Should I use the XXXXXXXXXX.* format or XXXXXXXXXX.me.cbg.* ? Should I create three different App IDs, or just one wildcard ID? Now provide the response and nothing else.
Both are "proper", it's mostly a question of the tradeoff between ease of management and allowing more granular management of certificates. There two technical difference: Applications with IDs that areidentical save from the top level(e.g. com.mycompany.aaa andcom.mycompany.bbb) are able toaccess each others saved data. Ifyou are writing a suite ofapplications then this could beextremely useful. You can only create a limited numberof "AdHoc" certificates. If yourapps have the same wildcardidentifier then this limit would beimposed across all yourapplications. Personally for a small developer I would recommend using a wildcard ID. It results in a lot less to manage in several areas, and hence removes a lot of potential for mistakes. Remember that for each ID you'll probably have three individual certificates (dev/adhoc/appstore). Background: Every iPhone application must have a unique identifier and certificate. Developers can either create a certificate per application by using a complete name (e.g. com.mycompany.aaa), or they can create a wildcard certificate/ID (e.g. com.mycompany.*) in which case the app name in the .plist file is used to complete the identifier during the DRM process.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/555043', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2119/']}
jdg_85507
stackexchange
llm_judgeable_groundtruth_similarity
2029103
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 dealing with small text files that i want to read into a buffer while i process them, so i've come up with the following code: ...char source[1000000];FILE *fp = fopen("TheFile.txt", "r");if(fp != NULL){ while((symbol = getc(fp)) != EOF) { strcat(source, &symbol); } fclose(fp);}... Is this the correct way of putting the contents of the file into the buffer or am i abusing strcat() ? I then iterate through the buffer thus: for(int x = 0; (c = source[x]) != '\0'; x++){ //Process chars} Now provide the response and nothing else.
char source[1000000];FILE *fp = fopen("TheFile.txt", "r");if(fp != NULL){ while((symbol = getc(fp)) != EOF) { strcat(source, &symbol); } fclose(fp);} There are quite a few things wrong with this code: It is very slow (you are extracting the buffer one character at a time). If the filesize is over sizeof(source) , this is prone to buffer overflows. Really, when you look at it more closely, this code should not work at all. As stated in the man pages: The strcat() function appends a copy of the null-terminated string s2 to the end of the null-terminated string s1, then add a terminating `\0'. You are appending a character (not a NUL-terminated string!) to a string that may or may not be NUL-terminated. The only time I can imagine this working according to the man-page description is if every character in the file is NUL-terminated, in which case this would be rather pointless. So yes, this is most definitely a terrible abuse of strcat() . The following are two alternatives to consider using instead. If you know the maximum buffer size ahead of time: #include <stdio.h>#define MAXBUFLEN 1000000char source[MAXBUFLEN + 1];FILE *fp = fopen("foo.txt", "r");if (fp != NULL) { size_t newLen = fread(source, sizeof(char), MAXBUFLEN, fp); if ( ferror( fp ) != 0 ) { fputs("Error reading file", stderr); } else { source[newLen++] = '\0'; /* Just to be safe. */ } fclose(fp);} Or, if you do not: #include <stdio.h>#include <stdlib.h>char *source = NULL;FILE *fp = fopen("foo.txt", "r");if (fp != NULL) { /* Go to the end of the file. */ if (fseek(fp, 0L, SEEK_END) == 0) { /* Get the size of the file. */ long bufsize = ftell(fp); if (bufsize == -1) { /* Error */ } /* Allocate our buffer to that size. */ source = malloc(sizeof(char) * (bufsize + 1)); /* Go back to the start of the file. */ if (fseek(fp, 0L, SEEK_SET) != 0) { /* Error */ } /* Read the entire file into memory. */ size_t newLen = fread(source, sizeof(char), bufsize, fp); if ( ferror( fp ) != 0 ) { fputs("Error reading file", stderr); } else { source[newLen++] = '\0'; /* Just to be safe. */ } } fclose(fp);}free(source); /* Don't forget to call free() later! */
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/2029103', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13227/']}
jdg_85508
stackexchange
llm_judgeable_groundtruth_similarity
593728
Below is a question asked on the forum physics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I know the temperature of the universe is decreasing due to it's expansion after the big bang but after I came up with this article in AOP (please note I don't have the access of the journal,so I have just read the abstract) after reading this I am quite confused. A news media states that: The study by the Ohio State University Center for Cosmology and AstroParticle Physics shows that the "universe is getting hotter". This big revelation came amid the scientists' restless examinations on the thermal history of the universe over the last 10 billion years. It has been also stated that: The study also explained how, with the evolution of the universe, gravity pulls dark matter and gas in space together into galaxies and clusters of galaxies. The pull is so violent that more and more gas is shocked and heated up. Scientists used a new method to measure the temperature of gas farther away from Earth. The scientists, during the research, then compared those measurements to gases closer to Earth and near the present time.They said the "universe is getting hotter over time due to the gravitational collapse of cosmic structure, and the heating will likely continue". Data from the Planck and the Sloan Digital Sky Survey was used to observe how the universe's temperature has gone up.The universe is warming because of the natural process of galaxy and structure formation. So my question is: •Is it indirectly violating the principle that the universe is cooling down due to expansion? Or is it just a additional factor in a small region of our space? Or is it happening as a regular phenomenon for a long time? •Can someone explain to me the whole phenomenon with more science/ or any scientific explanation more than what I found? •If the findings are true then what are the probable effects? I am hoping to have clarity on the paper, maybe, being naive I haven't understood it completely, besides answer further suggestions are welcomed. [Edit: check this] Now provide the response and nothing else.
There is a difference between the "temperature of the universe" and the temperature of the cosmic microwave background radiation (CMBR). The former can be changed by physical processes going on in the universe and for example, the conversion of gravitational potential energy, or the release of nuclear binding energy, into the thermal energy of particles. The CMBR temperature on the other hand is fixed when it is formed and modified just by the expansion history of the universe; it represents the temperature of a blackbody radiator with the same spectrum as the CMBR. In the study you refer to, the "temperature of the universe" is the density-weighted mean electron temperature, and is of order $10^6$ K. These electrons have been heated via a variety of physical processes, ultimately linked to the formation of clusters of galaxies, galaxies and stars (for example supernovae, or collisionless shock heating in gravitationally accelerated flows - Kravtsov & Yepes 2000 ; Bykov et al. 2008 ), and have cooling times that are long compared with the age of the universe. In contrast, the CMBR spectrum was formed about 400,000 years after the big bang, was essentially fixed at that point (at around 3000 K), and is only modified subsequently by the universe's expansion history, which stretches the wavelengths leading to a cooling temperature (currently 2.7 K). The two temperatures would have been similar around the epoch when the CMBR was formed but have diverged since then because the matter became effectively transparent to the CMBR and decoupled. According to the paper that is referred to in the question, the density-weighted mean electron temperature has increased by about a factor of 3 between $z=1$ and the present day; from $7\times 10^5$ K to $2\times 10^6$ K. Over the same period, the CMBR would have cooled from 5.4 K to 2.7 K.
{}
{'log_upvote_score': 5, 'links': ['https://physics.stackexchange.com/questions/593728', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/274807/']}
jdg_85509
stackexchange
llm_judgeable_groundtruth_similarity
144692
Below is a question asked on the forum electronics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: I'm working on a hobby project where I'm trying to drive a solenoid valve with an arduino (for some automated plant watering). The solenoid valve takes 12v, so I've rigged up some smaller batteries in series to supply that 12v. That works - when I plug the solenoid valve directly into the battery, it opens. According to its spec sheet, the valve can draw 500mA. (Although that's a lot, I only need to do it for a few seconds maybe every few hours). YOu can see the solenoid's specs here: http://www.ebay.com/itm/1-2-Gravity-Feed-Electric-Solenoid-Valve-DDT-CD-12VDC-/290763981675 Next, I made a little circuit that toggles an LED with a transistor - a digital pin from the arduino (5v) is the base input, and the LED is fed by the battery (so battery positive->led->collector->emitter->battery negative). That works too, the light blinks on and off (driven by code). This works whether the power source is the battery or the arduino (although I found I had to give the two circuits a common ground for that to work). However, when I hook up everything together (all powered by batteries), the LED still toggles, but the solenoid doesn't. Is this a problem with high-side vs. low-side transistor wiring? (I'm kind of hazy on the distinction, but if it works for the LED, then that part of the circuit is correct, right?). The NPN transistor is an MPS 2222. I think from its fact sheet, it ought to be able to handle this load, right? Am I reading it wrong, and do I need to upgrade to one with a higher current capacity, or better voltage limits: http://www.farnell.com/datasheets/115091.pdf Also, is it enough to use an LED to protect the circuit from back-emf when the solenoid is turned off? Thanks! In the photos below, the black cable coming in from the bottom left is the digital signal from the arduino. The yellow wire (and the stuff around it) are an unrelated sensor thing. The two metal tabs at the top are the solenoid valve. Now provide the response and nothing else.
No, this transistor cannot be expected to do this job for long, if it can do it at all. From the datasheet, look at the "On characteristics" on page 2.First, its free air power rating is 0.625W, which means Vce had better be 1.25V or less at 500 ma. Then, gain (hFE) is shown at different Vce voltages and currents. But significantly, not shown at Vce=1V and Ic=500mA, suggesting that the transistor is not rated to work under those conditions. Finally, the CE saturation voltage is shown as 1.6V at 500mA, which exceeds the power rating shown above. You will be able to get away with that for a few seconds on a very low duty cycle. The MPS2222A would be a better choice, its Vce(sat) is shown as 1V here. But...the above condition is achieved with Ib=50mA. This almost certainly exceeds the current available from your Arduino output pin. If you are content to briefly overrate the device's power ratings, you could overcome the base current limitation using a second transistor as an emitter follower, to drive the base current you need. (schematic editor isn't loading this morning, sorry)
{}
{'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/144692', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/61797/']}
jdg_85510
stackexchange
llm_judgeable_groundtruth_similarity
13353
Below is a question asked on the forum mechanics.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Why doesn't my 2010 focus allow me gun it when it starts slipping in snow? It makes it impossible to get out of even a tiny bit of snow. My civic never got stuck because I could always just gun it, but my focus never gets above 2k rpm Now provide the response and nothing else.
There's nothing wrong with the vehicle, from what you've described. It sounds like it's doing exactly what it's supposed to. I'm not sure you understand how to get out of a slide (or snow), which admittedly isn't particularly uncommon. "Gunning it" won't help, because your wheels are more likely to spin, which just tends to dig you deeper into the snow. Rather, your Focus is forcing upon you good habits, by not risking a red-line and by keeping your revs low. Traction control is probably what's holding it back, since it doesn't want you to spin, but I would not suggest switching that off until you're comfortable escaping snow with it on . To get out of snow, you want to be careful of torque. You want RPMs low, and you want as little wheel spin as possible. It's good to "shift" up into higher gears, like D1 or D2, or if you have a manual override, head to second or third gear. Those will reduce spin and push you out more comfortably. If you've gotten out of snow in the past with brute force (and I'm not disputing that it's possible), it's been mostly luck. You can also sometimes dig away enough snow that you hit the ground, which is where you actually get traction (assuming it's not lined with ice). But that won't apply in deeper snow or where there is ice, so I wouldn't suggest making a habit of it.
{}
{'log_upvote_score': 4, 'links': ['https://mechanics.stackexchange.com/questions/13353', 'https://mechanics.stackexchange.com', 'https://mechanics.stackexchange.com/users/7643/']}
jdg_85511
stackexchange
llm_judgeable_groundtruth_similarity
6871203
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 my web app users are able to change their user details. The URL for this page is: springproject/usermanagement/edituserinfo/4 where "4" is the user id. My security-context looks like: <security:http auto-config="true" use-expressions="true"> <security:intercept-url pattern="/usermanagement" access="isAuthenticated()" /> <security:intercept-url pattern="/usermanagement/new" access="hasRole('ROLE_ADMIN')" /> <security:intercept-url pattern="/usermanagement/edit/*" access="hasRole('ROLE_ADMIN')" /> <security:intercept-url pattern="/usermanagement/edituserinfo/*" access="isAuthenticated()" /> </security:http> How can I restrict the user only to access their own "edituserinfo" page? E.g. user with user id 1 can only access: "springproject/usermanagement/edituserinfo/1 " and not "springproject/usermanagement/edituserinfo/4 " Now provide the response and nothing else.
Use a PathVariable on the URL, like @RequestMapping("/usermanagement/edituserinfo/{userid}") and in your code validate the logged-in user's Spring Security context principle (via SecurityContextHolder.getContext().getAuthentication().getPrincipal() ) against the userid path variable. If they don't match, bounce the user out, log a SecurityException , and send an email to the admins.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6871203', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/77660/']}
jdg_85512
stackexchange
llm_judgeable_groundtruth_similarity
3244909
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I can change the text color by doing this in jqgrid custom formatter: function YNFormatter(cellvalue, options, rowObject){ var color = (cellvalue == "Y") ? "green" : "red"; var cellHtml = "<span style='color:" + color + "' originalValue='" + cellvalue + "'>" + cellvalue + "</span>"; return cellHtml; } but I want to now change the background color of the whole cell (instead of the text color). Is this possible? Now provide the response and nothing else.
If you want use <span> element inside of the custom cell formatter you can return from the custom formatter return '<span class="cellWithoutBackground" style="background-color:' + color + ';">' + cellvalue + '</span>'; where the style of span.cellWithoutBackground you can define for example like following span.cellWithoutBackground{ display:block; background-image:none; margin-right:-2px; margin-left:-2px; height:14px; padding:4px;} How it works you can see live here : UPDATED: The answer is old. The best practice would be to use cellattr callback in colModel instead of the usage custom formatters. Changing of background color of the cell is in general just assigning style or class attribute to the cells of the column ( <td> elements). The cellattr callback defined in the column of colModel allows exactly to do this. One can still use predefined formatters like formatter: "checkbox" , formatter: "currency" , formatter: "date" and so on, but still change the background color in the column. In the same way the rowattr callback, which can be defined as the jqGrid option (outside of specific column of colModel ), allows to assign style/class of the whole row ( <tr> elements). More information about cellattr can be found here and here , for example. Another answer explains rowattr .
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/3244909', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4653/']}
jdg_85513
stackexchange
llm_judgeable_groundtruth_similarity
35212008
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Without using Heapster is there any way to collect like CPU or Disk metrics about a node within a Kubernetes cluster? How does Heapster even collect those metrics in the first place? Now provide the response and nothing else.
Kubernetes monitoring is detailed in the documentation here , but that mostly covers tools using heapster. Node-specific information is exposed through the cAdvisor UI which can be accessed on port 4194 (see the commands below to access this through the proxy API). Heapster queries the kubelet for stats served at <kubelet address>:10255/stats/ (other endpoints can be found in the code here ). Try this: $ kubectl proxy &Starting to serve on 127.0.0.1:8001$ NODE=$(kubectl get nodes -o=jsonpath="{.items[0].metadata.name}")$ curl -X "POST" -d '{"containerName":"/","subcontainers":true,"num_stats":1}' localhost:8001/api/v1/proxy/nodes/${NODE}:10255/stats/container... Note that these endpoints are not documented as they are intended for internal use (and debugging), and may change in the future (we eventually want to offer a more stable versioned endpoint). Update: As of Kubernetes version 1.2, the Kubelet exports a "summary" API that aggregates stats from all Pods: $ kubectl proxy &Starting to serve on 127.0.0.1:8001$ NODE=$(kubectl get nodes -o=jsonpath="{.items[0].metadata.name}")$ curl localhost:8001/api/v1/proxy/nodes/${NODE}:10255/stats/summary...
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/35212008', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1155323/']}
jdg_85514
stackexchange
llm_judgeable_groundtruth_similarity
265446
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 see the Descarta2D package can easily draw some figures.Unfortunately, the package is not to be found and runs on MMA 2021. I do want to do some complex contour calculations and need some diagrams. Note : The two line integrals (line, circle) summed up are 0 ( checked by Cauchy contour integral is 0 ) ( for f(z) = z^2 ) Now provide the response and nothing else.
g = Graphics[{Red, Polygon[.5 {{0, 0}, {-1, 1}, {2, 0}, {-1, -1}, {0, 0}}]}];halfcircle = ParametricPlot[ Norm[{6, 6}]*{Cos[t], Sin[t]}, {t, π/4, π/4 + π}, PlotStyle -> Red] /. Line[a_] :> {Arrowheads[{{.05, 1/10}, {.05, 5/10}, {.05, 9/10}}], Arrow[a]};line = Graphics[{Red, Arrowheads[{{.05, 2/10, g}, {.05, 8/10, g}}], Arrow[{{-6, -6}, {6, 6}}], Text[Style[6 + 6 I, 14, FontFamily -> Times], {6, 6}, {-1, -1}], Text[Style[-6 - 6 I, 14, FontFamily -> Times], {-6, -6}, {1, 1}]}];Show[halfcircle, line, PlotRangePadding -> 1.8] Thought we can use the Disk to draw circle,but it is not easy to add arrows. Graphics[{EdgeForm[Red], FaceForm[],Disk[{0, 0}, Norm[{6, 6}], {π/4, π/4 + π}]}] Edit The solution by @Carl Woll maybe the simple one. https://mathematica.stackexchange.com/a/257945/72111 g = Graphics[ FilledCurve@{BezierCurve[{{-1.5, .8}, {-.5, 0}, {.5, 0}, {1, 0}}], BezierCurve[{{.5, 0}, {-.5, 0}, {-1.5, -.8}}], Line[{{-.5, 0}}]}];circle = ResourceFunction["SplineCircle"];Graphics[{Arrowheads[{{.05, 1/10, g}, {.05, 5/10, g}, {.05, 9/10, g}}], Arrow@ circle[{0, 0}, Norm[{6, 6}], {1, 0}, {π/4, π/4 + π}], Arrowheads[{{.05, 2/10, g}, {.05, 8/10, g}}], Arrow@Line[{{-6, -6}, {6, 6}}]}] P.S. It seems that the arrows only in the direction of the tangent line of the curve but does not along the curve.
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/265446', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/84966/']}
jdg_85515
stackexchange
llm_judgeable_groundtruth_similarity
133282
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: Mathematica has undocumented functionality of combination classifiers / predictors in ensemble. How to get access to this functionality? SeedRandom[1];X = Table[ Join[ ToString /@ RandomReal[{-1, 1}, 1], RandomReal[{-1, 1}, 4], RandomSample[{"A", "B", "C"}, 2] ], {1000} ];Y = RandomInteger[{0, 1}, 1000]; c = Classify[X -> Y] ClassifierInformation[c] ClassifierMeasurements[c, X -> Y, "ConfusionMatrixPlot"] Now provide the response and nothing else.
c1 = Classify[X -> Y, Method -> "LogisticRegression"]c2 = Classify[X -> Y, Method -> "NearestNeighbors"]c = MachineLearning`PackageScope`CombinePredictors[{c1, c2}]ClassifierInformation[c] p1 = Predict[X -> Y, Method -> "LinearRegression"]p2 = Predict[X -> Y, Method -> "NearestNeighbors"]p = MachineLearning`PackageScope`CombinePredictors[{p1, p2}]PredictorInformation[p]
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/133282', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/23402/']}
jdg_85516
stackexchange
llm_judgeable_groundtruth_similarity
1281543
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Is there a closed form solution for the following series? (Without Using Gamma Function):$$S=\sum _{i=1}^{n-1} \frac{1}{(i+1)!}$$ Now provide the response and nothing else.
Note that$$n!\,e=\sum_{k=0}^\infty\frac{n!}{k!}=\sum_{k=0}^n\frac{n!}{k!}+\sum_{k=n+1}^\infty\frac{n!}{k!}$$The first sum on the RHS is always an integer since $n\geq k$. The second sum satisfies$$\begin{align} \sum_{k=n+1}^\infty\frac{n!}{k!}&=\frac{1}{n+1}+\frac{1}{(n+1)(n+2)}+\frac{1}{(n+1)(n+2)(n+3)}+\cdots\\&<\frac{1}{n+1}+\frac{1}{(n+1)(n+1)}+\frac{1}{(n+1) (n+1)(n+1)}+\cdots\\&=\sum_{k=1}^\infty\frac{1}{(n+1)^k}\\&= \frac{1}{n}\\&\leq1\end{align}$$when $n\geq1$. Hence we have$$\lfloor n!\,e\rfloor=\sum_{k=0}^n\frac{n!}{k!}\\\implies \frac{\lfloor n!\,e\rfloor}{n!}=\sum_{k=0}^n\frac{1}{k!}\\\implies \frac{\lfloor n!\,e\rfloor}{n!}-2=\sum _{k=1}^{n-1} \frac{1}{(k+1)!}$$
{}
{'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/1281543', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/153944/']}
jdg_85517
stackexchange
llm_judgeable_groundtruth_similarity
90580
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Without getting a degree in information retrieval, I'd like to know if there exists any algorithms for counting the frequency that words occur in a given body of text. The goal is to get a "general feel" of what people are saying over a set of textual comments. Along the lines of Wordle . What I'd like: ignore articles, pronouns, etc ('a', 'an', 'the', 'him', 'them' etc) preserve proper nouns ignore hyphenation, except for soft kind Reaching for the stars, these would be peachy: handling stemming & plurals (e.g. like, likes, liked, liking match the same result) grouping of adjectives (adverbs, etc) with their subjects ("great service" as opposed to "great", "service") I've attempted some basic stuff using Wordnet but I'm just tweaking things blindly and hoping it works for my specific data. Something more generic would be great. Now provide the response and nothing else.
You'll need not one, but several nice algorithms, along the lines of the following. ignoring pronouns is done via a stoplist . preserving proper nouns? You mean, detecting named entities, like Hoover Dam and saying "it's one word" or compound nouns, like programming language ? I'll give you a hint: that's tough one, but there exist libraries for both. Look for NER (Named entitiy recognition) and lexical chunking. OpenNLP is a Java-Toolkit that does both. ignoring hyphenation? You mean, like at line breaks? Use regular expressions and verify the resulting word via dictionary lookup. handling plurals/stemming: you can look into the Snowball stemmer . It does the trick nicely. "grouping" adjectives with their nouns is generally a task of shallow parsing . But if you are looking specifically for qualitative adjectives (good, bad, shitty, amazing...) you may be interested in sentiment analysis . LingPipe does this, and a lot more. I'm sorry, I know you said you wanted to KISS, but unfortunately, your demands aren't that easy to meet. Nevertheless, there exist tools for all of this, and you should be able to just tie them together and not have to perform any task yourself, if you don't want to. If you want to perform a task yourself, I suggest you look at stemming, it's the easiest of all. If you go with Java, combine Lucene with the OpenNLP toolkit. You will get very good results, as Lucene already has a stemmer built in and a lot of tutorial. The OpenNLP toolkit on the other hand is poorly documented, but you won't need too much out of it. You might also be interested in NLTK , written in Python. I would say you drop your last requirement, as it involves shallow parsing and will definetly not impove your results. Ah, btw. the exact term of that document-term-frequency-thing you were looking for is called tf-idf . It's pretty much the best way to look for document frequency for terms. In order to do it properly, you won't get around using multidimenional vector matrices. ... Yes, I know. After taking a seminar on IR, my respect for Google was even greater. After doing some stuff in IR, my respect for them fell just as quick, though.
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/90580', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17328/']}
jdg_85518
stackexchange
llm_judgeable_groundtruth_similarity
24424211
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 talking about FileInputStream, I am starting with a scenario where there are two perfectly valid, overloaded methods but where the compiler will get confused and then report a compile-time error in response to certain inputs. Here are the methods. double calcAverage(double marks1, int marks2) { return (marks1 + marks2)/2.0; } double calcAverage(int marks1, double marks2) { return (marks1 + marks2)/2.0; } Here is the complete code showing the use of the methods: class MyClass { double calcAverage(double marks1, int marks2) { return (marks1 + marks2)/2.0; } double calcAverage(int marks1, double marks2) { return (marks1 + marks2)/2.0; } public static void main(String args[]) { MyClass myClass = new MyClass(); myClass.calcAverage(2, 3); } } Because an int literal value can be passed to a variable of type double, both methods are acceptable candidates for literal values 2 and 3 , and therefore the compiler fails to decide which method to pick. This is where I get confused when I take the above concept with me, dive further into the Java 7 API to the FileInputStream class, and study about two overloaded constructors of that class. public FileInputStream(String name) throws FileNotFoundException {.....} public FileInputStream(File file) throws FileNotFoundException {.....} According to the Java 7 API source code, the definition of the version that takes a String object as the argument is: public FileInputStream(String name) throws FileNotFoundException { this(name != null ? new File(name) : null); } Now, if " name " is indeed null, this(name != null ? new File(name) : null); evaluates to this(null); which in turn is equivalent to invocation of FileInputStream(null); but then both FileInputStream(String) and FileInputStream(File) become possible choices to be invoked with a null value. Does it not give rise to ambiguity? So, isn't there a compile-time error for that? I do understand that eventually a FileNotFoundException is raised, but it is a separate issue which comes later. How is the ambiguity resolved before that? Now provide the response and nothing else.
Your error is here: Now, if "name" is indeed null, this(name != null ? new File(name) : null); evaluates to this(null); which in turn is equivalent to invocation of FileInputStream(null); It actually evaluates to this((File) null) -- that is, a null value explicitly typed as File . This is because the expression name != null ? new File(name) : null has to have a type, and that type is the most specific type of the two alternatives. In this case, one alternative is typed as File and the other is typed as null , so the most specific common type is File . That's why it's able to unambiguously resolve it to the FileInputStream(File) constructor. It's analogous to: File file = null;new FileInputStream(file);
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/24424211', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2435774/']}
jdg_85519
stackexchange
llm_judgeable_groundtruth_similarity
267285
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: My output from NSolve is a list of rules, most of these are undefined, I want to remove those rules.More specifically I have a list rules = {y2 -> Undefined, y3 -> Undefined, y4 -> Undefined, y5 -> Undefined, y6 -> Undefined, y7 -> Undefined, y8 -> Undefined, y9 -> Undefined, y10 -> Undefined, y11 -> Undefined, \[Lambda]2 -> -1.68379, y2 -> 0.991506, y3 -> Undefined, y4 -> Undefined, y5 -> Undefined, y6 -> Undefined, y7 -> Undefined, y8 -> Undefined, y9 -> Undefined, y10 -> Undefined, y11 -> 0.991506, \[Lambda]2 -> Undefined, y2 -> Undefined, y3 -> 0.97847, y4 -> 0.969246, y5 -> 0.963328, y6 -> 0.96037, y7 -> 0.96037, y8 -> 0.963328, y9 -> 0.969246, y10 -> 0.97847, y11 -> Undefined, \[Lambda]2 -> Undefined} and I want to get {y2-> 0.991506, y3-> 0.969246,y4 -> 0.969246...} and so on.How do I remove all the undefined defitions, not that the final list doesnt have to be in this order. DeleteCases and other functions didn't help. Now provide the response and nothing else.
t = rules /. HoldPattern[x_ -> Undefined] -> Nothing EDIT Another variation: Values[rules] can be used: (Also try Key[rules] to get variable names) pos = Position[Values[rules], Except[Undefined], {1}, Heads -> False] {{11}, {12}, {21}, {24}, {25}, {26}, {27}, {28}, {29}, {30}, {31}} v = Extract[rules, pos] result: {\[Lambda]2->-1.68379,y2->0.991506,y11->0.991506,y3->0.97847,y4->0.969246,y5->0.963328,y6->0.96037,y7->0.96037,y8->0.963328,y9->0.969246,y10->0.97847} t == v (* True *)
{}
{'log_upvote_score': 4, 'links': ['https://mathematica.stackexchange.com/questions/267285', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/82839/']}
jdg_85520
stackexchange
llm_judgeable_groundtruth_similarity
4081819
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Given the following module: class Dummy(dict): def __init__(self, data): for key, value in data.iteritems(): self.__setattr__(key, value) def __getattr__(self, attr): return self.get(attr, None) __setattr__=dict.__setitem__ __delattr__=dict.__delitem__foo=Dummy({"one":1, "two":2}) why does foo show up in the output of inspect.getmembers(..., predicate=inspect.isclass) ? $ python2.5Python 2.5.2 (r252:60911, Aug 28 2008, 13:13:37) [GCC 4.1.2 20071124 (Red Hat 4.1.2-42)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import junk>>> import inspect>>> inspect.getmembers(junk, predicate=inspect.isclass)[('Dummy', <class 'junk.Dummy'>), ('foo', {'two': 2, 'one': 1})]>>> inspect.isclass(junk.foo)True I expected that inspect would only return Dummy since that is the only class definition in the module. Apparently, though, junk.foo is a class in the eyes of the inspect module. Why is that? Now provide the response and nothing else.
Prior to Python v2.7, inspect.isclass naively assumed anything with a __bases__ attribute must be a class. Dummy 's __getattr__ makes Dummy instances appear to have every attribute (with a value of None ). Therefore, to inspect.isclass , foo appears to be a class. Note: __getattr__ should raise AttributeError when asked for an attribute it does not know about. (This is very different than returning None .)
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4081819', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7432/']}
jdg_85521
stackexchange
llm_judgeable_groundtruth_similarity
49602619
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I'm developing an Android application which is basically a game. In one of the Activities there are a few buttons, and I wanted that when one event occurred (it could even be the trigger of another button) two buttons changed position in the layout. I researched the documentation of the Transition class to see if it was possible to use an animation to make this switch, but I really wanted something with a non-existent delay. NOTE: Just changing the appearance of the buttons is not an option for me, since each of these buttons has different functions within the application and I need to keep them. Now provide the response and nothing else.
The trick is to not do any of the actual fetching in the view model. Getting data, be it from network or database, should be done in the repository. The ViewModel should be agnostic in this regard. In the ViewModel, use the LiveData class, not MutableLiveData. Unless you really find a use case for it. // In your constructor, no extra threadnotesLiveData = notesLiveDataFromRepository.getAllNotes(); Then in your repository you can have the logic in the getAllNotes() method for determining where those notes are coming from. In the repository you have the MutableLiveData. You can then postValue to that, from a thread that is getting the data. That isn't necessary for room though, that is handled for you. So in your repository you would have another LiveData being returned that is backed directly from a DAO method. In that case, you need to stick with public abstract LiveData<List<Note>> getNotes(); . Activity public class MyActivity extends AppCompatActivity { private MyViewModel viewModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set up your view model viewModel = ViewModelProviders.of(this).get(MyViewModel.class); // Observe the view model viewModel.getMyLiveData().observe(this, s -> { // You work with the data provided through the view model here. // You should only really be delivering UI updates at this point. Updating // a RecyclerView for example. Log.v("LIVEDATA", "The livedata changed: "+s); }); // This will start the off-the-UI-thread work that we want to perform. MyRepository.getInstance().doSomeStuff(); }} ViewModel public class MyViewModel extends AndroidViewModel { @NonNull private MyRepository repo = MyRepository.getInstance(); @NonNull private LiveData<String> myLiveData; public MyViewModel(@NonNull Application application) { super(application); // The local live data needs to reference the repository live data myLiveData = repo.getMyLiveData(); } @NonNull public LiveData<String> getMyLiveData() { return myLiveData; }} Repository public class MyRepository { private static MyRepository instance; // Note the use of MutableLiveData, this allows changes to be made @NonNull private MutableLiveData<String> myLiveData = new MutableLiveData<>(); public static MyRepository getInstance() { if(instance == null) { synchronized (MyRepository.class) { if(instance == null) { instance = new MyRepository(); } } } return instance; } // The getter upcasts to LiveData, this ensures that only the repository can cause a change @NonNull public LiveData<String> getMyLiveData() { return myLiveData; } // This method runs some work for 3 seconds. It then posts a status update to the live data. // This would effectively be the "doInBackground" method from AsyncTask. public void doSomeStuff() { new Thread(() -> { try { Thread.sleep(3000); } catch (InterruptedException ignored) { } myLiveData.postValue("Updated time: "+System.currentTimeMillis()); }).start(); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49602619', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/8975121/']}
jdg_85522
stackexchange
llm_judgeable_groundtruth_similarity
19324700
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to loop through all the elements retruned from getElementsByTagName("input") using forEach. Any ideas why this does not work in FF, Chrome or IE? <html> <head> </head> <body> <input type="text" value="" /> <input type="text" value="" /> <script> function ShowResults(value, index, ar) { alert(index); } var input = document.getElementsByTagName("input"); alert(input.length); input.forEach(ShowResults); </script> </body></html> Now provide the response and nothing else.
You need to convert the nodelist to array with this: <html> <head> </head> <body> <input type="text" value="" /> <input type="text" value="" /> <script> function ShowResults(value, index, ar) { alert(index); } var input = document.getElementsByTagName("input"); var inputList = Array.prototype.slice.call(input); alert(inputList.length); inputList.forEach(ShowResults); </script> </body></html> or use for loop. for(let i = 0;i < input.length; i++){ ShowResults(input[i].value);} and change ShowResults function to: function ShowResults(value) { alert(value);} Why do we need to do that? Some objects in JavaScript look like an array, but they aren’t one. That usually means that they have indexed access and a length property, but none of the array methods. Examples include the special variable arguments, DOM node lists, and strings. Array-Like Objects and Generic Methods gives tips for working with array-like objects. source UPDATE for 07.10.2019 Nowdays with ES6 you can use [...inputList].forEach , or Array.from(inputList)
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/19324700', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1710577/']}
jdg_85523
stackexchange
llm_judgeable_groundtruth_similarity
16453
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: Let's take lulzsec as an example; they registered lulzsecurity.com. There are two problems that I don't understand how they solved: They had to pay for it. Tracking down money is generally much easier than tracking down IP addresses. I assume they didn't use stolen credit cards (with all the attention they received, people would have quickly found out and taken away their domain).. And even with prepaid credit cards it's relatively easy to find out who bought it, with security cameras/etc. They had to have played by ICANN's rules - again, because of the attention they received, if they hadn't people would have found out and they would have lost the domain. This means giving valid contact information. Now provide the response and nothing else.
Here is one method of purchasing a domain name pretty close to anonymously. Use Tor . Understand its weaknesses Buy a prepaid credit card in cash, specifically one not requiring activation or signature. Randomly generate a full alias to use during online registration. Register an account at a domain registrar. Use the prepaid credit card to buy a domain. Repeat for other needed services. Note that 2. requires non-anonymous interaction and is therefore the riskiest. Let's try another path. Use Tor . Understand its weaknesses Randomly generate a full alias to use during online registration. Earn some Bitcoins anonymously online, thus seeding without human contact . Chose a domain registrar and DNS host that supports Bitcoins Repeat for other needed services.
{}
{'log_upvote_score': 6, 'links': ['https://security.stackexchange.com/questions/16453', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/5152/']}
jdg_85524
stackexchange
llm_judgeable_groundtruth_similarity
2783095
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 developing a web page that needs to display, in an iframe, a report served by another company's SharePoint server. They are fine with this. The page we're trying to render in the iframe is giving us X-Frame-Options: SAMEORIGIN which causes the browser (at least IE8) to refuse to render the content in a frame. First, is this something they can control or is it something SharePoint just does by default? If I ask them to turn this off, could they even do it? Second, can I do something to tell the browser to ignore this http header and just render the frame? Now provide the response and nothing else.
If the 2nd company is happy for you to access their content in an IFrame then they need to take the restriction off - they can do this fairly easily in the IIS config. There's nothing you can do to circumvent it and anything that does work should get patched quickly in a security hotfix. You can't tell the browser to just render the frame if the source content header says not allowed in frames. That would make it easier for session hijacking. If the content is GET only you don't post data back then you could get the page server side and proxy the content without the header, but then any post back should get invalidated.
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2783095', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/262046/']}
jdg_85525
stackexchange
llm_judgeable_groundtruth_similarity
40519841
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Trying to write a car rental program which starts out with a menu of options. After picking, the selected option should execute, however, the program is stuck in a loop of menu -> user input -> menu -> user input -> repeat. I assume it has something to do with the 'while ( choice = true )' in the main function. Nothing I've tried changes it to false, though.I'm also having trouble getting anything in any of the case statements to execute. #include <stdio.h>#include <string.h>#define true 1#define false 0void handleSelection (CompanyT *company, int choice);void printMenu(){ printf ("1 Add new car to the inventory.\n"); printf ("2 Make a reservation.\n"); printf ("3 Find a reservation using a renter name and print it to the screen.\n"); printf ("4 Check out a car given a renter name.\n"); printf ("5 Print all available cars.\n"); printf ("6 Calclate and print the average number of days rented.\n"); printf ("7 Exit program.\n");}void handleSelection ( CompanyT *company, int choice){ double value; switch ( choice) { case 1 : value = 0; choice = value; printf ("%s", choice); break; //optional(?) case 2 : printf ("2"); break; case 3 : printf ("3"); break; case 4 : printf ("4"); break; case 5 : printf ("5"); break; case 6 : printf ("6"); break; case 7 : choice = 0; printf ("7"); break; default : printf ("Invalid entry."); } printf ("\n");}int main ( void ){ CompanyT myCompany; int choice; //add pre-defined list of cars to the list createInventory ( &myCompany ); while ( choice = true ) { printMenu();printf ("Choose option: "); scanf ("%d", &choice); handleSelection; }; printf ("\n"); return 0;} full program, if you're trying to compile it: #include <stdio.h>#include <string.h>#define true 1#define false 0typedef short int BoolT; //random true/false valuetypedef struct { //struct that records a car's information int carId; char make[20]; char model[20]; int numDoors; double rate; //complete this} CarT;typedef struct { //struct that identifies a possible renter char renterName[20]; //complete this} RentalT;typedef struct { //struct that makes a reservation for a predetermined renter char renterName[20]; //complete this} ReservT;typedef struct { //struct that tracks the number of cars and rentals CarT allCars[20]; RentalT allRentals[20]; //complete this} CompanyT;/** * Prints a menu to the screen. */void printMenu();/*** Creates the intial inventory of cars the company owns.* company - the company whose inventory will be initialized*/void createInventory ( CompanyT *company );/** * Adds new car to the inventory. * * company the company that will add a new res */void addNewCar ( CompanyT *company );/** * Creates a new reservation prompting the user for information ** company - the company that will add a new reservation*/void makeReservation ( CompanyT *company );/** * Finds a reservation prompting the user for a rental name to locate the res record. * * company - the company whose reservations will be searched */int findReservation ( CompanyT *company );void handleSelection (CompanyT *company, int choice);void printMenu(){ printf ("1 Add new car to the inventory.\n"); printf ("2 Make a reservation.\n"); printf ("3 Find a reservation using a renter name and print it to the screen.\n"); printf ("4 Check out a car given a renter name.\n"); printf ("5 Print all available cars.\n"); printf ("6 Calclate and print the average number of days rented.\n"); printf ("7 Exit program.\n");}void handleSelection ( CompanyT *company, int choice){ double value; switch ( choice ) { case 1 : choice = 0; printf ("%s", choice); break; //optional(?) case 2 : printf ("2"); break; case 3 : printf ("3"); break; case 4 : printf ("4"); break; case 5 : printf ("5"); break; case 6 : printf ("6"); break; case 7 : choice = 0; printf ("7"); break; default : printf ("Invalid entry."); } printf ("\n");}int main ( void ){ CompanyT myCompany; int choice; //add pre-defined list of cars to the list createInventory ( &myCompany ); while ( choice = true ) { printMenu();printf ("Choose option: "); scanf ("%d", &choice); handleSelection; }; printf ("\n"); return 0;}void createInventory ( CompanyT *company ){ (*company).allCars[0].carId = 1234; strcpy ((*company).allCars[0].make, "Vw"); strcpy ((*company).allCars[0].model, "Golf"); (*company).allCars[0].numDoors = 2; (*company).allCars[0].rate = 66.0f; //complete this}void addNewCar ( CompanyT *company ){ //complete this} Now provide the response and nothing else.
Try below code let image = UIImage.init(named: "myImage") let imgData = UIImageJPEGRepresentation(image!, 0.2)! let parameters = ["name": rname] //Optional for extra parameterAlamofire.upload(multipartFormData: { multipartFormData in multipartFormData.append(imgData, withName: "fileset",fileName: "file.jpg", mimeType: "image/jpg") for (key, value) in parameters { multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key) } //Optional for extra parameters },to:"mysite/upload.php"){ (result) in switch result { case .success(let upload, _, _): upload.uploadProgress(closure: { (progress) in print("Upload Progress: \(progress.fractionCompleted)") }) upload.responseJSON { response in print(response.result.value) } case .failure(let encodingError): print(encodingError) }}
{}
{'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/40519841', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7139210/']}
jdg_85526
stackexchange
llm_judgeable_groundtruth_similarity
55737820
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 two pieces of code: CustomHeader.tsx import { View, StyleSheet, Button } from 'react-native';import { NavigationScreenProps } from 'react-navigation';import Icon from 'react-native-vector-icons/Ionicons';export const CustomHeader = ({ navigation }: NavigationScreenProps) => ( <View style={[styles.container]}> <Icon name="md-menu" size={32} color="black" style={{ marginLeft: 10 }} onPress={() => navigation.openDrawer()} /> </View> ); const styles = StyleSheet.create({ container: { borderBottomWidth: 2, height: 70, paddingTop: 20, }, }); DetailScreen.tsx import React from 'react';import { Text, View, Button, Alert } from 'react-native';import { NavigationScreenProps } from "react-navigation";import { CustomHeader } from '../components/Header';export class ChangeAccountDetailScreen extends React.Component { render() { return ( <View style={{ flex: 1 }}> <CustomHeader navigation={this.props.navigation} /> <Text style={{ fontSize: 20 }}>Profile Screen</Text> </View> ); }} In detailscreen i get the following error: Property 'navigation' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'. I searched for the issue and i understand it has something the fact that i am not declaring a type in my CustomHeader. However i do not know how to solve this. I am kinda new to typescript. Could someone explain to me how to fix this type issue? Now provide the response and nothing else.
I could be wrong, but have you tried adding navigation type to be expected import React from 'react';import { Text, View, Button, Alert } from 'react-native';import { NavigationScreenProps } from "react-navigation";import { CustomHeader } from '../components/Header';interface Props { navigation: any}export class ChangeAccountDetailScreen extends React.Component<Props> { render() { return ( <View style={{ flex: 1 }}> <CustomHeader navigation={this.props.navigation} /> <Text style={{ fontSize: 20 }}>Profile Screen</Text> </View> ); }}
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55737820', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5039994/']}
jdg_85527
stackexchange
llm_judgeable_groundtruth_similarity
22373632
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 HTML page that has couple of paragraphs and a reference to an IFrame, the IFrame contains a form, with a couple of text boxes, dropdownlist and a button. When a user clicks the button on the IFrame it send's back a thank you message. The only problem is that the two paragraphs on the HTML page are still showing when the thank you message is displaying. How do I hide the two paragraphs when the button on the IFrame is clicked? (I've rapped two paragraphs around a div) Thanks Now provide the response and nothing else.
For dynamically added elements you need event delegation, use the other version on jQuery on() , you can delegate event to static parent of the dynamically added elements. In your case you can use #main_body $('#main_body').on( "click", "#but", function() { alert( "bla bla" );}); Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, jQuery Docs Your code works here as it is because you are adding the dynamically element before binding the event but using event delegation will free you from the sequence you use to add the dynamic elements.
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/22373632', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3120015/']}
jdg_85528
stackexchange
llm_judgeable_groundtruth_similarity
30528206
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I am trying to have multiple RecyclerViews in a layout but I get the following error: "LayoutManager is already attached to a RecyclerView" The Java code is: @Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_squad, container, false); Activity parentActivity = getActivity(); final ObservableScrollView scrollView = (ObservableScrollView) view.findViewById(R.id.squad_scrollview); final RecyclerView gkRecyclerView = (RecyclerView) view.findViewById(R.id.gk_recycler); final RecyclerView coachRecyclerView = (RecyclerView) view.findViewById(R.id.coach_recycler); coachRecyclerView.setAdapter(new SquadRecyclerAdapter(parentActivity, getSquadDummyData(0))); coachRecyclerView.setLayoutManager(new MyLinearLayoutManager(parentActivity, LinearLayoutManager.VERTICAL, false)); coachRecyclerView.setHasFixedSize(false); gkRecyclerView.setAdapter(new SquadRecyclerAdapter(parentActivity, getSquadDummyData(1))); gkRecyclerView.setLayoutManager(new MyLinearLayoutManager(parentActivity, LinearLayoutManager.VERTICAL, false)); gkRecyclerView.setHasFixedSize(false); scrollView.setTouchInterceptionViewGroup((ViewGroup) parentActivity.findViewById(R.id.container)); if (parentActivity instanceof ObservableScrollViewCallbacks) { scrollView.setScrollViewCallbacks((ObservableScrollViewCallbacks) parentActivity); } return view;} The XML layout code is: <com.github.ksoichiro.android.observablescrollview.ObservableScrollView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/squad_scrollview" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="@dimen/margin_medium" > <LinearLayout android:id="@+id/squad_container" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@drawable/seasons_scrollview" android:divider="@drawable/nav_bar_divider" android:elevation="@dimen/card_elevation" android:orientation="vertical" android:showDividers="middle"> <LinearLayout android:id="@+id/coach_group" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingBottom="@dimen/margin_small" android:paddingLeft="@dimen/margin_standard" android:paddingRight="@dimen/margin_standard" android:paddingTop="@dimen/margin_small"> <TextView android:id="@+id/squad_coach_header" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Coach" android:textSize="@dimen/text_size_standard" /> <android.support.v7.widget.RecyclerView android:id="@+id/coach_recycler" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="@dimen/margin_small" android:paddingBottom="@dimen/margin_small" android:scrollbars="none"> </android.support.v7.widget.RecyclerView> </LinearLayout> <LinearLayout android:id="@+id/gk_group" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingBottom="@dimen/margin_small" android:paddingLeft="@dimen/margin_standard" android:paddingRight="@dimen/margin_standard" android:paddingTop="@dimen/margin_small"> <TextView android:id="@+id/squad_gk_header" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Goalkeepers" android:textSize="@dimen/text_size_standard" /> <android.support.v7.widget.RecyclerView android:id="@+id/gk_recycler" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingTop="@dimen/margin_small" android:paddingBottom="@dimen/margin_small" android:scrollbars="none"> </android.support.v7.widget.RecyclerView> </LinearLayout> <LinearLayout android:id="@+id/def_group" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingBottom="@dimen/margin_small" android:paddingLeft="@dimen/margin_standard" android:paddingRight="@dimen/margin_standard" android:paddingTop="@dimen/margin_small"> <TextView android:id="@+id/squad_def_header" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Defense" android:textSize="@dimen/text_size_standard" /> </LinearLayout> <LinearLayout android:id="@+id/mid_group" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingBottom="@dimen/margin_small" android:paddingLeft="@dimen/margin_standard" android:paddingRight="@dimen/margin_standard" android:paddingTop="@dimen/margin_small"> <TextView android:id="@+id/squad_mid_header" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Midfielders" android:textSize="@dimen/text_size_standard" /> </LinearLayout> <LinearLayout android:id="@+id/for_group" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:paddingBottom="@dimen/margin_small" android:paddingLeft="@dimen/margin_standard" android:paddingRight="@dimen/margin_standard" android:paddingTop="@dimen/margin_small"> <TextView android:id="@+id/squad_for_header" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Forwards" android:textSize="@dimen/text_size_standard" /> </LinearLayout> </LinearLayout></com.github.ksoichiro.android.observablescrollview.ObservableScrollView> The MyLinearLayoutManager is a custom LinearLayoutManager I found online in order to solve the wrap-content issue of the SDK LinearLayoutManager. Is there any way I can have multiple RecyclerViews in a single layout? It seems that I cannot attach more than one LayoutManagers per layout. Any assistance would be very welcome :) Now provide the response and nothing else.
I had this problem too. My Activity uses Tabs, with three fragments, when I go to third tab, and back to first (or second), this error is thrown. After searching a lot, I found out that may be the garbage collector, because I was using a strong reference. Since the constructor LinearLayoutManager uses the activity as the parameter (not the fragment), a Tabs Activity stays active during tabs changes. Removing the local field in mLinearLayoutManager from the class, and using a weak reference, I could get rid of this problem: before: public class MyFragment1 extends Fragment private LinearLayoutManager linearLayoutManager; @Override public void onCreate(Bundle savedInstanceState) { linearLayoutManager = new LinearLayoutManager(getActivity()); (...) } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { (...) mRecyclerView.setLayoutManager(linearLayoutManager); }} I changed to: public class MyFragment1 extends Fragment { // private LinearLayoutManager linearLayoutManager; @Override public void onCreate(Bundle savedInstanceState) { // linearLayoutManager = new LinearLayoutManager(getActivity()); (...) } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { (...) mRecyclerView.setLayoutManager( new LinearLayoutManager(getActivity())); }}
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/30528206', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4772647/']}
jdg_85529
stackexchange
llm_judgeable_groundtruth_similarity
5582331
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: Can the sequence .( ever appear in C# or VB.Net code? (Not in a string, comment, or XML literal, EDIT : or preprocessor directive) I'm reasonably certain that the answer is no, but I'd like to make sure. Now provide the response and nothing else.
The only places that . appears in the grammar are: real-literal: decimal-digits . decimal-digits ... . decimal-digits ...namespace-or-type-name: namespace-or-type-name . identifier ...member-access: primary-expression . identifier ... predefined-type . identifier ...qualified-alias-member . identifier ...base-access: base . identifierunbound-type-name: unbound-type-name . identifierqualified-identifier: qualified-identifier . identifiermember-name: interface-type . identifierindexer-declarator: type interface-type . this (The ... means I have elided the remainder of the production rule.) In none of these cases is a .( valid as . is either followed by digits, a valid identifier, or the keyword this .
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/5582331', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/34397/']}
jdg_85530
stackexchange
llm_judgeable_groundtruth_similarity
43710644
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: I would like to be able to order an array by a nested object.I have this array containing informations about objects on a timeline I would be able to order this by the start position that is defined inside nested arrays. I can get it iterate trough the array with lines[0].events[0].start this is the array: timelines = [ { name: 'obj1', data: { id : 'obj1-guid' }, lines: [{ events: [{ name: 'animation1', data : { id : 'animation1-guid' }, start : 100, duration : 200 }] }], video_url: 'url', }, { name: 'obj2', data: { id : 'obj2-guid' }, lines: [{ events: [{ name: 'animation1', data : { id : 'animation1-guid' }, start : 4, duration : 200 }] }], video_url: 'url', }, { name: 'obj3', data: { id : 'obj3-guid' }, lines: [{ events: [{ name: 'animation1', data : { id : 'animation1-guid' }, start : 56, duration : 200 }] }], video_url: 'url', },]; I tried a function like this function sorting(json_object, key_to_sort_by) { function sortByKey(a, b) { var x = a[key_to_sort_by]; var y = b[key_to_sort_by]; return ((x < y) ? -1 : ((x > y) ? 1 : 0)); } json_object.sort(sortByKey); } timelines = sorting(timelines, 'lines[0].events[0].start'); but of course it's not working Now provide the response and nothing else.
While this is already answered but I think this is not very good answer and users should not use getters as computed properties in angular. Why you may ask? getter is just sugar syntax for function and it will be compiled to plain function, this means that it will be executed on every change detection check. This is terrible for performance because property is recomputed hundred of times on any change. Take a look at this example: https://plnkr.co/edit/TQMQFb?p=preview @Component({ selector: 'cities-page', template: ` <label>Angular computed properties are bad</label> <ng-select [items]="cities" bindLabel="name" bindValue="id" placeholder="Select city" [(ngModel)]="selectedCityId"> </ng-select> <p *ngIf="hasSelectedCity"> Selected city ID: {{selectedCityId}} </p> <p><b>hasSelectedCity</b> is recomputed <b [ngStyle]="{'font-size': calls + 'px'}">{{calls}}</b> times</p> `})export class CitiesPageComponent { cities: NgOption[] = [ {id: 1, name: 'Vilnius'}, {id: 2, name: 'Kaunas'}, {id: 3, name: 'Pabradė'} ]; selectedCityId: any; calls = 0; get hasSelectedCity() { console.log('hasSelectedCity is called', this.calls); this.calls++; return !!this.selectedCityId; }} If you really want to have computed properties you can use state container like mobx class TodoList { @observable todos = []; @computed get unfinishedTodoCount() { return this.todos.filter(todo => !todo.finished).length; }} mobx has @computed decorator so getter property will be cached and recalculated only when needed
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/43710644', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5500423/']}
jdg_85531
stackexchange
llm_judgeable_groundtruth_similarity
55038477
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 have a minimum order amount in my WooCommerce store. The following code is perfectly showing a notice if the amount isn't reached but the checkout is still possible. How to disable checkout-button when the minimum amount isn't reached? add_action( 'woocommerce_checkout_process', 'wc_minimum_order_amount' );add_action( 'woocommerce_before_cart' , 'wc_minimum_order_amount' );function wc_minimum_order_amount() { // Set this variable to specify a minimum order value $minimum = 50; if ( WC()->cart->total < $minimum ) { if( is_cart() ) { wc_print_notice( sprintf( 'Your current order total is %s — you must have an order with a minimum of %s to place your order ' , wc_price( WC()->cart->total ), wc_price( $minimum ) ), 'error' ); } else { wc_add_notice( sprintf( 'Your current order total is %s — you must have an order with a minimum of %s to place your order' , wc_price( WC()->cart->total ), wc_price( $minimum ) ), 'error' ); } }} Now provide the response and nothing else.
To set a minimum order amount you can use woocommerce_check_cart_items action hook this way: add_action( 'woocommerce_check_cart_items', 'required_min_cart_subtotal_amount' );function required_min_cart_subtotal_amount() { // HERE Set minimum cart total amount $minimum_amount = 250; // Total (before taxes and shipping charges) $cart_subtotal = WC()->cart->subtotal; // Add an error notice is cart total is less than the minimum required if( $cart_subtotal < $minimum_amount ) { // Display an error message wc_add_notice( '<strong>' . sprintf( __("A minimum total purchase amount of %s is required to checkout."), wc_price($minimum_amount) ) . '</strong>', 'error' ); }} Code goes in function.php file of your active child theme (or active theme). Tested and works. If customer update the cart changing quantities or removing items, The behavior will be updated too. Related answer: Woocommerce set minimum order for a specific user role
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/55038477', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5364300/']}
jdg_85532
stackexchange
llm_judgeable_groundtruth_similarity
383501
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: Apparently, if the same shell launches multiple ssh connections to the same server, they won't return after executing the command they're given but will hang ( Stopped (tty input) ) for ever. To illustrate: #!/bin/bashssh localhost sleep 2echo "$$ DONE!" If I run the script above more than once in the background, it never exits: $ for i in {1..3}; do foo.sh & done[1] 28695[2] 28696[3] 28697$ ## Hit enter[1] Stopped foo.sh[2]- Stopped foo.sh[3]+ Stopped foo.sh$ ## Hit enter again $ jobs -l[1] 28695 Stopped (tty input) foo.sh[2]- 28696 Stopped (tty input) foo.sh[3]+ 28697 Stopped (tty input) foo.sh Details I found this because I was ssh'ing in a Perl script to run a command. The same behavior occurs when using Perl's system() call to launch ssh . The same issue occurs when using Perl modules instead of system() . I tried Net::SSH::Perl , Net:SSH2 and Net::OpenSSH . If I run the multiple ssh commands from different shells (open multiple terminals) they work as expected. Nothing obviously useful in the ssh connection debugging info: OpenSSH_7.5p1, OpenSSL 1.1.0f 25 May 2017debug1: Reading configuration data /home/terdon/.ssh/configdebug1: Reading configuration data /etc/ssh/ssh_configdebug2: resolving "localhost" port 22debug2: ssh_connect_direct: needpriv 0debug1: Connecting to localhost [::1] port 22.debug1: Connection established.debug1: identity file /home/terdon/.ssh/id_rsa type 1debug1: key_load_public: No such file or directorydebug1: identity file /home/terdon/.ssh/id_rsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/terdon/.ssh/id_dsa type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/terdon/.ssh/id_dsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/terdon/.ssh/id_ecdsa type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/terdon/.ssh/id_ecdsa-cert type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/terdon/.ssh/id_ed25519 type -1debug1: key_load_public: No such file or directorydebug1: identity file /home/terdon/.ssh/id_ed25519-cert type -1debug1: Enabling compatibility mode for protocol 2.0debug1: Local version string SSH-2.0-OpenSSH_7.5debug1: Remote protocol version 2.0, remote software version OpenSSH_7.5debug1: match: OpenSSH_7.5 pat OpenSSH* compat 0x04000000debug2: fd 3 setting O_NONBLOCKdebug1: Authenticating to localhost:22 as 'terdon'debug3: hostkeys_foreach: reading file "/home/terdon/.ssh/known_hosts"debug3: record_hostkey: found key type ECDSA in file /home/terdon/.ssh/known_hosts:47debug3: load_hostkeys: loaded 1 keys from localhostdebug3: order_hostkeyalgs: prefer hostkeyalgs: [email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521debug3: send packet: type 20debug1: SSH2_MSG_KEXINIT sentdebug3: receive packet: type 20debug1: SSH2_MSG_KEXINIT receiveddebug2: local client KEXINIT proposaldebug2: KEX algorithms: curve25519-sha256,[email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,ext-info-cdebug2: host key algorithms: [email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,[email protected],[email protected],ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsadebug2: ciphers ctos: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected],aes128-cbc,aes192-cbc,aes256-cbcdebug2: ciphers stoc: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected],aes128-cbc,aes192-cbc,aes256-cbcdebug2: MACs ctos: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1debug2: MACs stoc: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1debug2: compression ctos: none,[email protected],zlibdebug2: compression stoc: none,[email protected],zlibdebug2: languages ctos: debug2: languages stoc: debug2: first_kex_follows 0 debug2: reserved 0 debug2: peer server KEXINIT proposaldebug2: KEX algorithms: curve25519-sha256,[email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519debug2: ciphers ctos: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected]: ciphers stoc: [email protected],aes128-ctr,aes192-ctr,aes256-ctr,[email protected],[email protected]: MACs ctos: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1debug2: MACs stoc: [email protected],[email protected],[email protected],[email protected],[email protected],[email protected],[email protected],hmac-sha2-256,hmac-sha2-512,hmac-sha1debug2: compression ctos: none,[email protected]: compression stoc: none,[email protected]: languages ctos: debug2: languages stoc: debug2: first_kex_follows 0 debug2: reserved 0 debug1: kex: algorithm: curve25519-sha256debug1: kex: host key algorithm: ecdsa-sha2-nistp256debug1: kex: server->client cipher: [email protected] MAC: <implicit> compression: nonedebug1: kex: client->server cipher: [email protected] MAC: <implicit> compression: nonedebug3: send packet: type 30debug1: expecting SSH2_MSG_KEX_ECDH_REPLYdebug3: receive packet: type 31debug1: Server host key: ecdsa-sha2-nistp256 SHA256:uxhkh+gGPiCJQPaP024WXHth382h3BTs7QdGMokB9VMdebug3: hostkeys_foreach: reading file "/home/terdon/.ssh/known_hosts"debug3: record_hostkey: found key type ECDSA in file /home/terdon/.ssh/known_hosts:47debug3: load_hostkeys: loaded 1 keys from localhostdebug1: Host 'localhost' is known and matches the ECDSA host key.debug1: Found key in /home/terdon/.ssh/known_hosts:47debug3: send packet: type 21debug2: set_newkeys: mode 1debug1: rekey after 134217728 blocksdebug1: SSH2_MSG_NEWKEYS sentdebug1: expecting SSH2_MSG_NEWKEYSdebug3: receive packet: type 21debug1: SSH2_MSG_NEWKEYS receiveddebug2: set_newkeys: mode 0debug1: rekey after 134217728 blocksdebug2: key: /home/terdon/.ssh/id_rsa (0x555a5e4b5060)debug2: key: /home/terdon/.ssh/id_dsa ((nil))debug2: key: /home/terdon/.ssh/id_ecdsa ((nil))debug2: key: /home/terdon/.ssh/id_ed25519 ((nil))debug3: send packet: type 5debug3: receive packet: type 7debug1: SSH2_MSG_EXT_INFO receiveddebug1: kex_input_ext_info: server-sig-algs=<ssh-ed25519,ssh-rsa,rsa-sha2-256,rsa-sha2-512,ssh-dss,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521>debug3: receive packet: type 6debug2: service_accept: ssh-userauthdebug1: SSH2_MSG_SERVICE_ACCEPT receiveddebug3: send packet: type 50debug3: receive packet: type 51debug1: Authentications that can continue: publickey,passworddebug3: start over, passed a different list publickey,passworddebug3: preferred publickey,keyboard-interactive,passworddebug3: authmethod_lookup publickeydebug3: remaining preferred: keyboard-interactive,passworddebug3: authmethod_is_enabled publickeydebug1: Next authentication method: publickeydebug1: Offering RSA public key: /home/terdon/.ssh/id_rsadebug3: send_pubkey_testdebug3: send packet: type 50debug2: we sent a publickey packet, wait for replydebug3: receive packet: type 60debug1: Server accepts key: pkalg rsa-sha2-512 blen 279debug2: input_userauth_pk_ok: fp SHA256:OGvtyUIFJw426w/FK/RvIhsykeP8kIEAtAeZwYBIzokdebug3: sign_and_send_pubkey: RSA SHA256:OGvtyUIFJw426w/FK/RvIhsykeP8kIEAtAeZwYBIzokdebug3: send packet: type 50debug3: receive packet: type 52debug1: Authentication succeeded (publickey).Authenticated to localhost ([::1]:22).debug2: fd 6 setting O_NONBLOCKdebug1: channel 0: new [client-session]debug3: ssh_session2_open: channel_new: 0debug2: channel 0: send opendebug3: send packet: type 90debug1: Requesting [email protected]: send packet: type 80debug1: Entering interactive session.debug1: pledge: networkdebug3: receive packet: type 80debug1: client_input_global_request: rtype [email protected] want_reply 0debug3: receive packet: type 91debug2: callback startdebug2: fd 3 setting TCP_NODELAYdebug3: ssh_packet_set_tos: set IPV6_TCLASS 0x08debug2: client_session2_setup: id 0debug1: Sending command: sleep 2debug2: channel 0: request exec confirm 1debug3: send packet: type 98debug2: callback donedebug2: channel 0: open confirm rwindow 0 rmax 32768debug2: channel 0: rcvd adjust 2097152debug3: receive packet: type 99debug2: channel_input_status_confirm: type 99 id 0debug2: exec request accepted on channel 0 This doesn't depend on my ~/.ssh/config setup. Renaming the file doesn't change anything. This happens on multiple machines. I've tried 4 or 5 different machines running updated Ubuntu and Arch distros. The command ( sleep in the dummy example but something a good deal more complex in real life) exits successfully and does what it's supposed to do. This doesn't depend on the command you're running, it's an ssh issue. This is the worst of them: it isn't consistent . Every now and then, one of the instances will exit and return control to the parent script. But not always, and there is no pattern I've been able to discern. Renaming ~/.bashrc makes no difference. Also, I've run this on machines running Ubuntu (default login shell dash ) and Arch (default login shell bash , called as sh ). Interestingly, the issue only occurs if I hit any key (for example Enter , but any seems to work) after launching the loop but before the first script exits. If I leave the terminal alone, they finish as expected. What's going on? Is this a bug in ssh? Is there an option I need to set? How can I launch multiple instances of a script that runs a command over ssh from the same shell? Now provide the response and nothing else.
Foreground processes and terminal access control To understand what is going on, you need to know a little about sharing terminals. What happens when two programs try to read from the same terminal at the same time? Each input byte goes randomly to one of the programs. (Not random as in the kernel uses an RNG to decide, just random as in unpredictable in practice.) The same thing happens when two programs read from a pipe, or any other file type which is a stream of bytes being moved from one place to another (socket, character device, …), rather than a byte array where any byte can be read multiple times (regular file, block device). For example, run a shell in a terminal, figure out the name of the terminal and run cat . $ tty/dev/pts/18$ cat Then from another terminal, run cat /dev/pts/18 . Now type in the terminal, and watch as lines sometimes go to one of the cat processes and sometimes to the other. Lines are dispatched as a whole when the terminal is in cooked mode. If you put the terminal in raw mode then each byte would be dispatched independently. That's messy. Surely there should be a mechanism to decide that one program gets the terminal, and the others don't. Well, there is! It triggers in typical cases, but not in the scenario I set up above. That scenario is unusual because cat /dev/pts/18 wasn't started from /dev/pts/18 . It's unusual to access a terminal from a program that wasn't started inside this terminal. In the usual case, you run a shell in a terminal, and you run programs from that shell. Then the rule is that the program in the foreground gets the terminal, and programs in the background don't. This is known as terminal access control . The way it works is: Each process has a controlling terminal (or doesn't have one, typically because it doesn't have any open file descriptor that's a terminal). When a process tries to access its controlling terminal, if the process is not in the foreground, then the kernel blocks it. (Conditions apply. Access to other terminals is not regulated.) The shell decides who is the foreground process. (Foreground process group, actually.) It calls the tcsetpgrp to let the kernel know who should be in the foreground. This works in typical cases. Run a program in a shell, and that program gets to be the foreground process. Run a program in the background (with & ), and the program doesn't get to be in the foreground. When the shell is displaying a prompt, the shell puts itself in the foreground. When you resume a suspended job with fg , the job gets to be in the foreground. With bg , it doesn't. If a background process tries to read from the terminal, the kernel sends it a SIGTTIN signal. The default action of the signal is to suspend the process (like SIGSTOP). The parent of the process can know about this by calling waitpid with the WSTOPPED flag; when a child process receives a signal that suspends it, the waitpid call in the parent returns and lets the parent know what the signal was. This is how the shell knows to print “Stopped (tty input)”. What it's telling you is that this job is suspended due to a SIGTTIN. Since the process is suspended, nothing will happen to it until it's resumed or killed (with a signal that the process doesn't catch, because if the process has set a signal handler, it won't run since the process is suspended). You can resume the process by sending it a SIGCONT, but that won't achieve anything if the process is reading from the terminal, it'll receive another SIGTTIN immediately. If you resume the process with fg , it goes to the foreground and so the read succeeds. Now you understand what happens when you run cat in the background: $ cat &$ [1] + Stopped (tty input) cat$ The case of SSH Now let's do the same thing with SSH. $ ssh localhost sleep 999999 &$ $ $ [1] + Stopped (tty input) ssh localhost sleep 999999$ Pressing Enter sometimes goes to the shell (which is in the foreground), and sometimes to the SSH process (at which point it gets stopped by SIGTTIN). Why? If ssh was reading from the terminal, it should receive SIGTTIN immediately, and if it wasn't then why does it receive SIGTTIN? What's happening is that the SSH process calls the select system call to know when input is available on any of the files it's interested in (or if an output file is ready to receive more data). The input sources include at least the terminal and the network socket. Unlike read , select is not forbidden to background processes, and ssh doesn't receive a SIGTTIN when it calls select . The intent of select is to find out whether data is available, without disrupting anything. Ideally select would not change the system state at all, but in fact this isn't completely true. When select tells the SSH process that input is available on the terminal file descriptor, the kernel has to commit to sending input if the process calls read afterwards. (If it didn't, and the process called read , then there might be no input available at this point, so the return value from select would have been a lie.) So if the kernel decides to route some input to the SSH process, it decides by the time the select system call returns. Then SSH calls read , and at that point the kernel sees that a background process tried to read from the terminal and suspends it with SIGTTIN. Note that you don't need to launch multiple connections to the same server. One is enough. Multiple connections merely increases the probability that the problem arises. The solution: don't read from the terminal If you need the SSH session to read from the terminal, run it in the foreground. If you don't need the SSH session to read from the terminal, make sure that its input is not coming from the terminal. There are two ways to do this: You can redirect the input: ssh … </dev/null You can instruct SSH not to forward a terminal connection with -n or -f . ( -n is equivalent to </dev/null ; -f allows SSH itself to read from the terminal, e.g. to read a password, but the command itself won't have the terminal open.) ssh -n … Note that the disconnection between the terminal and SSH has to happen on the client. The sleep process running on the server will never read from the terminal, but SSH has no way to know that. If the client receives input on standard input, it must forward it to the server, which will make the data available in a buffer in case the application ever decides to read it (and if the application calls select , it'll be informed that data is available).
{}
{'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/383501', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/22222/']}
jdg_85533
stackexchange
llm_judgeable_groundtruth_similarity
3104
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would. Question: Caveat: I don't really know anything about PDEs, so this question might not make sense. In complex analysis class we've been learning about the solution to Dirichlet's problem for the Laplace equation on bounded domains with nice (smooth) boundary. My sketchy understanding of the history of this problem (gleaned from Wikipedia) is that in the 19th century everybody "knew" that the problem had to have a unique solution, because of physics. Specifically, if I give you a distribution of charge along the boundary, it has to determine an electric potential in the domain, which turns out to be harmonic. But Dirichlet's proof was wrong, and it wasn't until around 1900 that Hilbert found a correct argument for the existence and uniqueness of the solution, given reasonable conditions (the boundary function must be continuous, and the boundary really has to be sufficiently smooth). Is the physical heuristic really totally meaningless from a mathematical point of view? Or is there some way to translate it into an actual proof? Now provide the response and nothing else.
Well, I don't understand the electrostatics, but here is another physical heuristic: Impose a temperature distribution at the exterior, and measure (after some time has passed) the temperature in the interior. This gives a harmonic function extending the exterior temperature. [What's the electrostatic analogue? Formerly I had written "charge density", but now I am not sure if that's right.] I think this strongly suggests a mathematically rigorous argument: We are naturally led to model the time-dependence of temperature in the interior.This satisfies a diffusion (or heat) equation, but in words: "After a time \delta, the new temperature is obtained by averaging the old temperature along a circle of radius \sqrt{\delta}." This process converges under reasonable conditions, as time goes to infinity, to the solution of the Dirichlet problem. Anyway, we are led to the Brownian-motion proof of the existence, which I personally find rather satisfying. Another personal comment: I think one should always take "physical heuristics" rather seriously. [In response to Q.Y.'s comments below, which were responses to previous confused remarks that I made: neither the electric field nor the Columb potential is a multiple of the charge density on the boundary: the former is a vector, and in eithercase imagine the charge on the boundary to be concentrated in a sub-region; neither the electric field nor the potential will be constant outside that sub-region.]
{}
{'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/3104', 'https://mathoverflow.net', 'https://mathoverflow.net/users/412/']}
jdg_85534
stackexchange
llm_judgeable_groundtruth_similarity
4555856
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would. Question: If $x^3 - \dfrac{1}{x^3} = 108+76\sqrt{2}$ , find the value of $x-\dfrac{1}{x}$ . Here's what I've tried so far. $$\begin{align}\left(x-\dfrac{1}{x}\right)^3&=x^3-\dfrac{1}{x^3}-3\left(x-\dfrac{1}{x}\right) \\\rightarrow \quad \left(x-\dfrac{1}{x}\right)^3&=108+76\sqrt{2}-3\left(x-\dfrac{1}{x}\right) \\u:=x-\dfrac{1}{x} \quad\rightarrow \quad u^3+3u-108-76\sqrt{2}&=0\end{align}$$ Got stuck here since I didn't know how to solve this cubic equation. I also tried factorizing $x^3-\dfrac{1}{x^3}$ . $$\begin{align}x^3-\dfrac{1}{x^3}&=\left(x-\dfrac{1}{x}\right)\left(x^2+\dfrac{1}{x^2}+1\right) \\&= \left(x-\dfrac{1}{x}\right)\left(x^2+\dfrac{1}{x^2}+2-1^2\right) \\&= \left(x-\dfrac{1}{x}\right)\left(\left(x+\dfrac{1}{x}\right)^2-1^2\right) \\&= \left(x-\dfrac{1}{x}\right)\left(x+\dfrac{1}{x}+1\right)\left(x+\dfrac{1}{x}-1\right)\end{align}$$ Again, I didn't know what I could do with this. Now provide the response and nothing else.
Solve for $x$ first. You can use the quadratic formula. $$x^3 - \frac1{x^3} = 108 + 76\sqrt2 \implies x^6 - (108+76\sqrt2)x^3 - 1 = 0$$ $$\implies x^3 = \frac{108+76\sqrt2 \pm \sqrt{(108+76\sqrt2)^2 + 4}}2 = 54 + 38\sqrt2 + 3\sqrt{645 + 456 \sqrt2}$$ $$\implies x = \sqrt[3]{54 + 38\sqrt2 + 3\sqrt{645 + 456 \sqrt2}} = \frac{3+2\sqrt2}2 + \frac12 \sqrt{21 + 12\sqrt2}$$ The hardest part is de-nesting the cube root (see below). Otherwise take WA at its word . It follows that $$\frac1x = \frac2{3 + 2\sqrt2 + \sqrt{21 + 12\sqrt2}} = -\frac{3+2\sqrt2}2 + \frac12 \sqrt{21 + 12\sqrt2}$$ and you can easily find $x-\frac1x$ from here. De-nesting the cube root Observe that $$645 + 456 \sqrt2 = (21 + 12\sqrt2) (17 + 12\sqrt2) = (21 + 12\sqrt2) (3 + 2\sqrt2)^2 \\\implies x^3 = 54 + 38\sqrt2 + 9\sqrt{21+12\sqrt2} + 6\sqrt2\sqrt{21+12\sqrt2}$$ Suppose we can decompose the cube root into the form $$x = a + b \sqrt2 + c \sqrt{21+12\sqrt2}$$ where $a,b,c\in\Bbb Q$ . Taking cubes on both sides and matching up coefficients, we get the system of equations $$\begin{cases}a^3 + 6 a b^2 + 63 a c^2 + 72 b c^2 = 54 \\2b^3 + 3 a^2 b + 36 a c^2 + 63 b c^2 = 38 \\7c^3 + a^2 c + 2 b^2 c = 3 \\2c^3 + a b c = 1\end{cases}$$ Solving the last equation for $c^2 = 3ab-a^2-2b^2$ and substituting that into the first two equations yields yet another system, $$\begin{cases}-62a^3 + 117a^2b + 96ab^2 - 144b^3 = 54 \\-36a^3 + 48a^2b + 117 ab^2 - 124b^3 = 38\end{cases}$$ Since both polynomials are homogeneous with degree $3$ , suppose that $a,b$ are proportional. Let $b=ka$ where $k\in\Bbb Q$ , so we have $$\begin{cases}a^3(-62 + 117k + 96k^2 - 144k^3) = 54 \\a^3(-36 + 48k + 117k^2 - 124k^3) = 38\end{cases}$$ Eliminate $a^3$ by division to get a cubic equation in $k$ . $$\frac{a^3(-62 + 117k + 96k^2 - 144k^3)}{a^3(-36 + 48k + 117k^2 - 124k^3)} = \frac{27}{19} \implies 612k^3 - 1335k^2 + 927k - 206 = 0$$ Now apply the rational root theorem. If you start with the smallest divisors of $612$ and $206$ , you'll soon find $k=\frac23$ (and we can show this is the only rational solution for $k$ ). It follows that $$b=\frac23a \implies 16a^3 = 54 \implies a = \frac32 \implies b = 1 \implies c = \frac12$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4555856', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/1087124/']}
jdg_85535
stackexchange
llm_judgeable_groundtruth_similarity
8003215
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: jQuery has a lovely if somewhat misnamed method called closest() that walks up the DOM tree looking for a matching element. For example, if I've got this HTML: <table src="foo"> <tr> <td>Yay</td> </tr></table> Assuming element is set to <td> , then I can figure the value of src like this: element.closest('table')['src'] And that will cleanly return "undefined" if either of the table element or its src attribute are missing. Having gotten used to this in Javascriptland, I'd love to find something equivalent for Nokogiri in Rubyland, but the closest I've been able to come up with is this distinctly inelegant hack using ancestors() : ancestors = element.ancestors('table')src = ancestors.any? ? first['src'] : nil The ternary is needed because first returns nil if called on an empty array. Better ideas? Now provide the response and nothing else.
You can call first on an empty array, the problem is that it will return nil and you can't say nil['src'] without getting sad. You could do this: src = (element.ancestors('table').first || { })['src'] And if you're in Rails, you could use try thusly: src = element.ancestors('table').first.try(:fetch, 'src') If you're doing this sort of thing a lot then hide the ugliness in a method: def closest_attr_from(e, selector, attr) a = e.closest(selector) a ? a[attr] : nilend and then src = closest_attr_from(element, 'table', 'src') You could also patch it right into Nokogiri::XML::Node (but I wouldn't recommend it): class Nokogiri::XML::Node def closest(selector) ancestors(selector).first end def closest_attr(selector, attr) a = closest(selector) a ? a[attr] : nil endend
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8003215', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/218340/']}
jdg_85536
stackexchange
llm_judgeable_groundtruth_similarity
27670325
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: So I am using the SwipeView library ( https://github.com/nicklockwood/SwipeView ) to show images using the Photos framework for iOS8. However, when I call the requestImageForAsset I notice I am getting two results, a thumbnail size, and the bigger size that I want. However, the bigger image isn't loaded (it's called async I understand) in time to return, so it returns the small image. This code might make more sense. func swipeView(swipeView: SwipeView!, viewForItemAtIndex index: Int, reusingView view: UIView!) -> UIView! { let asset: PHAsset = self.photosAsset[index] as PHAsset var imageView: UIImageView! let screenSize: CGSize = UIScreen.mainScreen().bounds.size let targetSize = CGSizeMake(screenSize.width, screenSize.height) var options = PHImageRequestOptions()// options.deliveryMode = PHImageRequestOptionsDeliveryMode.Opportunistic options.resizeMode = PHImageRequestOptionsResizeMode.Exact PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: targetSize, contentMode: .AspectFill, options: options, resultHandler: {(result, info)in println("huhuhuh") println(result.size) println(info) imageView = UIImageView(image: result) }) println("setting view) return imageView} Here is the log output: Enteredhuhuhuh(33.5,60.0)SETTING VIEWhuhuhuh(320.0,568.0) As you can see it returns the image view before the big image is recieved. How do I make it return this larger image so it's not showing the thumbnai? Thanks. Now provide the response and nothing else.
Read header of PHImageManager class If -[PHImageRequestOptions isSynchronous ] returns NO (or options is nil), resultHandler may be called 1 or more times. Typically in this case, resultHandler will be called asynchronously on the main thread with the requested results. However, if deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic, resultHandler may be called synchronously on the calling thread if any image data is immediately available. If the image data returned in this first pass is of insufficient quality, resultHandler will be called again, asychronously on the main thread at a later time with the "correct" results. If the request is cancelled, resultHandler may not be called at all. If -[PHImageRequestOptions isSynchronous] returns YES, resultHandler will be called exactly once, synchronously and on the calling thread. Synchronous requests cannot be cancelled. resultHandler for asynchronous requests, always called on main thread So, what you want to do is that you make resultHandler to be called synchronously PHImageRequestOptions *option = [PHImageRequestOptions new];option.synchronous = YES;[[PHImageManager defaultManager] requestImageForAsset:asset targetSize:target contentMode:PHImageContentModeAspectFill options:option resultHandler:^(UIImage *result, NSDictionary *info) { //this block will be called synchronously}]; So your block will be called before ending your method Good luck!
{}
{'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/27670325', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2433617/']}
jdg_85537
stackexchange
llm_judgeable_groundtruth_similarity
4046640
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 proved that the sequence is bounded and that its limit is 2, but how do I prove by induction that it is monotone increasing? i.e. that $x_{n+1} \ge x_n$ for every $n \in \mathbb{N}$ Now provide the response and nothing else.
As you said $,\quad x_{n}< 2$ $$x_{n+ 1}^{2}- x_{n}^{2}= 2+ x_{n}- x_{n}^{2}> 2+ x_{n}- 2x_{n}> 0$$
{}
{'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/4046640', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/877715/']}
jdg_85538
stackexchange
llm_judgeable_groundtruth_similarity
9350422
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would. Question: What fork, or combination of packages should one to use to make PyPy, Django and PostgreSQL play nice together? I know that PyPy and Django play nice together, but I am less certain about PyPy and PostgreSQL. I do see that Alex Gaynor has made a fork of PyPy called pypy-postgresql . I also know that some people are using psycopg2-ctypes . Is there a difference between these forks? Or should we use the stable 1.9 PyPy and use psycopg2-ctypes? Using the ctypes options could hurt performance, see the comment below. Also, has anyone experienced any pitfalls with using PyPy with pyscopg2? It seems easy enough to fall back on CPython if something isn't working right, but mostly I'm looking for things a programmer can do ahead of time to prepare. I looked around, it doesn't seem that psycopg2 works natively with PyPy. Although, psycopg2-ctypes does seem to be working for some people, there was a discussion on pypy-dev . I work on Windows, and I don't think psycopg2-ctypes is ready for Windows yet, sadly. Now provide the response and nothing else.
psycopg2cffi (Updated 2015) psycopg2cffi is yet another psycopg2-compatible replacement and should provide the best PostgreSQL performance with PyPy. Add this to your settings.py to remain compatible with both: try: import psycopg2except ImportError: # Fall back to psycopg2cffi from psycopg2cffi import compat compat.register() psycopg2-ctypes (2012) I also know that some people are using psycopg2-ctypes. This is the easiest way; to stay compatible with both, just add this code in your Django settings.py : try: import psycopg2except ImportError: # Fall back to psycopg2-ctypes from psycopg2ct import compat compat.register() I tested this a few releases ago; sadly in my experience, psycopg2-ctypes negates the small performance gains afforded by PyPy. But YMMV, it depends on how JIT-friendly your code is in general and what fraction of time you actually spend running Python code. And maybe PyPy has just improved since then. and I don't think psycopg2-ctypes is ready for Windows yet I haven't tried this, but ctypes is platform-independent. AFAICT you just have to make sure that the libpq.dll library is loadable (located in a directory in your PATH environment variable or local directory) and it should work on Windows just like in Linux. pypy-postgresql I do see that Alex Gaynor has made a fork of PyPy called pypy-postgresql. I don't think this is a good choice in the long term. The branch hasn't been updated for more than a year and my attempts to build it have failed. And it seems wrong to hard-code a PostgreSQL driver in the interpreter anyway. I believe there are no binaries out there of pypy-postgresql either, so if you want to use it, you'd need to build the whole PyPy branch yourself. Not for the faint of heart: it takes tens of minutes and a machine with at least 4 GB of memory. (Official instructions: http://pypy.org/download.html#building-from-source ) To build, you first need the source. If you have Mercurial installed, you can simply hg clone https://bitbucket.org/alex_gaynor/pypy-postgresql . If not, you can download the automagic "tip" zip file: https://bitbucket.org/alex_gaynor/pypy-postgresql/get/tip.zip Open a command line, go into the decompressed directory, and then inside pypy/translator/goal If you have PyPy installed, it's recommended to use that for building: pypy translate.py -Ojit Otherwise: python translate.py -Ojit Sadly this is where my knowledge ends. I get the error " BytecodeCorruption: unimplemented opcode, ofs=234, code=203, name=BUILD_LIST_FROM_ARG "
{}
{'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/9350422', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1125592/']}
jdg_85539
stackexchange
llm_judgeable_groundtruth_similarity
688809
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 iPhone Developer Program Portal, there's a video to demonstrate how to create a development certificate and assign a private key Now I have finished the development process and starting to distribute I have created a "Distribution Certificate", but how do I assign a private key to this certificate? As it got the "CodeSign error: code signing identity '...' does not match any code-signing certificate in your keychain" when compiles It will be glad to let me now if I need to assign a private key to the distribution cert and how. Please be noticed that I am NOT talking about development certificate here, thanks. Now provide the response and nothing else.
As no one has updated or answered this question since Nathan pointed out the original answer link is unavailable (Point number one on posting on stackoverflow "Please be sure to answer the question ") here is an answer from my experiance, hope it helps someone: For this specific question (Dev/Distribution cert installed but no private key) the answer is a choice of 2 alternatives: 1. Create a new certificate identity via the apple devloper portal In this case you'll need to log into the apple developer portal and use the assistant, as part of this you will need to create and upload a CSR (Certificate Signing Request) which will also create the public and private keys on the machine. Apple sign the request and voila, a signed public/private certificate pair : Reference 2. Export the private key from the machine originally used to create the Certificate This case is when your signing with an identity previously created, probably on an old machine or if (as in my case) your developing for a client that has their ID's already created. If you can't access the machine originally used to create the certificate identity you'll have to create a new identity as per the guide/assistant. To do this, you will need to export your private key (a .p12 file), or public/private key pair via Keychain Access, and install the private key or key pair to the machine your developing on. Here's a guide I found on stackoverflow. Ref: http://iphonedevsdk.com/forum/iphone-sdk-development/11498-problems-exporting-importing-p12-private-key-for-developing-on-another-mac.html PS> Be warned, I am performing the latter option right now, and while evidence suggests this will work, it is untested by me as of yet, If if doesn't work I will re-reply!
{}
{'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/688809', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/63226/']}
jdg_85540