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 | 228085 |
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:
Is it ever justifiable to write production-code without also writing tests for it when doing Test Driven Development?
Now provide the response and nothing else.
| Strict TDD? Absolutely not. How can you write a test, make it fail, make it pass, without writing a test? In the real world, very few people do strict TDD. It's an ideal that shouldn't be allowed to get in the way of common sense. Every rule has a scenario where it's justifiable to break it, and that's fine. But we shouldn't lie to ourselves or others and claim we do TDD when we don't. If for no other reason than it gives a bad impression of TDD, when it fails to achieve its goals. (Replace TDD with any other process and the point stands.) Also, the most common justification for not doing TDD is time. And that's very rarely a good reason. If a change isn't complex, it shouldn't take long to write the test. If it is complex then you're inviting issues down the line by not writing tests first, so the time isn't often truly saved. But, perhaps there is a justification even for that. Perhaps it's better to get something imperfect into the market and then fix it. Without knowing the justification being disputed, it's hard to know whether it's valid. But I will reiterate that most rules can be broken, with good justification. As long as we're honest with ourselves about it and acknowledge when it turns out to be a mistake. | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/228085', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/73675/']} | jdg_82641 |
stackexchange | llm_judgeable_groundtruth_similarity | 142243 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Terms like "impractical" and "unfeasible" are used to say the Robertson, Sanders, Seymour, and Thomas proof of the four color theorem needs computer assistance. Obviously no precise measure is possible, for many reasons. But is there an informed rough estimate what a graph theorist would need to verify the 633 reducible configurations in that proof? $10^4$ hours? $10^8$ years? I am not asking if other proofs are known. I want to know if graph theorists have an idea what scale of practicality we are talking about when we say the Robertson, Sanders, Seymour, and Thomas proof is impractical without machine assistance.
Now provide the response and nothing else.
| To answer the question it is important to disentangle the proof as follows. Theorem 1. Every minimum counterexample to the 4CT is an internally 6-connected triangulation. Theorem 2. If $T$ is a minimum counterexample to the 4CT, then no good configuration appears in $T$. Theorem 3. For every internally 6-connected triangulation $T$, some good configuration appears in $T$. See the actual paper for the definitions of these terms. Theorem 1 does not require computer assistance, while Theorem 2 and Theorem 3 both do require computer assistance. According to this version of the paper , Theorem 3 can in principle be checked by hand. Indeed it is explicitly mentioned that It can be checked by hand in a few months , or a few minutes by computer (this was about 15 years ago though). I quote more on Theorem 3: For each of these five cases we have a proof. Unfortunately, they are very long (altogether about 13000 lines, and a large proportion of the lines take some thought to verify), and so cannot be included in a journal article. Theorem 2, on the other hand really requires a computer. From the same paper, The proof of Theorem 2 takes about 3 hours on a Sun Sparc 20 workstation and the proof of Theorem 3 takes about 20 minutes. Thus, given that it took a computer 9 times longer to verify Theorem 2 than Theorem 3, and Theorem 3 apparently can be verified by hand in a few months (let us define few=3), then under some very dubious assumptions we have the ballpark answer of Ballpark Answer. 30 months. | {} | {'log_upvote_score': 6, 'links': ['https://mathoverflow.net/questions/142243', 'https://mathoverflow.net', 'https://mathoverflow.net/users/38783/']} | jdg_82642 |
stackexchange | llm_judgeable_groundtruth_similarity | 3633541 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I am having a hard time solving this one, and it seems so simple. \begin{align*}\int_{1}^{\infty} \dfrac{1}{x^{1+\frac{1}{x}}} dx\end{align*} I understand that it diverges, because I've tested it. As $x$ approaches infinity, the expression approaches $$\int_{1}^{\infty} \dfrac{1}{x} dx$$ Which we know diverges. But how can I prove/show that?
Now provide the response and nothing else.
| The accepted answer is incorrect . $\omega$ -consistency does not say "If you prove $P(n)$ for each standard $n$ , then you prove $\forall n(P(n))$ ." That would be $\omega$ - completeness . Rather, $\omega$ -consistency says "If you prove $\exists x\neg P(x)$ , then you must not prove $P(n)$ for each standard $n$ ." And in particular, both $AST$ and the theory $T$ introduced in that answer are $\omega$ -consistent, at least assuming $ZFC$ is to begin with. Getting back to the main question, it may help to drop $AST$ and consider the simpler fact about $ZFC$ alone, which is itself provable in ZFC: $(*)\quad$ For every $M\models ZFC$ there is some structure $A\in M$ such that $A\models ZFC$ ... even if $M\models\neg Con(ZFC)$ . The key point is that " $A\models ZFC$ " is interpreted in reality ; we may not have $M\models(A\models ZFC)$ . This also explains why the OP's reflection argument breaks down - it's exactly the same reason. Here's how to prove $(*)$ in ZFC: If $ZFC$ is inconsistent then $(*)$ is vacuously true. Suppose $ZFC$ is consistent. Let $M\models ZFC$ . If $M\models Con(ZFC)$ then since $ZFC$ proves the completeness theorem we're done. So suppose $M\models \neg Con(ZFC)$ . Let $n\in\omega^M$ be what $M$ thinks is the largest number such that there is no proof of a contradiction from the first $n$ axioms of $ZFC$ . If we can conclude that $n$ is nonstandard, we'll be done: by completeness in $M$ , any model $A$ of the first $n-1$ axioms of $ZFC$ in the sense of $M$ will in reality be a model of $ZFC$ , even if $M$ doesn't think so. Now here's the cute bit: we internalize the reflection principle. Looking at the usual argument we see in fact that ZFC proves "ZFC proves every finite subtheory of ZFC." (Note the crucial nested "proves" here.) This means we can next say... Since $M\models ZFC$ , for each standard $k$ we have $M\models$ "The first $k$ axioms of $ZFC$ are consistent." So $n$ is nonstandard and we're done. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/3633541', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/751321/']} | jdg_82643 |
stackexchange | llm_judgeable_groundtruth_similarity | 113615 |
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:
It appears that it is possible on a network mount to set a quota on how much space a user can consume. # edquota rameshDisk quotas for user ramesh (uid 500): Filesystem blocks soft hard inodes soft hard /dev/sda3 1419352 0 0 1686 0 0 You also can set a soft and a hard limit on how many inodes a user has. Why would you ever need to limit how many inodes a user has access to? Wouldn't the user still be able to fill up the disk with 1 really large file?
Now provide the response and nothing else.
| The reason you limit the number of inodes a user can access is so they don't make the system as a whole run out of inodes by creating a huge number of 0-byte files. With most Linux file systems (e.g. ext3 and ext4), each file (including device files) or directory has an inode -- a number used to point to a given file/directory. If a system runs out of inodes, it doesn't matter how much free space the hard disk has; it's impossible to make a new file until inodes are freed up. To see how many inodes each filesystem has left: df -i The number of inodes a filesystem has is determined by the -i argument when formatting the file system. Examples: mkfs -t ext4 -i 1024 /dev/foo # One inode per 1024 bytesmkfs -t ext4 -i 2048 /dev/foo # One inode per 2048 bytesmkfs -t ext4 -i 8192 /dev/foo # One inode per 8192 bytes The filesystem created with the -i 1024 option will have eight times as many inodes as the filesystem created with the -i 8192 option (assuming both file sytems are the same size). Sometimes, especially with some mail servers (that use "maildir") or old-school Usenet spools, one needs more inodes, since those use cases create a lot of small files. Note that some Linux filesystems, such as Reiserfs, are able to dynamically assign inodes and do not create all of them at filesystem creation time. | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/113615', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/39263/']} | jdg_82644 |
stackexchange | llm_judgeable_groundtruth_similarity | 4067866 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
After googling for a while, I'm aware that there quite a few ways to copy an array to another in Java, namely using System.arraycopy. However a few of my friends tried to use this: boolean a[][] = new boolean[90][90];boolean b[][] = new boolean[90][90];/* after some computations */a = b This produces a rather non deterministic result, does anyone know what this actually does?
Now provide the response and nothing else.
| It's not non-deterministic at all. a = b; simply assigns the value of b to a . The value of b is a reference to the array - so now both variables contain references to the same array. The old value of a is irrelevant - and if it referred to an array which nothing else referred to, it will now be eligible for garbage collection. Note that this isn't specific to arrays - it's the way all reference types work in Java. Basically, you're not copying one array into another at all - you're copying the reference to an array into another variable. That's all. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/4067866', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/361247/']} | jdg_82645 |
stackexchange | llm_judgeable_groundtruth_similarity | 7189 |
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:
Based on the 1D case mentioned in Griffiths, I decided to try looking at the features of 3D Gaussian wavefunctions, i.e. (position basis) wavefunctions of the form $\psi(\mathbf{r}) = Ae^{-\mathbf{r}^\dagger\mathsf\Sigma\mathbf{r}/4}$, where A is a normalization constant, r is position, Σ is a positive-definite symmetric matrix (which by a suitable change of coordinate basis can be made diagonal), and † denotes the conjugate transpose. Applying standard results for Gaussian integrals, I was able to get $\langle \mathbf{r} \rangle = 0$ $\langle r^2\rangle = \operatorname{Tr}\mathsf\Sigma$ $\langle \mathbf{p} \rangle = 0$ $\langle p^2\rangle = \frac{\hbar^2}{4}\operatorname{Tr}\mathsf\Sigma^{-1}$ So, substituting into Heisenberg's uncertainty principle and rearranging terms, it follows that, in order to get minimum uncertainty with respect to $\mathrm{r}$ and $\mathrm{p}$, we need to have $(\operatorname{Tr}\mathsf\Sigma)(\operatorname{Tr}\mathsf\Sigma^{-1})=1$. Here's where I'm running into a difficulty. As I mentioned before, the matrix Σ can always be assumed to be diagonal. Then the only possible solution for Σ is $\mathsf\Sigma = \begin{pmatrix} 1 & 0 & 0\\ 0 &-1 &0\\ 0 &0 &1\end{pmatrix}\times\mathrm{constant}$ But this contradicts the fact that Σ is positive-definite (the -1 would imply that one of the coordinates has negative uncertainty, an absurdity). Assuming I did all the calculations correctly, this seems to imply that a Gaussian wavefunction is not the minimum uncertainty wavefunction with respect to r and p . On the other hand, it's comparatively trivial to show that it is the minimum uncertainty wavefunction with respect to x and p x , y and p y , and z and p z individually. Is there a wavefunction which is the minimum unceratinty wavefunction with both respect to the individual coordinates (e.g. x and p x ) and with respect to r and p ? Edit It was asked by marek what I meant by "minimum uncertainty with respect to $\mathbf{r}$ and $\mathbf{p}$". To answer this, recall that the generalized uncertainty principle takes the form of$$ \sigma_A\sigma_B \geq \frac{1}{2}\left|\langle[A,B]\rangle\right|.$$Although I'm not entirely sure it's valid to do so, I assumed that to calculate the commutator $[\mathbf{r},\mathbf{p}]$ I could use the formalism of geometric algebra (see Geometric algebra ). Then$$\begin{align*} [\mathbf{r},\mathbf{p}]f &= \frac{\hbar}{i}\mathbf{r}\nabla f - \frac{\hbar}{i}\nabla(f\mathbf{r})\\ &= \frac{\hbar}{i}\sum_{jk} \left[x^j\hat{\mathbf{e}}_j\frac{\partial f}{\partial x^k}\hat{\mathbf{e}}^k - \frac{\partial}{\partial x^k}\left(fx^j\hat{\mathbf{e}}_j\right)\hat{\mathbf{e}}^k\right]\\ &= \frac{\hbar}{i}\sum_{jk} \left[ x^j\frac{\partial f}{\partial x^k} \hat{\mathbf{e}}_j\hat{\mathbf{e}}^k - \frac{\partial f}{\partial x^k}x^j\hat{\mathbf{e}}_j\hat{\mathbf{e}}^k - f{\delta^j}_k\hat{\mathbf{e}}_j\hat{\mathbf{e}}^k\right]\\ &= \frac{\hbar}{i} f,\end{align*}$$where $f$ is an arbitrary function, $x^1,x^2,x^3$ are the position coordinates, and $\hat{\mathbf{e}}_1,\hat{\mathbf{e}}_2,\hat{\mathbf{e}}_3$ are the standard Cartesian basis vectors. Thus, the uncertainty principle for $\mathbf{r}$ and $\mathbf{p}$ takes the form$$\sigma_\mathbf{r}\sigma_\mathbf{p} \geq \frac{\hbar}{2},$$which means that the minimum uncertainty wavepacket with respect to $\mathbf{r}$ and $\mathbf{p}$ must satisfy $$\sigma_\mathbf{r}\sigma_\mathbf{p} = \frac{\hbar}{2}.$$
Now provide the response and nothing else.
| It seems that problem here is with mishandling vector quantities. We want to compute things such as $\left<p^2\right>$ but these are in fact $\sum_i \left<p_i^2\right>$ and so the problem decomposes into components where the standard HUP and minimality conditions can be applied. But what you've done is that you applied one-dimensional HUP to $\left<x^2\right>$ and $\left<p^2\right>$ which just can't be right. The correct form of HUP in this case would be $$\sum_i \left<x_i^2\right>\left<p_i^2\right> \geq 3 {\hbar^2 \over 4}$$ So, to reiterate, there is really nothing new to solve in more dimensions as the problem decomposes completely and you can write your solution as $\Psi(x,y,z)$ = $\psi_x(x)\psi_y(y)\psi_z(z)$ with each $\psi_{\alpha}$ a Gaussian from the one-dimensional variant of this problem. | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/7189', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/2618/']} | jdg_82646 |
stackexchange | llm_judgeable_groundtruth_similarity | 4575787 |
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 display a bubble help for some short span elements. The bubbles are centered below that span and look great as long as the span isn't broken over two lines. Looks good: tell <span>irregular: told, told</span> Looks bad: tell <span>irregular: told,told</span> It looks bad, because the bubble isn't centered under the span anymore. Is there some way using JavaScript or jQuery to tell, if that span is broken over two lines?
Now provide the response and nothing else.
| 9000's comment is correct. The trick is having access to a <span> that you know will be rendered on a single line. You can do that by wrapping the first word of your block in a span with a specific id , you could also use the last word or some other single word; there are cases where a single word will cross lines but the first word should be safe. Once you have something that is only on one line you can compare its height to the height of the <span> that will get the tooltip. If the <span> that is getting the tooltip is taller than the single-line <span> then it has wrapped to multiple lines. Try this jsfiddle: http://jsfiddle.net/ambiguous/JbMhZ/1/ Adjust the size of the right panes until the red text wraps but the green text doesn't. Then hit Run in the toolbar at the top and it should say this at the bottom of the Result pane: #has-break spans more than one line#no-break spans only one line I'm not exactly proud of this hack but it should work. I'm left wondering if a better positioning algorithm for your tooltip would be a better idea. Maybe pull the mouse coordinates out of the hover event and use that to position the tooltip rather than positioning it based on the <span> . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/4575787', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/362378/']} | jdg_82647 |
stackexchange | llm_judgeable_groundtruth_similarity | 1137182 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have a table with more than 9 rows. If I do this : $('table tr:gt(3):lt(6)') , shall I receive 3 or 6 elements at the end, and why? Are all selectors applied to the same primary selection, or are they successively applied on different selections?
Now provide the response and nothing else.
| They're applied sequentially, so first you will filter away the first four elements ( :gt(3) ), then you will filter away all elements after the sixth ( :lt(6) ) element of the already filtered set. Imagine this HTML: <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/> Then do the following jQuery: $('br:gt(3):lt(6)').addClass('sel'); You will now have: <br/><br/><br/><br/><br class="sel"/><br class="sel"/><br class="sel"/><br class="sel"/><br class="sel"/><br class="sel"/><br/><br/> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1137182', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/118437/']} | jdg_82648 |
stackexchange | llm_judgeable_groundtruth_similarity | 1425141 |
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 determine the URL of the current page from within Flex?
Now provide the response and nothing else.
| Let's be clear here. 1. If you want the URL of the loaded SWF file, then use one of these. Inside your application: this.url; From anywhere else: Application.application.url; // Flex 3FlexGlobals.topLevelApplication.url; // Flex 4 If you are loading your SWF inside another SWF, then keep in mind that the code above will give different values. this.url will return the url of your SWF, where as Application.application.url will give the url of the parent/root SWF. 2. If you want to know the URL that is in the browser address bar , then use one of these. BrowserManager method(Make sure you have the History.js included in your wrapper html for this to work): var browser:IBrowserManager = BrowserManager.getInstance(); browser.init();var browserUrl:String = browser.url; // full url in the browservar baseUrl:String = browser.base; // the portion of the url before the "#"var fragment:String = browser.fragment; // the portion of the url after the "#" JavaScript method: var browserUrl:String = ExternalInterface.call("eval", "window.location.href"); If you are parsing the url for parameters, don't forget about this useful function: // parses a query string like "key=value&another=true" into an objectvar params:Object = URLUtil.stringToObject(browserURL, "&"); | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1425141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1432/']} | jdg_82649 |
stackexchange | llm_judgeable_groundtruth_similarity | 2212709 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Now that Rails 3 beta is out, I thought I'd have a look at rewriting an app I have just started work on in Rails 3 beta, both to get a feel for it and get a bit of a head-start. The app uses MongoDB and MongoMapper for all of its models and therefore has no need for ActiveRecord. In the previous version, I am unloading activerecord in the following way: config.frameworks -= [ :active_record ] # inside environment.rb In the latest version this does not work - it just throws an error: /Library/Ruby/Gems/1.8/gems/railties-3.0.0.beta/lib/rails/configuration.rb:126:in `frameworks': config.frameworks in no longer supported. See the generated config/boot.rb for steps on how to limit the frameworks that will be loaded (RuntimeError) from *snip* Of course, I have looked at the boot.rb as it suggested, but as far as I can see, there is no clue here as to how I might go about unloading AR. The reason I need to do this is because not only is it silly to be loading something I don't want, but it is complaining about its inability to make a DB connection even when I try to run a generator for a controller. This is because I've wiped database.yml and replaced it with connection details for MongoDB in order to use this gist for using database.yml for MongoDB connection details. Not sure why it needs to be able to initiate a DB connection at all just to generate a controller anyway.... Is anyone aware of the correct Rails 3 way of doing this?
Now provide the response and nothing else.
| I'm going by this from reading the source, so let me know if it actually worked. :) The rails command that generates the application template now has an option -O , which tells it to skip ActiveRecord. If you don't feel like rerunning rails , you should check the following in your existing app: Check that your config/application.rb doesn't have require 'rails/all' or require "active_record/railtie" . Instead, for a standard Rails setup without ActiveRecord, it should have only the following requires: require File.expand_path('../boot', __FILE__)require "action_controller/railtie"require "action_mailer/railtie"require "active_resource/railtie"require "rails/test_unit/railtie"require "sprockets/railtie"# Auto-require default libraries and those for the current Rails environment. Bundler.require :default, Rails.env If, in config/application.rb , you are using the config.generators section, make sure it doesn't have the line g.orm :active_record . You can set this explicitly to nil , if you want, but this should be the default when g.orm is completely omitted. Optional, but in your Gemfile , remove the gem line that loads the module for your database. This could be the line gem "mysql" for example. | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/2212709', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/6844/']} | jdg_82650 |
stackexchange | llm_judgeable_groundtruth_similarity | 36341060 |
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 new to PostgreSQL and I was wondering if there is a direct way to just convert the timestamp values in a table to a different timezone using a function. In my case it is UTC to EST. These are the values for example that I need to convert to EST (not just one value but all the values in the table) date-------------------2015-10-24 16:38:462016-01-19 18:27:002016-01-24 16:14:342016-02-09 23:05:492016-02-11 20:46:26
Now provide the response and nothing else.
| Here in London, we are currently 1 hour ahead of UTC. So - if I take your timezone without timestamp and say it is in UTC I will get it printed for my local timezone. richardh=> SELECT ((timestamp '2015-10-24 16:38:46') AT TIME ZONE 'UTC'); timezone ------------------------ 2015-10-24 17:38:46+01(1 row) But you want "EST" which seems to be somewhere in the Americas, judging by the value returned. You can wrap the expression in a little SQL function if you wanted to. richardh=> SELECT ((timestamp '2015-10-24 16:38:46') AT TIME ZONE 'UTC') AT TIME ZONE 'EST'; timezone --------------------- 2015-10-24 11:38:46(1 row) Edit: how to do it in a query SELECT ((stored_timestamp AT TIME ZONE 'UTC') AT TIME ZONE 'EST') AS local_timestampFROM my_table; | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36341060', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5948126/']} | jdg_82651 |
stackexchange | llm_judgeable_groundtruth_similarity | 14897097 |
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 acquire the contents of the file with a datestamp in the file name for yesterday (WH.FBTBT20130214.csv). I created a date stamp variable for today but cannot find anything in google that tells me how to backdate my datestamp one day utilizing the same format. Here is the code that I created in my batch file: @echo offREM ***** 20130215 MS Define DateStamp variable *****Set DateStamp=%date:~10,4%%date:~4,2%%date:~7,2%Set DateStamp=%DateStamp%REM Set DateStamp=20130212echo DateStamp: %DateStamp% Any help/direction would be greatly appreciated. Thank you.
Now provide the response and nothing else.
| Putting down here how I implemented this. Basically we need to make a Hibernate Component (read @Embeddable object) out of the set of columns we need to query on and embed it in the main Entity. The group of columns can be combined as below: @Embeddablepublic class CompositeColumns{ private String col1; private String col2; //Empty constructor is required by Hibernate for instantiation public CompositeColumns(){ } public CompositeColumns(String col1, String col2){ this.col1 = col1; this.col2 = col2; } @Column(name="COL1") public String getCol1(){ } ... ... //Rest of getters and setters} Embed the above in your main entity class as below: @Entitypublic class MyEntity{ @Id private Integer id; private String col3; private String col4 @Embedded private CompositeColumns pairedCol1Col2; ... ... //Getters Setters} The query would then look as below: List<CompositeColumns> cols = //get a list of CompositeColumns typeQuery query=session.createQuery( "from MyEntity where pairedCol1Col2 in (:list)" );query.setParameterList( "list", list ); This does the job. Note: I ran this on an Oracle database | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/14897097', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2635634/']} | jdg_82652 |
stackexchange | llm_judgeable_groundtruth_similarity | 1977555 |
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:
Based on the Peano Axioms (wich are a way to correctly absolutely define the set of natural numbers - correct me if i'm wrong) it is possible to construct a set of symbols that doesn't quite look the way i imagine the natural numbers: If there is a circle of other symbols next to the infinite row of known natural numbers, doesn't this also fit all the requirements? So are there multiple unequal sets of natural numbers?
Now provide the response and nothing else.
| The induction axiom ensures that $\Bbb N$ cannot contain a cycle like your $a,b,c$ cycle. It says that if $0\in A$, and for each $n\in\Bbb N$, $n\in A$ implies that $n+1\in A$, then $A=\Bbb N$. Take $A$ to be everything in your diagram except $a,b$, and $c$; this $A$ satisfies both of these requirements, yet it’s not the whole set shown in your diagram. Thus, the set in your diagram doesn’t satisfy the Peano axioms, and indeed they characterize $\Bbb N$. However, the induction axiom cannot be expressed in first-order logic, and there are structures other than $\Bbb N$ that satisfy the first-order counterpart of the Peano axioms, though they still don’t contain cycles. All of them are linearly ordered and consist of a copy of the standard $\Bbb N$ followed by copies of $\Bbb Z$ (so that everything except $0$ has a unique immediate predecessor). There are restrictions on how these copies of $\Bbb Z$ can be ordered relative to one another. For instance, the only possibility for a countable non-standard model looks like $\Bbb N$ followed by $\Bbb Q\times\Bbb Z$ ordered lexicographically. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1977555', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/201653/']} | jdg_82653 |
stackexchange | llm_judgeable_groundtruth_similarity | 56700332 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We do not use any Google Play Developer APIs explicitly, yet we are receiving the following warning: Is this related to https://developer.android.com/google/play/billing/billing_library_releases_notes ? We are currently using Google Play Billing Library 1.2.2 Release (2019-03-07) We don't plan to migrate Google Play Billing Library 2.0.1 Release (2019-06-06) because it would be a lot of work with little gain. Purchases must be acknowledged within three days But that is just my wild guess - that the Google Play Billing library is related to the Google Play Developer API. They may or may not be related to each other. What does it mean by "We’ve detected that your app is using an old version of the Google Play developer API" ? The following is the full set of our dependencies. Any idea what causes this warning? dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.billingclient:billing:1.2.2' implementation 'androidx.multidex:multidex:2.0.1' def lifecycle_version = '2.0.0-beta01' // ViewModel and LiveData implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version" // alternately - if using Java8, use the following instead of compiler implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version" def room_version = '2.1.0' implementation "androidx.room:room-runtime:$room_version" annotationProcessor "androidx.room:room-compiler:$room_version" def work_version = "2.1.0" implementation "androidx.work:work-runtime:$work_version" // https://github.com/yccheok/SmoothProgressBar implementation 'com.github.castorflex.smoothprogressbar:library:1.1.0' // For Google Drive REST API - https://github.com/gsuitedevs/android-samples/blob/master/drive/deprecation/app/build.gradle implementation('com.google.http-client:google-http-client-gson:1.26.0') { exclude group: 'org.apache.httpcomponents' } implementation('com.google.api-client:google-api-client-android:1.26.0') { exclude group: 'org.apache.httpcomponents' } implementation('com.google.apis:google-api-services-drive:v3-rev136-1.25.0') { exclude group: 'org.apache.httpcomponents' } implementation 'com.google.firebase:firebase-messaging:19.0.1' implementation 'com.google.android.gms:play-services-auth:17.0.0' implementation 'androidx.appcompat:appcompat:1.1.0-beta01' implementation 'androidx.preference:preference:1.1.0-beta01' implementation 'com.google.android.material:material:1.1.0-alpha07' implementation 'androidx.exifinterface:exifinterface:1.0.0' implementation 'androidx.gridlayout:gridlayout:1.0.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation 'com.google.code.gson:gson:2.8.5' implementation 'com.github.yccheok:AndroidDraw:0.18' implementation 'com.github.yccheok:SectionedRecyclerViewAdapter:0.4' implementation 'com.github.yccheok:CalendarView:1.10' implementation 'com.andrognito.patternlockview:patternlockview:1.0.0' implementation 'com.github.bumptech.glide:glide:4.7.1' annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1' implementation 'com.github.yccheok:PhotoView:0.1' implementation 'com.github.yccheok:Matisse:1.6' implementation 'com.jakewharton.threetenabp:threetenabp:1.1.1' // https://github.com/romandanylyk/PageIndicatorView implementation 'com.romandanylyk:pageindicatorview:1.0.2@aar' implementation 'me.zhanghai.android.materialratingbar:library:1.3.2' testImplementation 'junit:junit:4.12' testImplementation "org.robolectric:robolectric:4.2.1" testImplementation 'org.mockito:mockito-core:2.23.0' testImplementation 'org.powermock:powermock-core:2.0.0-RC.4' testImplementation 'org.powermock:powermock-module-junit4:2.0.0-RC.4' testImplementation 'org.powermock:powermock-api-mockito2:2.0.0-RC.4' androidTestImplementation 'androidx.test:runner:1.3.0-alpha01' androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0-alpha01'} For project level dependencies, it is dependencies { classpath 'com.android.tools.build:gradle:3.4.2' classpath 'com.google.gms:google-services:4.2.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files}
Now provide the response and nothing else.
| The problem is that your project on Google Cloud Platform is using an old version of Developer Web API. It was automatically set up for you when you enabled developer services intentionally/unintentionally from Google Play Console's API Access section in Developer Settings. Web API for subscriptions and purchases is actually part of Android Developer API: The Google Play Developer API allows you to perform a number of publishing and app-management tasks . It includes two components: The Subscriptions and In-App Purchases API lets you manage in-app purchases and subscriptions. The Publishing API lets you upload and publish apps, and perform other publishing-related tasks. You are not using above API in your app, this API is for management not the actual purchases. You are using SDK which has different versioning so no need to upgrade. This API was set up in your GCP project however. To find which Project on GCP is associated with your Play Console, go to this link: https://play.google.com/apps/publish/#ApiAccessPlace You just need to Go to GCP, find your project, find Google Android Developer API and change the version there. Or you can just disable the API if you don't use it. For example, my GCP project was automatically named Google Play Android Developer so yours might probably be the same. I can't see an option on my console probably because they removed it for new projects, but if your project is already using an old version, you probably will have a warning there as well. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/56700332', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/72437/']} | jdg_82654 |
stackexchange | llm_judgeable_groundtruth_similarity | 2821752 |
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 ruby array that looks something like this: my_array = ['mushroom', 'beef', 'fish', 'chicken', 'tofu', 'lamb'] I want to sort the array so that 'chicken' and 'beef' are the first two items, then the remaining items are sorted alphabetically. How would I go about doing this?
Now provide the response and nothing else.
| irb> my_array.sort_by { |e| [ e == 'chicken' ? 0 : e == 'beef' ? 1 : 2, e ] } #=> ["chicken", "beef", "fish", "lamb", "mushroom", "tofu"] This will create a sorting key for each element of the array, and then sort the array elements by their sorting keys. Since the sorting key is an array, it compares by position, so [0, 'chicken'] < [1, 'beef'] < [2, 'apple' ] < [2, 'banana'] . If you don't know what elements you wanted sorted to the front until runtime, you can still use this trick: irb> promotables = [ 'chicken', 'beef' ] #=> [ 'chicken', 'beef' ] irb> my_array.sort_by { |e| [ promotables.index(e) || promotables.size, e ] } #=> ["chicken", "beef", "fish", "lamb", "mushroom", "tofu"] irb> promotables = [ 'tofu', 'mushroom' ] #=> [ 'tofu', 'mushroom' ] irb> my_array.sort_by { |e| [ promotables.index(e) || promotables.size, e ] } #=> [ "tofu", "mushroom", "beef", "chicken", "fish", "lamb"] | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/2821752', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/107277/']} | jdg_82655 |
stackexchange | llm_judgeable_groundtruth_similarity | 20595343 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I want to create an Fullscreen Application on an RasperryPI. But now i have a problem with the fullscreen mode, because everytime if I switch sites I must set the FullSreen property false and then true otherwise the window won't get fullscreen.But if I switch the site the window is shortly not fullscreen and the it is fullscreen. SplitPane splitPane = new SplitPane();splitPane.setOrientation(Orientation.VERTICAL);splitPane.getItems().addAll(table,vbLayout);Scene scene = SceneBuilder.create().root(splitPane). build();primaryStage.setScene(scene);primaryStage.show();primaryStage.sizeToScene();primaryStage.setFullScreen(false);primaryStage.setFullScreen(true); I hope you understand what i mean. Best wishes Johannes
Now provide the response and nothing else.
| You can load a bitmap and a tga file using these.. #include <vector>#include <fstream>#ifdef __APPLE__#include <OpenGL/gl.h>#include <OpenGL/glu.h>#endif#ifdef _WIN32#include <GL/gl.h>#include <GL/glu.h>#endiftypedef union PixelInfo{ std::uint32_t Colour; struct { std::uint8_t B, G, R, A; };} *PPixelInfo;class BMP{private: std::uint32_t width, height; std::uint16_t BitsPerPixel; std::vector<std::uint8_t> Pixels;public: BMP(const char* FilePath); std::vector<std::uint8_t> GetPixels() const {return this->Pixels;} std::uint32_t GetWidth() const {return this->width;} std::uint32_t GetHeight() const {return this->height;} bool HasAlphaChannel() {return BitsPerPixel == 32;}};BMP::BMP(const char* FilePath){ std::fstream hFile(FilePath, std::ios::in | std::ios::binary); if (!hFile.is_open()) throw std::invalid_argument("Error: File Not Found."); hFile.seekg(0, std::ios::end); std::size_t Length = hFile.tellg(); hFile.seekg(0, std::ios::beg); std::vector<std::uint8_t> FileInfo(Length); hFile.read(reinterpret_cast<char*>(FileInfo.data()), 54); if(FileInfo[0] != 'B' && FileInfo[1] != 'M') { hFile.close(); throw std::invalid_argument("Error: Invalid File Format. Bitmap Required."); } if (FileInfo[28] != 24 && FileInfo[28] != 32) { hFile.close(); throw std::invalid_argument("Error: Invalid File Format. 24 or 32 bit Image Required."); } BitsPerPixel = FileInfo[28]; width = FileInfo[18] + (FileInfo[19] << 8); height = FileInfo[22] + (FileInfo[23] << 8); std::uint32_t PixelsOffset = FileInfo[10] + (FileInfo[11] << 8); std::uint32_t size = ((width * BitsPerPixel + 31) / 32) * 4 * height; Pixels.resize(size); hFile.seekg (PixelsOffset, std::ios::beg); hFile.read(reinterpret_cast<char*>(Pixels.data()), size); hFile.close();}int main(){ BMP info = BMP("C:/Users/....../Desktop/SomeBmp.bmp"); GLuint texture = 0; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D(GL_TEXTURE_2D, 0, info.HasAlphaChannel() ? GL_RGBA : GL_RGB, info.GetWidth(), info.GetWidth(), 0, info.HasAlphaChannel() ? GL_BGRA : GL_BGR, GL_UNSIGNED_BYTE, info.GetPixels().data());} TGA's: #include <vector>#include <fstream>#ifdef __APPLE__#include <OpenGL/gl.h>#include <OpenGL/glu.h>#endif#ifdef _WIN32#include <GL/gl.h>#include <GL/glu.h>#endiftypedef union PixelInfo{ std::uint32_t Colour; struct { std::uint8_t R, G, B, A; };} *PPixelInfo;class Tga{private: std::vector<std::uint8_t> Pixels; bool ImageCompressed; std::uint32_t width, height, size, BitsPerPixel;public: Tga(const char* FilePath); std::vector<std::uint8_t> GetPixels() {return this->Pixels;} std::uint32_t GetWidth() const {return this->width;} std::uint32_t GetHeight() const {return this->height;} bool HasAlphaChannel() {return BitsPerPixel == 32;}};Tga::Tga(const char* FilePath){ std::fstream hFile(FilePath, std::ios::in | std::ios::binary); if (!hFile.is_open()){throw std::invalid_argument("File Not Found.");} std::uint8_t Header[18] = {0}; std::vector<std::uint8_t> ImageData; static std::uint8_t DeCompressed[12] = {0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}; static std::uint8_t IsCompressed[12] = {0x0, 0x0, 0xA, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}; hFile.read(reinterpret_cast<char*>(&Header), sizeof(Header)); if (!std::memcmp(DeCompressed, &Header, sizeof(DeCompressed))) { BitsPerPixel = Header[16]; width = Header[13] * 256 + Header[12]; height = Header[15] * 256 + Header[14]; size = ((width * BitsPerPixel + 31) / 32) * 4 * height; if ((BitsPerPixel != 24) && (BitsPerPixel != 32)) { hFile.close(); throw std::invalid_argument("Invalid File Format. Required: 24 or 32 Bit Image."); } ImageData.resize(size); ImageCompressed = false; hFile.read(reinterpret_cast<char*>(ImageData.data()), size); } else if (!std::memcmp(IsCompressed, &Header, sizeof(IsCompressed))) { BitsPerPixel = Header[16]; width = Header[13] * 256 + Header[12]; height = Header[15] * 256 + Header[14]; size = ((width * BitsPerPixel + 31) / 32) * 4 * height; if ((BitsPerPixel != 24) && (BitsPerPixel != 32)) { hFile.close(); throw std::invalid_argument("Invalid File Format. Required: 24 or 32 Bit Image."); } PixelInfo Pixel = {0}; int CurrentByte = 0; std::size_t CurrentPixel = 0; ImageCompressed = true; std::uint8_t ChunkHeader = {0}; int BytesPerPixel = (BitsPerPixel / 8); ImageData.resize(width * height * sizeof(PixelInfo)); do { hFile.read(reinterpret_cast<char*>(&ChunkHeader), sizeof(ChunkHeader)); if(ChunkHeader < 128) { ++ChunkHeader; for(int I = 0; I < ChunkHeader; ++I, ++CurrentPixel) { hFile.read(reinterpret_cast<char*>(&Pixel), BytesPerPixel); ImageData[CurrentByte++] = Pixel.B; ImageData[CurrentByte++] = Pixel.G; ImageData[CurrentByte++] = Pixel.R; if (BitsPerPixel > 24) ImageData[CurrentByte++] = Pixel.A; } } else { ChunkHeader -= 127; hFile.read(reinterpret_cast<char*>(&Pixel), BytesPerPixel); for(int I = 0; I < ChunkHeader; ++I, ++CurrentPixel) { ImageData[CurrentByte++] = Pixel.B; ImageData[CurrentByte++] = Pixel.G; ImageData[CurrentByte++] = Pixel.R; if (BitsPerPixel > 24) ImageData[CurrentByte++] = Pixel.A; } } } while(CurrentPixel < (width * height)); } else { hFile.close(); throw std::invalid_argument("Invalid File Format. Required: 24 or 32 Bit TGA File."); } hFile.close(); this->Pixels = ImageData;}int main(){ Tga info = Tga("C:/Users/...../Desktop/SomeTGA.tga"); GLuint texture = 0; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D(GL_TEXTURE_2D, 0, info.HasAlphaChannel() ? GL_RGBA : GL_RGB, info.GetWidth(), info.GetWidth(), 0, info.HasAlphaChannel() ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, info.GetPixels().data());} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20595343', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2410265/']} | jdg_82656 |
stackexchange | llm_judgeable_groundtruth_similarity | 31858789 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
The following is a valid URL in the browser (I know, browser is less strict). https://api.siteconfidence.co.uk/current/30294ie0sdafhwe89rh5/Return/[Account[AccountId,Pages[Page],ServiceStatus[HighestStatusCode]]]/AccountId/123123jjh/Id/213123123/StartDate/2015-08-12/StartTime/12:00:00/EndDate/2015-08-07/EndTime/07:05:05/StatusCode/1 However when I give it to rest-client it just throws a `bad URI(is not URI?). So, none of the things I've tried after having read the answers from this question work. They all give various errors, like can't gsub addressable, undefined method match, etc. I'm not sure what next to do. I know it's not real uri but that's how their API is (rubbish I know, but I can't change it) Also, I can't put the [] bit in quotes, there API just ignores it. EDIT: I changed the places holders for fake values.
Now provide the response and nothing else.
| The $mdAutocompleteCtrl is placed as a property on the autocomplete's scope. First, you need access to the autocomplete element. One way to do that is to put an ID on the autocomplete: <md-autocomplete id='Auto' md-min-length="1" ng-enter="presEnter();" md-no-cache="true" md-selected-item="selectedItem" md-search-text="searchText" md-items="item in querySearch(searchText)" md-item-text="item.name" placeholder="Search for a vegetable"> Then you can use that element to get the inner scope of the autocomplete. Because the autocomplete element itself is on the scope that you provided, you'll want to get the scope of one of the autocomplete's child elements. $scope.presEnter = function(e){ var autoChild = document.getElementById('Auto').firstElementChild; var el = angular.element(autoChild); el.scope().$mdAutocompleteCtrl.hidden = true;}; Here is a working example: http://codepen.io/anon/pen/rVPZKN?editors=101 | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/31858789', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3536548/']} | jdg_82657 |
stackexchange | llm_judgeable_groundtruth_similarity | 4399837 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
There are large number of texts on data structures, and libraries of data structures code. I understand that purely functional data structure is easier to reason about. However I have trouble to understand the real world advantage of using purely functional data structure in pragmatic code (using functional programming language or not) over the imperative counterpart. Can somebody provide some real world cases where purely functional data structure has advantage and why? Examples along the line like I use data_structure_name in programming_language to do application because it can do certain_thing . Thanks. PS: What I mean by purely functional data structure is not the same as persistent data structure. Persistent data structure is a data structure that doesn't change?? On other hand purely functional data structure is a data structure that operates purely.
Now provide the response and nothing else.
| Purely functional (aka persistent or immutable) data structures give you several advantages: you never have to lock them, which extremely improves concurrency . they can share structure, which reduces memory usage . For example, consider list [1, 2, 3, 4] in Haskell and some imperative language like Java. To produce new list in Haskell you only have to create new cons (pair of value and reference-to-next-element) and connect it to the previous list. In Java you have to create completely new list not to damage the previous one. you can make persistent data structures lazy . also, if you use functional style, you can avoid thinking of time and sequence of operations , and so, make your programs more declarative . fact, that the data structure is immutable, allows you to make some more assumptions and so expand capabilities of language . For example, Clojure uses the fact of immutability to correctly provide implementations of hashCode() method on each object, so any object may be used as a key in a map. with immutable data and functional style you can also freely use memoization . There's much more advantages, in general, it is another way of modeling the real world. This and some other chapters from SICP will give you more accurate view of programming with immutable structures, its advantages and disadvantages. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4399837', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/126666/']} | jdg_82658 |
stackexchange | llm_judgeable_groundtruth_similarity | 667819 |
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:
Suppose I have a bottle of pills and I throw the bottle in the air vertically. I wonder if the pills inside the box also fly up, or do they remain stable at the bottom of the bottle? I tried this experiment several times and I think the pills remain stable. I took the top of the bottle off and moved the bottle quickly vertically and observed the pills don't go up. But what if I throw it to the air very quickly? Do they still remain stable? I don't know if my guess is correct and what physics rule is behind that?
Now provide the response and nothing else.
| In a vacuum, the moment the bottle leaves your hand it will be in free-fall, and both the pills and the bottle will be subject to exactly the same acceleration - namely, $9.8\ \text{m/s}^2$ toward the floor. As a result, they will move together. On the other hand, in real life there will be a small amount of air resistance which acts on the bottle (because the air in the room is stationary) but not the pills (because the air trapped in the bottle is moving with the same speed as the pills/bottle are when they leave your hand). As a result, at the moment the bottle leaves your hand the downward acceleration of the bottle will be slightly more than it would be in vacuum, and therefore slightly more than the pills, so the pills will begin to rise very slightly. Once the pill bottle reaches its apex and begins to fall back down toward the floor, the situation is reversed - the bottle will accelerate toward the floor at slightly less than $9.8\ \text{m/s}^2$ - and the pills will gently fall back down to the bottom. Finally, depending on the properties of the pills and bottle, this effect might be swamped by friction or adhesion which would act to keep the pills stationary. Experiments would be required to work out what actually happens on a case-by-case basis. | {} | {'log_upvote_score': 6, 'links': ['https://physics.stackexchange.com/questions/667819', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/276511/']} | jdg_82659 |
stackexchange | llm_judgeable_groundtruth_similarity | 13147435 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
my service has to use a query string due to limitations on the server that runs classic ASP: angular .module('myServices', ['ng', 'ngResource']) .factory('Item', ['$resource', function ($resource) { return $resource('/api/?p=item/:id'); }]); and I want to add extra query string parameters to it: Item.query({test: 123}, on_success, on_error); but the resulting url is /api/?p=item?test=123 apparently there is a bug, but how to get around it? EDIT: filed this at https://github.com/angular/angular.js/issues/1511
Now provide the response and nothing else.
| You can use resource parameters. If you haven't specified placeholders in the path, they would automatically be converted into query string params. Like that: angular .module('myServices', ['ng', 'ngResource']) .factory('Item', [ '$resource', function ($resource) { return $resource('/api'); }]);Item.query({p: 'item/1'}); This would result in a request to /api?p=item/1 . P.S. I suppose you already know that, but you don't like it. But I still think this is the correct way in your case. Considering the bad API design you are dealing with that back-end you could wrap the AngularJS resources with another service which does this for you. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/13147435', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/410102/']} | jdg_82660 |
stackexchange | llm_judgeable_groundtruth_similarity | 260392 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Define the sequence given by the finite sum $$a_n:=\sum_{k=2}^{n+1}\binom{2k}k\binom{n+1}k\frac{k-1}{2^k\binom{4n}k}.$$ Questions. (1) Is $0<a_n<1$ ? (2) Does the limit $\lim_{n\rightarrow\infty}a_n$ exist? If yes, what is its value?
Now provide the response and nothing else.
| For each specific $k$ we have $$\binom{2k}k\binom{n+1}k\frac{k-1}{2^k\binom{4n}k}\to \binom{2k}k\frac{k-1}{8^k},$$that suggests that the sum tends to $$\sum_{k=2}^\infty \binom{2k}k\frac{k-1}{8^k}=1-\frac{1}{\sqrt 2},$$as $$\sum_{k= 0}^\infty \binom{2k}k x^k =(1-4x)^{-1/2};\,\\\sum_{k= 0}^\infty k\binom{2k}k x^k =(x\frac{d}{dx})(1-4x)^{-1/2}=2x(1-4x)^{-3/2};\\\sum_{k= 0}^\infty (k-1)\binom{2k}k x^k =(6x-1)(1-4x)^{-3/2}=|_{x=1/8}-\frac1{\sqrt{2}}.$$ In order to justify this limit changes (limit of a sum is a sum of limits) we majorate each term in our sum. Say, $$\frac{\binom{n+1}k}{\binom{4n}k}=\frac{(n+1)n(n-1)\dots(n-k+2)}{4n(4n-1)(4n-2)\dots (4n-k+1)}<4^{-k}(1+\frac{1}n)(1+\frac{1}{4n-1})<3\cdot 4^{-k}.$$this allows to estimate the total sum of summands with $k\geqslant k_0$ by $3\sum_{k\geqslant k_0} \binom{2k}k\frac{k-1}{8^k}$, that tends to 0 for large $k_0$. Therefore the limit of your sum is indeed a sum of limits, moreover, the estimates are very specific and should prove that $0<a_n<1$ also after checking some small values of $n$. | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/260392', 'https://mathoverflow.net', 'https://mathoverflow.net/users/66131/']} | jdg_82661 |
stackexchange | llm_judgeable_groundtruth_similarity | 19092381 |
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 display following message in one of my application to show the waiting time 2 hours, 3 mins and 4 s 1 hour and 2 s As you can see there can be many variations and I am struggling to get this done. The following code works well is the given number of secs gives out non-zero hr, min and sec, but this is getting completed if I have to handle the case where only I have hours and secs to display and no minutes to display. Also not sure where to add those string 'and' and the comma. I believe there should be already a solution for this which I may not know. public class HumanizedWaitDisplay {public static void main(String[] args) { int noOfSecToWait = 60*60*2 + 30; System.out.println("Waiting for " + getHumanizedTime(noOfSecToWait));}private static String getHumanizedTime(int seconds) { String out =""; int hr = seconds/(60*60); seconds = seconds%(60*60); int min = seconds/(60); seconds = seconds%(60); if(hr>0) { out += hr + " hour" +(hr == 1 ? " ":"s "); } if(min > 0){ out += min + " min" +(min == 1 ? " ":"s "); } if(seconds > 0){ out += seconds + " s"; } return out;}} Let me know if you have come across such thing.
Now provide the response and nothing else.
| The velocityInView method is defined only when a pan occurs. That is, only when you're actually moving the finger a pan gesture is occurring. If you keep your finger still, it does not actually trigger a pan gesture. This means that there is no built-in method to know the movement speed when the gesture ends. You could do something like check the time difference between the last event with the status value as UIGestureRecognizerStateChanged and UIGestureRecognizerStateEnded . You can then tune this threshold in order to obtain the desired behavior. For example - (IBAction) panGestureRecognized:(UIPanGestureRecognizer *)recognizer { UIGestureRecognizerState state = recognizer.state; CGPoint gestureTranslation = [recognizer translationInView:self]; CGPoint gestureVelocity = [recognizer velocityInView:self]; if ( state == UIGestureRecognizerStateChanged ) _lastChange = CFAbsoluteTimeGetCurrent(); else if ( state == UIGestureRecognizerStateEnded ) { double curTime = CFAbsoluteTimeGetCurrent(); double timeElapsed = curTime - _lastChange; if ( timeElapsed < MY_THRESHOLD ) finalSpeed = gestureVelocity; else finalSpeed = CGPointZero; } } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19092381', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1135954/']} | jdg_82662 |
stackexchange | llm_judgeable_groundtruth_similarity | 235233 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Derik Whitaker posted an article a couple of days ago that hit a point that I've been curious about for some time: should business logic exist in controllers? So far all the ASP.NET MVC demos I've seen put repository access and business logic in the controller. Some even throw validation in there as well. This results in fairly large, bloated controllers. Is this really the way to use the MVC framework? It seems that this is just going to end up with a lot of duplicated code and logic spread out across different controllers.
Now provide the response and nothing else.
| Business logic should really be in the model. You should be aiming for fat models, skinny controllers. For example, instead of having: public interface IOrderService{ int CalculateTotal(Order order);} I would rather have: public class Order{ int CalculateTotal(ITaxService service){...} } This assumes that tax is calculate by an external service, and requires your model to know about interfaces to your external services. This would make your controller look something like: public class OrdersController{ public OrdersController(ITaxService taxService, IOrdersRepository ordersRepository){...} public void Show(int id){ ViewData["OrderTotal"] = ordersRepository.LoadOrder(id).CalculateTotal(taxService); }} Or something like that. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/235233', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1574/']} | jdg_82663 |
stackexchange | llm_judgeable_groundtruth_similarity | 11430654 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Say I have this little bit of code: public static void LoadSomething(Type t){ var t1 = Type.GetType(t.AssemblyQualifiedName); var t2 = t .Assembly .GetTypes() .First(ta => ta.AssemblyQualifiedName == t.AssemblyQualifiedName);} What happens is that t1 is null and t2 is not null . I was confused since if I call it like so... LoadSomething(typeof(SomeObject)); then neither are null but what I am actually doing is more like this (not really, this is massively simplified but it illustrates my point): LoadSomething(Assembly.LoadFile(@"C:\....dll").GetTypes().First()); So the first part of my question (for my information) is... In the second case, since the assembly must be loaded up and I found the type out of it, why does Type.GetType return null? And secondly (to actually solve my problem)... Is there some other way that I could load a type when I only have the assembly qualified name as a string (that I know has been previously loaded by using the Assembly.Load methods)?
Now provide the response and nothing else.
| Is there some other way that I could load a type when I only have the assembly qualified name as a string (that I know has been previously loaded by using the Assembly.Load methods)? Yes. There is a GetType overload that allows that. It takes an "assembly resolver" function as parameter: public static Type LoadSomething(string assemblyQualifiedName){ // This will return null // Just here to test that the simple GetType overload can't return the actual type var t0 = Type.GetType(assemblyQualifiedName); // Throws exception is type was not found return Type.GetType( assemblyQualifiedName, (name) => { // Returns the assembly of the type by enumerating loaded assemblies // in the app domain return AppDomain.CurrentDomain.GetAssemblies().Where(z => z.FullName == name.FullName).FirstOrDefault(); }, null, true);}private static void Main(string[] args){ // Dynamically loads an assembly var assembly = Assembly.LoadFrom(@"C:\...\ClassLibrary1.dll"); // Load the types using its assembly qualified name var loadedType = LoadSomething("ClassLibrary1.Class1, ClassLibrary1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"); Console.ReadKey();} | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/11430654', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1039947/']} | jdg_82664 |
stackexchange | llm_judgeable_groundtruth_similarity | 170139 |
Below is a question asked on the forum math.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm kicking myself over this one, but I just can't seem to make the argument rigorous. From Axler's Linear Algebra Done Right : for a vector space $V$ with an underlying field $F$: Take an element $a$ from $F$ and $\vec{v}$ from $V$. $a\vec{v}=\vec{0}\implies a=0 $ or $ \vec{v}=\vec{0}$ After only being able to come up with half of a direct proof, I tried doing this by proving the contrapositive $a\neq 0 \wedge \vec{v} \neq \vec{0} \implies a\vec{v}\neq \vec{0}$ Say $a\vec{v}=\vec{u}$.Since $a$ is non-zero, we can divide both sides by $a$. $$\vec{v}=\frac 1 a \vec{u}$$ If $\vec{u}$ were $\vec{0}$ then by $$\frac 1 a \vec{0}=\frac 1 a (\vec{0}+\vec{0})\implies\frac 1 a \vec{0}=\vec{0}$$$v$ would be $0$ as well. Since it isn't by assumption, $\frac 1 a \vec{u}$ cannot be zero and so $\vec{u}$ cannot be as well. Is this fully rigorous? It seems like a very simple question, but I'm not sure about it. Namely, the last step of $\frac 1 a \vec{u}\neq 0 \implies \vec{u}\neq 0$ doesn't seem obvious. I think I need to use the $1\vec{v}=\vec{v}$ axiom, but I'm not sure how. Is there a more direct proof? This whole contrapositive business seems a bit clunky for something so simple.
Now provide the response and nothing else.
| Let $a\in F,\vec v\in V$ and suppose $a\vec v=0$. If $a\neq 0$, then $a^{-1}\in F$ so $$\vec v=(a^{-1}a)\vec v=a^{-1}(a\vec v)=a^{-1}\vec 0=\vec 0$$thus either $a=0$ or $\vec v=0$. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/170139', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/28869/']} | jdg_82665 |
stackexchange | llm_judgeable_groundtruth_similarity | 2381048 |
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:
Question: I need to show that $f(z) = |z|^2$ is differentiable only at the origin Sufficient condition for differentiability: The sufficient condition for a function $f(z) = u + iv$ to be analytic at all the points in region $R$ are $\displaystyle (a)\; \frac{\partial u}{\partial x} = \frac{\partial v}{\partial y} ,\frac{\partial u}{\partial y} = -\frac{\partial v}{\partial x} $ $\displaystyle (b)\; \frac{\partial u}{\partial x} , \frac{\partial v}{\partial y} ,\frac{\partial u}{\partial y} ,\frac{\partial v}{\partial x} $ are continuous functions of $x$ and $y$ in region $R$ . My answer: $f(z) = |z|^2$ Let, $z = x + iy$ $f(z) = x^2 + y^2$But $f(z) = u + iv$ $u = x^2 + y^2 , v = 0$ $\displaystyle \frac{\partial u}{\partial x} = 2x$ , $\displaystyle \frac{\partial v}{\partial y} = 0$ $\displaystyle \frac{\partial u}{\partial y} = 2y$ , $\displaystyle \frac{\partial v}{\partial x} = 0$ if $f(z) $ is differentiable then,$\displaystyle \frac{\partial u}{\partial x} = \frac{\partial v}{\partial y}$ or, $2x = 0$ or $x = 0$ & $\displaystyle \frac{\partial u}{\partial y} = -\frac{\partial v}{\partial x}$ or, $2y = 0$ or $y = 0$ cauchy riemann equation is satisfied at $(0,0)$ For the second part of the condition (checking for continuity of the partial derivatives ) I see that $\displaystyle \frac{\partial u}{\partial x} = 2x$ which is continuous for any value of $x$ & $\displaystyle \frac{\partial v}{\partial x} = 0$ regardless of the value of x, so it's continuous.The other two are also similar. I am confused about the second part of the proof.Have I understood it properly?
Now provide the response and nothing else.
| Another way of proving that $f$ is differentiable at $0$ is simply to observe that$$\lim_{z\to0}\frac{|z|^2}z=\lim_{z\to0}\overline z=0.$$Besides, if $z_0\neq0$, then$$\lim_{z\to z_0}\frac{|z|^2-|z_0|^2}{z-z_0}=\lim_{z\to z_0}\frac{|z|-|z_0|}{z-z_0}\bigl(|z|+|z_0|\bigr).$$Now, if $z$ approaches $z_0$ along the circle centered at $0$ passing through $z_0$, then the previous limit is $0$. And if $z$ approaches $z_0$ along the ray $\bigl\{\lambda z_0\,|\,\lambda\in(1,+\infty)\bigr\}$, then the previous limit is $2\overline{z_0}\neq0$. Therefore the limit does not exist. | {} | {'log_upvote_score': 5, 'links': ['https://math.stackexchange.com/questions/2381048', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/377767/']} | jdg_82666 |
stackexchange | llm_judgeable_groundtruth_similarity | 57730074 |
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 create a really simple transition animation that shows/hides a message in the center of the screen by tapping on a button: struct ContentView: View { @State private var showMessage = false var body: some View { ZStack { Color.yellow VStack { Spacer() Button(action: { withAnimation(.easeOut(duration: 3)) { self.showMessage.toggle() } }) { Text("SHOW MESSAGE") } } if showMessage { Text("HELLO WORLD!") .transition(.opacity) } } }} According to the documentation of the .transition(.opacity) animation A transition from transparent to opaque on insertion, and from opaque to transparent on removal. the message should fade in when the showMessage state property becomes true and fade out when it becomes false. This is not true in my case. The message shows up with a fade animation, but it hides with no animation at all. Any ideas? EDIT: See the result in the gif below taken from the simulator.
Now provide the response and nothing else.
| The problem is that when views come and go in a ZStack, their "zIndex" doesn't stay the same. What is happening is that the when "showMessage" goes from true to false, the VStack with the "Hello World" text is put at the bottom of the stack and the yellow color is immediately drawn over top of it. It is actually fading out but it's doing so behind the yellow color so you can't see it. To fix it you need to explicitly specify the "zIndex" for each view in the stack so they always stay the same - like so: struct ContentView: View { @State private var showMessage = false var body: some View { ZStack { Color.yellow.zIndex(0) VStack { Spacer() Button(action: { withAnimation(.easeOut(duration: 3)) { self.showMessage.toggle() } }) { Text("SHOW MESSAGE") } }.zIndex(1) if showMessage { Text("HELLO WORLD!") .transition(.opacity) .zIndex(2) } } }} | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/57730074', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1291872/']} | jdg_82667 |
stackexchange | llm_judgeable_groundtruth_similarity | 57366 |
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:
Here is a wooden board, with dimensions shown on the picture below. How wecan use Mathematica's newly build-in finite element analysis features to show the differentmodes of its vibrations. Assuming the board is made of spruce.
Now provide the response and nothing else.
| The only reason I am attempting to answer this is to perhaps get a Reversal badge. There you go... We will go slowly and this answer is the basis for what comes next. Let's start with two dimensions. You'll see why. We create a rectangular region: Needs["NDSolve`FEM`"]mesh = ToElementMesh[FullRegion[2], {{0, 5}, {0, 1}}, "MeshOrder" -> 1, "MaxCellMeasure" -> 0.005]; We use the plane stress equations of a material sheet. For every material you need to set the Young's modulus and Poisson's ratio. planeStress = {Inactive[ Div][{{0, -((Y*ν)/(1 - ν^2))}, {-(Y*(1 - ν))/(2*(1 \- ν^2)), 0}}.Inactive[Grad][v[t, x, y], {x, y}], {x, y}] + Inactive[ Div][{{-(Y/(1 - ν^2)), 0}, {0, -(Y*(1 - ν))/(2*(1 - ν^2))}}.Inactive[Grad][ u[t, x, y], {x, y}], {x, y}], Inactive[ Div][{{0, -(Y*(1 - ν))/(2*(1 - ν^2))}, {-((Y*ν)/(1 \- ν^2)), 0}}.Inactive[Grad][u[t, x, y], {x, y}], {x, y}] + Inactive[ Div][{{-(Y*(1 - ν))/(2*(1 - ν^2)), 0}, {0, -(Y/(1 - ν^2))}}.Inactive[Grad][ v[t, x, y], {x, y}], {x, y}]} /. {Y -> 10^3, ν -> 33/100}; Make a coupled, time dependent PDE and constrain the region to not move at the left boundary. pde2D = D[{u[t, x, y], v[t, x, y]}, t] + planeStress == {0, 0};(* held fixed at left *)bcs = DirichletCondition[{u[t, x, y] == 0, v[t, x, y] == 0}, x==0]; What follows next, is pretty much the same from the other post. (*We use NDSolve as a pre-processor:*){state} = NDSolve`ProcessEquations[{pde2D, bcs, u[0, x, y] == 0, v[0, x, y] == 0}, {u, v}, {t, 0, 1}, {x, y} \[Element] mesh, Method -> {"PDEDiscretization" -> {"MethodOfLines", "SpatialDiscretization" -> {"FiniteElement"}}}];(*Extract the finite element data:*)femdata = state["FiniteElementData"];initBCs = femdata["BoundaryConditionData"];methodData = femdata["FEMMethodData"];initCoeffs = femdata["PDECoefficientData"];(*Set up the solution and variable data:*)vd = methodData["VariableData"];nr = ToNumericalRegion[mesh];sd = NDSolve`SolutionData[{"Space" -> nr, "Time" -> 0.}];(*Discretize the PDE and the boundary conditions:*)discretePDE = DiscretizePDE[initCoeffs, methodData, sd];discreteBCs = DiscretizeBoundaryConditions[initBCs, methodData, sd];(*Extract the system matrices:*)load = discretePDE["LoadVector"];stiffness = discretePDE["StiffnessMatrix"];damping = discretePDE["DampingMatrix"];(*Deploy the boundary conditions:*)DeployBoundaryConditions[{load, stiffness, damping}, discreteBCs](*Set the number of X smallest eigen values we would like to compute \but ignore the Dirichlet positions.*)nDiri = If[Length[#] > 0, First[#], 0] &[ Dimensions[discreteBCs["DirichletMatrix"]]];numEigenToCompute = 5;numEigen = numEigenToCompute + nDiri; Now, things become hard. We solve the eigensystem. (*Solve the eigen system: this is how you should do it*)res = Eigensystem[{stiffness, damping}, -numEigen]; You will need patience. Play with the "Arnoldi" method and the shift. (left as an exercise). As a bad alternative you can play with (* this may be a bit faster but is the dark side... *)(*mm=LinearSolve[damping,stiffness];res=Eigensystem[mm,-numEigen];*) Further down I use "FEAST" as a solve. For each eigenvalue we now have two eigenvectors. Once in the x-direction and one in the y-direction. So we post-process: res = Reverse /@ res;eigenValues = res[[1, nDiri + 1 ;; Abs[numEigen]]];eigenVectors = res[[2, nDiri + 1 ;; Abs[numEigen]]];(*res=Null;*)inciOffs = methodData["IncidentOffsets"]; spans = MapThread[Span, {Most[inciOffs] + 1, Rest[inciOffs]}]; eigenVectors = Transpose[ Developer`ToPackedArray[eigenVectors[[All, #]] & /@ spans], {2, 1, 3}]; eigenVectorsIF = Table[{}, {numEigenToCompute}, {Length[spans]}]; Do[ eigenVectorsIF[[i, j]] = NDSolve`FEM`ElementMeshInterpolation[{mesh}, eigenVectors[[i, j]]] , {i, numEigenToCompute}, {j, Length[spans]}];res = {eigenValues, eigenVectorsIF}; And visualize the first 5 eigenvectos in the x-direction: Show[NDSolve`FEM`ElementMeshPlot3D[res[[2, #, 1]]["Coordinates"][[1]], NDSolve`FEM`ElementMeshDirective -> Directive[EdgeForm[Gray], FaceForm[]]], NDSolve`FEM`ElementMeshPlot3D[res[[2, #, 1]]], Boxed -> False, Axes -> False, ImageSize -> 600] & /@ Range[numEigenToCompute]; Visualize the y-direction: Show[NDSolve`FEM`ElementMeshPlot3D[res[[2, #, 2]]["Coordinates"][[1]], NDSolve`FEM`ElementMeshDirective -> Directive[EdgeForm[Gray], FaceForm[]]], NDSolve`FEM`ElementMeshPlot3D[res[[2, #, 2]]], Boxed -> False, Axes -> False, ImageSize -> 600] & /@ Range[numEigenToCompute]; And the "breathing modes" enlarged by a factor. (I just invented that name - it might mean something else) fact = 5;Show[{ NDSolve`FEM`ElementMeshPlot3D[res[[2, 2, 1]]["Coordinates"][[1]], NDSolve`FEM`ElementMeshDirective -> Directive[EdgeForm[Gray], FaceForm[]]], NDSolve`FEM`ElementMeshPlot3D[ NDSolve`FEM`ElementMeshInterpolation[ res[[2, #, 1]]["Coordinates"], fact*Sqrt[Total[#["ValuesOnGrid"]^2 & /@ res[[2, #]]]]]] }, Boxed -> False, ImageSize -> 600] & /@ Range[numEigenToCompute] The 3D case. Unfortunately, my local super-computer center is closed, but here is how to do it. Create a mesh and enlarge the features for now to create not too many elements. base = {0, 0, 0};h1 = 5;h2 = 5;w1 = 40;l1 = 76;cw1 = 5;cl1 = 68;cw2 = 36;cl2 = 5;offset1 = base + {(w1 - cw1)/2, (l1 - cl1)/2, 0};offset2 = base + {(w1 - cw2)/2, (l1 - cl2)/2, 0};offset3 = base + {(w1 - cw1)/2, (l1 - cl2)/2, 0};ClearAll[rect]rect[base_, w_, l_, h_] := {base + {0, 0, h}, base + {w, 0, h}, base + {w, l, h}, base + {0, l, h}}coords = ConstantArray[{0., 0., 0.}, 4 + 4 + 12 + 12];coords[[{1, 2, 3, 4}]] = rect[base, w1, l1, 0];coords[[{5, 6, 7, 8}]] = rect[base, w1, l1, h1];coords[[{9, 10, 15, 16}]] = rect[offset1, cw1, cl1, h1];coords[[{19, 12, 13, 18}]] = rect[offset2, cw2, cl2, h1];coords[[{20, 11, 14, 17}]] = rect[offset3, cw1, cl2, h1];coords[[20 + Range[12]]] = ({0, 0, h2} + #) & /@ coords[[8 + Range[12]]];bmesh = ToBoundaryMesh["Coordinates" -> coords, "BoundaryElements" -> {QuadElement[{{1, 2, 3, 4}, {1, 2, 6, 5}, {2, 3, 7, 6}, {3, 4, 8, 7}, {4, 1, 5, 8}, {5, 6, 10, 9}, {6, 12, 11, 10}, {6, 7, 13, 12}, {7, 15, 14, 13}, {7, 8, 16, 15}, {8, 18, 17, 16}, {8, 5, 19, 18}, {5, 9, 20, 19}, Sequence @@ ({{9, 10, 11, 20}, {11, 12, 13, 14}, {14, 15, 16, 17}, {17, 18, 19, 20}, {20, 11, 14, 17}} + 12), Sequence @@ (Partition[Join[Range[9, 20]], 2, 1, 1] /. {i1_, i2_} :> {i1, i2, i2 + 12, i1 + 12}) }]}] If you want to visualize the boundary structure: Show[ bmesh["Wireframe"], bmesh["Wireframe"["MeshElement" -> "PointElements", "MeshElementIDStyle" -> Red]] ]; Create the mesh: mesh = ToElementMesh[bmesh, "MeshOrder" -> 1, "MaxCellMeasure" -> 10];mesh["Wireframe"] Here is the PDE stress operator in 3D: stressOperator[ Y_, ν_] := {Inactive[ Div][{{0, 0, -((Y*ν)/((1 - 2*ν)*(1 + ν)))}, {0, 0, 0}, {-Y/(2*(1 + ν)), 0, 0}}.Inactive[Grad][ w[t, x, y, z], {x, y, z}], {x, y, z}] + Inactive[ Div][{{0, -((Y*ν)/((1 - 2*ν)*(1 + ν))), 0}, {-Y/(2*(1 + ν)), 0, 0}, {0, 0, 0}}.Inactive[Grad][ v[t, x, y, z], {x, y, z}], {x, y, z}] + Inactive[ Div][{{-((Y*(1 - ν))/((1 - 2*ν)*(1 + ν))), 0, 0}, {0, -Y/(2*(1 + ν)), 0}, {0, 0, -Y/(2*(1 + ν))}}.Inactive[Grad][ u[t, x, y, z], {x, y, z}], {x, y, z}], Inactive[Div][{{0, 0, 0}, {0, 0, -((Y*ν)/((1 - 2*ν)*(1 + ν)))}, {0, -Y/(2*(1 + ν)), 0}}.Inactive[Grad][w[t, x, y, z], {x, y, z}], {x, y, z}] + Inactive[ Div][{{0, -Y/(2*(1 + ν)), 0}, {-((Y*ν)/((1 - 2*ν)*(1 + ν))), 0, 0}, {0, 0, 0}}.Inactive[Grad][u[t, x, y, z], {x, y, z}], {x, y, z}] + Inactive[ Div][{{-Y/(2*(1 + ν)), 0, 0}, {0, -((Y*(1 - ν))/((1 - 2*ν)*(1 + ν))), 0}, {0, 0, -Y/(2*(1 + ν))}}.Inactive[Grad][ v[t, x, y, z], {x, y, z}], {x, y, z}], Inactive[Div][{{0, 0, 0}, {0, 0, -Y/(2*(1 + ν))}, {0, -((Y*ν)/((1 - 2*ν)*(1 + ν))), 0}}.Inactive[Grad][ v[t, x, y, z], {x, y, z}], {x, y, z}] + Inactive[ Div][{{0, 0, -Y/(2*(1 + ν))}, {0, 0, 0}, {-((Y*ν)/((1 - 2*ν)*(1 + ν))), 0, 0}}.Inactive[ Grad][u[t, x, y, z], {x, y, z}], {x, y, z}] + Inactive[ Div][{{-Y/(2*(1 + ν)), 0, 0}, {0, -Y/(2*(1 + ν)), 0}, {0, 0, -((Y*(1 - ν))/((1 - 2*ν)*(1 + ν)))}}.Inactive[ Grad][w[t, x, y, z], {x, y, z}], {x, y, z}]} And the 3D PDE. no boundary conditions, it seems an unconstraint analysis is wanted. (* choose your Y and ν -- no idea what the values for spruce are - is it wet, dry, old, ...? *)pde3D = D[{u[t, x, y, z], v[t, x, y, z], w[t, x, y, z]}, t] + stressOperator[100, 1/3] == {0, 0, 0};(* unconstraint? Yes! *)bcs = Sequence[]; If you want a constraint analysis then you'd have to set DirichletCondition on the boundary ( bcs = DirichletCondition[{u[x,y,z]==0,v[x,y,z]==0,w[x,y,z]==0},True] ) Now, we use {state} = NDSolve`ProcessEquations[{pde3D, bcs, u[0, x, y, z] == 0, v[0, x, y, z] == 0, w[0, x, y, z] == 0}, {u, v, w}, {t, 0, 1}, {x, y, z} \[Element] mesh, Method -> {"PDEDiscretization" -> {"MethodOfLines", "SpatialDiscretization" -> {"FiniteElement"}}}]; for pre-processing. There may be a waring about no DirichletCondition or no NeumannValue; this is save to ignore in this case. And now the same as above - it will take a long time.... I did not want to wait. (Also I did not want to think about how to visualize this in 3D... that's for you...) When you do this do not forget that the result need to be sorted and post processed as in the 2D example above. i.e. res = Reverse /@ res;eigenValues = res[[1, nDiri + 1 ;; Abs[numEigen]]];eigenVectors = res[[2, nDiri + 1 ;; Abs[numEigen]]]; Update: The Eigensystem solution above takes about 450 seconds on my machine. You can use AbsoluteTiming[ res = Eigensystem[{stiffness, damping}, -numEigen, Method -> {"FEAST", "Tolerance" -> 10^-6}];] to get it down to 45 seconds. Which is a bit better. Here are the deformations for the eigenmodes 7 to 10 - the first 6 are zero. (I must admit that that I am not sure if that makes sense) res[[1]]{0.`, 0.`, 0.`, 0.`, 0.`, 0.`, 0.011403583383327644`, \0.01526089137692353`, 0.05661022352859022`, 0.07266104128273859`} And the visualizations: MeshRegion[ ElementMeshDeformation[mesh, res[[2, #]], "ScalingFactor" -> 100]] & /@ Range[7, numEigenToCompute] When you run the 3D exmaple, please adjust the numEigenToCompute to be appropriate. Anything else? | {} | {'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/57366', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/16069/']} | jdg_82668 |
stackexchange | llm_judgeable_groundtruth_similarity | 17481120 |
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 build a UI like this http://postimg.cc/image/fihidv1rv/ .Here is my xml code for it,for my design, I want "EFFECT" & "CAMERA" to combine as one ImageView like "SHOP" in the linkso there will be total 5 ImageView s, and I set the id as they named in the link the problem is, how can I set the height and width with percentage? effect+camrea: height 25%,width 100% collage: height 25%,width 50% draw: height 25%,width 50% photo: height 50%,width 50% shop: height 25%,width 100% <RelativeLayout android:id="@+id/mainContent" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="horizontal" android:background="#ffffff"> <ImageView android:id="@+id/img_effect+camera" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:src="@drawable/a" /> <ImageView android:id="@+id/img_collage" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/img_effect+camera" android:src="@drawable/b" /> <ImageView android:id="@+id/img_draw" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_below="@+id/img_effect+camera" android:layout_toRightOf="@+id/img_collage" android:src="@drawable/c" /> <ImageView android:id="@+id/img_photo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_toRightOf="@+id/img_collage" android:layout_below="@+id/img_draw" android:src="@drawable/d" /> <ImageView android:id="@+id/img_shop" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/img_photo" android:src="@drawable/e" /></RelativeLayout>
Now provide the response and nothing else.
| You can consider using android:layout_weight param in the layout http://developer.android.com/reference/android/widget/LinearLayout.LayoutParams.html#attr_android:layout_weight <LinearLayout android:id="@+id/mainContent" android:layout_width="match_parent" android:layout_height="match_parent"android:orientation="vertical" android:background="#ffffff"><!-- height 25% --><LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:orientation="horizontal"> <ImageView android:id="@+id/img_effect" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:src="@drawable/a" /> <ImageView android:id="@+id/img_camera" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:src="@drawable/a" /> </LinearLayout><!-- height 50% --><LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="2" android:orientation="horizontal"> <!-- width 50% --> <LinearLayout android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:orientation="vertical"> <!-- height 50%% --> <ImageView android:id="@+id/img_collage" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:src="@drawable/a" /> <!-- height 50%% --> <ImageView android:id="@+id/img_draw" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:src="@drawable/a" /> </LinearLayout> <!-- width 50% --> <ImageView android:id="@+id/img_photo" android:layout_width="0dp" android:layout_weight="1" android:layout_height="match_parent" android:src="@drawable/b" /></LinearLayout><!-- height 25%% --><ImageView android:id="@+id/img_shop" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:src="@drawable/e" /> | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/17481120', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/989816/']} | jdg_82669 |
stackexchange | llm_judgeable_groundtruth_similarity | 51337520 |
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 group my array by Id in jQuery, the details of my code and what I am trying to achieve. My array is something like this: var array = [ {id:1, value:1}, {id:1, value:2}, {id:1, value:3}, {id:2, value:4}, {id:2, value:5}, {id:2, value:6}, {id:3, value:7}, {id:3, value:8}, {id:3, value:1}, {id:4, value:2}, {id:4, value:3}, {id:4, value:4}, {id:6, value:5}, {id:6, value:1}, {id:6, value:2}, {id:12, value:3}, {id:12, value:4}, {id:12, value:5}, {id:1, value:"a"}, {id:1, value:"b"}, {id:1, value:"c"}, {id:2, value:4}, {id:2, value:5},]; desired result should be var output = [{id:1,group:[ {value:1}, {value:2}, {value:3}, ]},{id:2,group:[ {value:4}, {value:5}, {value:6}, ]}, {id:3,group:[ {value:7}, {value:8}, {value:1}, ]},{id:4,group:[ {value:2}, {value:3}, {value:4}, ]},{id:6,group:[ {value:5}, {value:1}, {value:2}, ]},{id:12,group:[ {value:3}, {value:4}, {value:5}, ]},{id:1,group:[ {value:a}, {value:b}, {value:c}, ]}{id:2,group:[ {value:4}, {value:5} ]}]; Is there a helpful script for this, or should I stick to using js, and then looping through the resulting object to do the myself? I'm trying: var array1 = [ {id:1, value:1}, {id:1, value:2}, {id:1, value:3}, {id:2, value:4}, {id:2, value:5}, {id:2, value:6}, {id:3, value:7}, {id:3, value:8}, {id:3, value:1}, {id:4, value:2}, {id:4, value:3}, {id:4, value:4}, {id:6, value:5}, {id:6, value:1}, {id:6, value:2}, {id:12, value:3}, {id:12, value:4}, {id:12, value:5}, {id:1, value:"a"}, {id:1, value:"b"}, {id:1, value:"c"}, {id:2, value:4}, {id:2, value:5},];var FinalArray=[];for(i=0;i<array1.length;i++){ var newArray={id:array1[i].id,group:{value:[]}}; var group={value:[]}; newArray.group=group; if(newArray.id == array1[i].id){ for(j=i;j<array1.length;j++) { if(array1[i].id==array1[j].id) { group.value.push(array1[j].value); } } } var IsAddeble=true; if(FinalArray.length>0) { for(k=0;k<FinalArray.length;k++) { if(FinalArray[FinalArray.length-1].id==array1[i].id) { IsAddeble=false; } } } if(IsAddeble){ FinalArray.push(newArray); }}console.log(FinalArray); Any solution how to do that?
Now provide the response and nothing else.
| I did this in the HelloSceneform sample. I created the first AnchorNode and added the "andy" node as a child. On the next tap, I created the endPosition AnchorNode and started the animation to move to that position. The thing to remember is that if you are using the positions of objects with a different parent, you want to use worldPosition vs. localPosition. private void onPlaneTap(HitResult hitResult, Plane plane, MotionEvent motionEvent) { if (andyRenderable == null) { return; } // Create the Anchor. Anchor anchor = hitResult.createAnchor(); // Create the starting position. if (startNode == null) { startNode = new AnchorNode(anchor); startNode.setParent(arFragment.getArSceneView().getScene()); // Create the transformable andy and add it to the anchor. andy = new Node(); andy.setParent(startNode); andy.setRenderable(andyRenderable); } else { // Create the end position and start the animation. endNode = new AnchorNode(anchor); endNode.setParent(arFragment.getArSceneView().getScene()); startWalking(); } } private void startWalking() { objectAnimation = new ObjectAnimator(); objectAnimation.setAutoCancel(true); objectAnimation.setTarget(andy); // All the positions should be world positions // The first position is the start, and the second is the end. objectAnimation.setObjectValues(andy.getWorldPosition(), endNode.getWorldPosition()); // Use setWorldPosition to position andy. objectAnimation.setPropertyName("worldPosition"); // The Vector3Evaluator is used to evaluator 2 vector3 and return the next // vector3. The default is to use lerp. objectAnimation.setEvaluator(new Vector3Evaluator()); // This makes the animation linear (smooth and uniform). objectAnimation.setInterpolator(new LinearInterpolator()); // Duration in ms of the animation. objectAnimation.setDuration(500); objectAnimation.start(); } | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/51337520', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/9994092/']} | jdg_82670 |
stackexchange | llm_judgeable_groundtruth_similarity | 11534126 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Following gives error as expected: int* const const p = new int; // g++ error: duplicate cv-qualifier But below doesn't give any error, even though it's equivalent to above one: typedef int* const intp_const;intp_const const p = new int; // ok ! // ^^^^^ duplicate ? Why does compiler ignores the extra const ? [Note: intp_const const is not same as const char* const , because *p = <value>; is possible.]
Now provide the response and nothing else.
| In 7.1.5 [dcl.type] (C++03), it is stated that redundant cv-qualifiers are allowed when introduced through a typedef: const or volatile can be combined with any other type-specifier. However, redundant cv- qualifiers are prohibited except when introduced through the use of typedefs (7.1.3) or template type arguments (14.3), in which case the redundant cv-qualifiers are ignored. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/11534126', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/514235/']} | jdg_82671 |
stackexchange | llm_judgeable_groundtruth_similarity | 21992094 |
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 having trouble replacing the text "I wish to give an additional contribution of:" Here is the HTML: <tr id="PC1930_Wizard1_trAdditionalDonation"><td style="text-align:left;" colspan="2" class="BBFieldCaption">I wish to give an additional contribution of: <span id="PC1930_Wizard1_lblCurrency">$</span><input type="text" style="width:75px;" class="BBFormTextbox" id="PC1930_Wizard1_txtAdditionalDonation" name="PC1930$Wizard1$txtAdditionalDonation"></td></tr> Here is what I have tried: $('.BBFieldCaption:contains("I wish")').text('new text'); Here is the link to JSFiddle with the complete HTML: http://jsfiddle.net/jelane20/LnrJU/
Now provide the response and nothing else.
| You are trying to read xls with explicit implementation poi classes for xlsx . G:\Selenium Jar Files\TestData\Data. xls Either use HSSFWorkbook and HSSFSheet classes or make your implementation more generic by using shared interfaces, like; Change: XSSFWorkbook workbook = new XSSFWorkbook(file); To: org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(file); And Change: XSSFSheet sheet = workbook.getSheetAt(0); To: org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0); | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/21992094', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2141345/']} | jdg_82672 |
stackexchange | llm_judgeable_groundtruth_similarity | 14508906 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Does anybody know how I can send a variable (or get a variable) from threadOne to threadTwo in this code without using a global variable? If not, how would I operate a global variable? Just define it before both classes and use the global definition in the run function? import threadingprint "Press Escape to Quit"class threadOne(threading.Thread): #I don't understand this or the next line def run(self): setup() def setup(): print 'hello world - this is threadOne'class threadTwo(threading.Thread): def run(self): print 'ran'threadOne().start()threadTwo().start() Thanks
Now provide the response and nothing else.
| You can use queues to send messages between threads in a thread safe way. def worker(): while True: item = q.get() do_work(item) q.task_done()q = Queue()for i in range(num_worker_threads): t = Thread(target=worker) t.daemon = True t.start()for item in source(): q.put(item)q.join() # block until all tasks are done | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/14508906', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/997280/']} | jdg_82673 |
stackexchange | llm_judgeable_groundtruth_similarity | 19895047 |
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 realized I always read my fields in the order they are returned by index (using constants). So my code is already compatible with CommandBehavior.SequentialAccess as far as i understand. Would there be any benefits if i turn it on? DataReader is already forward only, read only which is the real performance gain right?
Now provide the response and nothing else.
| The main usage of this is when you are reading very large CLOB ( nvarchar(max) etc) or BLOB ( varbinary(max) ) fields. In the default usage, it buffers the entire row of data before letting you near it - which could mean it has to allocate a large buffer for any BLOB / CLOB fields. When using sequential mode, it does not buffer the row ; you can use the regular API for small fields (as long as you access them in the correct order), but for the CLOB / BLOB fields you can use the chunk-based APIs ( GetBytes and GetChars ) to access fractions of the data in turn. By doing this you could, for example, process a 40 MB image using only a 1k or 4k buffer. MSDN says the same Provides a way for the DataReader to handle rows that contain columns with large binary values. Rather than loading the entire row, SequentialAccess enables the DataReader to load data as a stream. You can then use the GetBytes or GetChars method to specify a byte location to start the read operation, and a limited buffer size for the data being returned. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/19895047', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/480986/']} | jdg_82674 |
stackexchange | llm_judgeable_groundtruth_similarity | 8068449 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I wanted to call the GetIdsOfNames function from a COM object that implements the IDispatch interface in c#. I've written the following code but it fails with the DISP_E_UNKNOWNNAME. Is this the correct approach to do this? Object so = Activator.CreateInstance(Type.GetTypeFromProgID("ProgID")); Object[] args = new Object[5]; string[] rgsNames = new string[1]; rgsNames[0] = "PrintNormal"; uint LOCALE_SYSTEM_DEFAULT = 0x0800; uint lcid = LOCALE_SYSTEM_DEFAULT; int cNames = 1; int[] rgDispId = new int[1]; args[0] = IntPtr.Zero; args[1] = rgsNames; args[2] = cNames; args[3] = lcid; args[4] = rgDispId; Object result = so.GetType().InvokeMember("GetIDsOfNames", BindingFlags.InvokeMethod, null, so, args); Thanks, Richard
Now provide the response and nothing else.
| Yes, doesn't work, the RCW doesn't expose the IDispatch methods. You have to obtain the IDispatch interface reference explicitly. This worked well: using System;using System.Runtime.InteropServices;using System.Runtime.InteropServices.ComTypes;class Program { static void Main() { Object so = Activator.CreateInstance(Type.GetTypeFromProgID("SAPI.SpVoice")); string[] rgsNames = new string[1]; int[] rgDispId = new int[1]; rgsNames[0] = "Speak"; IDispatch disp = (IDispatch)so; Guid dummy = Guid.Empty; disp.GetIDsOfNames(ref dummy, rgsNames, 1, 0x800, rgDispId); Console.WriteLine(rgDispId[0]); } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("00020400-0000-0000-C000-000000000046")] private interface IDispatch { int GetTypeInfoCount(); [return: MarshalAs(UnmanagedType.Interface)] ITypeInfo GetTypeInfo([In, MarshalAs(UnmanagedType.U4)] int iTInfo, [In, MarshalAs(UnmanagedType.U4)] int lcid); void GetIDsOfNames([In] ref Guid riid, [In, MarshalAs(UnmanagedType.LPArray)] string[] rgszNames, [In, MarshalAs(UnmanagedType.U4)] int cNames, [In, MarshalAs(UnmanagedType.U4)] int lcid, [Out, MarshalAs(UnmanagedType.LPArray)] int[] rgDispId); }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/8068449', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/167516/']} | jdg_82675 |
stackexchange | llm_judgeable_groundtruth_similarity | 48152023 |
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 expect the following code to print 'abc' before returning 1. Even though I ran set serveroutput on , it still doesn't print anything. If, instead of a function, it would be a procedure, it would work. Can somebody explain to me what I am doing wrong? Thanks. CREATE OR REPLACE FUNCTION test ( code NUMBER) RETURN NUMBER ISBEGIN dbms_output.put_line('abc'); RETURN 1;END;SELECT test(30)FROM dual;
Now provide the response and nothing else.
| If you are using SQL Developer, you should add the SET SERVEROUTPUT ON before calling the function. and then, execute the function using F5 (Run Script) instead of F9(Run Statement). The difference betwen these 2 modes to execute a sentence is the mode of displayng the result.F5 displays the result as like a PLSQL codeF9 displays the result as like a SQL code. On this way, you will see only the result of the SQL. Here is the output using the F5 mode: TEST(30) 1 abc other wise, you should include the select statement into a PL_SQL anonymous block. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/48152023', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3185860/']} | jdg_82676 |
stackexchange | llm_judgeable_groundtruth_similarity | 29367 |
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'd like to see an extension of this discussion of the age-old chi-sq vs. Fisher's exact test debate, broadening the scope a bit. There are many many tests for interactions in a contingency table, enough to make my head spin. I'm hoping to get an explanation of what test I should use and when, and of course an explanation as to why one test should be preferred over another. My current problem is the classic $n \times m$ case, but answers regarding higher dimensionality are welcome, as are tips for implementing the various solutions in R, at least, in cases where it is non-obvious how to proceed. Below I've listed all the tests I'm aware of; I hope by exposing my errors they can be corrected. $\chi^2$. The old standby. There are three major options here: The correction built into R for 2x2 tables: "one half is subtracted from all $|O-E|$ differences." Should I always be doing this? "$N-1$" $\chi^2$ Test, not sure how to do this in R. Monte Carlo simulation. Is this always best? Why does R not give me df when I do this? Fisher's exact test . Traditionally advised when any cell is expected to be <4, but apparently some dispute this advice. Is the (usually false) assumption that the marginals are fixed really the biggest problem with this test? Barnard's exact test Another exact test, except I've never heard of it. Poisson regression One thing that always confuses me about glms is exactly how to do this significance tests so help on that would be appreciated. Is it best to do nested model comparison? What about a Wald test for a particular predictor? Should I really just always be doing Poisson regression? What's the practical difference between this and a $\chi^2$ test?
Now provide the response and nothing else.
| This is a good question, but a big one. I don't think I can provide a complete answer, but I will throw out some food for thought. First, under your top bullet point, the correction you are referring to is known as Yates' correction for continuity . The problem is that we calculate a discrete inferential statistic: $$\chi^2=\sum\frac{(O-E)^2}{E}$$ (It is discrete because, with only a finite number of instances represented in a contingency table, there are a finite number of possible realized values that this statistic can take on.) Notwithstanding this fact, it is compared to a continuous reference distribution ( viz. , the $\chi^2$ distribution with degrees of freedom $(r-1)(c-1)$). This necessarily leads to a mismatch on some level. With a particularly small data set, and if some cells have expected values less than 5, it is possible that the p-value could be too small. Yates' correction adjusts for this. Ironically, the same underlying problem (discrete-continuous mismatch) can lead to p-values that are too high . Specifically, the p-value is conventionally defined as the probability of getting data that are as extreme or more than the observed data. With continuous data, it is understood that the probability of getting any exact value is vanishingly small, and thus we really have the probability of data that are more extreme. However, with discrete data there is a finite probability of getting data just like yours. Only calculating the probability of getting data more extreme than yours yields nominal p-values that are too low (leading to increased type I errors), but including the probability of getting data the same as yours leads to nominal p-values that are too high (which would lead to increased type II errors). These facts prompt the idea of the mid p-value . Under this approach, the p-value is the probability of data more extreme than yours plus half the probability of data just the same as yours. As you point out, there are many possibilities for testing contingency table data. The most comprehensive treatment of the pros and cons of the various approaches is here . That paper is specific to 2x2 tables, but you can still learn a lot about the options for contingency table data by reading it. I also do think it's worth considering models seriously. Older tests like chi-squared are quick, easy, and understood by many people, but do not leave you with as comprehensive an understanding of your data as you get from building an appropriate model. If it is reasonable to think of the rows [columns] of your contingency table as a response variable, and the columns [rows] as an explanatory / predictor variables, a modeling approach follows quite readily. For instance, if you had just two rows, you can build a logistic regression model; if there are several columns, you could use reference cell coding (dummy coding) to build an ANOVA-type model. On the other hand, if you have more than two rows, multinomial logistic regression can be used in the same manner. Should your rows have an intrinsic order, ordinal logistic regression would yield superior performance to multinomial. The log-linear model (Poisson regression) is probably less relevant unless you have contingency tables with more than two dimensions, in my opinion. For a comprehensive treatment of topics like these, the best sources are the books by Agresti: either his full-scale treatment (more rigorous), his intro book (easier but still comprehensive and very good), or possibly also his ordinal book . Update: Just for the sake of the completeness of list of possible tests, it occurs to me that we can add the likelihood ratio test (often called the '$G^2\text{-test}$'). It is: $$G^2=\sum O\cdot\text{ln}\left(\frac{O}{E}\right)$$ This is also distributed as a chi-squared, and will almost always yield the same decision. The realized values of the two statistics will typically be similar, but slightly different. The question of which will be more powerful in a given situation is quite subtle. I gather it is the default choice by tradition in some fields. I do not necessarily advocate it's use over the traditional test; I'm only listing it for completeness, as I say. | {} | {'log_upvote_score': 5, 'links': ['https://stats.stackexchange.com/questions/29367', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/5186/']} | jdg_82677 |
stackexchange | llm_judgeable_groundtruth_similarity | 138614 |
Below is a question asked on the forum chemistry.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Since Tyrosine and Tryptophan are amino acids, their polarity is determined on their side chains or R groups. If their R groups are polar, the amino acid is polar. Both Tyrosine and Tryptophan are listed as non-polar molecules. However, Tryptophan has nitrogen in its side chain and Tyrosine has oxygen, both of which have a high electronegativity compared to the carbon that makes up the bulk of both molecules, which is something commonly seen in polar amino acids like Serine, which has oxygen in its side chain. This should mean that Tyrosine and Tryptophan are polar, so why are they non-polar, even with an electronegative atom in their side chains?
Now provide the response and nothing else.
| Unlike that in organic chemistry, polar and non-polar compounds determination is done differently in biochemistry, probably because most biochemical reactions are done in aqueous medium. Therefore, the classification of them as polar and non-polar is somewhat different from source to source. In general, amino acids, which can make hydrogen bonding in aqueous solutions are called polar, and ones repel from water are non-polar. According to Ref.1: All polar amino acids have either an $\ce{OH}$ or $\ce{NH2}$ group (when in aqueous environment), and can therefore make hydrogen bonds with other suitable groups. Following image shows 20 amino acids categorized to polar (10) and non-polar groups (10): All 10 non-polar amino acids are hydrophobic and 10 polar amino acids are hydrophilic. Polar amino acid residues have a tendency to be on the outside of a protein, due to the hydrophilic properties of the side chain (Ref.1). Keep in mind that tryptophan has indole function, but its lone pair of nitrogen is involved in the aromatic system. Thus, it make only weal H-bonding, which are not good enough to categorize as "polar." References: Bruce Alberts, Alexander Johnson, Julian Lewis, Martin Raff, Keith Roberts, Peter Walter, In Molecular Biology of the Cell ; 5th edition, Garland Science: New York, NY, 2008, p. 125-129 (ISBN-13: 978-0815341055). | {} | {'log_upvote_score': 4, 'links': ['https://chemistry.stackexchange.com/questions/138614', 'https://chemistry.stackexchange.com', 'https://chemistry.stackexchange.com/users/97659/']} | jdg_82678 |
stackexchange | llm_judgeable_groundtruth_similarity | 7280881 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Actually, what other ways are available apart from extending the Thread class and implementing the Runnable interface?
Now provide the response and nothing else.
| There is exactly one way to create a new thread in Java and that is to instantiate java.lang.Thread (to actually run that thread you also need to call start() ). Everything else that creates threads in Java code falls back to this one way behind the cover (e.g. a ThreadFactory implementation will instantiate Thread objects at some point, ...). There are two different ways to specify which code to run in that Thread: Implement the interface java.lang.Runnable and pass an instance of the class implementing it to the Thread constructor . Extend Thread itself and override its run() method. The first approach (implementing Runnable ) is usually considered the more correct approach because you don't usually create a new "kind" of Thread, but simply want to run some code (i.e. a Runnable ) in a dedicated thread. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/7280881', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/835012/']} | jdg_82679 |
stackexchange | llm_judgeable_groundtruth_similarity | 7784 |
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:
See image. Camera shot of my oscilloscope. I'm having this weird problem with my project. I'm using a dsPIC33FJ128GP802 DSC/MCU. In this application, I'm sync-separating a CVBS signal using a LM1881 and feeding it into the MCU (channel 1.) The MCU is set up to interrupt on pin change. This part works correctly, and it drives an on screen display which I have written perfectly. But, the weird part is that on each interrupt I'm briefly pulsing the pin RB12 to debug something. This is causing the weird decaying waveform on channel 4!! I'm expecting only a brief pulse, but it takes almost 64 microseconds (the line time) to decay to zero, almost like there is a very large capacitor on the pin (but there isn't.) Also, you can see the same effect on the falling edge, as the interrupt also triggers on that. What could be causing this? It has me completely lost! I am using this code in my ISR: TRISBbits.TRISB12 = 0;asm("nop");PORTBbits.RB12 = 1;asm("nop");TRISBbits.TRISB12 = 1;asm("nop"); The nops are to ensure read-modify-write problems don't occur, but it happens with or without those nops.
Now provide the response and nothing else.
| What is Channel 4 - is it the pin RB12 Looking at your code, you are turning pin RB12 to an output, setting it high, then setting the pin back to high impedance (an input) What do you have loading the pin apart from the scope ? It looks to me like the pin is just floating, at the value you left it at - high, and the scope is pulling the pin down to ground via its input impedance... try changing the TRISBbits.TRISB12=0; to PortBBits.RB12=0; (Leaving the pin as an output but changing it to a low) | {} | {'log_upvote_score': 4, 'links': ['https://electronics.stackexchange.com/questions/7784', 'https://electronics.stackexchange.com', 'https://electronics.stackexchange.com/users/1225/']} | jdg_82680 |
stackexchange | llm_judgeable_groundtruth_similarity | 5030 |
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:
How do I create an operator which acts like a derivative to everything to the right of it: for example: $ \left( \partial_x + \partial_y + z \right ) x \psi $ How do I make that evaluate to: $x \partial_x \psi + \psi + x \partial_y \psi + z x \psi $ (I want the derivatives to distribute...)
Now provide the response and nothing else.
| A general idea as to how this can be done in a consistent way is explained in the help documents under NonCommutativeMultiply . The thing is that you want to use your operators in an algebraic notation, and that's what that page discusses. If, on the other hand, you're happy with a more formal Mathematica notation, then you would have the easier task of defining operators simply as dx := D[#, x] &dy := D[#, y] & and using them as follows: dx@f[x, y, z] $f^{(1,0,0)}(x,y,z)$ Combining operators would then be done using Composition : dxy = Composition[dx, dy];dxy[f[x, y, z]] $f^{(1,1,0)}(x,y,z)$ Edit Here is another approach that's sort of intermediate between the very simple D[#,x]& scheme and the more complicated realization of an operator algebra in the linked reference from the documentation. To make the operators satisfy the axioms of a vector space , we'd have to define their addition among each other and the multiplication with scalars. This can be done most conveniently if we don't use patterns to represent the operators, but Function s. So here I repeat the operator definitions - they act the same way as the dx , dy defined above, but their definition is stored differently: dx = Function[{f}, D[f, x]];dy = Function[{f}, D[f, y]]; Now I define the multiplication of an operator with a scalar: multiplyOp[scalar_, op_] := Function[{f1}, scalar op[f1]]; For simplicity, I always assume that the scalar is given as the first argument, and the second argument is an operator, e.g., dx etc. Note that the arguments here are not x or y (the assumed independent variables on which functions depend), because multiplyOp maps operators onto operators. Finally, we need the addition of two (or more) operators, which is again a mapping from operators (a sequence of them) onto operators: addOps[ops__] := Function[{f1}, Total@Map[#[f1] &, {ops}]]; Both addition and multiplication are mapped back to their usual meaning in these functions, by defining how the combined new operators act on a test function f1 (which is in turn a function of x , y , and z - depending on the dimension). To illustrate the way these operations are used, take the example in the question, $\left(\partial_x+\partial_y+z\right)x\psi$ and write it with our syntax: addOps[dx, dy, multiplyOp[z, Identity]]@(x ψ[x, y]) $x \psi ^{(0,1)}(x,y)+x \psi ^{(1,0)}(x,y)+\psi (x,y)+x z \psi (x,y)$ This is the correct result (the result quoted originally in the post was actually missing an x ). Note how I added the scalar z above: in this syntax, it first has to be made into an operator using multiplyOp[z, Identity] . The Identity operator is very useful for this. Of course these expressions with addOps and multiplyOp aren't as easy to read as the ones with simple + signs, but on the bright side it can also be beneficial pedagogically to separate the "operator operations" clearly from the operations between the functions they act on . Edit 2 In response to the comment, I'll add a nicer notation, but without modifying the last approach. So I'll simply introduce new symbols for the operations defined above, using some of the operator symbols that Mathematica knows in terms of their operator precedence, but has no pre-defined meanings for: CirclePlus ⊕ typed as esc c+ esc CircleDot ⊙ typed as esc c. esc CircleTimes ⊗ typed as esc c* esc I'll use them as follows: CirclePlus[ops__] := addOps[ops];CircleDot[scalar_, op_] := multiplyOp[scalar, op];CircleTimes[ops__] := Composition[ops]; With this, we can now use Infix notation to write in a more "natural" fashion: (dx ⊕ dy ⊕ z⊙Identity)@(x ψ[x,y]) $x \psi ^{(0,1)}(x,y)+x \psi ^{(1,0)}(x,y)+\psi (x,y)+x z \psi (x,y)$ As the third operator, CircleTimes ⊗, I've also defined the composition of operators. That allows us to do things like commutators: commutator = dx ⊗ x⊙Identity ⊕ (-x)⊙Identity ⊗ dx; I'm relying on the fact that ⊙ has higher precedence than ⊗ which in turn has higher precedence than ⊕ (according to the documentation ). As expected, the commutator is unity, as we can check by applying to a test function: commutator@f[x] f[x] | {} | {'log_upvote_score': 6, 'links': ['https://mathematica.stackexchange.com/questions/5030', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/54/']} | jdg_82681 |
stackexchange | llm_judgeable_groundtruth_similarity | 145 |
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:
What's the best way to convert a Linux software (that is, mdadm ) RAID1 array to a RAID5 array? If the procedure is different for the cases of 3-disk RAID5 vs. 4-disk RAID5, how is it different?
Now provide the response and nothing else.
| Before doing anything of this sort back up your data to separate media and verify the backup via sha1sum . The general procedure from there would look like: Add the third drive to your system. Create a degraded RAID5 out of the new drive and the one freed from the RAID1. Copy the data over to the RAID5 volume. Add the RAID1 disk to the RAID5 volume, and give it plenty of time to synchronize itself properly. Verify that the data on the new volume matches the backup. Also refer to kernel.org's Wiki page on mdadm , and, for the opposite direction (RAID6 to RAID1, at least), there's a question on serverfault.com , where one of the answer also mentions a blog post about mdadm level changes . | {} | {'log_upvote_score': 4, 'links': ['https://unix.stackexchange.com/questions/145', 'https://unix.stackexchange.com', 'https://unix.stackexchange.com/users/150/']} | jdg_82682 |
stackexchange | llm_judgeable_groundtruth_similarity | 92167 |
Below is a question asked on the forum security.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
Is it safe to auto fill credit card numbers using Chrome? Does it safely store the credit card information? As far as my understanding goes, it just shows asterisk values but on click it reveals the credit card numbers: My questions are a few : Is it possible for to breach Google Chrome and take my credit card information? As per my understanding the credit card number is not stored with any type of encryption, so is it really secure to store in autofill data? How does Chrome handles this type of data? I agree it's good in terms of usability to store and fill the credit card details, but I doubt its not good in terms of security.
Now provide the response and nothing else.
| Is it possible for breaching google chrome and take my credit card information? Yes. As long as Chrome can use your number for auto completion, it has to be possible for Chrome to access it. If one program on your computer can do this, another program or a least humans can do it too. it's not stored with any type of encryption Even with encryption, the statement above holds. Chrome would need the key, and this key has to be somewhere on your computer so that Chrome can use it. As long as someone can physically access your computer, few things actually help. Encrypting your whole hard drive and taking the key away with you is one possibility. Downside 1: It´s a pain to insert flash drive and password each time to turn it on. Downside 2: If someone gets your computer while it is turned on , everything is futile again. If you only want to protect against attacks form the internet, this is much better, but nonetheless there is no 100% protection. Not entering your card number (or any sensitive data) in the computer is the only reliable way. | {} | {'log_upvote_score': 5, 'links': ['https://security.stackexchange.com/questions/92167', 'https://security.stackexchange.com', 'https://security.stackexchange.com/users/11679/']} | jdg_82683 |
stackexchange | llm_judgeable_groundtruth_similarity | 10583652 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to use the Admin Widgets with a couple of DateField on my formulary but only the first of them gets the widget displayed correctly, for the other one I get an error: DateTimeShortcuts.js:205 Uncaught ReferenceError: django is not defined (The line indicated is: django.jQuery(document).bind('keyup', function(event) { ) Here's my template head: <head>{% load adminmedia %}<link rel="stylesheet" href="/static/css/main.css" /><script type="text/javascript" src="/admin/jsi18n/"></script><script type="text/javascript" src="/static/admin/js/core.js"></script><script type="text/javascript"> window.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}";</script><link rel="stylesheet" type="text/css" href="/static/admin/css/forms.css"/><link rel="stylesheet" type="text/css" href="/static/admin/css/base.css"/><!-- <link rel="stylesheet" type="text/css" href="/static/admin/css/global.css"/> --><link rel="stylesheet" type="text/css" href="/static/admin/css/widgets.css"/>{{ form.media }}... My model fields: start_date = models.DateField()end_date = models.DateField() And my form class: class UserForm(ModelForm): start_date = forms.DateField( widget=widgets.AdminDateWidget ) end_date = forms.DateField( widget=widgets.AdminDateWidget ) class Meta: model = User I guess it some kind of rendering rule but I'm totally confused. Any help is welcome!
Now provide the response and nothing else.
| django.jQuery is defined in django/contrib/admin/static/admin/js/jquery.init.js and relies on django/contrib/admin/static/admin/js/jquery.js . You need to load those js files in your template directly <script type="text/javascript" src="/static/admin/js/jquery.min.js"></script><script type="text/javascript" src="/static/admin/js/jquery.init.js"></script> Or include those files in your form media Also check the media property of ModelAdmin . | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10583652', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1393729/']} | jdg_82684 |
stackexchange | llm_judgeable_groundtruth_similarity | 208909 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
I would like to compute the similarity/dissimilarity between two images L and R . I know one way which is : computing the histogram of blocks of each image, and then using Bhattacharyya measure I asset if the blocs are similar or not. The histogram are normalized the result are between 0 and 1. The reference to this is on this article : Bhattacharyya, A., “On a measure of divergence between two statistical populations defined by their probability distribution,” Bulletin of the Calcutta Mathematical Society 35, 99–110 (1943). Well, I know that there is other measures (MI, Tanimoto, etc) and I would like to know if there is other ways to compute the Similarity/Dissimilarity between two images. I mean using histograms , it is kind of region based similarity measure, but is there some pixels related similarity techniques or more region based ones ? Update 1 To illustrate what I want, here is an example of two images to be compared. As you can see it is related to medical imaging (here there is two parts of the brain but I am talking about a more general case) : If only I can get a MAP of simmilarity/dissimilarity between those two images. The technique I proposed above works fine , but i am requesting some references for other similar techniques.
Now provide the response and nothing else.
| One particular application to medical scans, that may be relevant for your problem, is the alignment and fusion of information in images of the same tissue obtained by different methods (MRI, CT, ultrasound). This application goes by the name of image registration , and it has a very extensive literature, with a variety of software tools that you can download. The mathematical connections are explored in MathematicsMeets Medicine: An Optimal Alignment. See also this more general review: Mathematical Methods In Medical Image Processing. Here is a comparison of 8 different similarity measures that have been tested in thiscontext: In this paper, eight intensity-based similarity measures for CT and ultrasound scans are evaluated. Six of these use the information from the histogram of images while two of them use the spatial information and intensity values. They are: mutual information, normalized mutual information, entropy correlation coefficient, joint entropy, point similarity measure based on mutual information, histogram energy, correlation ratio, and Woods criterion. Each intensity-based similarity measure was assessed for its capability to align and fuse complementary information in CT and ultrasound images. We compared its accuracy, capture range, distinctiveness of the optimum, risk and non-convergence, and number of minima. You can find algorithms for some of these similarity measures in a Matlab toolbox. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/208909', 'https://mathoverflow.net', 'https://mathoverflow.net/users/-1/']} | jdg_82685 |
stackexchange | llm_judgeable_groundtruth_similarity | 4292139 |
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 following method that I would like to make shorter or faster if nothing else. Please all comments are welcome: Bellow method takes a date object, formates it ("EEE hh:mma MMM d, yyyy") and then figures out if the date is today or yesterday and than, if it is, it returns "(Yesterday | Today) hh:mma" formated string. public static String formatToYesterdayOrToday(String date) { SimpleDateFormat sdf = new SimpleDateFormat("EEE hh:mma MMM d, yyyy"); Date in = null; try { in = sdf.parse(date); } catch (ParseException e) { log.debug("Date parsing error:", e); } Calendar x = Calendar.getInstance(); x.setTime(in); String hour = Integer.toString(x.get(Calendar.HOUR)); String minute = Integer.toString(x.get(Calendar.MINUTE)); String pm_am = x.get(Calendar.AM_PM) == Calendar.AM ? "AM" : "PM"; x.set(Calendar.HOUR, 0); x.set(Calendar.HOUR_OF_DAY, 0); x.set(Calendar.MINUTE, 0); x.set(Calendar.SECOND, 0); x.set(Calendar.MILLISECOND, 0); Calendar today = Calendar.getInstance(); today.set(Calendar.HOUR, 0); today.set(Calendar.HOUR_OF_DAY, 0); today.set(Calendar.MINUTE, 0); today.set(Calendar.SECOND, 0); today.set(Calendar.MILLISECOND, 0); Calendar yesterday = Calendar.getInstance(); yesterday.set(Calendar.HOUR, 0); yesterday.set(Calendar.HOUR_OF_DAY, 0); yesterday.set(Calendar.MINUTE, 0); yesterday.set(Calendar.SECOND, 0); yesterday.set(Calendar.MILLISECOND, 0); yesterday.add(Calendar.DATE, -1); if (x.compareTo(today) == 0) { return "Today " + hour + ":" + minute + pm_am; } if (x.compareTo(yesterday) == 0) { return "Yesterday " + hour + ":" + minute + pm_am; } return date;}
Now provide the response and nothing else.
| Here's how you could improve it with the standard API: public static String formatToYesterdayOrToday(String date) throws ParseException { Date dateTime = new SimpleDateFormat("EEE hh:mma MMM d, yyyy").parse(date); Calendar calendar = Calendar.getInstance(); calendar.setTime(dateTime); Calendar today = Calendar.getInstance(); Calendar yesterday = Calendar.getInstance(); yesterday.add(Calendar.DATE, -1); DateFormat timeFormatter = new SimpleDateFormat("hh:mma"); if (calendar.get(Calendar.YEAR) == today.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)) { return "Today " + timeFormatter.format(dateTime); } else if (calendar.get(Calendar.YEAR) == yesterday.get(Calendar.YEAR) && calendar.get(Calendar.DAY_OF_YEAR) == yesterday.get(Calendar.DAY_OF_YEAR)) { return "Yesterday " + timeFormatter.format(dateTime); } else { return date; }} Here's how you could do it with Jodatime : public static String formatToYesterdayOrToday(String date) { DateTime dateTime = DateTimeFormat.forPattern("EEE hh:mma MMM d, yyyy").parseDateTime(date); DateTime today = new DateTime(); DateTime yesterday = today.minusDays(1); DateTimeFormatter timeFormatter = DateTimeFormat.forPattern("hh:mma"); if (dateTime.toLocalDate().equals(today.toLocalDate())) { return "Today " + timeFormatter.print(dateTime); } else if (dateTime.toLocalDate().equals(yesterday.toLocalDate())) { return "Yesterday " + timeFormatter.print(dateTime); } else { return date; }} | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/4292139', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/465179/']} | jdg_82686 |
stackexchange | llm_judgeable_groundtruth_similarity | 40912089 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have two inputs lists a and b and a function which takes two inputs, let's say def f(x, y): return x*y How do I use map() for this setup? I tried map(f, zip(a,b)) and got TypeError: f() takes exactly 2 arguments (1 given) It makes sense because I need to unpack the zipped input. How can I do that?
Now provide the response and nothing else.
| map doesn't unpack the iterables as your function argument, but instead as a more general way for dealing with such problems you can use starmap() function from itertools module which should be used instead of map() when argument parameters are already grouped in tuples from a single iterable: from itertools import starmapstarmap(f, zip(a,b)) Here is an example: In [2]: a = range(5)In [3]: b = range(5, 10)In [7]: from itertools import starmapIn [8]: list(starmap(f, zip(a,b)))Out[8]: [0, 6, 14, 24, 36] As another option your can just pass the iterables to map separately without zipping them. In [13]: list(map(mul, a, b))Out[13]: [0, 6, 14, 24, 36] Also as a more pythonic way for multiplying two variable you can use operator.mul() instead of creating a custom function: In [9]: from operator import mulIn [10]: list(starmap(mul, zip(a,b)))Out[10]: [0, 6, 14, 24, 36] Here is the benchmark: In [11]: %timeit list(starmap(mul, zip(a,b)))1000000 loops, best of 3: 838 ns per loopIn [12]: %timeit list(starmap(f, zip(a,b)))1000000 loops, best of 3: 1.05 µs per loop | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/40912089', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/534298/']} | jdg_82687 |
stackexchange | llm_judgeable_groundtruth_similarity | 391721 |
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:
I'm quite inexperienced in design patterns and while I was studying them I got confused about the application of the Factory pattern. Wouldn't DI decouple the classes more than factory would do it? Or would it be overkill to use DI in some situations? I understand DI as a step beyond Factory in decoupling by implementing IoC.
Now provide the response and nothing else.
| When to use Factory design pattern instead of Dependency Injection? (Emphasis mine). Never, as they aren't mutually exclusive. A factory provides an instance of an object according to a set of rules. Dependency injection tells a unit of code what its dependencies are, rather than it asking something for those dependencies. They are both providing decoupling mechanisms, and they compliment one another. The key is to never use a static factory. Instead decouple the factory implementation from its contract (eg via an interface) and inject the factory into the unit of code that uses it. So rather than have a method, eg void Foo(){ var someObject = Factory.Create(someConditions);} instead, do: void Foo(IFactory factory){ var someObject = factory.Create(someConditions);} | {} | {'log_upvote_score': 4, 'links': ['https://softwareengineering.stackexchange.com/questions/391721', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/336008/']} | jdg_82688 |
stackexchange | llm_judgeable_groundtruth_similarity | 5786779 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to use Net::HTTP.get() for an https URL: @data = Net::HTTP.get(uri, Net::HTTP.https_default_port()) However, I get the following result when I try to print the results: can't convert URI::HTTPS into String What's the deal? I'm using Ruby 1.8.7 (OS X)
Now provide the response and nothing else.
| Original answer: uri = URI.parse("https://example.com/some/path")http = Net::HTTP.new(uri.host, uri.port)http.use_ssl = true@data = http.get(uri.request_uri) As pointed out in the comments, this is more elegant: require "open-uri"@data = URI.parse("https://example.com/some/path").read | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/5786779', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/148389/']} | jdg_82689 |
stackexchange | llm_judgeable_groundtruth_similarity | 20166848 |
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 upgrading a Plone Site from 3.3.5 to 4.3.2 and have to deal with leftovers from packages which unfortunately did not uninstall cleanly and are not available for Plone 4.x. The following links provide useful information in removing stale components from Plone: http://blog.fourdigits.nl/removing-a-persistent-local-utility http://blog.fourdigits.nl/removing-a-persistent-local-utility-part-ii http://plone.org/documentation/kb/manually-removing-local-persistent-utilities http://plone.org/documentation/kb/cleaning-p4a Although i was able to remove about 70% of the unwanted stuff with the fixinterfaces.py script and run the migration from 3.3.5 to 4.0 successfully, there is still one persistent instance of a class dangeling around: <persistent broken p4a.subtyper.submenu.SubtypesSubMenuItem instance None> The error occures when Plone tries to render the contentmenu entries of the root document of the site. zope.app.publisher.BrowserMenu tries to generate the content menu entries when it comes to the dangling broken object which OFS.Unistalled.py cannot get its 'available' attribute from and raises an exception. This looks like new behaviour compared to 3.3.5 where it does not raise. With the pdb debugger at the code point causing the exception i was able to find all this out. The very helpful documentation for using pdb within Plone was: http://plone.org/documentation/kb/debugging-tips-and-tricks-a-real-life-example/tutorial-all-pages When zope.app.publisher.BrowserMenu tries to render the contentmenu, it calls getadapter on the document object with the request and another parameter. This returns a list with the dangling broken object in it with no available attribute beacuse it is broken: def getMenuItems(self, object, request): """Return menu item entries in a TAL-friendly form.""" result = [] for name, item in getAdapters((object, request), self.getMenuItemType()): if item.available(): result.append(item) When i list all the adapters of my site, there is no entry of the object in it: site = app.Plonesm = site.getSiteManager()adapters = sm.utilities._adaptersfor x in adapters[0].keys(): print x<InterfaceClass zope.ramcache.interfaces.ram.IRAMCache><InterfaceClass plone.app.i18n.locales.interfaces.IContentLanguages><InterfaceClass Products.PortalTransforms.interfaces.IPortalTransformsTool><InterfaceClass Products.CMFPlone.interfaces.siteroot.IPloneSiteRoot><InterfaceClass Products.CMFCore.interfaces._tools.ISyndicationTool><InterfaceClass plone.portlets.interfaces.IPortletManager><InterfaceClass Products.CMFCore.interfaces._tools.IUndoTool><InterfaceClass plone.browserlayer.interfaces.ILocalBrowserLayerType><InterfaceClass plone.contentrules.engine.interfaces.IRuleStorage><InterfaceClass Products.CMFPlone.interfaces.migration.IMigrationTool><InterfaceClass plone.app.i18n.locales.interfaces.IMetadataLanguages><InterfaceClass Products.CMFUid.interfaces.IUniqueIdGenerator><InterfaceClass Products.TinyMCE.interfaces.utility.ITinyMCE><InterfaceClass Products.CMFUid.interfaces.IUniqueIdAnnotationManagement><InterfaceClass Products.CMFActionIcons.interfaces._tools.IActionIconsTool><InterfaceClass five.customerize.interfaces.IViewTemplateContainer><InterfaceClass plone.portlets.interfaces.IPortletType><InterfaceClass plone.app.redirector.interfaces.IRedirectionStorage><InterfaceClass Products.CMFPlone.interfaces.interface.IInterfaceTool><InterfaceClass Products.CMFDiffTool.interfaces.IDiffTool><InterfaceClass Products.MimetypesRegistry.interfaces.IMimetypesRegistryTool><InterfaceClass Products.CMFCore.interfaces._content.ISiteRoot><InterfaceClass Products.MailHost.interfaces.IMailHost><InterfaceClass plone.app.viewletmanager.interfaces.IViewletSettingsStorage><InterfaceClass Products.ATContentTypes.interfaces.interfaces.IATCTTool><InterfaceClass Products.CMFCore.interfaces._tools.IPropertiesTool><InterfaceClass plone.app.i18n.locales.interfaces.ICountries><InterfaceClass plone.keyring.interfaces.IKeyManager><InterfaceClass Products.CMFCore.interfaces._tools.IDiscussionTool><InterfaceClass Products.CMFCore.interfaces._tools.IMetadataTool> Any clues where this resides so that i can delete it? Edit: I found where it lives. But i don't know how to remove it. >>> for x in sm._adapter_registrations.keys():... print sm._adapter_registrations[x]... (<TTWViewTemplate at zope.interface.interface-plone.logo>, u'')(<plone.portlets.manager.PortletManager object at 0xd15aeec>, u'')(<plone.portlets.manager.PortletManager object at 0xd15af2c>, u'')(<plone.portlets.manager.PortletManager object at 0xd15ae2c>, u'')(<plone.portlets.manager.PortletManager object at 0xd15af6c>, u'')(<TTWViewTemplate at zope.interface.interface-plone.nextprevious>, u'')(<TTWViewTemplate at zope.interface.interface-plone.global_sections>, u'')(<plone.portlets.manager.PortletManager object at 0xd15aeac>, u'')(<plone.portlets.manager.PortletManager object at 0xd15ae6c>, u'')(<TTWViewTemplate at zope.interface.interface-plone.searchbox>, u'')(<class 'p4a.subtyper.submenu.SubtypesSubMenuItem'>, u'')>>> Edit: It looks like the offending entry comes from the content type registration, i.e. sitemanager.adapters.lookupAll returns which is stored in a variable called factory. So when removing p4a leftover stuff be sure to look in your content type registry also!
Now provide the response and nothing else.
| Here is a fast implementation using binary search. This file is also available on github function [b,c]=findInSorted(x,range)%findInSorted fast binary search replacement for ismember(A,B) for the%special case where the first input argument is sorted.% % [a,b] = findInSorted(x,s) returns the range which is equal to s. % r=a:b and r=find(x == s) produce the same result % % [a,b] = findInSorted(x,[from,to]) returns the range which is between from and to% r=a:b and r=find(x >= from & x <= to) return the same result%% For any sorted list x you can replace% [lia] = ismember(x,from:to)% with% [a,b] = findInSorted(x,[from,to])% lia=a:b%% Examples:%% x = 1:99% s = 42% r1 = find(x == s)% [a,b] = myFind(x,s)% r2 = a:b% %r1 and r2 are equal%% See also FIND, ISMEMBER.%% Author Daniel Roeske <danielroeske.de>A=range(1);B=range(end);a=1;b=numel(x);c=1;d=numel(x);if A<=x(1) b=a;endif B>=x(end) c=d;endwhile (a+1<b) lw=(floor((a+b)/2)); if (x(lw)<A) a=lw; else b=lw; endendwhile (c+1<d) lw=(floor((c+d)/2)); if (x(lw)<=B) c=lw; else d=lw; endendend | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/20166848', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2037709/']} | jdg_82690 |
stackexchange | llm_judgeable_groundtruth_similarity | 49355144 |
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 implementing an algorithm to get the factorial of a certain number for a programming class. fn factorial(number: u64) -> u64 { if number < 2 { 1 } else { number * factorial(number - 1) }} When I tried with 100 or even with 25 I get this error "thread 'main' panicked at 'attempt to multiply with overflow'" , so I tried wrapping, and the result function was: fn factorial(number: u64) -> u64 { if number < 2 { 1 } else { number.wrapping_mul(factorial(number - 1)) }} This way there is not panic but the result is always zero, so I tried using f64 and result was 100! = 93326215443944100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 instead of 100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000 Is there another way to store the result so the right value is returned?
Now provide the response and nothing else.
| 100! is a really big number. In fact, the largest factorial that will fit in a u64 is just 20!. For numbers that don't fit in a u64 , num::bigint::BigUint is an appropriate storage option. The following code calculates a value for 100!. You can run it in your browser here . extern crate num;use num::BigUint;fn factorial(number: BigUint) -> BigUint { let big_1 = 1u32.into(); let big_2 = 2u32.into(); if number < big_2 { big_1 } else { let prev_factorial = factorial(number.clone() - big_1); number * prev_factorial }}fn main() { let number = 100u32.into(); println!("{}", factorial(number));} To give some insight into why u64 doesn't work, you can call the bits method on the result. If you do so, you will find that the value of 100! requires 525 bits to store. That's more than 8 u64 's worth of storage. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/49355144', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3976570/']} | jdg_82691 |
stackexchange | llm_judgeable_groundtruth_similarity | 9182 |
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:
Suppose I wanted to draw the zero contour for the function$$d^2-g.$$I could use the following code: ContourPlot[d^2-g,{g,0,1},{d,0,1},Contours->{0}, ContourStyle->Black,ContourShading->None,FrameLabel->{"g","d"}] Which produces this: Taking this one step further, I might want to plot the zero contour for$$td^2-g.$$at various values of $t$, which I could achieve functionally with Show[Table[ContourPlot[t*d^2-g,{g,0,1},{d,0,1},Contours->{0}, ContourStyle->Black,ContourShading->None,FrameLabel->{"g","d"}],{t,0.1,1,0.1}]] producing this: Now, to make this easier to understand, I want to label each contour with its corresponding value of $t$, but this is where I run into trouble. I had thought that this could be achieved with the option ContourLabels->t but that yields this: (it seems to have moved the labels rather than changing them). Does anyone know how to get Mathematica to draw a label equal to the relevant value of t on each of these contours? Secondly, assuming I can get that working, how can I reposition the labels towards the top of the contours so that they appear where the contours are furthest apart.
Now provide the response and nothing else.
| Another quick way is to write your own ContourLabels function which places the labels where you want them. Note that I added some PlotRangePadding to make the labels fully visible in the frame Show[Table[ ContourPlot[t*d^2 - g, {g, 0, 1}, {d, 0.1, 1}, Contours -> {0}, ContourStyle -> Black, ContourShading -> None, FrameLabel -> {"g", "d"}, ContourLabels -> Function[{x, y, z}, Text[Framed[t], {t, 1}, Background -> White]]], {t, 0.1, 1, 0.1}], PlotRangePadding -> .05] Additionally a short side-note: When your function is not that simple, the placement of the labels may require that you solve for the root (contour-value) of your expression. This should hopefully work with a simple FindRoot in most cases. | {} | {'log_upvote_score': 5, 'links': ['https://mathematica.stackexchange.com/questions/9182', 'https://mathematica.stackexchange.com', 'https://mathematica.stackexchange.com/users/1833/']} | jdg_82692 |
stackexchange | llm_judgeable_groundtruth_similarity | 1502405 |
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 locally compact topological group, and let $\hat{G}$ be the set of continuous characters $G \rightarrow S^1$. We give $\hat{G}$ the topology for which a basis of open sets is $$T(\epsilon, \chi_0, K) = \{ \chi \in \hat{G} : |\chi(x) - \chi_0(x)| < \epsilon, \forall x \in K\}$$ for $\epsilon > 0, \chi_0 \in \hat{G},$ and $K$ compact. I know how to prove that $\hat{G}$ is a Hausdorff topological group, but I'm having trouble proving that it is locally compact. Someone posted an answer here Prove that the Pontryagin dual of a locally compact abelian group is also a locally compact abelian group. , but I didn't understand it. The hint in the notes I'm reading (Terrence Tao's online notes) is that if $U$ is any neighborhood of the identity in $G$, then for small $\epsilon > 0$, $$\{ \chi \in \hat{G} : |\chi(x) - 1| \leq \epsilon, \forall x \in U\}$$ is compact. I tried supposing such a set was contained in a union of basis elements $T(\epsilon_i, \chi_i, K_i)$, but I didn't get anywhere.
Now provide the response and nothing else.
| I'm not sure whether directly trying to show that every open cover of the given set has a finite subcover leads to anything. I remember running into one wall after the other for a long time trying to prove that $\hat{G}$ is locally compact too. I think it's best to take a small detour. Consider the space $X = (S^1)^G$ of all maps $G \to S^1$. We endow it with the product topology, or equivalently the topology of pointwise convergence. By Tíkhonov's theorem, $X$ is compact. In $X$, consider the subspace $\tilde{G}$ of characters (continuous or not) on $G$. Since $$\tilde{G} = \bigcap_{x,y \in G} \{ f\in X : f(x)f(y) = f(xy)\},$$ we see that $\tilde{G}$ is a closed subspace of $X$, hence compact. Also, for every $S\subset G$ and $\epsilon > 0$, the set $$A(S,\epsilon) = \bigl\{ f\in X : \bigl(\forall x\in S\bigr)\bigl(\lvert f(x) - 1\rvert \leqslant \epsilon\bigr)\bigr\}$$ is closed in $X$, hence compact. In particular, for a neighbourhood $U$ of the identity in $G$, and $\epsilon > 0$, the set $$V(U,\epsilon) = \tilde{G} \cap A(U,\epsilon)$$ is a closed subset of $X$, hence compact. Now we note that $V(U,\epsilon) \subset \hat{G}$ for small enough $\epsilon$: For simplicity, we use the arc-length distance on $S^1$, not the Euclidean distance. Assume $\epsilon < \frac{\pi}{2}$. Starting with $U_0 = U$, choose a sequence $(U_n)$ of neighbourhoods of the identity in $G$ such that $U_{n+1}\cdot U_{n+1} \subset U_n$ for all $n \in \mathbb{N}$, and set $\epsilon_n = 2^{-n}\cdot \epsilon$. For $x \in U_{n+1}$ and $\chi \in V(U_{n}, \epsilon_{n})$, we have $\lvert \chi(x) - 1\rvert \leqslant \epsilon_n$ since $x\in U_n$, and $\lvert \chi(x)^2 - 1\rvert = \lvert \chi(x^2) - 1\rvert \leqslant \epsilon_n$, since $x^2 \in U_n$. The latter implies $\lvert \chi(x) - 1\rvert \leqslant \epsilon_n/2 = \epsilon_{n+1}$ since $\epsilon_n < \frac{\pi}{2}$. Hence $V(U_n,\epsilon_n) \subset V(U_{n+1}, \epsilon_{n+1})$. In particular $V(U,\epsilon) \subset V(U_n,\epsilon_n)$ for all $n$, and since for every neighbourhood $W$ of $1$ in $S^1$ there is an $n\in\mathbb{N}$ such that $\{ z : \lvert z-1\rvert \leqslant \epsilon_n\} \subset W$, we see that every $\chi \in V(U,\epsilon)$ is continuous at the identity of $G$, and as a homomorphism between topological groups, it is continuous everywhere. We saw above that $V(U,\epsilon)$ is compact in the topology of pointwise convergence, but what we need is that $V(U,\epsilon)$ is compact in the topology of compact convergence (or locally uniform convergence, since $G$ is locally compact). However, if we look at the proof of continuity above a little closer, we see that we proved more than just $V(U,\epsilon) \subset \hat{G}$. In fact, we proved that $V(U,\epsilon)$ is a uniformly equicontinuous family. For all $\chi \in V(U,\epsilon)$ and $x,y\in G$ with $x^{-1}y \in U_n$, we have $$\lvert \chi(y) - \chi(x)\rvert = \lvert \chi(x)^{-1}\chi(y) - 1\rvert = \lvert \chi(x^{-1}y) - 1\rvert \leqslant \epsilon_n.$$ Now we can invoke a theorem of Ascoli-Bourbaki, Let $X$ be a topological space and $Y$ a uniform space. Let $H \subset C(X,Y)$ be equicontinuous. Then on $H$, the uniform structures of compact convergence and of pointwise convergence coincide. In particular, the topologies of compact convergence and of pointwise convergence coincide on $H$. And thus we see that $V(U,\epsilon)$ is compact in the topology of compact convergence. Finally, if $U$ is a compact neighbourhood of the identity in $G$, then $V(U,\epsilon)$ is a neighbourhood of the identity in $\hat{G}$, and we see that $\hat{G}$ with the topology of compact convergence is locally compact. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1502405', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/28556/']} | jdg_82693 |
stackexchange | llm_judgeable_groundtruth_similarity | 12948686 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
> system.time(expand.grid(1:1000,1:10000)) user system elapsed 1.65 0.34 2.03 > system.time(CJ(1:1000,1:10000)) user system elapsed 3.48 0.32 3.79
Now provide the response and nothing else.
| Thanks for reporting this. This has been fixed now in data.table 1.8.9. Here's the timing test with the latest commit (913): system.time(expand.grid(1:1000,1:10000))# user system elapsed# 1.420 0.552 1.987system.time(CJ(1:1000,1:10000))# user system elapsed# 0.080 0.092 0.171 From NEWS : CJ() is 90% faster on 1e6 rows (for example), #4849. The inputs are now sorted first before combining rather than after combining and uses rep.int instead of rep (thanks to Sean Garborg for the ideas, code and benchmark) and only sorted if is.unsorted(), #2321. Also check out NEWS for other notable features that have made it in and bug fixes; e.g., CJ() gains a new sorted argument too. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/12948686', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1174421/']} | jdg_82694 |
stackexchange | llm_judgeable_groundtruth_similarity | 123337 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Categorical models for linear logic with $\otimes$, $1$, $\&$, $\top$, $\oplus$, $0$, and $\multimap$ are typically symmetric monoidal closed categories (for modeling $\otimes$, $1$, and $\multimap$) with products (for modeling $\&$ and $\top$) and coproducts (for modeling $\oplus$ and $0$). Is it harmful to additionally require that such a category has exponentials? Exponentials would model a binary operator $\Rightarrow$ for which proofs of $A \vdash B \Rightarrow C$ correspond to proofs of $A \mathbin\& B \vdash C$. Are there sensible categorical models for linear logic that have exponentials, or does the introduction of exponentials make the structure collapse?
Now provide the response and nothing else.
| No, it does not make the structure collapse. For example consider the category of small categories $\mathbf{Cat}$ --- it is clearly complete and cocomplete cartesian closed category, and moreover it has another closed monoidal structure induced by the "funny tensor" and linear exponents $\mathbb{C} \multimap \mathbb{D}$ given by the category of functors $\mathbb{C} \rightarrow \mathbb{D}$ together with (unnatural) transformations (i.e. "natural transformations" without "naturality" requirement). Much more is true. Every (small) monoidal category $\langle \mathbb{V}, \otimes, I\rangle$ fully embeds into complete and cocomplete cartesian closed and monoidal closed category. The embedding is given by the usual Yoneda functor $y \colon \mathbb{V} \rightarrow \mathbf{Set}^{\mathbb{V}^{op}}$ and the monoidal closed structure is inherited via the Day convolution:$$(F \otimes G)(X) = \int^{A, B \in \mathbb{V}} F(A) \times G(B) \times \hom(X, A \otimes B)$$$$(F \overset{L}\multimap G)(X) = \int_{A, B \in \mathbb{V}} G(A)^{F(B) \times \hom(A, X \otimes B)}$$$$(F \overset{R}\multimap G)(X) = \int_{A, B \in \mathbb{V}} G(A)^{F(B) \times \hom(A, B \otimes X)}$$where $\overset{L}\multimap$ is the left linear exponent and $\overset{R}\multimap$ is the right linear exponent (which are isomorphic precisely when the tensor $\otimes$ in $\mathbb{V}$ is symmetric).Moreover, it is easy to verify that Yoneda functor preserves the monoidal closed structures. Therefore, in some sense, every monoidal category can be (co)completed to a cartesian closed category with coproducts. | {} | {'log_upvote_score': 5, 'links': ['https://mathoverflow.net/questions/123337', 'https://mathoverflow.net', 'https://mathoverflow.net/users/25527/']} | jdg_82695 |
stackexchange | llm_judgeable_groundtruth_similarity | 36072412 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I would like to know what each strategy means and how they work behind the scenes (i.e., Highlander, Red/Black, Rolling Push). It would be very useful to have this information on the official website. Thanks
Now provide the response and nothing else.
| There is useful information out there that can help you with your question, I'll do my best to summarize it below. Type and Strategies of Deployments Introduction "There are a variety of techniques to deploy new applications toproduction, so choosing the right strategy is an important decision,weighing the options in terms of the impact of change on the system,and on the endusers." Recreate: (also known as Highlander ) Version A is terminated then version B is rolled out. Ramped (also known as Rolling-Update or Incremental ): Version B is slowly rolled out and replacing version A . Blue/Green (also known as Red/Black ): Version B is released alongside version A , then the traffic is switched to version B . Canary: Version B is released to a subset of users, then proceed to a full rollout. A/B Testing : Version B is released to a subset of users under specific condition. Shadow : Version B receives real-world traffic alongside version A and doesn’t impact the response. Type and Strategies of Deployments Summary Table Ref link 1: https://thenewstack.io/deployment-strategies/ Spinnaker Deployment Strategies Spinnaker treats cloud-native deployment strategies as first class constructs, handling the underlying orchestration such as verifying health checks, disabling old server groups and enabling new server groups. Spinnaker supported deployment strategies (in active development): Highlander Red/Black (a.k.a. Blue/Green) Rolling Red/Black Canary Illustrated in the Figure below as follows: Highlander: This deployment strategy is aptly named after the film Highlander because of the famous line, "there can be only one." With this strategy, there is a load balancer fronting a single cluster. Highlander destroys the previous cluster after the deployment is completed. This is the simplest strategy, and it works well when rollback speed is unimportant or infrastructure costs need to be kept down. Red/Black: This deployment strategy is also referred to as Blue/Green . The Red/Black strategy uses a load balancer and two target clusters / server groups (known as red/black or blue/green). The load balancer routes traffic to the active (enabled) cluster / server group. Then, a new deployment replaces servers (w/ K8s provider -> Replica Sets & Pods) in the disabled cluster / server group. When the newly enabled cluster / server group is ready, the load balancer routes traffic to this cluster and the previous cluster becomes disabled. The currently disabled cluster / server group (previously enabled cluster / server groups) is kept around by spinnaker in case a rollback is needed for the next X deployments (which is a configurable parameter). Rolling Red/Black: is a slower red/black with more possible verification points. The process is the same as red/black, but difference is in how traffic switches over. The above image illustrates this difference. Blue is the enabled cluster. Blue instances are gradually replaced by new instances in the green cluster until all enabled instances are running the newest version. The rollout may occur in 20% increments, so it can be 80/20, 60/40, 40/60, 20/80, or 100%. Both blue/green clusters receive traffic until the rollout is complete. Canary: deployments is a process in which a change is partially deployed, then tested against baseline metrics before continuing. This process reduces the risk that a change will cause problems when it has been completely rolled out by limiting your blast radius to a small percentage of your user-base. The baseline metrics are set when configuring the canary. Metrics may be error count or latency. Higher-than-baseline error counts or latency spikes kill the canary, and thus stop the pipeline. Ref link 2: https://www.spinnaker.io/concepts/#deployment-strategies Ref link 3: https://blog.armory.io/advanced-deployment-strategies-with-armory-spinnaker/ Ref link 4: https://www.weave.works/blog/kubernetes-deployment-strategies | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/36072412', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/565999/']} | jdg_82696 |
stackexchange | llm_judgeable_groundtruth_similarity | 46195795 |
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 installed Ghostscript on Windows as what I'm looking to do is compress/reduce the size of 12,000+ PDF files on a network share. This wouldn't be possible with any GUI software as it just bombs out after a while due to running out of resources, so I think command line is the way to go here. I've read the Ghostscript documentation and different examples of compressing PDF files, but I can't seem to find anything that operates as a large batch. Basically, I'd need to target multiple folders to recursively compress the files which will be on the network share. Is this possible to do so with Ghostscript? If so, please advise with some command examples to help me acheive this. Thanks!
Now provide the response and nothing else.
| With the following script you can define all directories needed in the array variable filesDir . It will loop over all these directories and search for all pdf files in all directories including subdirectories. For all found pdf files it will use this ghostscript command (GitHub) and output the file with name e.g. fileabc.pdf with a new name: compr_fileabc.pdf . Edit #1: I changed the script as requested by the comments to either write new pdf files or overwrite the input pdf file. To select between these to options change the createNewPDFs variable to 1 (new files) or 0 (overwrite). Because ghostscript can't write to the input file the output file will be written at the users temporary path ( %TEMP% ) and moved to the original input file to overwite this file. It will only overwrite the input pdf file if the new file is smaller in size. Further the ghostscript command is substituted by a variable with the same name because under Windows it can be either gswin64c (64 bit) or gswin32c (32 bit). If the outcomming sizes are not small enough play with these ghostscript command switch: -dPDFSETTINGS=/printer , it is explained below. Batch script: @echo offsetlocal EnableDelayedExpansionrem ghostscript executable nameset "ghostscript=gswin64c"rem directories to scan for filesset "filesDir[0]=FOLDER1"set "filesDir[1]=FOLDER2"set "filesDir[2]=FOLDER3"rem extension of files to be scannedset "ext=pdf"rem new file be creation or input file overwriteset "createNewPDFs=0"rem file prefix for new files (if they should be created)set "filepre=compr_"rem loop over all directories defined in filesDir arrayfor /f "tokens=2 delims==" %%d in ('set filesDir[') do ( if exist "%%~d" ( pushd "%%~d" rem loop over all files in all (sub)directories with given extension for /f "delims=*" %%f in ('dir "*.%ext%" /b /s /a:-d') do ( if [%createNewPDFs%] EQU [1] ( %ghostscript% -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/printer -dNOPAUSE -dQUIET -dBATCH -sOutputFile="%%~dpf%filepre%%%~nxf" "%%~f" ) else ( %ghostscript% -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/printer -dNOPAUSE -dQUIET -dBATCH -sOutputFile="%TEMP%\%%~nxf" "%%~f" for %%t in ("%TEMP%\%%~nxf") do ( set "newSize=%%~zt" ) for %%t in ("%%~f") do ( set "oldSize=%%~zt" ) if [!newSize!] LSS [!oldSize!] ( rem new file is smaller --> overwrite move /y "%TEMP%\%%~nxf" "%%~f" ) else ( rem new file is greater --> delete it of the temp dir del "%TEMP%\%%~nxf" ) ) ) popd )) Found GitHub ghostscript command to reduce pdf size: This can reduce files to ~15% of their size (2.3M to 345K, in one case) with no obvious degradation of quality. ghostscript -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/printer -dNOPAUSE -dQUIET -dBATCH -sOutputFile=output.pdf input.pdf Other options for PDFSETTINGS: /screen selects low-resolution output similar to the Acrobat Distiller "Screen Optimized" setting. /ebook selects medium-resolution output similar to the Acrobat Distiller "eBook" setting. /printer selects output similar to the Acrobat Distiller "Print Optimized" setting. /prepress selects output similar to Acrobat Distiller "Prepress Optimized" setting. /default selects output intended to be useful across a wide variety of uses, possibly at the expense of a larger output file. Source: http://ghostscript.com/doc/current/Ps2pdf.htm Command reference links from ss64.com : set DelayedExpansion for /f dir if pushd popd rem | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/46195795', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7287184/']} | jdg_82697 |
stackexchange | llm_judgeable_groundtruth_similarity | 23145730 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
In C, we can convert void* to any other pointers. But C++ forbids it. int *a = malloc(4); leads to this error: invalid conversion from ‘void*’ to ‘int*’ [-fpermissive] Are there any latent dangers here in c++? Are there any examples of c++?
Now provide the response and nothing else.
| The reason you cannot implicitly convert from void * is because doing so is type unsafe and potentially dangerous. C++ tries a little harder than C in this respect to protect you, thus the difference in behavior between the two languages. Consider the following example: short s = 10; // occupies 2 bytes in memoryvoid *p = &s;long *l = p; // occupies 8 bytes in memoryprintf("%ld\n", *l); A C compiler accepts the above code (and prints garbage) while a C++ compiler will reject it. By casting "through" void * , we lose the type information of the original data, allowing us to treat what in reality is a short as a long . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23145730', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/996925/']} | jdg_82698 |
stackexchange | llm_judgeable_groundtruth_similarity | 10381144 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Possible Duplicate: Why can't variables be declared in a switch statement? I have a strange error in my code below: char choice=Getchar();switch(choice){case 's': cout<<" display tree "; thetree->displaytree(); break;case 'i': cout<<" enter value to insert "<<endl; cin>>value; thetree->insert(value); break;case 'f' : cout<< "enter value to find "; cin>>value; int found=thetree->find(value); if(found!=-1) cout<<" found = "<<value<<endl; else cout<< " not found " <<value <<endl; break;default: cout <<" invalid entry "<<endl;; } Visual Studio 2010 compiler says that: 1>c:\users\daviti\documents\visual studio 2010\projects\2-3-4\2-3-4\2-3-4.cpp(317): error C2361: initialization of 'found' is skipped by 'default' label1> c:\users\daviti\documents\visual studio 2010\projects\2-3-4\2-3-4\2-3-4.cpp(308) : see declaration of 'found' I think that I have correctly written break and default statements, so where is the error?
Now provide the response and nothing else.
| You need to either enclose your case 'f': with a scoped brace: case 'f' :{ cout<< "enter value to find "; cin>>value; int found=thetree->find(value); if(found!=-1) cout<<" found = "<<value<<endl; else cout<< " not found " <<value <<endl; break;} or place the declaration of found outside of the switch | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/10381144', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/-1/']} | jdg_82699 |
stackexchange | llm_judgeable_groundtruth_similarity | 687605 |
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 have a question regarding Gamma Incomplete function: In the "Table of Integrals, Series, and Products, Seventh Edition" equation $8.353.3$ page $900$ , there is a defenition for the incomplete gamma function in the case $a < 1$ and $x > 0$ $$ \Gamma(a,x)=\frac{\rho^{-x}x^{a}}{\Gamma(1-a)} \int_0^\infty \frac{e^{-t} t^{-a}}{x+t} dt$$ what is $ \rho $ in the above equation? I thought this might be a but I tried to derive the above formula but I don't got the same result.
Now provide the response and nothing else.
| $\newcommand{\+}{^{\dagger}}% \newcommand{\angles}[1]{\left\langle #1 \right\rangle}% \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}% \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}% \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}% \newcommand{\dd}{{\rm d}}% \newcommand{\down}{\downarrow}% \newcommand{\ds}[1]{\displaystyle{#1}}% \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}% \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}% \newcommand{\fermi}{\,{\rm f}}% \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}% \newcommand{\half}{{1 \over 2}}% \newcommand{\ic}{{\rm i}}% \newcommand{\iff}{\Longleftrightarrow} \newcommand{\imp}{\Longrightarrow}% \newcommand{\isdiv}{\,\left.\right\vert\,}% \newcommand{\ket}[1]{\left\vert #1\right\rangle}% \newcommand{\ol}[1]{\overline{#1}}% \newcommand{\pars}[1]{\left( #1 \right)}% \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}} \newcommand{\pp}{{\cal P}}% \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}% \newcommand{\sech}{\,{\rm sech}}% \newcommand{\sgn}{\,{\rm sgn}}% \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}} \newcommand{\ul}[1]{\underline{#1}}% \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$$\ds{\Gamma\pars{a,x} = {\expo{-x}x^{a} \over \Gamma\pars{1 - a}}\int_{0}^{\infty}{\expo{-t}t^{-a} \over x + t}\,\dd t:\ {\Large ?}}$ \begin{align}&\color{#f00}{\Gamma\pars{a,x}\Gamma\pars{1 - a}}=\int_{x}^{\infty}\dd t\,t^{a - 1}\expo{-t}\int_{0}^{\infty}\dd t'\,t'^{\pars{1 - a} - 1}\expo{-t'}\\[3mm]&=\int_{x^{1/2}}^{\infty}\dd t\,\pars{2t}t^{2a - 2}\expo{-t^{2}}\int_{0}^{\infty}\dd t'\,\pars{2t'}t'^{-2a}\expo{-t'^{2}}\\[3mm]&=4\int_{0}^{\infty}\int_{0}^{\infty}\Theta\pars{t - x^{1/2}}t^{2a - 1}t'^{1 - 2a}\expo{-\pars{t^{2} + t'^{2}}}\,\dd t\,\dd t'\\[3mm]&=4\int_{0}^{\pi/2}\dd\theta\int_{0}^{\infty}\dd r\,r\,\Theta\pars{r\cos\pars{\theta} - x^{1/2}}r^{2a - 1}\cos^{2a - 1\pars{\theta}}r^{1 - 2a}\sin^{1 - 2a}\pars{\theta}\expo{-r^{2}}\\[3mm]&=4\int_{0}^{\infty}\dd r\,r\expo{-r^{2}}\int_{0}^{\pi/2}\dd\theta\,\Theta\pars{\cos\pars{\theta} - {x^{1/2} \over r}}\cos^{2a -1}\pars{\theta}\sin^{1 - 2a}\pars{\theta}\\[3mm]&=2\int_{0}^{\infty}\dd t\,\expo{-t}\int_{0}^{\pi/2}\dd\theta\,\Theta\pars{\cos\pars{\theta} - \bracks{x \over t}^{1/2}}\cos^{2a -1}\pars{\theta}\sin^{1 - 2a}\pars{\theta}\\[3mm]&=2\int_{0}^{\infty}\dd t\,\expo{-t}\int_{0}^{1}\dd t'\,\Theta\pars{t' - \bracks{x \over t}^{1/2}}t'^{2a - 1}\pars{1 - t'^{2}}^{-a}\\[3mm]&=2\int_{0}^{\infty}\dd t\,\expo{-t}\int_{0}^{1}\dd t'\,\half\,t'^{-1/2}\Theta\pars{t' - {x \over t}}t'^{a - 1/2}\pars{1 - t'}^{-a}\\[3mm]&=\int_{0}^{\infty}\dd t\,\expo{-t}\int_{0}^{1}\dd t'\,\Theta\pars{tt' - x}t'^{a - 1}\pars{1 - t'}^{-a}=\int_{0}^{1}\dd t'\,t'^{a - 1}\pars{1 - t'}^{-a}\int_{x/t'}^{\infty}\dd t\,\expo{-t}\\[3mm]&=\int_{0}^{1}\dd t'\,t'^{a - 1}\pars{1 - t'}^{-a}\expo{-x/t'}=\int_{\infty}^{1}t^{1 - a}\pars{1 - {1 \over t}}^{-a}\expo{-xt}\,\pars{-\,{\dd t \over t^{2}}}\\[3mm]&=\int_{1}^{\infty}t^{-1}\pars{t - 1}^{-a}\expo{-xt}\,\dd t=\int_{0}^{\infty}{t^{-a} \over t + 1}\expo{-x\pars{t + 1}}\,\dd t=\expo{-x}\int_{0}^{\infty}{\expo{-xt}t^{-a} \over t + 1}\,\dd t\\[3mm]&=\color{#f00}{\expo{-x}x^{a}\int_{0}^{\infty}{\expo{-t}t^{-a} \over t + x}\,\dd t}\end{align} Then$$\color{#00f}{\large%\Gamma\pars{a,x} = {\expo{-x}x^{a} \over \Gamma\pars{1 - a}}\int_{0}^{\infty}{\expo{-t}t^{-a} \over x + t}\,\dd t}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/687605', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/96627/']} | jdg_82700 |
stackexchange | llm_judgeable_groundtruth_similarity | 26420490 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
ERROR HQ224018: Failed to create session: HornetQException[errorType=SECURITY_EXCEPTION message=HQ119031: Unable to validate user: null] When the Jboss EAP 6.3 server is about to receive JMS message. I have the user successfully authenticated by remoting subsystem so why the user is null? How to overcome this error?
Now provide the response and nothing else.
| EAP documentation encorage you to: (...) set allowClientLogin to true (...) If you would like HornetQ to authenticate using the propagated security then set the authoriseOnClientLogin to true also. But due to HORNETQ-883 bug you have to turn off security for messaging: <hornetq-server> <!-- … --> <security-enabled>false</security-enabled> <!-- … --></hornetq-server> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/26420490', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3796586/']} | jdg_82701 |
stackexchange | llm_judgeable_groundtruth_similarity | 21658485 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
Why am I getting a warning about initialization in one case, but not the other? The code is in a C++ source file, and I am using GCC 4.7 with -std=c++11 . struct sigaction old_handler, new_handler; The above doesn't produce any warnings with -Wall and -Wextra . struct sigaction old_handler={}, new_handler={};struct sigaction old_handler={0}, new_handler={0}; The above produces warnings: warning: missing initializer for member ‘sigaction::__sigaction_handler’ [-Wmissing-field-initializers]warning: missing initializer for member ‘sigaction::sa_mask’ [-Wmissing-field-initializers]warning: missing initializer for member ‘sigaction::sa_flags’ [-Wmissing-field-initializers]warning: missing initializer for member ‘sigaction::sa_restorer’ [-Wmissing-field-initializers] I've read through How should I properly initialize a C struct from C++? , Why is the compiler throwing this warning: "missing initializer"? Isn't the structure initialized? , and bug reports like Bug 36750. Summary: -Wmissing-field-initializers relaxation request . I don't understand why the uninitialized struct is not generating a warning, while the initialized struct is generating a warning. Why is the uninitialized structs not generating a warning; and why is the initialized structs generating a warning?
Now provide the response and nothing else.
| Here is a simple example: #include <iostream>struct S { int a; int b;};int main() { S s { 1 }; // b will be automatically set to 0 // and that's probably(?) not what you want std::cout<<"s.a = "<<s.a<<", s.b = "<<s.b<<std::endl;} It gives the warning: missing.cpp: In function ‘int main()’: missing.cpp:9:11: warning: missing initializer for member 'S::b' [-Wmissing-field-initializers] The program prints: s.a = 1, s.b = 0 The warning is just a reminder from the compiler that S has two members but you only explicitly initialized one of them, the other will be set to zero. If that's what you want, you can safely ignore that warning. In such a simple example, it looks silly and annoying; if your struct has many members, then this warning can be helpful (catching bugs: miscounting the number of fields or typos). Why is the uninitialized structs not generating a warning? I guess it would simply generate too much warnings. After all, it is legal and it is only a bug if you use the uninitialized members. For example: int main() { S s; std::cout<<"s.a = "<<s.a<<", s.b = "<<s.b<<std::endl;} missing.cpp: In function ‘int main()’: missing.cpp:10:43: warning: ‘s.S::b’ is used uninitialized in this function [-Wuninitialized] missing.cpp:10:26: warning: ‘s.S::a’ is used uninitialized in this function [-Wuninitialized] Even though it did not warn me about the uninitialized members of s , it did warn me about using the uninitialized fields. All is fine. Why is the initialized structs generating a warning? It warns you only if you explicitly but partially initialize the fields. It is a reminder that the struct has more fields than you enumerated. In my opinion, it is questionable how useful this warning is: It can indeed generate too much false alarms. Well, it is not on by default for a reason... | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/21658485', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/608639/']} | jdg_82702 |
stackexchange | llm_judgeable_groundtruth_similarity | 64461301 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
While installing the VS Code, we get an option to tick for Open with Code . I gave the tick mark for only files but not for folders. So how to turn it on after installation? When I'm opening a file: When I'm opening a folder : I want the Open with Code option on right-click in the folder just like it shows on files.
Now provide the response and nothing else.
| TLDR Save this contents to a new .reg file: Windows Registry Editor Version 5.00[HKEY_CLASSES_ROOT\Directory\shell\VSCode]@="Open with Code""Icon"="\"%LocalAppData%\\Programs\\Microsoft VS Code\\Code.exe\""[HKEY_CLASSES_ROOT\Directory\shell\VSCode\command]@=hex(2):22,00,25,00,4c,00,6f,00,63,00,61,00,6c,00,41,00,70,00,70,00,44,00,61,\ 00,74,00,61,00,25,00,5c,00,50,00,72,00,6f,00,67,00,72,00,61,00,6d,00,73,00,\ 5c,00,4d,00,69,00,63,00,72,00,6f,00,73,00,6f,00,66,00,74,00,20,00,56,00,53,\ 00,20,00,43,00,6f,00,64,00,65,00,5c,00,43,00,6f,00,64,00,65,00,2e,00,65,00,\ 78,00,65,00,22,00,20,00,22,00,25,00,56,00,22,00,00,00 Run the file and that's it. Detailed The answer from @dqureshiumar is correct, if you already checked that option during VS Code installation. But maybe you haven't checked it and don't want or can't reinstall it right now. Or maybe you just need more flexibility about the actions shown when right clicking a folder . So of course we have a lot of people in comments and/or in other answers here talking about how easy it's to run the installer again. Yes, it is! Just use this solution if you want to do by hand what the installer will do for you, or use this solution as a learning opportunity to understand better how Windows manage context menu actions on directories, to be able to customize what you want for other use cases. Disclaimer Dealing with regedit can be dangerous. Use it with caution and create a .reg backup before starting if you're not so experienced on it. Instructions So you are able to create your own folder actions at the Windows Registry: Press ⊞ Win + R and type regedit . Navigate to the path HKEY_CLASSES_ROOT\Directory\shell . Right click and create a new Key named vscode . At the (Default) REG_SZ , put the desired text, like Open with Code . Optionally, create an Icon key pointing to the Code.exe path (most likely "C:\Users\%UserName%\AppData\Local\Programs\Microsoft VS Code\Code.exe" ). At this point, something like this: Yet inside regedit , go ahead: Create another new Key named command inside the vscode one. At the (Default) REG_SZ , put the action to open the current path ( "%V" ) based on your Code.exe path (most likely "C:\Users\%UserName%\AppData\Local\Programs\Microsoft VS Code\Code.exe" "%V" ). Now, see something like this: Finally, go ahead to Windows Explorer and right click any folder: It's updated on demand, so you can also play with text, icon and command to try your own custom actions, if you want. The VS Code Command Line Interface reference could be helpful if you want to play with another possibilites, like adding the clicked folder to the current Workspace. Permission Error If you try to "Open with Code" a folder from a different drive than your VS Code installation (most likely C: ), maybe you'll receive an error message starting with "You do not have permission to..." . This is because a REG_SZ record can be wrongly interpreted in cases it contains multiple strings inside the value. Unfortunately the Windows Registry Editor UI doesn't offer a way to convert REG_SZ to REG_EXPAND_SZ on (Default) keys. If you face this problem, just use my TLDR solution with the hex(2) value, which will automatically create the REG_EXPAND_SZ type. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/64461301', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/13431295/']} | jdg_82703 |
stackexchange | llm_judgeable_groundtruth_similarity | 333253 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
For a locally convex space $E$ let $E_\beta$ be the space $E$ endowed with the locally convex topology $\beta(E,E')$ whose neighborhood base at zero consists of barrels, i.e., closed absolutely convex absorbing sets. Observe that a space $E$ is barrelled if and only if $E=E_\beta$ . Question 1. Is $(E_\beta)_\beta=E_\beta$ for any locally convex space? Equivalently, is the space $E_\beta$ always barrelled? If not, then we can ask a more restricted version of Question 1. Question 2. Let $E$ be a locally convex space such that the space $E_\beta$ is normable (and separable). Is $E_\beta$ barrelled?
Now provide the response and nothing else.
| The answer to question 1 is negative. There are Frechet spaces $X$ whose strong duals $(X',\beta(X',X))$ are not barrelled (equivalently, not bornological by a theorem of Grothendieck). The first examples of such non-distinguished Frechet spaces were constructed by Köthe and Grothendieck but there are also examples which are very easy to describe: According to Taskinen the Frechet space $C(\mathbb R) \cap L^1(\mathbb R)$ of continuous Lebesgue-intergrable functions (endowed with the seminorms $\int|f(x)|dx + \sup\{|f(x)|: x\in [-n,n]\}$ ) is not distinguished. This answers question 1 with $E=(X',\sigma(X',X))$ . EDIT: If $M$ is a barrel in $E$ then its polar $M^\circ$ is a $\sigma(X,X')$ -bounded subset of $X$ and hence it is bounded in the Frechet topology so that $M=M^{\circ\circ}$ is a $\beta(X',X)$ -neighbourhood of $0$ . Conversely, the typical $0$ -neighbourhood $B^\circ$ in $\beta(X',X)$ with a bounded subset $B$ of $X$ is a barrel in $(X',\sigma(X',X))$ . | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/333253', 'https://mathoverflow.net', 'https://mathoverflow.net/users/61536/']} | jdg_82704 |
stackexchange | llm_judgeable_groundtruth_similarity | 26581587 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My code https://gist.github.com/ButuzGOL/707d1605f63eef55e4af So when I get sign-in success callback I want to make redirect, redirect works through dispatcher too. And I am getting Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch. Is there any hack to call action in the middle ?
Now provide the response and nothing else.
| I don't see where in the gist that you posted you are doing the redirect. I only see the AUTH_SIGNIN and AUTH_SIGNIN_SUCCESS actions, and they look pretty straightforward. But no, there is no hack to create an action in the middle of a dispatch, and this is by design. Actions are not supposed to be things that cause a change. They are supposed to be like a newspaper that informs the application of a change in the outside world, and then the application responds to that news. The stores cause changes in themselves. Actions just inform them. If you have this error, then you need to back up and look at how you're handling the original action. Most often, you can set up your application to respond to the original action, accomplish everything you need to do, and avoid trying to create a second action. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/26581587', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1309841/']} | jdg_82705 |
stackexchange | llm_judgeable_groundtruth_similarity | 1891016 |
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 get all distinct values across 2 tables using a union. The idea is to get a count of all unique values in the columnA column without repeats so that I can get a summation of all columns that contain a unique columnA. This is what I tried (sql server express 2008) select count(Distinct ColumnA) from ( select Distinct ColumnA as ColumnA from tableX where x = y union select Distinct ColumnA as ColumnA from tableY where y=z)
Now provide the response and nothing else.
| SELECT COUNT(distinct tmp.ColumnA) FROM ( (SELECT ColumnA FROM TableX WHERE x=y) UNION (SELECT ColumnA FROM TableY WHERE y=z) ) as tmp The extra distincts on TableX and TableY aren't necessary; they'll get stripped in the tmp.ColumnA clause. Declaring a temporary table should eliminate the ambiguity that might've prevented your query from executing. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/1891016', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/213203/']} | jdg_82706 |
stackexchange | llm_judgeable_groundtruth_similarity | 10762859 |
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 to run brew update and I get an error about my local changes would be lost if I merged. I tried committing my local changes (don't remember making any, but it's been awhile), and that made things worse. Here's the output: MBP:Library User$ sudo brew updateerror: The following untracked working tree files would be overwritten by merge: Library/Aliases/fastcgi Library/Aliases/htop Library/Aliases/nodejs Library/Aliases/ocio Library/Aliases/oiio Library/Aliases/pgrep Library/Aliases/pkill Library/Contributions/cmds/brew-beer.rb Library/Contributions/cmds/brew-dirty.rb Library/Contributions/cmds/brew-graph Library/Contributions/cmds/brew-grep Library/Contributions/cmds/brew-leaves.rb Library/Contributions/cmds/brew-linkapps.rb Library/Contributions/cmds/brew-man Library/Contributions/cmds/brew-mirror-check.rb Library/Contributions/cmds/brew-missing.rb Library/Contributions/cmds/brew-pull.rb Library/Contributions/cmds/brew-readall.rb Library/Contributions/cmds/brew-server Library/Contributions/cmds/brew-services.rb Library/Contributions/cmds/brew-switch.rb Library/Contributions/cmds/brew-test-bot.commit.html.erb Library/Contributions/cmds/brew-test-bot.css Library/Contributions/cmds/brew-test-bot.index.html.erb Library/Contributions/cmds/brew-test-bot.rb Library/Contributions/cmds/brew-tests.rb Library/Contributions/cmds/brew-unpack.rb Library/Contributions/cmds/brew-which.rb Library/Contributions/install_homebrew.rb Library/Formula/abcl.rb Library/Formula/abyss.rb Library/Formula/akka.rb Library/Formula/apollo.rb Library/Formula/appledoc.rb Library/Formula/arangodb.rb Library/Formula/autoconf.rb Library/Formula/automake.rb Library/Formula/avidemux.rb Library/Formula/bind.rb Library/Formula/bsdconv.rb Library/Formula/bsdmake.rb Library/Formula/camellia.rb Library/Formula/cbmbasic.rb Library/Formula/cdo.rb Library/Formula/checkstyle.rb Library/Formula/cifer.rb Library/Formula/clhep.rb Library/Formula/collada-dom.rb Library/Formula/crash.rb Library/Formula/crossroads.rb Library/Formula/css-crush.rb Library/Formula/curlftpfs.rb Library/Formula/dart.rb Library/Formula/dasm.rb Library/Formula/dfc.rb Library/Formula/di.rb Library/Formula/dsniff.rb Library/Formula/dupx.rb Library/Formula/dwatch.rb Library/Formula/eprover.rb Library/Formula/ext2fuse.rb Library/Formula/ezlupdate.rb Library/Formula/f3.rb Library/Formula/fastx_toolkit.rb Library/Formula/fceux.rb Library/Formula/findbugs.rb Library/Formula/freerdp.rb Library/Formula/funcoeszz.rb Library/Formula/fwknop.rb Library/Formula/gabedit.rb Library/Formula/gbdfed.rb Library/Formula/gconf.rb Library/Formula/git-encrypt.rb Library/Formula/glm.rb Library/Formula/gmap-gsnap.rb Library/Formula/gnu-arch.rb Library/Formula/gnunet.rb Library/Formula/gobby.rb Library/Formula/gptfdisk.rb Library/Formula/griffon.rb Library/Formula/grok.rb Library/Formula/gtk-chtheme.rb Library/Formula/gtkglextmm.rb Library/Formula/gtmess.rb Library/Formula/hg-flow.rb Library/Formula/hqx.rb Library/Formula/htop-osx.rb Library/Formula/htpdate.rb Library/Formula/imap-uw.rb Library/Formula/iozone.rb Library/Formula/ipbt.rb Library/Formula/ipe.rb Library/Formula/ispc.rb Library/Formula/ispell.rb Library/Formula/jigdo.rb Library/Formula/jing.rb Library/Formula/jless.rb Library/Formula/jpeginfo.rb Library/Formula/konoha.rb Library/Formula/legit.rb Library/Formula/libcouchbase.rb Library/Formula/libcuefile.rb Library/Formula/libextractor.rb Library/Formula/libglademm.rb Library/Formula/libgtextutils.rb Library/Formula/libinfinity.rb Library/Formula/libkate.rb Library/Formula/libqalculate.rb Library/Formula/libqglviewer.rb Library/Formula/libreplaygain.rb Library/Formula/libtool.rb Library/Formula/libvbucket.rb Library/Formula/libvo-aacenc.rb Library/Formula/libxmi.rb Library/Formula/lifelines.rb Library/Formula/makeicns.rb Library/Formula/mathgl.rb Library/Formula/meld.rb Library/Formula/mesalib-glw.rb Library/Formula/minisat.rb Library/Formula/minuit2.rb Library/Formula/mobile-shell.rb Library/Formula/movgrab.rb Library/Formula/mp3cat.rb Library/Formula/mpich2.rb Library/Formula/mrfast.rb Library/Formula/musepack.rb Library/Formula/ndiff.rb Library/Formula/net6.rb Library/Formula/nrpe.rb Library/Formula/nuttcp.rb Library/Formula/oath-toolkit.Updating aa07533..3f070efAbortingError: Failed while executing git pull origin refs/heads/master:refs/remotes/origin/master
Now provide the response and nothing else.
| Don't forget to fetch the origin: cd /usr/local/Homebrewgit fetch origingit reset --hard origin/master What happens is that you are trying to update brew, but brew itself is either not up to date (likely), there is a permissions change via some OS update (also likely), or brew is slightly corrupt (unlikely). Since brew itself is a git repo, you have to update or reset brew to the master branch version. brew [by default] is located in the /usr/local/Homebrew folder, so you Go to that folder [first command] which also should update permissions (if not see below) Fetch the origin [second command] which means to update your LOCAL version of the remote branch of brew Hard reset [3rd command] based on the REMOTE master branch (which also uses your current permissions). You can also chown the first command if you are in a non sudo or admin profile sudo chown -R `whoami` /usr/local/Homebrewcd /usr/local/Homebrewgit reset --hard origin/master To understand git reset, take a look at this article . | {} | {'log_upvote_score': 11, 'links': ['https://Stackoverflow.com/questions/10762859', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/716082/']} | jdg_82707 |
stackexchange | llm_judgeable_groundtruth_similarity | 10782978 |
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 added some files to the index but then by mistake I deleted them with git reset --hard . How do I recover them?Here's what happened: I added all files using git add . I then committed When I checked the status, there were still files that weren't included in the commit from the add, which was strange I added the untracked files again and it worked this time But I wanted everything to be in 1 single commit so I looked up how to unstage what I just committed I used git reset --hard HEAD^ — bad idea obviously, all files were deleted so then I used git reflog to find where I left off then I used git reflog ______ to go back to my last commit. then I used git reset HEAD to unstage the commit (what I should have originally done) but the files I added (see above) after the commit were still gone. How do I get those files back?
Now provide the response and nothing else.
| First, make a full backup of your Git repository! When you git add a file, git will create a blob out of this file's content and add it to its object database ( .git/objects/??/* ). Let's look at your commands, one by one: I added all files using git add . $ git add . This will add all files contained in the current directory and its subdirectories to Git's object database. Untracked files matching patterns from .gitignore files will not be added. Tree files will also be written. Please see the end of my answer. I then committed $ git commit -m'added all files' This will write a new commit object to the object database. This commit will reference a single tree. The tree references blobs (files) and other trees (subdirectories). When I checked the status, there were still files that weren't included in the commit from the add, which was strange $ git status I can think of two scenarios where this happens: something modified your files or new files were added behind your back. I added the untracked files again and it worked this time $ git add . I assume you used the same add command again, as in step 1. But I wanted everything to be in 1 single commit so I looked up how to unstage what I just committed I will tell you a better way at the end of this answer, which does not require the user to issue a potentially dangerous reset I used git reset --hard HEAD^ — bad idea obviously, all files were deleted $ git reset --hard HEAD^ This command will set your current working tree and index to be exactly at the commit HEAD^ (the second-last commit). In other words, it will discard any local uncommitted changes and move the branch pointer back one commit. It does not touch untracked files. so then I used git reflog to find where I left off $ git reflog This shows the last commits that were recently checked out (identical to git reflog HEAD ). If you specify a branch name, it will show you the last commits that this branch pointed to recently. then I used git reflog __ to go back to my last commit. Not sure about this one. git reflog is (mostly) a read-only command and cannot be used to "get back" to commits. You can only use it, to find commits a branch (or HEAD ) pointed to. then I used git reset HEAD to unstage the commit (what I should have originally done) but the files I added (see above) after the commit were still gone. $ git reset HEAD This will not unstage this commit, but it will unstage all staged (but uncommitted) changes from the index. Originally (1st step), you wanted to say git reset HEAD^ (or git reset --mixed HEAD^ ) – this will leave your working tree untouched, but set the index to match the tree pointed to by the commit named by HEAD^ . Now, to get back your files, you have to use git fsck --full --unreachable --no-reflog . It will scan all objects in Git's object database and perform a reachability analysis. You want to look for blob objects. There should also be a tree object, describing the state after your second git add . git cat-file -p <object hash> will print the files content, so you can verify that you have the right objects. For blobs, you can use IO redirection to write the content to the correct file name. For trees, you have to use git commands ( git read-tree ). If it's only a few files, you are better off writing them directly to files. A few notes here: If you want to add files to the last commit (or edit its commit message), you can simply use git commit --amend . It's basically a wrapper around git reset --soft HEAD^ && git commit -c HEAD@{1} . Also, it's almost never a good idea to use git add . . Usually, you only want to use it the first time, when you are creating a new repository.Better alternatives are git add -u , git commit -a , which will stage all changes to tracked files. To track new files, better specify them explicitely. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/10782978', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1402685/']} | jdg_82708 |
stackexchange | llm_judgeable_groundtruth_similarity | 7730260 |
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 making a little experiment with WebSockets and Java. Apperantly, according to the last draft of WebSocket, the message can be binary or a plain string. I use Webbit server and it has two functions: public void onMessage(WebSocketConnection connection, String message) public void onMessage(WebSocketConnection connection, byte[] message) I wonder what makes a difference. Is byte[] faster? Or why does it matter? I can write everything I write with the bytes because even a string is composed into bytes while transfer, so why do we have two multiple methods? Only Google Chrome 15 Beta and 16 Dev supports binary transfer, so I was thinking of using Base64 encoding/decoding on both client and server. Is this the only difference? What if I just read each byte, compose them into a string and send them? I think, only difference will be that not all bytes are String chars, so I wouuld just add an overhead when converting to a String? tl;dr -> What is the difference between Binary transfer and String transfer?
Now provide the response and nothing else.
| The WebSocket protocol (HyBi) supports two different payload types: text, binary. The text payload is UTF-8 encoded string data. Any ASCII codes above 127 in the string that you send will be converted into a two-byte UTF-8 encoding. To successfully send/receive raw binary data you will probably want to encode the data in something like base64 (which is UTF-8 compatible). The binary payload type is sent directly. The bytes are sent as-is in the payload. This is more bandwidth efficient. It is means that you don't have to do an encode/decode step. The bytes you send get sent directly, and the bytes you receive can be accessed directly with no decoding. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7730260', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/337504/']} | jdg_82709 |
stackexchange | llm_judgeable_groundtruth_similarity | 222179 |
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:
Imagine a standard machine-learning scenario: You are confronted with a large multivariate dataset and you have a pretty blurry understanding of it. What you need to do is to make predictions about some variable based on what you have. As usual, you clean the data, look at descriptive statistics, run some models, cross-validate them etc., but after several attempts, going back and forth and trying multiple models nothing seems to work and your results are miserable. You can spend hours, days, or weeks on such a problem... The question is: when to stop? How do you know that your data actually is hopeless and all the fancy models wouldn't do you any more good than predicting the average outcome for all cases or some other trivial solution? Of course, this is a forecastability issue, but as far as I know, it is hard to assess forecastability for multivariate data before trying something on it. Or am I wrong? Disclaimer: this question was inspired by this one When have I to stop looking for a model? that did not attract much attention. It would be nice to have detailed answer to such question for reference.
Now provide the response and nothing else.
| Forecastability You are right that this is a question of forecastability. There have been a few articles on forecastability in the IIF's practitioner-oriented journal Foresight . (Full disclosure: I'm an Associate Editor.) The problem is that forecastability is already hard to assess in "simple" cases. A few examples Suppose you have a time series like this but don't speak German: How would you model the large peak in April, and how would you include this information in any forecasts? Unless you knew that this time series is the sales of eggs in a Swiss supermarket chain, which peaks right before western calendar Easter , you would not have a chance. Plus, with Easter moving around the calendar by as much as six weeks, any forecasts that don't include the specific date of Easter (by assuming, say, that this was just some seasonal peak that would recur in a specific week next year) would probably be very off. Similarly, assume you have the blue line below and want to model whatever happened on 2010-02-28 so differently from "normal" patterns on 2010-02-27: Again, without knowing what happens when a whole city full of Canadians watches an Olympic ice hockey finals game on TV, you have no chance whatsoever to understand what happened here, and you won't be able to predict when something like this will recur. Finally, look at this: This is a time series of daily sales at a cash and carry store. (On the right, you have a simple table: 282 days had zero sales, 42 days saw sales of 1... and one day saw sales of 500.) I don't know what item it is. To this day, I don't know what happened on that one day with sales of 500. My best guess is that some customer pre-ordered a large amount of whatever product this was and collected it. Now, without knowing this, any forecast for this particular day will be far off. Conversely, assume that this happened right before Easter, and we have a dumb-smart algorithm that believes this could be an Easter effect (maybe these are eggs?) and happily forecasts 500 units for the next Easter. Oh my, could that go wrong. Summary In all cases, we see how forecastability can only be well understood once we have a sufficiently deep understanding of likely factors that influence our data. The problem is that unless we know these factors, we don't know that we may not know them. As per Donald Rumsfeld : [T]here are known knowns; there are things we know we know. We also know there are known unknowns; that is to say we know there are some things we do not know. But there are also unknown unknowns – the ones we don't know we don't know. If Easter or Canadians' predilection for Hockey are unknown unknowns to us, we are stuck - and we don't even have a way forward, because we don't know what questions we need to ask. The only way of getting a handle on these is to gather domain knowledge. Conclusions I draw three conclusions from this: You always need to include domain knowledge in your modeling and prediction. Even with domain knowledge, you are not guaranteed to get enough information for your forecasts and predictions to be acceptable to the user. See that outlier above. If "your results are miserable", you may be hoping for more than you can achieve. If you are forecasting a fair coin toss, then there is no way to get above 50% accuracy. Don't trust external forecast accuracy benchmarks, either. The Bottom Line Here is how I would recommend building models - and noticing when to stop: Talk to someone with domain knowledge if you don't already have it yourself. Identify the main drivers of the data you want to forecast, including likely interactions, based on step 1. Build models iteratively, including drivers in decreasing order of strength as per step 2. Assess models using cross-validation or a holdout sample. If your prediction accuracy does not increase any further, either go back to step 1 (e.g., by identifying blatant mis-predictions you can't explain, and discussing these with the domain expert), or accept that you have reached the end of your models' capabilities. Time-boxing your analysis in advance helps. Note that I am not advocating trying different classes of models if your original model plateaus. Typically, if you started out with a reasonable model, using something more sophisticated will not yield a strong benefit and may simply be "overfitting on the test set". I have seen this often, and other people agree . | {} | {'log_upvote_score': 9, 'links': ['https://stats.stackexchange.com/questions/222179', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/35989/']} | jdg_82710 |
stackexchange | llm_judgeable_groundtruth_similarity | 39265396 |
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 docs provide good examples, how metadata can be provided . However I still feel unsure, when it comes to picking the right dtypes for my dataframe. Could I do something like meta={'x': int 'y': float,'z': float} instead of meta={'x': 'i8', 'y': 'f8', 'z': 'f8'} ? Could somebody hint me to a list of possible values like 'i8'? Whatdtypes exist? How can I specify a column, that contains arbitrary objects? How can I specify a column, that contains only instances of one class?
Now provide the response and nothing else.
| The available basic data types are the ones which are offered through numpy. Have a look at the documentation for a list. Not included in this set are datetime-formats (e.g. datetime64 ), for which additional information can be found in the pandas and numpy documentation. The meta-argument for dask dataframes usually expects an empty pandas dataframe holding definitions for columns, indices and dtypes. One way to construct such a DataFrame is: import pandas as pdimport numpy as npmeta = pd.DataFrame(columns=['a', 'b', 'c'])meta.a = meta.a.astype(np.int64)meta.b = meta.b.astype(np.datetime64) There is also a way to provide a dtype to the constructor of the pandas dataframe, however, I am not sure how to provide them for individual columns each. As you can see, it is possible to provide not only the "name" for datatypes, but also the actual numpy dtype. Regarding your last question, the datatype you are looking for is "object". For example: import pandas as pdclass Foo: def __init__(self, foo): self.bar = foodf = pd.DataFrame(data=[Foo(1), Foo(2)], columns=['a'], dtype='object')df.a# 0 <__main__.Foo object at 0x00000000058AC550># 1 <__main__.Foo object at 0x00000000058AC358> | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/39265396', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/5082048/']} | jdg_82711 |
stackexchange | llm_judgeable_groundtruth_similarity | 25505146 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I need to copy file form machine A to machine B whereas my control machine from where i run all my ansible tasks is machine C(local machine) I have tried the following: Use scp command in shell module of ansible hosts: machine2user: user2tasks: - name: Copy file from machine1 to machine2 shell: scp user1@machine1:/path-of-file/file1 /home/user2/file1 This approach just goes on and on never ends. use fetch & copy modules hosts: machine1user: user1tasks: - name: copy file from machine1 to local fetch: src=/path-of-file/file1 dest=/path-of-file/file1hosts: machine2user: user2tasks: - name: copy file from local to machine2 copy: src=/path-of-file/file1 dest=/path-of-file/file1 This approach throws me an error as follows: error while accessing the file /Users/<myusername>/.ansible/cp/ansible-ssh-machine2-22-<myusername>, error was: [Errno 102] Operation not supported on socket: u'/Users/<myusername>/.ansible/cp/ansible-ssh-machine2-22-<myusername>' Any suggestions would be helpful.
Now provide the response and nothing else.
| To copy remote-to-remote files you can use the synchronize module with ' delegate_to: source-server ' keyword: - hosts: serverB tasks: - name: Copy Remote-To-Remote (from serverA to serverB) synchronize: src=/copy/from_serverA dest=/copy/to_serverB delegate_to: serverA This playbook can run from your machineC. | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/25505146', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3228188/']} | jdg_82712 |
stackexchange | llm_judgeable_groundtruth_similarity | 377248 |
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:
I have been having trouble clearly defining/specifying how a URL/URI should be applied to situations such as search queries or different resource formats. The question is what an actual "uniform resource identifier" is, and how it should be applied to complex situations involving queries and formats. The REST paradigm (at least from my history with Ruby on Rails) made it so that you can define clean URLs that got rid of the older URL query parameter style in earlier PHP and related apps. So instead of: /?format=html&articleId=123 It became: /articles/123.html This made it so (what seems like) all URLs could be expressed "RESTfully" without using the ? . So it would be like: /:class1/:id/:class2/:id/... You can also get "collections" of resources like this: /articles That would return all the articles. But here's where the idea of URL and REST breaks down. Typically when you return data to /articles , it might be paginated, and might be the most recent articles. Let's say this is Twitter and there is a constant stream of new content. Then /tweets will constantly return something different than what was returned before. So the question is, what the actual "uniform resource" is. It seems clear to imagine a "uniform resource" when you are talking about an individual database record, like a user record. You have a list of properties, and an ID: id: 123email: [email protected]: Example name... That would be accessed via /users/123 . However, even this sort of breaks down, when you modify the user record. Say you change the email of the user: id: 123email: [email protected]: Example name... Now the same URL returns something different than before. To solve this, you start to bring in the idea of versions. So it might be like this: /users/123/v1/users/123/v2.../users/123/v<hash> But you don't really see that out in real-world apps. However, that data might be returned in an ETag or other HTTP header, so it is there somewhere, sometimes, but it's not in the URL, the "uniform resource identifier". So the URL is lacking some important uniqueness information. Another example is with queries. Searching in Google Chome for "StackOverflow" uses this URL: https://www.google.com/search?q=stackoverflow&oq=stackoverflow&aqs=chrome..123123.abcabc&sourceid=chrome&ie=UTF-8 There is no date or version information there, and the results are tailored to me, so the same URL will return something different for another user. Another example is with API calls for collections. A facebook URL that provides a cursor to paginated data is closer to a good "URL": https://graph.facebook.com/me/albums?limit=25&after=MA123123...= That unique after token probably goes to the database, which stored a set of IDs to use as the next query result if the API call is made, so in a sense it accurately captures the "uniqueness" in URL (unique resource identifier :p). But I'm not sure exactly how Facebook implements that, so it could still be off and not totally accurate in uniquely representing the resource (for example, maybe if new data is added in between now and the usage of that URL, it will return those new records in the result). The definition of URI from Wikipedia says: A Uniform Resource Identifier (URI) is a string of characters designed for unambiguous identification of resources and extensibility via the URI scheme. However, all of the cases presented here (twitter feed, google search results, facebook api response) are ambiguous. Even the simple REST api call to /users/123 is ambiguous because of the versioning changes to the user record. So my question is, if there is a solution to the problem of using URLs, or something like URLs, to accurately represent a unique resource. That seems like what IPFS and other blockchain technologies are partly doing, creating a unique hash from the content every time it changes (sort of like git). However, this only seems like it would work for objects, not for collections of objects, or api/search results. For that I haven't seen a solution. It is almost as if you want to accurately snapshot the state of the system at a particular time, and use that as a URL. So a search URL would look like this: /articles?titleMatches=foo×tamp=123123 And that would return a result set like Facebook's API does, paginated. But then the after cursor would essentially take a snapshot of the database state of all the objects at the current version they are at when that URL request was made. So the after cursor would contain data along the lines of: articleIdVersionHashes: [<hash1>, <hash2>, ...] That would make the URL uniquely identify the content. However, this would break down the meaning of the URL address bar in browsers. Typically you just want to go to https://twitter.com and see your home profile (content under the / URL that is unique to you, or if you are logged out, the Twitter homepage). The URL bar is more of a guideline than a U nique Resource Identifier. In all of these ways, it seems that the idea of URL is broken. Wondering if there are any solutions to this problem, or alternatives to the idea of a URL, and how to effectively think about the idea of uniquely representing a "resource" (and what a resource actually should mean). Basically I'm wondering if there is a better way to conceptualize the URL address bar, what it's meaning and purpose is. Because the name "URL" isn't accurately describing what's happening.
Now provide the response and nothing else.
| I'm afraid that you misunderstood the meaning of “unambiguous identification.” What it means is that an URI points to a specific resource, not that it points to an immutable entity. This also means that a resource may not exist at a given moment (HTTP 404) or may not be accessible in a specific context (HTTP 401), etc. An URI to your profile identifies precisely and unambiguously the resource which is your profile. It doesn't mean that all the calls to this URI would always result in the exact same response. Performing successive calls over time, you should expect some changes to the profile (for instance after you change your email address). The unambiguous part, however, ensures that whenever you call this URI, it will point to your profile . If URIs were ambiguous, a call to a same ambiguous URI could give the first time your profile, the second time your bookmarks, the third time the date of your last connection and the fourth time the number of users who used the app today. That is the ambiguity Wikipedia was talking about. Now to answer your question about how you can represent a given state of a mutable entity, you already have a great solution in your question. Store the snapshots of an entity, and include either the version or the hash of the snapshot in the URI. Of course, this doesn't mean the exact same call will still always give you the exact same result. For instance, if you did a call yesterday to retrieve a specific state of an entity, doing the same call today can result in, for instance, HTTP 401 if your API key expired during the night, or HTTP 404 if all traces of the entity were removed for legal reasons. If you absolutely need the response to always be the same, HTTP is not a good choice in your case. | {} | {'log_upvote_score': 5, 'links': ['https://softwareengineering.stackexchange.com/questions/377248', 'https://softwareengineering.stackexchange.com', 'https://softwareengineering.stackexchange.com/users/73722/']} | jdg_82713 |
stackexchange | llm_judgeable_groundtruth_similarity | 2656792 |
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 often want to do essentially the following: mat <- matrix(0,nrow=10,ncol=1)lapply(1:10, function(i) { mat[i,] <- rnorm(1,mean=i)}) But, I would expect that mat would have 10 random numbers in it, but rather it has 0. (I am not worried about the rnorm part. Clearly there is a right way to do that. I am worry about affecting mat from within an anonymous function of lapply) Can I not affect matrix mat from inside lapply? Why not? Is there a scoping rule of R that is blocking this?
Now provide the response and nothing else.
| I discussed this issue in this related question: " Is R’s apply family more than syntactic sugar ". You will notice that if you look at the function signature for for and apply , they have one critical difference: a for loop evaluates an expression, while an apply loop evaluates a function . If you want to alter things outside the scope of an apply function, then you need to use <<- or assign . Or more to the point, use something like a for loop instead. But you really need to be careful when working with things outside of a function because it can result in unexpected behavior. In my opinion, one of the primary reasons to use an apply function is explicitly because it doesn't alter things outside of it. This is a core concept in functional programming, wherein functions avoid having side effects . This is also a reason why the apply family of functions can be used in parallel processing (and similar functions exist in the various parallel packages such as snow). Lastly, the right way to run your code example is to also pass in the parameters to your function like so, and assigning back the output: mat <- matrix(0,nrow=10,ncol=1)mat <- matrix(lapply(1:10, function(i, mat) { mat[i,] <- rnorm(1,mean=i)}, mat=mat)) It is always best to be explicit about a parameter when possible (hence the mat=mat ) rather than inferring it. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/2656792', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/318976/']} | jdg_82714 |
stackexchange | llm_judgeable_groundtruth_similarity | 135961 |
Below is a question asked on the forum cs.stackexchange.com. Provide a good and informational response to it like a helpful human would.
Question:
While learning about computers I will read about RAM and Storage and the CPU, and while these explain the architecture of a computer and how parts of a computer work together, I still don't understand the fundamental workings of a computer program. Let me take an example. I'm on the web on a mac right now. When I push two fingers away from me on the trackpad, I understand that the trackpad is made up of a capacitive touch screen that, when your finger is placed on it, draws current and the trackpad detects that and converts it into data that explains the movement of my fingers up the screen. However, when you have this data in binary form, or machine code, it goes through logic gates and other things to make it in scroll down on the page. But what is actually happening here? How would the computer have physical things that operate differently based on the input? What operations are carried out on the machine code that says "if data looks like 01001010 10101010... send instruction 10010010... to CPU that tells computer to scroll down". Surely if you had some logic gates that turned input x into output y, yes they would give different outputs based on the input, but unless you somehow redirected the current to the right set of logic gates every time the action was carried out, how would it go to the correct one? To me this step is still magic. Especially with computers now that have no moving parts it seems even more alien. Could someone explain this to me?
Now provide the response and nothing else.
| This is a complex matter. To begin with, when you move your mouse, there is so much going on at once, that I cannot even begin to explain everything here. So, I will focus on the most fundamental thing: How does the computer actually compute? As you are probably familiar with, computers have memory called RAM, and a CPU that is able to execute "commands". Commands, are essentially some form of data, that allows the computer to decide which logic gates to pass the input to. At its core, this is the work of the ALU in the CPU. ALU stands for Arithmetic Logic Unit, and it had three inputs, contrary to what you may think. The first two inputs are normal inputs for the operations, for example: two numbers $a,b$ that we want to sum up. The third input, decides what operation to do on them. For example, you can encode that "0001" means we want to sum the two numbers, while "0010" might mean multiplication and "0011" is division. This ALU does this magic! This "magic" that decides based on the third input which operation to do, is done via applying a multiplexer circuit to take the output from the correct series of logic gates in the ALU. Basically, an $n$ -to- $1$ multiplexer is given $n$ "normal" inputs, and one "special" input that decides which of the $n$ inputs to output. Yes, it simply outputs one of its inputs without changing anything. Basically, if we think of its inputs as an list $inp$ , and the "special" input is called $s$ , then the output is $inp[s]$ . The ALU takes this, and gives to it as the $inp$ the list of all possible operations on the two numbers $a,b$ , and thats how the ALU knows which operation to apply when. | {} | {'log_upvote_score': 4, 'links': ['https://cs.stackexchange.com/questions/135961', 'https://cs.stackexchange.com', 'https://cs.stackexchange.com/users/132443/']} | jdg_82715 |
stackexchange | llm_judgeable_groundtruth_similarity | 58654309 |
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 install google-chrome-stable on alpine image using dpkg. However, the dpkg is installed but it does not install google-chrome-stable and return this error instead? Is there a way to install google-chrome-stable in alpine image either using dpkg or other way? dpkg: regarding google-chrome-stable_current_amd64.deb containing google-chrome-stable:amd64, pre-dependency problem: google-chrome-stable:amd64 pre-depends on dpkg (>= 1.14.0)dpkg: error processing archive google-chrome-stable_current_amd64.deb (--install): pre-dependency problem - not installing google-chrome-stable:amd64Errors were encountered while processing: Dockerfile: # Base imageFROM ruby:2.6.3-alpine3.10# Use node version 10.16.3, yarn version 1.16.0RUN apk add --no-cache --repository http://dl-cdn.alpinelinux.org/alpine/v3.10/main/ nodejs=10.16.3-r0RUN apk add --no-cache --repository http://dl-cdn.alpinelinux.org/alpine/v3.10/community/ yarn=1.16.0-r0# Install dependenciesRUN apk upgradeRUN apk --update \ add build-base \ git \ tzdata \ nodejs \ nodejs-npm \ bash \ curl \ yarn \ gzip \ postgresql-client \ postgresql-dev \ imagemagick \ imagemagick-dev \ imagemagick-libs \ chromium \ chromium-chromedriver \ ncurses \ less \ dpkg=1.19.7-r0 \ chromium \ chromium-chromedriverRUN dpkg --add-architecture amd64RUN wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.debRUN dpkg -i google-chrome-stable_current_amd64.deb# This is the base directory used in any# further COPY, RUN and ENTRYPOINT commandsWORKDIR /webapp# Copy Gemfile and Gemfile.lock and run bundle installCOPY Gemfile* /webapp/RUN gem install bundler -v '1.17.3' && \ bundle _1.17.3_ install# Copy everything to /webapp for docker imageCOPY . ./EXPOSE 3000# Run the applicationCMD ["rails", "server", "-b", "0.0.0.0"]
Now provide the response and nothing else.
| Installing the Chrome .deb file this way won't work on Alpine. While the dpkg package is available in the Alpine repository, and is useful for installing lightweight Debian packages, you won't be able to use it for installing complex Debian packages, since it'll be impossible to satisfy many Debian dependencies. Alpine is generally not Debian compatible (relying on musl libc ), so installing native Alpine packages using apk is the right way to go. AFAIK, there's currently no Google Chrome Alpine Linux compatible, musl-libc build. You could, however, install the Chromium browser, which is available using an apk package: apk add chromium Another option is enabling glibc on a vanilla Alpine image, making it compatible with Debian binaries. This is a fairly simple procedure, see: Dockerfile . However, it may not be suitable for images with existing applications such as ruby:2.6.3-alpine3.10 . Moreover, even with a glibc setup on Alpine, Chrome is not likely to run without issues. I have made a quick attempt ( Dockerfile ) but couldn't get past the first segfault. Edit 9/5/21 : Running the debian compatible Chrome stable on Alpine is going to be a very difficult task to say the least. This is in part due to the very large number of dependencies and libraries. Trying to run it results with segfaults during dynamic linking and finally assertions from the dynamic linker. Even if we manage to get passed these issues and start Chrome it will probably be very unstable. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/58654309', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/7397660/']} | jdg_82716 |
stackexchange | llm_judgeable_groundtruth_similarity | 23914303 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I've got response as json array ['1', '1', '2'] or as json array of objects [{'name': 'blabla', age: '30'}, {'name': 'lala', age: '35'}] And I would like to arrays to grails objects, what grails features can I use in this case? I'm looking at command objects , but also found @Validatable annotation. What to use for binding json to grails object ( without persistence )?
Now provide the response and nothing else.
| In most cases there is no difference in writing a or (a) . The relevant part of the spec is §5.1p6 (emphasis mine): A parenthesized expression is a primary expression whose type and value are identical to those of the enclosed expression. The presence of parentheses does not affect whether the expression is an lvalue. The parenthesized expression can be used in exactly the same contexts as those where the enclosed expression can be used, and with the same meaning , except as otherwise indicated. Hence, the same reasoning applies to the return value of your function g as you have given for f . In the upcomming standard C++14 this has been clarified §12.8p32 (emphasis mine): When the criteria for elision of a copy/move operation are met, but not for an exception-declaration, and the object to be copied is designated by an lvalue, or when the expression in a return statement is a ( possibly parenthesized ) id-expression that names an object with automatic storage duration declared in the body or parameter-declaration-clause of the innermost enclosing function or lambda-expression, overload resolution to select the constructor for the copy is first performed as if the object were designated by an rvalue. For those who want to know, when the parentheses matter, here is an example: namespace N {struct S { }; void f(S);}void g() { N::S s; f(s); // OK: calls N::f (f)(s); // error: N::f not considered; parentheses // prevent argument-dependent lookup} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/23914303', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1815058/']} | jdg_82717 |
stackexchange | llm_judgeable_groundtruth_similarity | 7059721 |
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 array_merge() with associative arrays I get what I want, but when I use them with numerical key arrays the keys get changed. With + the keys are preserved but it doesn't work with associative arrays. I don't understand how this works, can anybody explain it to me?
Now provide the response and nothing else.
| Because both arrays are numerically-indexed, only the values in the first array will be used. The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored. http://php.net/manual/en/language.operators.array.php array_merge() has slightly different behavior: If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. Values in the input array with numeric keys will be renumbered with incrementing keys starting from zero in the result array. http://php.net/manual/en/function.array-merge.php | {} | {'log_upvote_score': 8, 'links': ['https://Stackoverflow.com/questions/7059721', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/894243/']} | jdg_82718 |
stackexchange | llm_judgeable_groundtruth_similarity | 376668 |
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:
Take $P\in\mathbb{Z}[X]$ and factorize it modulo $p$, where $p$ is a prime. Modulo different $p$'s the factorization varies. Is there a pattern in this variation? I mean, for example, if $P$ is quartic, it can factorize as "linear*cubic", "quadratic*quadratic", "quadratic*linear*linear" and so on. Does it tend to factorize more in one way than in the other ways? I came up with this question, because I am calculating these factorizations of a few polynomials, and they tend to "prefer" certain ways of factorization. This is looking curious, though of course, it could just be the odds.
Now provide the response and nothing else.
| No, you are onto something. I like to use the variable $z$ for this. I forget what happens if you factor $z^3 - 2 \pmod 3.$ After that, there is one simple pattern when $p \equiv 2 \pmod 3,$ when you factor $z^3 - 2 \pmod p.$ That is, a linear factor times a quadratic. Here is the cute bit: once $p \equiv 1 \pmod 3,$ and you factor $z^3 - 2 \pmod p,$ you get two wildly different outcomes: if there is an expression $p = x^2 + 27 y^2$ in integers, you get three linear terms, distinct. However, if $p = 4 x^2 + 2 x y + 7 y^2,$ irreducible. Go Figure. A similar example, see Numbers represented by a cubic form and factor $$ z^3 - z^2 - z - 1 $$ separately for primes with Legendre $(p|11) = -1$ and then for $p = x^2 + 11 y^2$ and then for $p = 3 x^2 + 2 x y + 4 y^2.$ As before, when there is an $xy$ term, you need to allow $xy$ both positive and negative to get all possible such primes. For example, with $x=1,y=-1,3 x^2 + 2 x y + 4 y^2 =5. $ Quartic examples: factor $z^4 + 3 \pmod p,$ when (A) $p=2,3$, (B) larger $p \equiv 3 \pmod 4,$ (C) $p = 5 x^2 \pm 4 xy + 8 y^2,$ (D) $p = 4 x^2 + 9 y^2,$ (E) $p = x^2 + 36 y^2$ Factor $z^4 + 2 z^2 - 7 \pmod p,$ when (A) $(-56|p) = -1,$ (B) $p = 3 x^2 \pm 2 xy + 5 y^2,$ (C) $p = 2 x^2 + 7 y^2,$ (D) $p = x^2 + 14 y^2.$ This is the one that is worked out in full in David A. Cox, Primes of the Form $x^2 + n y^2.$ On page 188 of that book, Theorem 9.12 gives the frequencies of the types of primes I have been specifying. This is an application of the Chebotarev Density that Qiaochu mentions. I LIKE EXAMPLES. SUE ME. ============================= ================================= | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/376668', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/26655/']} | jdg_82719 |
stackexchange | llm_judgeable_groundtruth_similarity | 33609832 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I use uwp navigation example as an example for my application navigation. I need to set the focus on TextBox. I try it on uwp navigation example . For BasicPage I add this code: <StackPanel Orientation="Vertical"> <TextBox x:Name="Test" /> <TextBox x:Name="Test1" /> </StackPanel> public BasicPage() { this.InitializeComponent(); this.Loaded += BasicPage_Loaded; } private void BasicPage_Loaded(object sender, RoutedEventArgs e) { Test1.Focus(FocusState.Programmatic); } Test1 does not receive the focus. I try this code in a "normal" windows universal app - it is work. What do you advise?
Now provide the response and nothing else.
| It is because Focus function gets called in other place after you call the Test1.Focus. In AppShell.xaml.cs, you can find the following code: private void OnNavigatedToPage(object sender, NavigationEventArgs e){ // After a successful navigation set keyboard focus to the loaded page if (e.Content is Page && e.Content != null) { var control = (Page)e.Content; control.Loaded += Page_Loaded; }}private void Page_Loaded(object sender, RoutedEventArgs e){ ((Page)sender).Focus(FocusState.Programmatic); ((Page)sender).Loaded -= Page_Loaded; this.CheckTogglePaneButtonSizeChanged();} The above code means when you navigate to a page, it will subscribe the page loaded event and set the focus on page. Your code subscribe the page loaded event in the page itself. And your code will be executed before the Page_Loaded function in AppShell. So you didn't get what you want. So if you simply comment out ((Page)sender).Focus(FocusState.Programmatic); in the Page_Loaded function. You will get what you want. I am not sure what's the exact purpose of that line. But everything seems good. If you do find something wrong after comment out that line, we can also work it around. Call the focus function once in LayoutUpdated event after loaded event. public sealed partial class BasicPage : Page{ bool bAfterLoaded = false; public BasicPage() { this.InitializeComponent(); this.Loaded += BasicPage_Loaded; this.LayoutUpdated += BasicPage_LayoutUpdated; } private void BasicPage_LayoutUpdated(object sender, object e) { if (bAfterLoaded) { Test1.Focus(FocusState.Programmatic); bAfterLoaded = !bAfterLoaded; } } private void BasicPage_Loaded(object sender, RoutedEventArgs e) { bAfterLoaded = !bAfterLoaded; }} Hope this can help you. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/33609832', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/631843/']} | jdg_82720 |
stackexchange | llm_judgeable_groundtruth_similarity | 6054016 |
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 find out day of the week given date in just one line of C code? For example Given 19-05-2011(dd-mm-yyyy) gives me Thursday
Now provide the response and nothing else.
| A one-liner is unlikely, but the strptime function can be used to parse your date format and the struct tm argument can be queried for its tm_wday member on systems that modify those fields automatically (e.g. some glibc implementations). int get_weekday(char * str) { struct tm tm; memset((void *) &tm, 0, sizeof(tm)); if (strptime(str, "%d-%m-%Y", &tm) != NULL) { time_t t = mktime(&tm); if (t >= 0) { return localtime(&t)->tm_wday; // Sunday=0, Monday=1, etc. } } return -1;} Or you could encode these rules to do some arithmetic in a really long single line: 1 Jan 1900 was a Monday. Thirty days has September, April, June and November; all the rest have thirty-one, saving February alone, which has twenty-eight, rain or shine, and on leap years, twenty-nine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. EDIT: note that this solution only works for dates after the UNIX epoch (1970-01-01T00:00:00Z). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/6054016', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/441077/']} | jdg_82721 |
stackexchange | llm_judgeable_groundtruth_similarity | 30568258 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I'm trying to use ANSI escape sequences to set the color of my zsh prompt, but the escape character ( \e ) seems to be being escaped when displaying the prompt. Here's an example of what I'm running and the output I'm getting: > autoload promptinit && promptinit> autoload colors && colors> echo "Not sure if those two lines are required" > /dev/null> PROMPT="\e[32mhi> "\e[32mhi> echo "Note that the escape character wasn't interpreted correctly" > /dev/null\e[32mhi> print -P "$PROMPT"hi>\e[32mhi> echo "The hi> was printed in green, as I want" > /dev/null The zsh print documentation seems to say the -P flag makes it print as if it was in the prompt, but it doesn't match the actual prompt behavior. Does anyone know why the escape character doesn't work? I tried using $fg_no_bold , and things like $fg_no_bold[red] do work, but I'd like to use more than the 8 standard colors, but $fg_no_bold[32] doesn't work (for any number, not just 32). If getting 256 colors working with $fg_no_bold is easier, then I'd be ok doing that! Thanks!
Now provide the response and nothing else.
| You need to use dollar single quote in order to tell zsh to interpret ANSI escape sequences.So PROMPT=$'\e[32mhi> ' will do what you want, however it is safer to additionally put all special codes inside %{...%} brackets to treat code literally and prevent unwanted moving of the cursor position.Moreover you should change back the colour to the default, unless you want to colourize all terminal text foreground to green. After all your prompt setting should look like PROMPT=$'%{\e[32m%}hi> %{\e[0m%}' | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/30568258', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/4948030/']} | jdg_82722 |
stackexchange | llm_judgeable_groundtruth_similarity | 133398 |
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:
Lets say that there are only two bodies in the universe, 65 kg each. Other than that the universe is completely empty, no neutrons, no photons, no dark energy/matter, not even neutrinos (that is to make things less complicated. If the loss of other things leads to something like the universe exploding like a bubble at the speed of light or something, you can change these parameters. I'm mainly concerned about gravity here). Those two bodies are placed apart from each other at the distance of the observable universe. Will they start moving into each other? Will they collide? (Optional question: If so, with how much speed will they collide?)
Now provide the response and nothing else.
| I assume a steady-state universe and that the bodies have no velocity relative to each other. Yes, they will eventually collide. Gravity has an effect over any distance, including the ~46 billion light-year radius that constitutes the spherical observable universe (the actual size of the universe may be much larger). Of course, the force will not be very strong over a 100 billion light-year separation, so the bodies would not collide for a very long time. A rough estimate of the time taken would be on the order of billions of years. EDIT: As pointed out in the comments, the above time estimation was wrong by a over a factor of $10^{20}$. The amount of time taken would be around $10^{38}$ years (100 undecillion years or 100 sextillion years, depending on whether you subscribe to the short scale or long scale ). The equation used to find this number can be found here . | {} | {'log_upvote_score': 4, 'links': ['https://physics.stackexchange.com/questions/133398', 'https://physics.stackexchange.com', 'https://physics.stackexchange.com/users/58292/']} | jdg_82723 |
stackexchange | llm_judgeable_groundtruth_similarity | 9322773 |
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 dataframe with the lengths and widths of various arthropods from the guts of salamanders. Because some guts had thousands of certain prey items, I only measured a subset of each prey type. I now want to replace each unmeasured individual with the mean length and width for that prey. I want to keep the dataframe and just add imputed columns (length2, width2). The main reason is that each row also has columns with data on the date and location the salamander was collected. I could fill in the NA with a random selection of the measured individuals but for the sake of argument let's assume I just want to replace each NA with the mean. For example imagine I have a dataframe that looks something like: id taxa length width101 collembola 2.1 0.9102 mite 0.9 0.7103 mite 1.1 0.8104 collembola NA NA105 collembola 1.5 0.5106 mite NA NA In reality I have more columns and about 25 different taxa and a total of ~30,000 prey items in total. It seems like the plyr package might be ideal for this but I just can't figure out how to do this. I'm not very R or programming savvy but I'm trying to learn. Not that I know what I'm doing but I'll try to create a small dataset to play with if it helps. exampleDF <- data.frame(id = seq(1:100), taxa = c(rep("collembola", 50), rep("mite", 25), rep("ant", 25)), length = c(rnorm(40, 1, 0.5), rep("NA", 10), rnorm(20, 0.8, 0.1), rep("NA", 5), rnorm(20, 2.5, 0.5), rep("NA", 5)), width = c(rnorm(40, 0.5, 0.25), rep("NA", 10), rnorm(20, 0.3, 0.01), rep("NA", 5), rnorm(20, 1, 0.1), rep("NA", 5))) Here are a few things I've tried (that haven't worked): # mean imputation to recode NA in length and width with means (could do random imputation but unnecessary here)mean.imp <- function(x) { missing <- is.na(x) n.missing <-sum(missing) x.obs <-a[!missing] imputed <- x imputed[missing] <- mean(x.obs) return (imputed) } mean.imp(exampleDF[exampleDF$taxa == "collembola", "length"])n.taxa <- length(unique(exampleDF$taxa))for(i in 1:n.taxa) { mean.imp(exampleDF[exampleDF$taxa == unique(exampleDF$taxa[i]), "length"])} # no way to get back into dataframe in proper places, try plyr? another attempt: imp.mean <- function(x) { a <- mean(x, na.rm = TRUE) return (ifelse (is.na(x) == TRUE , a, x)) } # tried but not sure how to use this in ddplyDiet2 <- ddply(exampleDF, .(taxa), transform, length2 = function(x) { a <- mean(exampleDF$length, na.rm = TRUE) return (ifelse (is.na(exampleDF$length) == TRUE , a, exampleDF$length)) }) Any suggestions?
Now provide the response and nothing else.
| Not my own technique I saw it on the boards a while back: dat <- read.table(text = "id taxa length width101 collembola 2.1 0.9102 mite 0.9 0.7103 mite 1.1 0.8104 collembola NA NA105 collembola 1.5 0.5106 mite NA NA", header=TRUE)library(plyr)impute.mean <- function(x) replace(x, is.na(x), mean(x, na.rm = TRUE))dat2 <- ddply(dat, ~ taxa, transform, length = impute.mean(length), width = impute.mean(width))dat2[order(dat2$id), ] #plyr orders by group so we have to reorder Edit A non plyr approach with a for loop: for (i in which(sapply(dat, is.numeric))) { for (j in which(is.na(dat[, i]))) { dat[j, i] <- mean(dat[dat[, "taxa"] == dat[j, "taxa"], i], na.rm = TRUE) }} Edit many moons later here is a data.table & dplyr approach: data.table library(data.table)setDT(dat)dat[, length := impute.mean(length), by = taxa][, width := impute.mean(width), by = taxa] dplyr library(dplyr)dat %>% group_by(taxa) %>% mutate( length = impute.mean(length), width = impute.mean(width) ) | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/9322773', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1019128/']} | jdg_82724 |
stackexchange | llm_judgeable_groundtruth_similarity | 1989649 |
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 a GZIPInputStream in my program, and I know that the performance would be helped if I could get Java running my program in parallel. In general, is there a command-line option for the standard VM to run on many cores? It's running on just one as it is. Thanks! Edit I'm running plain ol' Java SE 6 update 17 on Windows XP. Would putting the GZIPInputStream on a separate thread explicitly help? No! Do not put the GZIPInputStream on a separate thread! Do NOT multithread I/O! Edit 2 I suppose I/O is the bottleneck, as I'm reading and writing to the same disk... In general, though, is there a way to make GZIPInputStream faster? Or a replacement for GZIPInputStream that runs parallel? Edit 3 Code snippet I used: GZIPInputStream gzip = new GZIPInputStream(new FileInputStream(INPUT_FILENAME));DataInputStream in = new DataInputStream(new BufferedInputStream(gzip));
Now provide the response and nothing else.
| AFAIK the action of reading from this stream is single-threaded, so multiple CPUs won't help you if you're reading one file. You could, however, have multiple threads, each unzipping a different file. That being said, unzipping is not particularly calculation intensive these days, you're more likely to be blocked by the cost of IO (e.g., if you are reading two very large files in two different areas of the HD). More generally (assuming this is a question of someone new to Java), Java doesn't do things in parallel for you. You have to use threads to tell it what are the units of work that you want to do and how to synchronize between them. Java (with the help of the OS) will generally take as many cores as is available to it, and will also swap threads on the same core if there are more threads than cores (which is typically the case). | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/1989649', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/203104/']} | jdg_82725 |
stackexchange | llm_judgeable_groundtruth_similarity | 72101414 |
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 learning functions and trying to create a function which takes an array as a parameter. function printArray(arr){ for (let i = 0; i < arr.length; i++){ let upperCased = arr[i].toUpperCase(); return upperCased; };}const testArray = ['o', 'p'];printArray(testArray); However, it returns only the first value 'O'
Now provide the response and nothing else.
| Thanks to Chris for the explanation and links to look around. TL;DR One can safely use the command git config --global core.fsmonitor true to get rid of the message for good. The answer to the what is in Chris's answer and to why is below. Seems like both of them are interconnected and hence they haven't yet disabled one. The new FSMonitor feature is controlled by the core.useBuiltinFSMonitor boolean. Link In a recent post they seemed to have addressed this issue . So I understand that the builtin FS monitor is not actually deprecated, just that the name in the config is going to change, is there, on the current version, any way to use the new name or is the only way to get rid of the message to disable it via the provided command? I guess we should clarify by saying core.useBuiltinFSMonitor=true was experimental, please set core.fsmonitor=true` instead. Link And finnaly, the reason for the prompt: With the feature going upstream into core Git, a decision was made to overload the existing core.fsmonitor setting to take a hook-pathname or a boolean value for the builtin FSMonitor. However, users may have multiple versions of Git installed on their systems on Windows . One in the C:/program files/... and hidden versions installed by tools like Visual Studio. And these may be at different revision levels, so one install might only understand the old keyword and one version might understand both (during the transition). So, auto transitioning it would break whichever one is the older release. So it's safer to just warn the user and let them decide. (And if they know they have multiple versions, they can just set both for now.) Link | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/72101414', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/17235455/']} | jdg_82726 |
stackexchange | llm_judgeable_groundtruth_similarity | 83324 |
Below is a question asked on the forum mathoverflow.net. Provide a good and informational response to it like a helpful human would.
Question:
Hi MathOverflow, I'm not sure if it makes sense to ask this question in the general setting, but: Are there any necessary conditions for a function, such that if $N$ is a not Lebesgue measurable, $f(N)$ is Lebesgue measurable? I am working on a problem, which seems to suggest that there are no 'trivial' conditions on the function (in particular, $f$ can be injective, which is a surprise to me). The problem is a as follows: Pick a non Lebesgue measurable set $N \subset (0,1) \subset \mathbb{R}$ and write $x \in (0,1)$ in an infinite binary expansion, i.e. $x = 0.x_1x_2...$ with $x_i = 0$ or $1$ and infinitely many $x_i$'s equal to $1$ (this is ok, since $0.1 = 0.0111...$). Now, take $f(x) = 2 \sum_{i=1}^{\infty} x_i 3^{-i}$. Then $f(N)$ is Lebesgue measurable, since it maps any set to a Cantor-like set (of measure zero) (thanks to Tapio Rajala for the easy solution). $f$ just takes $x$ to a base $3$ representation with no $1$'s in the expansion, thus is clearly injective. It sort of "spreads out" the elements of set $N$. Also, clearly $f(N) \subset (0,1)$. The thing that bothers me is that this seems to suggest that this $f$ is able to transform any non-measurable set into a measurable one, without really "loosing information" about it (because it is injective), which just sounds too good to be true. I tried to look for sources on functions applied on non-Lebesgue measurable sets, but failed to find anything, so if anyone could guide me to some I would highly appreciate it too. Thanks.
Now provide the response and nothing else.
| My guess is that the characterization is the following: A function $f$ maps every non-measurable set into a measurable set if and only if the domain or the image of $f$ has measure zero. One direction is trivial. For the other direction assume that the image of $f$ is positive. Take a non-measurable subset $N$ of the image and a measurable subset $M$ of the image so that $N$ and $M$ are well separated. $f^{-1}(N)$ and $f^{-1}(M)$ are well separated. $f^{-1}(M)$ has positive measure. Take a non-measurable subset $K$ of $f^{-1}(M)$ and consider $K \cup f^{-1}(N)$. This set is non-measurable and so is its image under $f$. Are there more mistakes hidden somewhere? | {} | {'log_upvote_score': 4, 'links': ['https://mathoverflow.net/questions/83324', 'https://mathoverflow.net', 'https://mathoverflow.net/users/12597/']} | jdg_82727 |
stackexchange | llm_judgeable_groundtruth_similarity | 14836958 |
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 setup for packages (not sure if there is a better recommended one): (require 'package)(setq package-archives '(("ELPA" . "http://tromey.com/elpa/") ("gnu" . "http://elpa.gnu.org/packages/") ("marmalade" . "http://marmalade-repo.org/packages/"))); Apparently needed for the package auto-complete (why?)(add-to-list 'package-archives '("melpa" . "http://melpa.milkbox.net/packages/") t)(package-initialize)(setq url-http-attempt-keepalives nil) I have three questions related to the installation and updating of packages. Q1. Is there a way to update the list of available packages (and most recent versions) and update a specific package? Q.2 What is the difference between the following package sources?: ELPA, GNU marmalade melpa Q.3 Does it matter the order in which they are added to package-archives ?
Now provide the response and nothing else.
| In order to automatically update the list of packages, only if there is no package list already , use the following: (when (not package-archive-contents) (package-refresh-contents)) In order to update all installed packages, type package-list-packages , which will take you to the *Packages* buffer (and also update the list of packages), and then type U x . package-refresh-contents unconditionally tries to download a package list from all repos you've added to package-archives ; package-archive-contents is non nil if you have already downloaded the package list. ELPA is the original. I don't think it's really maintained anymore, but I'm not sure. I don't use it. GNU is "official". It's maintained along with Emacs, which means things should always work but updates and new packages don't come very often. Marmalade is basically a website where you can upload a complete package, and it will be added to the marmalade repo. You don't just submit a link to the package's upstream, and it doesn't quite automate the creation of the package completely. I think this is the Right Thing, because you don't necessarily want to track upstream. Unfortunately, it has been unmaintained for a while, but someone recently took it over so it should be back and better at some point. Melpa takes a URL to e.g. the EmacsWiki lisp area or a github repo, and builds a package automatically from it. Thus it is usually at most a day behind whatever it is tracking. Although it tracks upstream, I've never had a problem in practice, and this is where most of my packages are from. There is also Melpa Stable , which is like Melpa but grabs tagged revisions of the upstream repo instead of the latest revision. Melpa stable has fewer packages than Melpa. Org mode has its own package.el repo ( http://orgmode.org/elpa/ ). All of the package repos work the same, you just add them to your package-archives . Here's a more in-depth blog post about this subject, which I mostly agree with. I'm not sure, but I think if a package is duplicated in different repos, the order the repos appear in in package-archives determines precedence. I don't know if higher precedence is at the beginning or end of the list. Update: In Emacs 25, there is a variable package-archive-priorities that you can use to prioritize your package repos (e.g. prefer ELPA over MELPA). Here is the relevant section of my init.el , if you're interested: (setq jpk-packages '( ac-dabbrev ... yasnippet ))(package-initialize)(add-to-list 'package-archives '("melpa" . "http://melpa.org/packages/"))(add-to-list 'package-archives '("org" . "http://orgmode.org/elpa/"));; install any packages in jpk-packages, if they are not installed already(let ((refreshed nil)) (when (not package-archive-contents) (package-refresh-contents) (setq refreshed t)) (dolist (pkg jpk-packages) (when (and (not (package-installed-p pkg)) (assoc pkg package-archive-contents)) (unless refreshed (package-refresh-contents) (setq refreshed t)) (package-install pkg))))(defun package-list-unaccounted-packages () "Like `package-list-packages', but shows only the packages that are installed and are not in `jpk-packages'. Useful for cleaning out unwanted packages." (interactive) (package-show-package-list (remove-if-not (lambda (x) (and (not (memq x jpk-packages)) (not (package-built-in-p x)) (package-installed-p x))) (mapcar 'car package-archive-contents)))) | {} | {'log_upvote_score': 9, 'links': ['https://Stackoverflow.com/questions/14836958', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/283296/']} | jdg_82728 |
stackexchange | llm_judgeable_groundtruth_similarity | 5973618 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
I have created a Greenhouse Monitoring system using SunSPOTS. The code modules are written in java.The problem I face is that I need to run these programs using ant commands. Im able to do it through a terminal independently but Im unable to find a way to build a gui and execute these modules through that. Any kind of help is welcome. Thanks
Now provide the response and nothing else.
| Some points: You need to return something in either case. Even if you return null on if(condition > 10) , your next compilation error will say you need to return a value on every path (actually, that's the same compilation error) GetObjectValue(obj,condition); may result in an infinite recursion - you call it with the same values over and over. You cannot "do stuff" after a return statement - that marks the end of the executed code (unless you have a finally block, but that's another subject). If you don't want to return that value that's also great, but you probably want to use it somehow: object returnedValue = GetObjectValue(obj, condition); You may be looking for something like: public object GetObjectValue(object obj, int condition){ if(condition > 10) { //exit from method return null; } else { IChild current = (IChild)obj //Do stuffs HERE return GetObjectValue(current.Parent, condition + 1); recursive call. }} | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/5973618', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/749931/']} | jdg_82729 |
stackexchange | llm_judgeable_groundtruth_similarity | 20882062 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
How can I call a nested hash of methods names on an object? For example, given the following hash: hash = {:a => {:b => {:c => :d}}} I would like to create a method that, given the above hash, does the equivalent of the following: object.send(:a).send(:b).send(:c).send(:d) The idea is that I need to get a specific attribute from an unknown association (unknown to this method, but known to the programmer). I would like to be able to specify a method chain to retrieve that attribute in the form of a nested hash. For example: hash = {:manufacturer => {:addresses => {:first => :postal_code}}}car.execute_method_hash(hash)=> 90210
Now provide the response and nothing else.
| I'd use an array instead of a hash, because a hash allows inconsistencies (what if there is more than one key in a (sub)hash?). object = Thing.newobject.call_methods [:a, :b, :c, :d] Using an array, the following works: # This is just a dummy class to allow introspection into what's happening# Every method call returns self and puts the methods name.class Thing def method_missing(m, *args, &block) puts m self endend# extend Object to introduce the call_methods methodclass Object def call_methods(methods) methods.inject(self) do |obj, method| obj.send method end endend Within call_methods we use inject in the array of symbols, so that we send every symbol to the result of the method execution that was returned by the previous method send. The result of the last send is automatically returned by inject . | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20882062', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1202726/']} | jdg_82730 |
stackexchange | llm_judgeable_groundtruth_similarity | 2353542 |
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 know from my intuition that the sequence $$x_n=\left(1-\cfrac{1}{3}\right)^2 \left(1-\cfrac{1}{6}\right)^2 \left(1-\cfrac{1}{10}\right)^2\cdots \cdots\left(1-\cfrac{1}{\cfrac{n\left(n+1\right)}{2}}\right)^2,\quad n\geq2$$ is convergent. But i don't know how to prove it.I almost try to apply every theorem I know (for eg ratio test ,monotone convergence theorem,...). Help me to prove this. Proof or idea is needed.Where does the sequence converge to?
Now provide the response and nothing else.
| $$\prod_{k=2}^n\left(1-\frac{2}{k(k+1)}\right)=\prod_{k=2}^n\frac{(k+2)(k-1)}{k(k+1)}=$$$$\frac{4\cdot1}{2\cdot3}\cdot\frac{5\cdot2}{3\cdot4}\cdot\frac{6\cdot3}{4\cdot5}\cdot...\cdot\frac{n(n-3)}{(n-2)(n-1)}\cdot\frac{(n+1)(n-2)}{(n-1)n}\cdot\frac{(n+2)(n-1)}{n(n+1)}=\frac{n+2}{3n}$$ | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2353542', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/355833/']} | jdg_82731 |
stackexchange | llm_judgeable_groundtruth_similarity | 20033201 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
While this code will raise indexError: In [1]: lst = [1, 2, 3]In [2]: lst[3]IndexError: list index out of range Slicing the list with "out of range index" will not produce any error. In [3]: lst[3:]Out[3]: [] What is the rationale of this design?
Now provide the response and nothing else.
| When you are accessing an element in a list whose index is beyond its length, we cannot return anything. (There is no way we can represent an element which is not there). That's why the error is thrown. But when you are slicing, you are making a sliced COPY of the original list and that new list can be empty if the start or end are not valid. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/20033201', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1471491/']} | jdg_82732 |
stackexchange | llm_judgeable_groundtruth_similarity | 21300924 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
My question is : does it make sense to use Executors.newFixedThreadPool(1)?? . In two threads (main + oneAnotherThread) scenarios is it efficient to use executor service?. Is creating a new thread directly by calling new Runnable(){ } better than using ExecutorService?. What are the upsides and downsides of using ExecutorService for such scenarios? PS: Main thread and oneAnotherThread dont access any common resource(s). I have gone through : What are the advantages of using an ExecutorService? . and Only one thread at a time!
Now provide the response and nothing else.
| does it make sense to use Executors.newFixedThreadPool(1) ? It is essentially the same thing as an Executors.newSingleThreadExecutor() except that the latter is not reconfigurable, as indicated in the javadoc , whereas the former is if you cast it to a ThreadPoolExecutor . In two threads (main + oneAnotherThread) scenarios is it efficient to use executor service? An executor service is a very thin wrapper around a Thread that significantly facilitates the thread lifecycle management. If the only thing you need is to new Thread(runnable).start(); and move on, then there is no real need for an ExecutorService. In any most real life cases, the possibility to monitor the life cycle of the tasks (through the returned Future s), the fact that the executor will re-create threads as required in case of uncaught exceptions, the performance gain of recycling threads vs. creating new ones etc. make the executor service a much more powerful solution at little additional cost. Bottom line: I don't see any downsides of using an executor service vs. a thread. The difference between Executors.newSingleThreadExecutor().execute(command) and new Thread(command).start(); goes through the small differences in behaviour between the two options. | {} | {'log_upvote_score': 6, 'links': ['https://Stackoverflow.com/questions/21300924', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2193767/']} | jdg_82733 |
stackexchange | llm_judgeable_groundtruth_similarity | 7531866 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
//for( unsigned int i=0; i < c.size(); i++ ) tolower( c[i] );for_each( c.begin(), c.end(), tolower ); I am trying to use a for_each loop in place of the for loop for an assignment. I am unsure why I am getting this error message: In function âvoid clean_entry(const std::string&, std::string&)â:prog4.cc:62:40: error: no matching function for call to âfor_each(std::basic_string<char>::iterator, std::basic_string<char>::iterator, <unresolved overloaded function type>)â
Now provide the response and nothing else.
| Write: for_each( c.begin(), c.end(), ::tolower ); Or : for_each( c.begin(), c.end(), (int(*)(int))tolower); I've faced this problem so many times that I'm tired of fixing this in my code, as well as in others' code. Reason why your code is not working : there is another overloaded function tolower in the namespace std which is causing problem when resolving the name, because the compiler is unable to decide which overload you're referring to, when you simply pass tolower 1 . That is why the compiler is saying unresolved overloaded function type in the error message, which indicates the presence of overload(s). So to help the compiler in resolving to the correct overload, you've to cast tolower as (int (*)(int))tolower then the compiler gets the hint to select the global tolower function, which in other ways, can be used by writing ::tolower . 1. I guess you've written using namespace std in your code. I would also suggest you to not to do that. Use fully-qualified names in general. By the way, I think you want to transform the input string into lower case, if so, then std::for_each wouldn't do that. You've to use std::transform function as: std::string out;std::transform(c.begin(), c.end(), std::back_inserter(out), ::tolower);//out is output here. it's lowercase string. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/7531866', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/636824/']} | jdg_82734 |
stackexchange | llm_judgeable_groundtruth_similarity | 1328210 |
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 got this task two days ago, quite difficult for me, since I have not done applications of Vieta's formulas and Bezout's Theorem for a while. If can someone solve this and add exactly how I am supposed to use these two theorem's on this task, I would be thankful. Given $x^2 + 4x + 6$ as factor of $x^4 + ax^2 + b$, then $a + b$ is equal to?
Now provide the response and nothing else.
| There is some quadratic $x^2 + cx + d$ such that:$$(x^2 + 4x + 6)(x^2 + cx + d) = x^4 + ax^2 + b$$Multiply it out:$$x^4 + (c + 4)x^3 + (d + 4c + 6)x^2 + (6c + 4d)x + 6d = x^4 + ax^2 + b$$Equate coefficients: $$\begin{cases}c + 4 = 0 \\d + 4c + 6 = a \\4d + 6c = 0 \\6d = b\end{cases}$$ Use the first equation to find $c$. Use the third to find $d$. Use those to find $a$ and $b$. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/1328210', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/248456/']} | jdg_82735 |
stackexchange | llm_judgeable_groundtruth_similarity | 31808 |
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:
One of my friends gave me a problem that stumped me... You have two concentric circles, one with a radius of 1 and one with a radius of 2. What is the probability that a random chord will pass through the inner circle? Why?
Now provide the response and nothing else.
| This is equivalent to the problem that yields the Betrand Paradox , which shows that how we define a probability measure on a continuous set can greatly affect how we define the probability of an event. As other people have argued, if you pick two points on the outer circle at random, then the probability that the chord between them hits the inner circle is 1/3. If you pick two random points inside the outer circle, then the odds that the chord between them intersects the inner circle is at least as great as the probability of one of the two points being inside the inner circle, and that probability is 7/16 = 1-9/16. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/31808', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/4890/']} | jdg_82736 |
stackexchange | llm_judgeable_groundtruth_similarity | 42896141 |
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 iterate on an OrderedDict in reverse order. I.e. reverse the order of: for k, v in my_ordered_dict.iteritems(): # < do stuff > So far I've gotten a non-lazy version, by reversing a list: for k, v in list(my_ordered_dict.iteritems())[::-1]: # < do stuff > Any ideas how to make it better?
Now provide the response and nothing else.
| If you use reversed on the dict it should evaluate lazily: for k, v in ((k, my_ordered_dict[k]) for k in reversed(my_ordered_dict)): ..... How does this work? The key element here is a generator expression , which is evaluated lazily. So this will lazily evaluate over the keys of the ordered dict, and then return a tuple of the key and the dict value when needed. I only need to support python 3: In python 3, dict.items() is now a view and is evaluated lazily. Thus the above can be simplified to: for k, v in reversed(my_ordered_dict.items()): While Python 2.7 does have a viewitems() method, Python 2.7 OrderedDict views do not support the __reversed__ hook that reversed needs to reverse non-sequences. | {} | {'log_upvote_score': 5, 'links': ['https://Stackoverflow.com/questions/42896141', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2476373/']} | jdg_82737 |
stackexchange | llm_judgeable_groundtruth_similarity | 2790218 |
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:
Solve $\int \frac{1}{x^{1/2}+x^{1/3}} dx$ My Attempt $$\int \frac{1}{x^{1/2}+x^{1/3}} dx=\int\frac{dx}{x^{1/2}(1+x^{-1/6})}$$Put $t=x^{1/2}\implies dt=\frac{dx}{2.x^{1/2}}\implies\frac{dx}{x^{1/2}}=2dt$$$\int \frac{1}{x^{1/2}+x^{1/3}} dx=2\int\frac{dt}{1+\frac{1}{t^{1/3}}}$$What is the easiest method to solve this indefinite integral and how do I choose a proper substitution in such problems ?
Now provide the response and nothing else.
| Hint . Make the change of variable$$x=u^6,\qquad dx=6u^5du,$$ then you get$$\int \frac{1}{x^{1/2}+x^{1/3}} dx=6\int \frac{u^3}{u+1} du$$ which is standard to evaluate. | {} | {'log_upvote_score': 4, 'links': ['https://math.stackexchange.com/questions/2790218', 'https://math.stackexchange.com', 'https://math.stackexchange.com/users/223599/']} | jdg_82738 |
stackexchange | llm_judgeable_groundtruth_similarity | 11180125 |
Below is a question asked on the forum Stackoverflow.com. Provide a good and informational response to it like a helpful human would.
Question:
We want to get an array that looks like this: 1,1,1,2,2,2,3,3,3,4,4,4,1,1,1,2,2,2,3,3,3,4,4,4,1,1,1,2,2,2,3,3,3,4,4,4 What is the easiest way to do it?
Now provide the response and nothing else.
| You can do it with a single rep call. The each and times parameters are evaluated sequentially with the each being done first. rep(1:4, times=3, each=3) # 'each' done first regardless of order of named parameters#[1] 1 1 1 2 2 2 3 3 3 4 4 4 1 1 1 2 2 2 3 3 3 4 4 4 1 1 1 2 2 2 3 3 3 4 4 4 | {} | {'log_upvote_score': 7, 'links': ['https://Stackoverflow.com/questions/11180125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1403232/']} | jdg_82739 |
stackexchange | llm_judgeable_groundtruth_similarity | 140719 |
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:
The word shrinkage gets thrown around a lot in certain circles. But what is shrinkage, there does not seem to be a clear definition. If I have a time series (or any collection of observations of some process) what are the different ways I can measure some type of empirical shrinkage on the series? What are the different types of theoretical shrinkage I can talk about? How can shrinkage help in prediction? Can people provide some good insight or references?
Now provide the response and nothing else.
| In 1961 James and Stein published an article called "Estimation with Quadratic Loss" https://projecteuclid.org/download/pdf_1/euclid.bsmsp/1200512173 . While it doesn't specifically coin the term shrinkage, they discuss minimax estimators for high dimensional (actually even for a 3 parameter location) statistics that have less risk (expected loss) than the usual MLE (each component the sample average) for normal data. Bradley Efron calls their finding "the most striking theorem of post-war mathematical statistics". This article has been cited 3,310 times. Copas in 1983 writes the first article Regression, Prediction and Shrinkage to coin the term "shrinkage". It's defined implicitly in the abstract: The fit of a regression predictor to new data is nearly always worse than its fit to the original data. Anticipating this shrinkage leads to Stein‐type predictors which, under certain assumptions, give a uniformly lower prediction mean squared error than least squares. And in all successive research, it seems that shrinkage refers to the operating characteristics (and estimates thereof) for out-of-sample validity of prediction and estimation in the context of finding admissible and/or minimax estimators. | {} | {'log_upvote_score': 4, 'links': ['https://stats.stackexchange.com/questions/140719', 'https://stats.stackexchange.com', 'https://stats.stackexchange.com/users/36049/']} | jdg_82740 |
Subsets and Splits